problem
stringlengths
26
131k
labels
class label
2 classes
How to secure client app (react) and API communication : <p>I have a client side React application and a Rails API from which the React app is fetching data.</p> <p>As you would expect I only want my React application to be able to fetch data from the API and the rest of the world shouldn't be able to receive data from it. </p> <p>Despite much searching I am yet to find the best way to secure the communication between the two applications. </p> <p>I have read about JWT tokens and cookie based session authentication but the majority of articles seem to be focused on authentication of users (ie sign in/sign out) rather than communication between just the two applications. </p> <p>The two apps will share the same domain so is it enough to rely on Cross Origin to secure communication?</p> <p>Any advice really would be much appreciated. </p>
0debug
How do you adjust the height and borderRadius of a BottomSheet in Flutter? : <p>I'm probably missing something obvious here, but my BottomSheet only takes up the bottom half the screen, even though the widgets in it take up more space. So now there is scrolling behavior inside the BottomSheet. I'd like to be able to increase the BottomSheet so that the user doesn't have to scroll as much.</p> <p>I also want to add a borderRadius to the top of my BottomSheet, so that it looks more "modal"-y or "tab"-like.</p> <p>Code:</p> <pre><code>void _showBottomSheet(BuildContext context) { showModalBottomSheet&lt;Null&gt;( context: context, builder: (BuildContext context) { return _bottomSheetScreen; // defined earlier on }, ); } </code></pre> <p>I've tried:</p> <pre><code>showModalBottomSheet&lt;Null&gt;( context: context, builder: (BuildContext context) { return Container( decoration: BoxDecoration( borderRadius: _borderRadius, ), height: 1000.0, child: _bottomSheetScreen, ); }, ); </code></pre> <p>but it seems like that only affects the contents inside the BottomSheet, and does not customize the BottomSheet itself.</p>
0debug
void pc_machine_done(Notifier *notifier, void *data) { PCMachineState *pcms = container_of(notifier, PCMachineState, machine_done); PCIBus *bus = pcms->bus; rtc_set_cpus_count(pcms->rtc, pcms->boot_cpus); if (bus) { int extra_hosts = 0; QLIST_FOREACH(bus, &bus->child, sibling) { if (pci_bus_is_root(bus)) { extra_hosts++; } } if (extra_hosts && pcms->fw_cfg) { uint64_t *val = g_malloc(sizeof(*val)); *val = cpu_to_le64(extra_hosts); fw_cfg_add_file(pcms->fw_cfg, "etc/extra-pci-roots", val, sizeof(*val)); } } acpi_setup(); if (pcms->fw_cfg) { pc_build_smbios(pcms); pc_build_feature_control_file(pcms); fw_cfg_modify_i16(pcms->fw_cfg, FW_CFG_NB_CPUS, pcms->boot_cpus); } if (pcms->apic_id_limit > 255) { IntelIOMMUState *iommu = INTEL_IOMMU_DEVICE(x86_iommu_get_default()); if (!iommu || !iommu->x86_iommu.intr_supported || iommu->intr_eim != ON_OFF_AUTO_ON) { error_report("current -smp configuration requires " "Extended Interrupt Mode enabled. " "You can add an IOMMU using: " "-device intel-iommu,intremap=on,eim=on"); exit(EXIT_FAILURE); } } }
1threat
how must i write this code withoud error : i want to write a code thats write somthing into a file but it says it cant but how i must fix this please help. Imports System.IO Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load yes.Visible = False no.Visible = False Label1.Visible = False ProgressBar1.Visible = False Label2.Visible = False Label3.Visible = False TextBox1.Visible = False TextBox2.Visible = False apply.Visible = False back.Visible = False End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Button1.Visible = False yes.Visible = True no.Visible = True Label1.Visible = True setings.Visible = False End Sub Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles yes.Click Label1.Text = "dowloading" no.Visible = False yes.Visible = False End Sub Private Sub Button3_Click(sender As Object, e As EventArgs) Handles no.Click yes.Visible = False no.Visible = False Label1.Visible = False Button1.Visible = True setings.Visible = True End Sub Private Sub setings_Click(sender As Object, e As EventArgs) Handles setings.Click Label2.Visible = True Label3.Visible = True TextBox1.Visible = True TextBox2.Visible = True apply.Visible = True back.Visible = True Button1.Visible = False setings.Visible = False End Sub Private Sub back_Click(sender As Object, e As EventArgs) Handles back.Click Label2.Visible = False Label3.Visible = False TextBox1.Visible = False TextBox2.Visible = False apply.Visible = False back.Visible = False Button1.Visible = True setings.Visible = True End Sub Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged End Sub Private Sub apply_Click(sender As Object, e As EventArgs) Handles apply.Click Dim forgepath = TextBox1.Text Dim savefolder = Path.Combine(TextBox2.Text, "crazydolphininstaller") Directory.CreateDirectory(savefolder) Dim configfolder = Path.Combine(savefolder, "config") Directory.CreateDirectory(configfolder) Dim configfile = Path.Combine(configfolder, "config.txt") File.Create(configfile) Using writer = New StreamWriter(configfile) writer.WriteLine(forgepath) writer.WriteLine(savefolder) End Using End Sub Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged End Sub Private Sub Label3_Click(sender As Object, e As EventArgs) Handles Label3.Click End Sub End Class
0debug
static void curl_close(BlockDriverState *bs) { BDRVCURLState *s = bs->opaque; int i; DPRINTF("CURL: Close\n"); for (i=0; i<CURL_NUM_STATES; i++) { if (s->states[i].in_use) curl_clean_state(&s->states[i]); if (s->states[i].curl) { curl_easy_cleanup(s->states[i].curl); s->states[i].curl = NULL; } if (s->states[i].orig_buf) { g_free(s->states[i].orig_buf); s->states[i].orig_buf = NULL; } } if (s->multi) curl_multi_cleanup(s->multi); timer_del(&s->timer); g_free(s->url); }
1threat
Changing values of dictionary to integers : <p>I'm currently setting up a dictionary and am attempting to convert the values associated with a key from strings to integers. So I'm trying to go from this:</p> <pre><code> {'Georgia': ['18', '13', '8', '14']} </code></pre> <p>To this:</p> <pre><code> {'Georgia': [18, 13, 8, 14]} </code></pre> <p>Any ideas on how I would go about doing this?</p>
0debug
how to run python query directly from teamcity : I 2 machines on which I need to download Anaconda.sh and some compiler zipped files. One machine is Linux and I downloaded all zip files plus .sh files using below curl command :- curl -s -o cmake-3.4.1-Linux-x86_64.tar.gz http://ccm- XYZ/tools/cmake-3.4.1-Linux-x86_64.tar.gz As this is the linux machine, I am calling it from teamcity and its working fine as expected. Unfortunately, getting issue with the Windows machine as usually we get error on windows. I want the same behaviour for windows also. I want to download .gz file as mentioned above from the teamcity build step. And then need to extract it. As of now, I am using python script as below :- import subprocess subprocess.call("curl -s -o cmake-3.4.1-Linux-x86_64.tar.gz http://tools/cmake-3.4.1-Linux-x86_64.tar.gz", shell=True) It is not running. I think here, the issue is with the running of python commands. Any suggestions here. How can I do that, how can I get into python interactive mode to run the python scripts ?? Thanks in advance.....!!
0debug
get random char in a specific range in java : <p>Am designing wumpus hunting program using java. Where i can include three gold, 3 pits, one wumpus, one player. and the position of the game item should be random generator.How to generate random characters in 2d array . How to specify the range for the characters in java. Thanks.</p>
0debug
void virtio_scsi_exit(VirtIODevice *vdev) { virtio_cleanup(vdev); }
1threat
i need to change my url seo friendly with url routing : i need to know how i change my site url my i try url routing what is not work my site product url is => [http://www.shahilibas.in/product.php?p_id=5] and i want seo friendly url like [http://www.shahilibas.in/product.php/5] i try this code for url routing function getCurrentUri() { $basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/'; $uri = substr($_SERVER['REQUEST_URI'], strlen($basepath)); if (strstr($uri, '?')) $uri = substr($uri, 0, strpos($uri, '?')); $uri = '/' . trim($uri, '/'); return $uri; echo $uri; }
0debug
Xamarin: Error CS0118: `SessionsManager.Create()' is a `method group' but a `type' was expected (CS0118) : I have this error message. I'm creating a Xamarin.ios table view app. If anyone can help me thanks in advanced. public partial class SessionsViewController : UITableViewController { public SessionsViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); var sessionManager = new SessionsManager.Create();// receive the error here. TableView.Source = new SessionsTableViewSource(sessionManager.Sessions); } } --------------------------------------------------------------------------- public class SessionsManager { private static SessionsManager _instance = null; public SessionData[] Sessions; public static SessionsManager Create() { if (_instance == null) _instance = new SessionsManager(); return _instance; } internal SessionsManager() { SessionData[] sessions = new SessionData[5] { new Data("1", "Title1", "speaker1", "desc1", DateTime.Today, true), new Data("2", "Title2", "speaker2", "desc2", DateTime.Today, false), new Data("3", "Title3", "speaker3", "desc3", DateTime.Today, false), new Data("4", "Title4", "speaker4", "desc4", DateTime.Today, true), new Data("5", "Title5", "speaker5", "desc5", DateTime.Today, true) };
0debug
How to create an automatic function in laravel : as described in the title I want to create an automatic function with php laravel that launches after the end of each month. Thank you in advance.
0debug
VB.Net Textbox to DateTimePicker : <p>DateTimePicker1 = dateofbirth.Text</p> <p>it says The Value of type 'String' cannot be converted to 'System.Windows.Forms.DateTimePicker'.</p> <p>please help me how to convert the date from textbox to datetimepicker the format of date is yyyy/MM/dd. thank you in advance.</p>
0debug
argparse: flatten the result of action='append' : <p>I'd like to make a script that supports an argument list of the form</p> <pre><code>./myscript --env ONE=1,TWO=2 --env THREE=3 </code></pre> <p>Here's my attempt:</p> <pre><code>import argparse parser = argparse.ArgumentParser() parser.add_argument( '--env', type=lambda s: s.split(','), action='append', ) options = parser.parse_args() print options.env $ ./myscript --env ONE=1,TWO=2 --env THREE=3 [['ONE=1', 'TWO=2'], ['THREE=3']] </code></pre> <p>Sure I can fix this in postprocessing:</p> <pre><code>options.env = [x for y in options.env for x in y] </code></pre> <p>but I'm wondering if there's some way to get the flattened list directly from argparse, so that I don't have to maintain a list of "things I need to flatten afterwards" in my head as I'm adding new options to the program.</p> <p>The same question applies if I were to use <code>nargs='*'</code> instead of <code>type=lambda...</code>.</p> <pre><code>import argparse parser = argparse.ArgumentParser() parser.add_argument( '--env', nargs='+', action='append', ) options = parser.parse_args() print options.env $ ./myscript --env ONE=1 TWO=2 --env THREE=3 [['ONE=1', 'TWO=2'], ['THREE=3']] </code></pre>
0debug
Disable gesture to pull down form/page sheet modal presentation : <p>In iOS 13 modal presentations using the form and page sheet style can be dismissed with a pan down gesture. This is problematic in one of my form sheets because the user draws into this box which interferes with the gesture. It pulls the screen down instead of drawing a vertical line.</p> <p>How can you disable the vertical swipe to dismiss gesture in a modal view controller presented as a sheet?</p> <p>Setting <code>isModalInPresentation = true</code> still allows the sheet to be pulled down, it just won't dismiss.</p>
0debug
What's the difference between Laravel's @yield and @include? : <p>I'm learning Laravel (starting at version 5.3) and those two look very much alike, the only difference I know is that @include inject parent's variables and can also send other variables.</p> <ul> <li>What's the difference between @yield and @include?</li> <li>When should I use @yield?</li> <li>When should I use @include?</li> </ul>
0debug
int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options, int flags, BlockDriver *drv, Error **errp) { int ret; char tmp_filename[PATH_MAX + 1]; BlockDriverState *file = NULL; QDict *file_options = NULL; const char *drvname; Error *local_err = NULL; if (options == NULL) { options = qdict_new(); } bs->options = options; options = qdict_clone_shallow(options); if (flags & BDRV_O_SNAPSHOT) { BlockDriverState *bs1; int64_t total_size; BlockDriver *bdrv_qcow2; QEMUOptionParameter *create_options; char backing_filename[PATH_MAX]; if (qdict_size(options) != 0) { error_setg(errp, "Can't use snapshot=on with driver-specific options"); ret = -EINVAL; goto fail; } assert(filename != NULL); bs1 = bdrv_new(""); ret = bdrv_open(bs1, filename, NULL, 0, drv, &local_err); if (ret < 0) { bdrv_unref(bs1); goto fail; } total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK; bdrv_unref(bs1); ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename)); if (ret < 0) { error_setg_errno(errp, -ret, "Could not get temporary filename"); goto fail; } if (path_has_protocol(filename)) { snprintf(backing_filename, sizeof(backing_filename), "%s", filename); } else if (!realpath(filename, backing_filename)) { error_setg_errno(errp, errno, "Could not resolve path '%s'", filename); ret = -errno; goto fail; } bdrv_qcow2 = bdrv_find_format("qcow2"); create_options = parse_option_parameters("", bdrv_qcow2->create_options, NULL); set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size); set_option_parameter(create_options, BLOCK_OPT_BACKING_FILE, backing_filename); if (drv) { set_option_parameter(create_options, BLOCK_OPT_BACKING_FMT, drv->format_name); } ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options, &local_err); free_option_parameters(create_options); if (ret < 0) { error_setg_errno(errp, -ret, "Could not create temporary overlay " "'%s': %s", tmp_filename, error_get_pretty(local_err)); error_free(local_err); local_err = NULL; goto fail; } filename = tmp_filename; drv = bdrv_qcow2; bs->is_temporary = 1; } if (flags & BDRV_O_RDWR) { flags |= BDRV_O_ALLOW_RDWR; } qdict_extract_subqdict(options, &file_options, "file."); ret = bdrv_file_open(&file, filename, file_options, bdrv_open_flags(bs, flags | BDRV_O_UNMAP), &local_err); if (ret < 0) { goto fail; } drvname = qdict_get_try_str(options, "driver"); if (drvname) { drv = bdrv_find_whitelisted_format(drvname, !(flags & BDRV_O_RDWR)); qdict_del(options, "driver"); } if (!drv) { ret = find_image_format(file, filename, &drv, &local_err); } if (!drv) { goto unlink_and_fail; } ret = bdrv_open_common(bs, file, options, flags, drv, &local_err); if (ret < 0) { goto unlink_and_fail; } if (bs->file != file) { bdrv_unref(file); file = NULL; } if ((flags & BDRV_O_NO_BACKING) == 0) { QDict *backing_options; qdict_extract_subqdict(options, &backing_options, "backing."); ret = bdrv_open_backing_file(bs, backing_options, &local_err); if (ret < 0) { goto close_and_fail; } } if (qdict_size(options) != 0) { const QDictEntry *entry = qdict_first(options); error_setg(errp, "Block format '%s' used by device '%s' doesn't " "support the option '%s'", drv->format_name, bs->device_name, entry->key); ret = -EINVAL; goto close_and_fail; } QDECREF(options); if (!bdrv_key_required(bs)) { bdrv_dev_change_media_cb(bs, true); } return 0; unlink_and_fail: if (file != NULL) { bdrv_unref(file); } if (bs->is_temporary) { unlink(filename); } fail: QDECREF(bs->options); QDECREF(options); bs->options = NULL; if (error_is_set(&local_err)) { error_propagate(errp, local_err); } return ret; close_and_fail: bdrv_close(bs); QDECREF(options); if (error_is_set(&local_err)) { error_propagate(errp, local_err); } return ret; }
1threat
overwrite hive partitions using spark : <p>I am working with AWS and I have workflows that use Spark and Hive. My data is partitioned by the date, so everyday I have a new partition in my S3 storage. My problem is when one day the load data fails and I have to re-execute that partition. The code that writes is next:</p> <pre><code>df // My data in a Dataframe .write .format(getFormat(target)) // csv by default, but could be parquet, ORC... .mode(getSaveMode("overwrite")) // Append by default, but in future it should be Overwrite .partitionBy(partitionName) // Column of the partition, the date .options(target.options) // header, separator... .option("path", target.path) // the path where it will be storage .saveAsTable(target.tableName) // the table name </code></pre> <p>What happens in my flow? If I use the SaveMode.Overwrite, the complete table will be delete and I will have only the partition saved. If I use the SaveMode.Append I could have duplicate data. </p> <p>Making a search, I found that Hive support this kind of overwrite, only partition, but using the hql sentences, I don´t have it.</p> <p>We need the solution on Hive, so we can´t use this <a href="https://stackoverflow.com/questions/38487667/overwrite-specific-partitions-in-spark-dataframe-write-method">alternative option</a> (direct to csv).</p> <p>I had found this <a href="https://issues.apache.org/jira/browse/SPARK-20236" rel="noreferrer">Jira ticket</a> that suppose to solve the problem that I´m having, but trying that with the last version of Spark (2.3.0), the situation was the same. It delete the whole table and save the partition instead of overwrite the partition that my data has.</p> <p>Trying to make clearer this, this is an example:</p> <p>Partitioned by A</p> <p>Data: </p> <pre><code>| A | B | C | |---|---|---| | b | 1 | 2 | | c | 1 | 2 | </code></pre> <p>Table:</p> <pre><code>| A | B | C | |---|---|---| | a | 1 | 2 | | b | 5 | 2 | </code></pre> <p>What I want is: In Table, the partition <code>a</code> stay in table, partition <code>b</code> overwrite with the Data, and add the partition <code>c</code>. Is there any solution using Spark that I can do this? </p> <p>My last option to do this is first deleting the partition that is going to be saved and then use the SaveMode.Append, but I would try this in case no other solution.</p>
0debug
static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref) { PadContext *pad = inlink->dst->priv; AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0); int plane; inlink->dst->outputs[0]->out_buf = outpicref; for (plane = 0; plane < 4 && outpicref->data[plane]; plane++) { int hsub = (plane == 1 || plane == 2) ? pad->hsub : 0; int vsub = (plane == 1 || plane == 2) ? pad->vsub : 0; outpicref->data[plane] -= (pad->x >> hsub) * pad->line_step[plane] + (pad->y >> vsub) * outpicref->linesize[plane]; } outpicref->video->w = pad->w; outpicref->video->h = pad->h; avfilter_start_frame(inlink->dst->outputs[0], outpicref); }
1threat
Ned to print the below string as: 10-30 03:45:04.312 2760 2760 GrowthKit: job GrowthKit.PeriodicSyncJob failed E : string as 10-30 03:45:04.312 2760 2760 GrowthKit: job GrowthKit.PeriodicSyncJob E So the output should look as below 10-30 03:45:04.312 2760 2760 GrowthKit: job GrowthKit.PeriodicSyncJob failed E Need to be done with RegularExpression matcher and pattern. Written code: public static void main(String[] args) { String s = "10-30 03:45:04.312 2760 2760 GrowthKit: job GrowthKit.PeriodicSyncJob E "; Pattern regex = Pattern.compile("^([a-zA-Z0-9]+).*"); Matcher matcher = regex .matcher(s); while (matcher.find()) { for (int i = 0; i < matcher.groupCount(); i++) { String[] words = matcher.group(i).split("\\s+"); for (String line : words) { System.out.println("" + line); } } } } } Please provide us the solution for this:
0debug
stdout progress bars don't work in Pycharm : <p>Many programs display progress bars by prnting to stdout and then returning to beginnign of line and pronting again. This way they achieve realtime progress bar appearence.</p> <p>Unfortunately, in many cases this functionality does not work in PyCharm's console.</p> <p>This is an example on how it shows keras train progress bar:</p> <p><a href="https://i.stack.imgur.com/g1RLN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/g1RLN.png" alt="enter image description here"></a></p> <p>i.e. each progress bar change goes to separate line.</p> <p>Is it possible to fix this?</p>
0debug
static int ac3_probe(AVProbeData *p) { int max_frames, first_frames = 0, frames; uint8_t *buf, *buf2, *end; AC3HeaderInfo hdr; if(p->buf_size < 7) return 0; max_frames = 0; buf = p->buf; end = buf + p->buf_size; for(; buf < end; buf++) { buf2 = buf; for(frames = 0; buf2 < end; frames++) { if(ff_ac3_parse_header(buf2, &hdr) < 0) break; buf2 += hdr.frame_size; } max_frames = FFMAX(max_frames, frames); if(buf == p->buf) first_frames = frames; } if (first_frames>=3) return AVPROBE_SCORE_MAX * 3 / 4; else if(max_frames>=3) return AVPROBE_SCORE_MAX / 2; else if(max_frames>=1) return 1; else return 0; }
1threat
Can not pass this by reference, this is readonly : <p>Getting this error message is quite confusing, as saying <code>this.property = value</code> is totally valid. quite obviously, this can be used to set values. However, when passing this as a reference into a function it errors, stating the above. How can this be passed into a function expecting a ref?</p>
0debug
float32 helper_fdtos(CPUSPARCState *env, float64 src) { float32 ret; clear_float_exceptions(env); ret = float64_to_float32(src, &env->fp_status); check_ieee_exceptions(env); return ret; }
1threat
Wil a C/C++ compiler inline a for-loop with a small number of terms? : Suppose I have a class `5x5matrix` (with suitably overloaded index operators) and I write a method `trace` for calculating the sum of its diagonal elements: double 5x5matrix::trace(void){ double t(0.0); for(int i(0); i <= 4; ++i){ t += (*this)[i][i]; } return t; } Of course, if I instead wrote: return (*this)[0][0]+(*this)[1][1]+(*this)[2][2]+(*this)[3][3]+(*this)[4][4]; then I would be sure to avoid the overhead of declaring and incrementing my `i` variable. But it feels quite stupid to write out all those terms! Since my loop has a "constexpr" number of terms that happens to be quite small, would a compiler inline it for me?
0debug
Are cURL calls secure using HTTPS? : <p>I am using cURL to call an API over HTTPS. Assuming the API is secured and the HTTPS connection is too, would a simple cURL call on my end be secure or do I need to change cURL parameters to make it secure or should I not use cURL at all?</p> <p>Security is very important in this project.</p>
0debug
static int usb_wacom_handle_data(USBDevice *dev, USBPacket *p) { USBWacomState *s = (USBWacomState *) dev; uint8_t buf[p->iov.size]; int ret = 0; switch (p->pid) { case USB_TOKEN_IN: if (p->devep == 1) { if (!(s->changed || s->idle)) return USB_RET_NAK; s->changed = 0; if (s->mode == WACOM_MODE_HID) ret = usb_mouse_poll(s, buf, p->iov.size); else if (s->mode == WACOM_MODE_WACOM) ret = usb_wacom_poll(s, buf, p->iov.size); usb_packet_copy(p, buf, ret); break; } case USB_TOKEN_OUT: default: ret = USB_RET_STALL; break; } return ret; }
1threat
How to Pass Parameter to array.map()? : <p>I am trying to map values to a function that will accept two numbers to multiply but am having trouble doing so (if this doesn't make sense, take a look at the examples below).</p> <p>I have an array of numbers and I would like to double/triple/quadruple... the values of this array. I have created functions that would do this, and am feeding these <code>double()</code> and <code>triple()</code> into <code>map()</code>.</p> <pre><code>var arr = [1, 2, 3, 4, 5]; function double(num) { return num * 2; } function triple(num) { return num * 3; } console.log( arr.map(double) ); console.log( arr.map(triple) ); </code></pre> <p>This solution is not scalable as what if I want to multiply the values by 5, or 10? I need a more abstract function that would take a parameter of what to multiply. I am confused about how to do this. My attempt so far is:</p> <pre><code>var arr = [1, 2, 3, 4, 5]; function multiply(num, multiplyBy) { return num * multiplyBy; } console.log( arr.map(multiplyBy(4) ); // Uncaught TypeError: NaN is not a function </code></pre> <p>How would I pass <code>multiply()</code> the <code>multiplyBy</code> parameter?</p>
0debug
Singleton Factory to produces multiple singleton instances : <p>I have two singleton classes in my project. </p> <pre><code>public class VStateManager : IVState { private static readonly object _createLock = new object(); private static VStateManager _vsManager = null; public static VStateManager GetVStateManager() { lock (_createLock) { if (_vsManager == null) { return new VStateManager(); } return _vsManager; } } } public class VTRFactory : IVTR { private static VehicleFactory _VTRFactory =null; private static readonly object _createLock = new object(); public static VehicleFactory GetVTRFactory() { lock(_createLock) { if(_VTRFactory == null) { return new VTRFactory(); } return _VTRFactory; } } } </code></pre> <p>My colleague suggested to create a singleton class (<code>something like a singleton factory</code>) that accepts a generic interface and produces both these <code>singleton objects</code></p> <p>How can this be done.? </p>
0debug
A namespace-style import cannot be called or constructed, and will cause a failure at runtime : <p>Strange stuff happening here, with TypeScript 2.7.2, in VSCode version 1.21 with @types/express and the code that follows, in some cases VSCode throws errors stating that "A namespace-style import cannot be called or constructed, and will cause a failure at runtime.". However on other machines with similar setups and similar tsconfig.json files the code just works.. What is happening here:</p> <pre><code>import { Bank } from './Bank'; import * as Express from 'express'; &lt;== errors here.. let app: Express.Express; this.app = Express(); &lt;== and here </code></pre> <p>Why is this happening? </p> <p>TIA, </p> <p>John.</p>
0debug
How to view the FrameLayout content to the right of NavigationView when the NavigationView is opened : i want to do this layout on android i tried using DrawerLayout with FrameLayout and NavigationView as DrawerLayout children but i don't know how to make the left side of the FrameLayout appears to the right of the NavigationView when the NavigationView is opened so does anyone have a suggestion to achieve this? [enter image description here][1] [1]: https://i.stack.imgur.com/tbLwt.png
0debug
Implementing HashMap: Avoid collisions caused by compress function : <p>I'm implementing a hashmap to contain all words in a word file (e.g <code>dictionary.txt</code>, <code>bible.txt</code>) and I am having a collision problem. I know that there are many good hash functions out there but when I try compressing the hash code using this compression function, the number of collisions raises significantly (I'm using <a href="http://www.cse.yorku.ca/~oz/hash.html" rel="nofollow noreferrer" title="dbj2">dbj2</a> for my hash function).</p> <p>My hashmap basically converts a key to its hash value and compresses that hash value to the index of the entry in the internal hash table, which is an array. It resizes itself to <code>2 * capacity - 1</code> if the <code>load factor</code> of <code>0.5</code> is reached. When collisions happen, my hashmap generates new indexes using quadratic probing.</p> <p>This is what my current compress function looks like:</p> <pre><code>private int compress(int hashCode) { return Math.abs(hashCode) % capacity; } </code></pre> <p>Is there any (efficient) way I can do to avoid collisions? Changing the structure of the hashmap itself is also accepted.</p>
0debug
Servlet Not Found Error : <p>Im getting a servlet not found error. Im using WIldFly. My directory structure looks like this:</p> <p>root --> app, converter.html, src</p> <p>app --> WEB-INF</p> <p>WEB-INF--> classes, lib, web.xml</p> <p>src --> servlet.java</p> <p>I have been looking over it for awhile and can't pin point the problem. I think I have the mapping down correctly in the web.xml and the form action seems to be sent to the right place as well in the .html file.</p> <p>Servlet Class:</p> <pre><code>import java.io.IOException; import java.util.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class servlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ String username = request.getParameter("username"); String email = request.getParameter("email"); response.getWriter().println("&lt;html&gt;"); response.getWriter().println("&lt;head&gt;"); response.getWriter().println("&lt;title&gt;Title&lt;/title&gt;"); response.getWriter().println("&lt;/head&gt;"); response.getWriter().println("&lt;body&gt;"); response.getWriter().println("Convert. "); response.getWriter().println("&lt;/body&gt;"); response.getWriter().println("&lt;/html&gt;"); } } </code></pre> <p>web.xml</p> <pre><code>&lt;web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"&gt; &lt;servlet&gt; &lt;servlet-name&gt;servlet&lt;/servlet-name&gt; &lt;servlet-class&gt;servlet&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;servlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/servlet&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;/web-app&gt; </code></pre> <p>converter.html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt; Test form &lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="http://localhost:8080/root/src/servlet" method="get"&gt; Name: &lt;input type="text" name="username"&gt;&lt;br&gt; Email: &lt;input type="text" name="email"&gt;&lt;br&gt; &lt;input type="submit" value="Submit"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
0debug
How do I resolve Activity Not Found Exception : <p>In my android app, I've added an activity <em>MainActivity</em> in the manifest file, on navigating to that activity using an inten I get <code>activity not found error</code> asking if I've added it to manifest</p> <p>here is my manifest activity</p> <pre><code> &lt;activity android:name=".MainActivity" android:clearTaskOnLaunch="true" android:configChanges="orientation|keyboardHidden|screenSize" android:icon="@mipmap/ic_launcher" android:rotationAnimation="seamless" android:screenOrientation="portrait" android:theme="@style/Theme.AppCompat" tools:targetApi="O"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.OPENABLEk" /&gt; &lt;/intent-filter&gt; &lt;!-- Register as a system camera app--&gt; &lt;intent-filter&gt; &lt;action android:name="android.media.action.IMAGE_CAPTURE" /&gt; &lt;action android:name="android.media.action.STILL_IMAGE_CAMERA" /&gt; &lt;action android:name="android.media.action.VIDEO_CAMERA" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;!-- App links for http/s --&gt; &lt;intent-filter android:autoVerify="true"&gt; &lt;action android:name="android.intent.action.VIEW" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;category android:name="android.intent.category.BROWSABLE" /&gt; &lt;data android:scheme="http" /&gt; &lt;data android:scheme="https" /&gt; &lt;data android:host="example.android.com" /&gt; &lt;data android:pathPattern="/camerax" /&gt; &lt;/intent-filter&gt; &lt;!-- Declare notch support --&gt; &lt;meta-data android:name="android.notch_support" android:value="true" /&gt; &lt;/activity&gt; </code></pre> <p>here is the log</p> <pre><code>E/AndroidRuntime: FATAL EXCEPTION: main Process: com.virtusync.scanningtool, PID: 28538 android.content.ActivityNotFoundException: Unable to find explicit activity class {com.virtusync.scanningtool/com.android.example.cameraxbasic.MainActivityKt}; have you declared this activity in your AndroidManifest.xml? at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2005) at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673) at android.app.Activity.startActivityForResult(Activity.java:4586) at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:675) at android.app.Activity.startActivityForResult(Activity.java:4544) at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:662) at android.app.Activity.startActivity(Activity.java:4905) at android.app.Activity.startActivity(Activity.java:4873) at com.android.example.cameraxbasic.SelectOperation$1.onClick(SelectOperation.java:36) at android.view.View.performClick(View.java:7044) at android.view.View.performClickInternal(View.java:7017) at android.view.View.access$3200(View.java:784) at android.view.View$PerformClick.run(View.java:26596) at android.os.Handler.handleCallback(Handler.java:873) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6819) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912) </code></pre> <p>I've done this <a href="https://stackoverflow.com/questions/54634397/how-to-fix-android-content-activitynotfoundexception-android-studio-2-3-3">How to fix &quot;android.content.ActivityNotFoundException&quot; android-studio 2.3.3</a> no solution yet</p>
0debug
How do you write (9.5*(4.5)-2.5*3)/(45.5-3.5) in Java? : <p>How do you write (9.5*(4.5)-2.5*3)/(45.5-3.5) in Java?</p>
0debug
Concatenating string and int in c++ : <p>I am doing some exercises in C++ when I came upon something not so clear for me: </p> <pre><code>cout &lt;&lt; "String" + 1 &lt;&lt; endl; </code></pre> <p>outputs : tring</p> <p>I suggest it is something with pointer arithmetic, but does that mean that everytime I print something in quotes that is not part of previous defined array,I actually create a char array ? </p>
0debug
static int __qemu_rdma_add_block(RDMAContext *rdma, void *host_addr, ram_addr_t block_offset, uint64_t length) { RDMALocalBlocks *local = &rdma->local_ram_blocks; RDMALocalBlock *block = g_hash_table_lookup(rdma->blockmap, (void *) block_offset); RDMALocalBlock *old = local->block; assert(block == NULL); local->block = g_malloc0(sizeof(RDMALocalBlock) * (local->nb_blocks + 1)); if (local->nb_blocks) { int x; for (x = 0; x < local->nb_blocks; x++) { g_hash_table_remove(rdma->blockmap, (void *)old[x].offset); g_hash_table_insert(rdma->blockmap, (void *)old[x].offset, &local->block[x]); } memcpy(local->block, old, sizeof(RDMALocalBlock) * local->nb_blocks); g_free(old); } block = &local->block[local->nb_blocks]; block->local_host_addr = host_addr; block->offset = block_offset; block->length = length; block->index = local->nb_blocks; block->nb_chunks = ram_chunk_index(host_addr, host_addr + length) + 1UL; block->transit_bitmap = bitmap_new(block->nb_chunks); bitmap_clear(block->transit_bitmap, 0, block->nb_chunks); block->unregister_bitmap = bitmap_new(block->nb_chunks); bitmap_clear(block->unregister_bitmap, 0, block->nb_chunks); block->remote_keys = g_malloc0(block->nb_chunks * sizeof(uint32_t)); block->is_ram_block = local->init ? false : true; g_hash_table_insert(rdma->blockmap, (void *) block_offset, block); DDPRINTF("Added Block: %d, addr: %" PRIu64 ", offset: %" PRIu64 " length: %" PRIu64 " end: %" PRIu64 " bits %" PRIu64 " chunks %d\n", local->nb_blocks, (uint64_t) block->local_host_addr, block->offset, block->length, (uint64_t) (block->local_host_addr + block->length), BITS_TO_LONGS(block->nb_chunks) * sizeof(unsigned long) * 8, block->nb_chunks); local->nb_blocks++; return 0; }
1threat
How to delete rows in python pandas DataFrame using regular expressions? : <p>I have a pattern:</p> <pre><code>patternDel = "( \\((MoM|QoQ)\\))"; </code></pre> <p>And I want to delete all rows in pandas dataframe where column <code>df['Event Name']</code> matches this pattern. Which is the best way to do it? There are more than 100k rows in dataframe.</p>
0debug
Essence of Laziness. Haskell : <p>I am learning a haskell for a few days and the laziness is something like buzzword. Because of the fact I am not familiar with laziness ( I have been working mainly with non-functional languages ) it is not easy concept for me.</p> <p>So, I am asking for any excerise / example which show me what laziness is in the fact. </p> <p>Thanks in advance ;)</p>
0debug
static QDict *build_qmp_error_dict(const QError *err) { QObject *obj; obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %p } }", ErrorClass_lookup[err->err_class], qerror_human(err)); return qobject_to_qdict(obj); }
1threat
Is using magic (me/self) resource identifiers going against REST principles? : <p>I've seen URIs that support magic ids for the authenticated user like below:</p> <pre><code>GET /user/me - list my profile GET /user/me/photos - list my photos </code></pre> <p>where the ones below use the actual user id</p> <pre><code>GET /user/742924 GET /user/742924/photos </code></pre> <p>The problem I see is that the same resource id points to a different resource depending on the authenticated user. </p> <p>Is this going against any REST principles?</p>
0debug
How can i display multiple value of an array in angular : How can i display mutliple value of an array? I manage to display one but i don't know how i can display all the value of my array public products: product[] = [ { id: 1, name: "McFlurry", price: 2, enseigne:"McDonalds" }, { id: 2, name: "Potatoes", price: 3, enseigne:"McDonalds" }, { id: 3, name: "BigMac", price: 4, enseigne:"KFC" }, { id: 4, name: "Nuggets", price: 3, enseigne:"KFC" }]; searchEnseigne(){ let server = this.products.find(x => x.enseigne === "McDonalds"); console.log(server); }
0debug
Pandas: working of exponential operator ** : I am running a python script where I am computing following: t - 2 ** (j - 1) * l where t = 302536, j = 6, l=0 this returns me 302536, I am not able to understand how. As per me the result should have been 302536. `2 ** (j - 1) * l` results in 0 which according to me should have resulted in 1 as `(j - 1) * l results in 0` how is this being computed.
0debug
2 instance of class , but seems they are the same : <p>I am expecting obj1 and obj2 will have different deck.cards, why they are the same, how do I make them 2 instance?</p> <pre><code>class deck: cards ={} def __init__(self, key, value): self.cards[key]=value return &gt;&gt;&gt; obj1 = deck("a", "1") &gt;&gt;&gt; obj2 = deck("b", "2") &gt;&gt;&gt; print (obj1.cards, obj2.cards) {'a': '1', 'b': '2'} {'a': '1', 'b': '2'} </code></pre>
0debug
Python crashing on MacOS 10.15 Beta (19A582a) with "/usr/lib/libcrypto.dylib" : <p>I ran my Django project with new macOS Catalina and was running fine.<br> I installed oh_my_zsh then I tried to run the same project it is crashing with the following errors. I uninstalled oh_my_zsh and tried again but it did not worked.</p> <pre><code>Path: /usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python Identifier: Python Version: 3.7.4 (3.7.4) Code Type: X86-64 (Native) Parent Process: Python [7526] Responsible: Terminal [7510] User ID: 501 Date/Time: 2019-10-07 20:59:20.675 +0530 OS Version: Mac OS X 10.15 (19A582a) Report Version: 12 Anonymous UUID: CB7F20F6-96C0-4F63-9EC5-AFF3E0989687 Time Awake Since Boot: 3000 seconds System Integrity Protection: enabled Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Exception Note: EXC_CORPSE_NOTIFY Application Specific Information: /usr/lib/libcrypto.dylib abort() called Invalid dylib load. Clients should not load the unversioned libcrypto dylib as it does not have a stable ABI. </code></pre>
0debug
Sorting a Tuple list by the Counter Python : Python 3.6+ I have a list of tuples tuple_list=[(a=3,b=gt,c=434),(a=4,b=lodf,c=We),(a=3,b=gt,c=434)] I want to count the number of duplicates in the list and then sort the list so the number with the highest duplicates is at the top so I used tuple_counter = collections.Counter(tuple(sorted(tup)) for tup in tuple_list) But this returns in error because TypeError: unorderable types: int() < str() I've also tried this but it doesn't seem to sort by the highest counter. tuple_counter = collections.Counter(tuple_list) tuple_counter = sorted(tuple_counter, key=lambda x: x[1]) As well as this tuple_counter = collections.Counter(tuple_list) tuple_counter = tuple_counter.most_common() Is there a better way to do this?
0debug
Regular expression to select everything outside <> in a string : <p>I'm not very handy with regex and I need to select everything outside &lt;> to get the length of the string, excluding the "&lt;>".</p> <p>For example: <code>first&lt;second&gt;third&lt;fourth&gt;fifth</code> should give me <code>first third fifth</code>.</p> <p>How can I do it? I spent some hours searching the web but I didn't really find what I needed. The regex is needed for use in javascript.</p>
0debug
Changing chunk background color in RMarkdown : <p>I would like to have a certain code chunk highlighted in a different color (e.g. red) to indicate that it is bad practice. If I was using <code>.Rnw</code>, I could add the chunk option <code>background = 'red'</code> and get what I want, but this does not seem to work in <code>.Rmd</code>. My guess is that I need to make a custom css stylesheet (though what the selector would be, I don't know), and maybe also create a custom hook. I'd like it to be on a per-chunk basis, not an overall change for the entire document.</p>
0debug
If Else Not Work in Php Script : I have php code to display information messages returned. But this is not working. As this is an example of the codes: <?php if(intval(mysql_num_rows($req2))==0) { ?> (No reply) <?php } else { ?> (<?php echo $dn2['reps']-1; ?> time reply) <?php } ?> How to fix?
0debug
void cpu_set_log(int log_flags) { loglevel = log_flags; if (loglevel && !logfile) { logfile = fopen(logfilename, log_append ? "a" : "w"); if (!logfile) { perror(logfilename); _exit(1); } #if !defined(CONFIG_SOFTMMU) { static char logfile_buf[4096]; setvbuf(logfile, logfile_buf, _IOLBF, sizeof(logfile_buf)); } #elif !defined(_WIN32) setvbuf(logfile, NULL, _IOLBF, 0); #endif log_append = 1; } if (!loglevel && logfile) { fclose(logfile); logfile = NULL; } }
1threat
Python3 index of char on String when not found : <p>As said in the official <a href="https://docs.python.org/3/library/stdtypes.html#string-methods" rel="nofollow noreferrer">documentation</a>, in Python when calling the function <code>index</code> on a String</p> <blockquote> <p>index raises ValueError when x is not found in s</p> </blockquote> <p>I know we can test the existence of a char in a String simply like this <code>'c' in String</code>, but it makes the syntax kind of akward. </p> <p>Is there any known implementation of the function <code>index</code> that would return a -1 or such an error code instead of raising an <code>Error</code></p>
0debug
static DisplaySurface *qemu_create_dummy_surface(void) { static const char msg[] = "This VM has no graphic display device."; DisplaySurface *surface = qemu_create_displaysurface(640, 480); pixman_color_t bg = color_table_rgb[0][COLOR_BLACK]; pixman_color_t fg = color_table_rgb[0][COLOR_WHITE]; pixman_image_t *glyph; int len, x, y, i; len = strlen(msg); x = (640/FONT_WIDTH - len) / 2; y = (480/FONT_HEIGHT - 1) / 2; for (i = 0; i < len; i++) { glyph = qemu_pixman_glyph_from_vgafont(FONT_HEIGHT, vgafont16, msg[i]); qemu_pixman_glyph_render(glyph, surface->image, &fg, &bg, x+i, y, FONT_WIDTH, FONT_HEIGHT); qemu_pixman_image_unref(glyph); } return surface; }
1threat
Change date format with month name to dd/mm/YYYY : <p>I have a string with a date in this format: April 16, 2017 23:59, I would like to write a function to change it so that it's in this format: dd/mm/YYYY eg 16/04/2017</p> <p>I tried to use the date function but couldn't get it to work. Does anyone know how I can do this in PHP?</p>
0debug
rxjs - Discard future returning observables : <p>So here is my observable code:</p> <pre><code> var suggestions = Rx.Observable.fromEvent(textInput, 'keyup') .pluck('target','value') .filter( (text) =&gt; { text = text.trim(); if (!text.length) // empty input field { this.username_validation_display("empty"); } else if (!/^\w{1,20}$/.test(text)) { this.username_validation_display("invalid"); return false; } return text.length &gt; 0; }) .debounceTime(300) .distinctUntilChanged() .switchMap(term =&gt; { return $.ajax({ type: "post", url: "src/php/search.php", data: { username: term, type: "username" } }).promise(); } ); suggestions.subscribe( (r) =&gt; { let j = JSON.parse(r); if (j.length) { this.username_validation_display("taken"); } else { this.username_validation_display("valid"); } }, function (e) { console.log(e); } ); </code></pre> <p>The problem I have is when the input is empty I have a another piece of code that basically returns a 'error: empty input' but it gets overridden by the returning observable. So I was wondering if there was a way to disregard all observables if the <code>text.length</code> is 0, but also re-subscribe when the text length isn't zero.</p> <p>I've thought about <code>unsubscribe</code> but don't know where to fit it in to try.</p>
0debug
What's the best way to store who a user is following for a social network? : <p>I'm working on a social network right now, and I was wondering: to store which users are following who, should I make another table called "Following" with rows of who is following who, or add a Following column in my users table and store all the user IDs they are following as an array?</p>
0debug
Router getCurrentNavigation always returns null : <p>In the latest version of Angular 7.2.6, I'm trying to pass data in router itself</p> <pre><code>this.router.navigate(['other'], {state: {someData: 'qwert'}} </code></pre> <p>In the <code>OtherComponent</code> file, <code>this.router.getCurrentNavigation()</code> always return null</p> <p><a href="https://stackblitz.com/edit/angular-uapqsj" rel="noreferrer">Stackblitz Link</a></p> <p><a href="https://angular.io/api/router/Router#getcurrentnavigation" rel="noreferrer">Angular Docs - getCurrentNavigation</a></p> <p><a href="https://angular.io/api/router/NavigationExtras#state" rel="noreferrer">Angular Docs - state</a></p>
0debug
void bdrv_append_temp_snapshot(BlockDriverState *bs, Error **errp) { char tmp_filename[PATH_MAX + 1]; int64_t total_size; BlockDriver *bdrv_qcow2; QEMUOptionParameter *create_options; QDict *snapshot_options; BlockDriverState *bs_snapshot; Error *local_err; int ret; total_size = bdrv_getlength(bs); if (total_size < 0) { error_setg_errno(errp, -total_size, "Could not get image size"); return; } total_size &= BDRV_SECTOR_MASK; ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename)); if (ret < 0) { error_setg_errno(errp, -ret, "Could not get temporary filename"); return; } bdrv_qcow2 = bdrv_find_format("qcow2"); create_options = parse_option_parameters("", bdrv_qcow2->create_options, NULL); set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size); ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options, &local_err); free_option_parameters(create_options); if (ret < 0) { error_setg_errno(errp, -ret, "Could not create temporary overlay " "'%s': %s", tmp_filename, error_get_pretty(local_err)); error_free(local_err); return; } snapshot_options = qdict_new(); qdict_put(snapshot_options, "file.driver", qstring_from_str("file")); qdict_put(snapshot_options, "file.filename", qstring_from_str(tmp_filename)); bs_snapshot = bdrv_new("", &error_abort); bs_snapshot->is_temporary = 1; ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options, bs->open_flags & ~BDRV_O_SNAPSHOT, bdrv_qcow2, &local_err); if (ret < 0) { error_propagate(errp, local_err); return; } bdrv_append(bs_snapshot, bs); }
1threat
static void coroutine_fn commit_run(void *opaque) { CommitBlockJob *s = opaque; BlockDriverState *active = s->active; BlockDriverState *top = s->top; BlockDriverState *base = s->base; BlockDriverState *overlay_bs = NULL; int64_t sector_num, end; int ret = 0; int n = 0; void *buf; int bytes_written = 0; int64_t base_len; ret = s->common.len = bdrv_getlength(top); if (s->common.len < 0) { goto exit_restore_reopen; } ret = base_len = bdrv_getlength(base); if (base_len < 0) { goto exit_restore_reopen; } if (base_len < s->common.len) { ret = bdrv_truncate(base, s->common.len); if (ret) { goto exit_restore_reopen; } } overlay_bs = bdrv_find_overlay(active, top); end = s->common.len >> BDRV_SECTOR_BITS; buf = qemu_blockalign(top, COMMIT_BUFFER_SIZE); for (sector_num = 0; sector_num < end; sector_num += n) { uint64_t delay_ns = 0; bool copy; wait: block_job_sleep_ns(&s->common, rt_clock, delay_ns); if (block_job_is_cancelled(&s->common)) { break; } ret = bdrv_co_is_allocated_above(top, base, sector_num, COMMIT_BUFFER_SIZE / BDRV_SECTOR_SIZE, &n); copy = (ret == 1); trace_commit_one_iteration(s, sector_num, n, ret); if (copy) { if (s->common.speed) { delay_ns = ratelimit_calculate_delay(&s->limit, n); if (delay_ns > 0) { goto wait; } } ret = commit_populate(top, base, sector_num, n, buf); bytes_written += n * BDRV_SECTOR_SIZE; } if (ret < 0) { if (s->on_error == BLOCKDEV_ON_ERROR_STOP || s->on_error == BLOCKDEV_ON_ERROR_REPORT|| (s->on_error == BLOCKDEV_ON_ERROR_ENOSPC && ret == -ENOSPC)) { goto exit_free_buf; } else { n = 0; continue; } } s->common.offset += n * BDRV_SECTOR_SIZE; } ret = 0; if (!block_job_is_cancelled(&s->common) && sector_num == end) { ret = bdrv_drop_intermediate(active, top, base); } exit_free_buf: qemu_vfree(buf); exit_restore_reopen: if (s->base_flags != bdrv_get_flags(base)) { bdrv_reopen(base, s->base_flags, NULL); } if (s->orig_overlay_flags != bdrv_get_flags(overlay_bs)) { bdrv_reopen(overlay_bs, s->orig_overlay_flags, NULL); } block_job_completed(&s->common, ret); }
1threat
How can i get sub string that is after three #? : <p>I have a string "Century Gothic#12,75#True#FFFFFFFF" and i would be able to retrive just the string "FFFFFFFF" so how can i use substring to get the string after the third #? or can i just start in someway to substring the String from the end?</p>
0debug
Netty: Idle State Handler is not showing if channel is idle : <p><strong>My Requirement:</strong><br> I want to detect if the channel is idle for reading for some amount of time and want to timeout based on that. My Netty client is sending request to 1000 servers. </p> <p><strong>Problem</strong>: My Netty Client is never showing that if there is any idle channel for sometime even if i am using some ips that will always timeout. I doubt that i am not implementing IdleStateHandler correctly. I have tried decreasing read timeout of IdleStateHandler but no luck. I have spent hours in figuring this out. Any help will be really appreciated.<br> So, below is my code:<br> <strong>My Netty Client:</strong></p> <pre><code>public void connect(final InetAddress remoteAddress){ new Bootstrap() .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeout) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .group(eventLoopGroup) .channel(NioSocketChannel.class) .handler(httpNettyClientChannelInitializer) .connect(remoteAddress, serverPort) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { future.cancel(!future.isSuccess()); } }); } </code></pre> <p><strong>My Netty Channel Initalizer:</strong></p> <pre><code>public class HttpNettyClientChannelInitializer extends ChannelInitializer&lt;SocketChannel&gt; { private final Provider&lt;HttpNettyClientChannelHandler&gt; handlerProvider; private final int timeout; private int maxContentLength; @Inject public HttpNettyClientChannelInitializer(Provider&lt;HttpNettyClientChannelHandler&gt; handlerProvider, @Named("readResponseTimeout") int timeout, @Named("maxContentLength") int maxContentLength) { this.handlerProvider = handlerProvider; this.timeout = timeout; this.maxContentLength = maxContentLength; } @Override protected void initChannel(SocketChannel socketChannel) { ChannelPipeline pipelineNettyClientChannel = socketChannel.pipeline(); pipelineNettyClientChannel.addLast("codec", new HttpClientCodec()); pipelineNettyClientChannel.addLast("idleStateHandler", new IdleStateHandler(timeout,0,0, TimeUnit.MILLISECONDS)); pipelineNettyClientChannel.addLast("aggregator", new HttpObjectAggregator(maxContentLength)); //handlerProvider.get() will provide new instance of channel handler pipelineNettyClientChannel.addLast("handler", handlerProvider.get()); } } </code></pre> <p><strong>My Netty Channel Handler</strong></p> <pre><code> @ChannelHandler.Sharable public class HttpNettyClientChannelHandler extends SimpleChannelInboundHandler&lt;HttpObject&gt; { @Override public void channelActive(ChannelHandlerContext channelHandlerContext){...} @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject){...} @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent e = (IdleStateEvent) evt; if (e.state() == IdleState.READER_IDLE) { System.out.println("Idle channel"); ctx.close(); } } } } </code></pre>
0debug
Multiple headers, how to use function on Object : <p>How do I access a variable or typedef in a header from a method? It seems that the typedef isn't global even though I included the header file, why?</p> <p>I have the following situation:</p> <h1>Snake.h</h1> <pre><code>#ifndef SNAKE_H #define SNAKE_H #include &lt;utility&gt; class Snake { public: Snake(int difficulty, int posX, int posY) : difficulty(difficulty) { position.first = posX; position.second = posY; } inline std::pair&lt;int,int&gt; const getPosition() { return position; } private: typedef std::pair&lt;int, int&gt; Point; Point position; }; #endif // !Snake.h </code></pre> <h1>Movement.cpp</h1> <pre><code>#include "Movement.h" #include "Snake.h" Snake moveDown() { Point dummy = SnakeObject.getPosition(); return .....; } </code></pre> <p>Now obviously this doesn't compile since there is stuff missing, but the compiler fails to recognize the Point type in the Movement.cpp file. Also, do I need a Snake pointer in the Movement.h so I can use the snake object to call getPosition?</p> <p>I'm sorry for the vague description, also your help is much appreciated.</p>
0debug
static void gen_wrtee(DisasContext *ctx) { #if defined(CONFIG_USER_ONLY) gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC); #else TCGv t0; if (unlikely(ctx->pr)) { gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC); return; } t0 = tcg_temp_new(); tcg_gen_andi_tl(t0, cpu_gpr[rD(ctx->opcode)], (1 << MSR_EE)); tcg_gen_andi_tl(cpu_msr, cpu_msr, ~(1 << MSR_EE)); tcg_gen_or_tl(cpu_msr, cpu_msr, t0); tcg_temp_free(t0); gen_stop_exception(ctx); #endif }
1threat
JSON array count in jQuery : I have below JSON array [{"__metadata":{"id":"bba6f593-167d-4f14-85cf-3b69288f5434","etag":"\"1\"","type":"SP.Data.PollLogListItem"},"PollId":1,"Answer":"Option3"},{"__metadata":{"id":"925dceaf-250f-43c1-be73-9972b0a34750","etag":"\"2\"","type":"SP.Data.PollLogListItem"},"PollId":1,"Answer":"Option4"},{"__metadata":{"id":"85c73abb-a565-4e2c-b74c-1883c15e2eb6","etag":"\"1\"","type":"SP.Data.PollLogListItem"},"PollId":1,"Answer":"Option3"}] How can I get count by group as below [ {"Answer":"Option3","Count":2}, {"Answer":"Option4","Count":1} ] I my previous array there is no Count key. I tried below but it is giving error. Can somebody help me function getCount(pollLog){ counts = pollLog.reduce(function (r, o) { if (r[o.Answer]) { //!(o.Answer in r) r.push(r[o.Answer] = o); r[o.Answer].Count = 1; } else { r[o.Answer].Count += 1; } }, {}) return counts; }
0debug
void qio_channel_socket_connect_async(QIOChannelSocket *ioc, SocketAddressLegacy *addr, QIOTaskFunc callback, gpointer opaque, GDestroyNotify destroy) { QIOTask *task = qio_task_new( OBJECT(ioc), callback, opaque, destroy); SocketAddressLegacy *addrCopy; addrCopy = QAPI_CLONE(SocketAddressLegacy, addr); trace_qio_channel_socket_connect_async(ioc, addr); qio_task_run_in_thread(task, qio_channel_socket_connect_worker, addrCopy, (GDestroyNotify)qapi_free_SocketAddressLegacy); }
1threat
How to detect duplicate words in a list and count them in a specific way : <p>I've been learning python 3 for about 1 week now and I just can't find a way to do this, so here is my question.</p> <p>I have this list:</p> <pre><code>['apple', 'banana', 'apple', 'tomato', 'carrot', 'apple', 'banana'] </code></pre> <p>Now I want to detect the duplicated words, count them, put the result in front of the word and print in a single string like this example:</p> <p>Apple 3, Banana 2, tomato, carrot</p> <p>Order doesn't matter.</p>
0debug
Node.js, Mongo find and return data : <p>I’m new to node and mongo after 15 years of VB6 and MySql. I’m sure this is not what my final program will use but I need to get a basic understanding of how to call a function in another module and get results back.</p> <p>I want a module to have a function to open a DB, find in a collection and return the results. I may want to add a couple more functions in that module for other collections too. For now I need it as simple as possible, I can add error handlers, etc later. I been on this for days trying different methods, module.exports={… around the function and with out it, .send, return all with no luck. I understand it’s async so the program may have passed the display point before the data is there.</p> <p>Here’s what I’ve tried with Mongo running a database of db1 with a collection of col1.</p> <pre><code>Db1.js var MongoClient = require('mongodb').MongoClient; module.exports = { FindinCol1 : function funk1(req, res) { MongoClient.connect("mongodb://localhost:27017/db1", function (err,db) { if (err) { return console.dir(err); } var collection = db.collection('col1'); collection.find().toArray(function (err, items) { console.log(items); // res.send(items); } ); }); } }; app.js a=require('./db1'); b=a.FindinCol1(); console.log(b); </code></pre> <p>Console.log(items) works when the 'FindinCol1' calls but not console.log(b)(returns 'undefined') so I'm not getting the return or I'm pasted it by the time is returns. I’ve read dozens of post and watched dozens of videos but I'm still stuck at this point. Any help would be greatly appreciated.</p>
0debug
React: The `style` prop expects a mapping from style properties to values, not a string : <p>I have the following HTML to render using React:</p> <pre><code> &lt;a style='background-color:black;color:white;text-decoration:none;padding:4px 6px;font-family:-apple-system, BlinkMacSystemFont, "San Francisco", "Helvetica Neue", Helvetica, Ubuntu, Roboto, Noto, "Segoe UI", Arial, sans-serif;font-size:8px;font-weight:bold;line-height:1;display:inline-block;border-radius:3px' href= //... target='_blank' rel='noopener noreferrer' className='credit-box-abs' &gt; &lt;span style='display:inline-block;padding:2px 3px;font-size:11px'&gt; &lt;i className='fas fa-camera-retro'&gt;&lt;/i&gt; &lt;/span&gt; &lt;span style='display:inline-block;padding:2px 3px'&gt;Photographer name&lt;/span&gt; &lt;/a&gt; </code></pre> <p>When I try to compile, I get the following warnings about each <code>style</code>:</p> <pre><code>Style prop value must be an object </code></pre> <p>And the error:</p> <pre><code>The `style` prop expects a mapping from style properties to values, not a string. </code></pre> <p>The suggested solution from the compiler, as well as online, states:</p> <pre><code>&lt;div style={{ styleAttribute: 'whatever', ... }}&gt; </code></pre> <p>So I've tried the following:</p> <pre><code> &lt;a style={{background-color:'black';color:'white';text-decoration:'none';padding:'4px 6px';font-family:'-apple-system , BlinkMacSystemFont, \"San Francisco\", \"Helvetica Neue\", Helvetica, Ubuntu, Roboto, Noto, \"Segoe UI\", Arial, sans-serif ';font-size:'8px';font-weight:'bold';line-height:'1';display:'inline-block';border-radius:'3px'}} href= //... target='_blank' rel='noopener noreferrer' className='credit-box-abs' &gt; &lt;span style='display:inline-block;padding:2px 3px;font-size:11px'&gt; &lt;i className='fas fa-camera-retro'&gt;&lt;/i&gt; &lt;/span&gt; &lt;span style='display:inline-block;padding:2px 3px'&gt;Photographer name&lt;/span&gt; &lt;/a&gt; </code></pre> <p>But the syntax is not correct. Am I supposed to wrap all values of each attribute in <code>''</code>? In particular, the syntax for <code>background-color: 'black'</code> is giving redlines under, as well as redline under my closing <code>&lt;/a&gt;</code> tag.</p>
0debug
static int dump_init(DumpState *s, int fd, bool paging, bool has_filter, int64_t begin, int64_t length, Error **errp) { CPUState *cpu; int nr_cpus; Error *err = NULL; int ret; if (runstate_is_running()) { vm_stop(RUN_STATE_SAVE_VM); s->resume = true; } else { s->resume = false; } cpu_synchronize_all_states(); nr_cpus = 0; for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) { nr_cpus++; } s->errp = errp; s->fd = fd; s->has_filter = has_filter; s->begin = begin; s->length = length; guest_phys_blocks_init(&s->guest_phys_blocks); s->start = get_start_block(s); if (s->start == -1) { error_set(errp, QERR_INVALID_PARAMETER, "begin"); goto cleanup; } ret = cpu_get_dump_info(&s->dump_info); if (ret < 0) { error_set(errp, QERR_UNSUPPORTED); goto cleanup; } s->note_size = cpu_get_note_size(s->dump_info.d_class, s->dump_info.d_machine, nr_cpus); if (ret < 0) { error_set(errp, QERR_UNSUPPORTED); goto cleanup; } memory_mapping_list_init(&s->list); if (paging) { qemu_get_guest_memory_mapping(&s->list, &err); if (err != NULL) { error_propagate(errp, err); goto cleanup; } } else { qemu_get_guest_simple_memory_mapping(&s->list); } if (s->has_filter) { memory_mapping_filter(&s->list, s->begin, s->length); } s->phdr_num = 1; if (s->list.num < UINT16_MAX - 2) { s->phdr_num += s->list.num; s->have_section = false; } else { s->have_section = true; s->phdr_num = PN_XNUM; s->sh_info = 1; if (s->list.num <= UINT32_MAX - 1) { s->sh_info += s->list.num; } else { s->sh_info = UINT32_MAX; } } if (s->dump_info.d_class == ELFCLASS64) { if (s->have_section) { s->memory_offset = sizeof(Elf64_Ehdr) + sizeof(Elf64_Phdr) * s->sh_info + sizeof(Elf64_Shdr) + s->note_size; } else { s->memory_offset = sizeof(Elf64_Ehdr) + sizeof(Elf64_Phdr) * s->phdr_num + s->note_size; } } else { if (s->have_section) { s->memory_offset = sizeof(Elf32_Ehdr) + sizeof(Elf32_Phdr) * s->sh_info + sizeof(Elf32_Shdr) + s->note_size; } else { s->memory_offset = sizeof(Elf32_Ehdr) + sizeof(Elf32_Phdr) * s->phdr_num + s->note_size; } } return 0; cleanup: guest_phys_blocks_free(&s->guest_phys_blocks); if (s->resume) { vm_start(); } return -1; }
1threat
static unsigned int * create_elf_tables(char *p, int argc, int envc, struct elfhdr * exec, unsigned long load_addr, unsigned long load_bias, unsigned long interp_load_addr, int ibcs, struct image_info *info) { target_ulong *argv, *envp; target_ulong *sp, *csp; sp = (unsigned int *) (~15UL & (unsigned long) p); csp = sp; csp -= (DLINFO_ITEMS + 1) * 2; #ifdef DLINFO_ARCH_ITEMS csp -= DLINFO_ARCH_ITEMS*2; #endif csp -= envc+1; csp -= argc+1; csp -= (!ibcs ? 3 : 1); if ((unsigned long)csp & 15UL) sp -= ((unsigned long)csp & 15UL) / sizeof(*sp); #define NEW_AUX_ENT(nr, id, val) \ put_user (tswapl(id), sp + (nr * 2)); \ put_user (tswapl(val), sp + (nr * 2 + 1)) sp -= 2; NEW_AUX_ENT (0, AT_NULL, 0); sp -= DLINFO_ITEMS*2; NEW_AUX_ENT( 0, AT_PHDR, (target_ulong)(load_addr + exec->e_phoff)); NEW_AUX_ENT( 1, AT_PHENT, (target_ulong)(sizeof (struct elf_phdr))); NEW_AUX_ENT( 2, AT_PHNUM, (target_ulong)(exec->e_phnum)); NEW_AUX_ENT( 3, AT_PAGESZ, (target_ulong)(TARGET_PAGE_SIZE)); NEW_AUX_ENT( 4, AT_BASE, (target_ulong)(interp_load_addr)); NEW_AUX_ENT( 5, AT_FLAGS, (target_ulong)0); NEW_AUX_ENT( 6, AT_ENTRY, load_bias + exec->e_entry); NEW_AUX_ENT( 7, AT_UID, (target_ulong) getuid()); NEW_AUX_ENT( 8, AT_EUID, (target_ulong) geteuid()); NEW_AUX_ENT( 9, AT_GID, (target_ulong) getgid()); NEW_AUX_ENT(11, AT_EGID, (target_ulong) getegid()); #ifdef ARCH_DLINFO ARCH_DLINFO; #endif #undef NEW_AUX_ENT sp -= envc+1; envp = sp; sp -= argc+1; argv = sp; if (!ibcs) { put_user(tswapl((target_ulong)envp),--sp); put_user(tswapl((target_ulong)argv),--sp); } put_user(tswapl(argc),--sp); info->arg_start = (unsigned int)((unsigned long)p & 0xffffffff); while (argc-->0) { put_user(tswapl((target_ulong)p),argv++); while (get_user(p++)) ; } put_user(0,argv); info->arg_end = info->env_start = (unsigned int)((unsigned long)p & 0xffffffff); while (envc-->0) { put_user(tswapl((target_ulong)p),envp++); while (get_user(p++)) ; } put_user(0,envp); info->env_end = (unsigned int)((unsigned long)p & 0xffffffff); return sp; }
1threat
Difference in using malloc() vs "operator new" function in C++ : The thread here answers the question about the difference between the two: [diff-between-malloc-operatornew][1] What I'm interested to know is: does one use the other? I suspect "operator new" function calls malloc in some form, but I may be way off. Anyone knows the implementation with say gcc? [1]: https://stackoverflow.com/questions/23271495/difference-between-global-operator-new-and-malloc
0debug
static inline uint32_t lduw_phys_internal(hwaddr addr, enum device_endian endian) { uint8_t *ptr; uint64_t val; MemoryRegionSection *section; section = phys_page_find(address_space_memory.dispatch, addr >> TARGET_PAGE_BITS); if (!(memory_region_is_ram(section->mr) || memory_region_is_romd(section->mr))) { addr = memory_region_section_addr(section, addr); val = io_mem_read(section->mr, addr, 2); #if defined(TARGET_WORDS_BIGENDIAN) if (endian == DEVICE_LITTLE_ENDIAN) { val = bswap16(val); } #else if (endian == DEVICE_BIG_ENDIAN) { val = bswap16(val); } #endif } else { ptr = qemu_get_ram_ptr((memory_region_get_ram_addr(section->mr) & TARGET_PAGE_MASK) + memory_region_section_addr(section, addr)); switch (endian) { case DEVICE_LITTLE_ENDIAN: val = lduw_le_p(ptr); break; case DEVICE_BIG_ENDIAN: val = lduw_be_p(ptr); break; default: val = lduw_p(ptr); break; } } return val; }
1threat
static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len) { int i; uint16_t limit; VncDisplay *vd = vs->vd; if (data[0] > 3) { vd->timer_interval = VNC_REFRESH_INTERVAL_BASE; if (!qemu_timer_expired(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval)) qemu_mod_timer(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval); } switch (data[0]) { case VNC_MSG_CLIENT_SET_PIXEL_FORMAT: if (len == 1) return 20; set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5), read_u8(data, 6), read_u8(data, 7), read_u16(data, 8), read_u16(data, 10), read_u16(data, 12), read_u8(data, 14), read_u8(data, 15), read_u8(data, 16)); break; case VNC_MSG_CLIENT_SET_ENCODINGS: if (len == 1) return 4; if (len == 4) { limit = read_u16(data, 2); if (limit > 0) return 4 + (limit * 4); } else limit = read_u16(data, 2); for (i = 0; i < limit; i++) { int32_t val = read_s32(data, 4 + (i * 4)); memcpy(data + 4 + (i * 4), &val, sizeof(val)); } set_encodings(vs, (int32_t *)(data + 4), limit); break; case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST: if (len == 1) return 10; framebuffer_update_request(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4), read_u16(data, 6), read_u16(data, 8)); break; case VNC_MSG_CLIENT_KEY_EVENT: if (len == 1) return 8; key_event(vs, read_u8(data, 1), read_u32(data, 4)); break; case VNC_MSG_CLIENT_POINTER_EVENT: if (len == 1) return 6; pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4)); break; case VNC_MSG_CLIENT_CUT_TEXT: if (len == 1) return 8; if (len == 8) { uint32_t dlen = read_u32(data, 4); if (dlen > 0) return 8 + dlen; } client_cut_text(vs, read_u32(data, 4), data + 8); break; case VNC_MSG_CLIENT_QEMU: if (len == 1) return 2; switch (read_u8(data, 1)) { case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT: if (len == 2) return 12; ext_key_event(vs, read_u16(data, 2), read_u32(data, 4), read_u32(data, 8)); break; case VNC_MSG_CLIENT_QEMU_AUDIO: if (len == 2) return 4; switch (read_u16 (data, 2)) { case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE: audio_add(vs); break; case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE: audio_del(vs); break; case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT: if (len == 4) return 10; switch (read_u8(data, 4)) { case 0: vs->as.fmt = AUD_FMT_U8; break; case 1: vs->as.fmt = AUD_FMT_S8; break; case 2: vs->as.fmt = AUD_FMT_U16; break; case 3: vs->as.fmt = AUD_FMT_S16; break; case 4: vs->as.fmt = AUD_FMT_U32; break; case 5: vs->as.fmt = AUD_FMT_S32; break; default: printf("Invalid audio format %d\n", read_u8(data, 4)); vnc_client_error(vs); break; } vs->as.nchannels = read_u8(data, 5); if (vs->as.nchannels != 1 && vs->as.nchannels != 2) { printf("Invalid audio channel coount %d\n", read_u8(data, 5)); vnc_client_error(vs); break; } vs->as.freq = read_u32(data, 6); break; default: printf ("Invalid audio message %d\n", read_u8(data, 4)); vnc_client_error(vs); break; } break; default: printf("Msg: %d\n", read_u16(data, 0)); vnc_client_error(vs); break; } break; default: printf("Msg: %d\n", data[0]); vnc_client_error(vs); break; } vnc_read_when(vs, protocol_client_msg, 1); return 0; }
1threat
static MegasasCmd *megasas_next_frame(MegasasState *s, hwaddr frame) { MegasasCmd *cmd = NULL; int num = 0, index; cmd = megasas_lookup_frame(s, frame); if (cmd) { trace_megasas_qf_found(cmd->index, cmd->pa); return cmd; } index = s->reply_queue_head; num = 0; while (num < s->fw_cmds) { if (!s->frames[index].pa) { cmd = &s->frames[index]; break; } index = megasas_next_index(s, index, s->fw_cmds); num++; } if (!cmd) { trace_megasas_qf_failed(frame); } trace_megasas_qf_new(index, cmd); return cmd; }
1threat
On aws able to access yourdomain.com but not able to access http://www.yourdomain.com and https://www.yourdomain.com.? : I have done the configuration on aws I'm able to access yourdomain.com(For example) but not able to access http://www.yourdomain.com and https://www.yourdomain.com.? can some one help me ASAP.
0debug
static int build_filter(ResampleContext *c, void *filter, double factor, int tap_count, int alloc, int phase_count, int scale, int filter_type, double kaiser_beta){ int ph, i; double x, y, w, t; double *tab = av_malloc_array(tap_count+1, sizeof(*tab)); const int center= (tap_count-1)/2; if (!tab) return AVERROR(ENOMEM); if (factor > 1.0) factor = 1.0; av_assert0(phase_count == 1 || phase_count % 2 == 0); for(ph = 0; ph <= phase_count / 2; ph++) { double norm = 0; for(i=0;i<=tap_count;i++) { x = M_PI * ((double)(i - center) - (double)ph / phase_count) * factor; if (x == 0) y = 1.0; else y = sin(x) / x; switch(filter_type){ case SWR_FILTER_TYPE_CUBIC:{ const float d= -0.5; x = fabs(((double)(i - center) - (double)ph / phase_count) * factor); if(x<1.0) y= 1 - 3*x*x + 2*x*x*x + d*( -x*x + x*x*x); else y= d*(-4 + 8*x - 5*x*x + x*x*x); break;} case SWR_FILTER_TYPE_BLACKMAN_NUTTALL: w = 2.0*x / (factor*tap_count) + M_PI; t = cos(w); y *= 0.3635819 - 0.4891775 * t + 0.1365995 * (2*t*t-1) - 0.0106411 * (4*t*t*t - 3*t); break; case SWR_FILTER_TYPE_KAISER: w = 2.0*x / (factor*tap_count*M_PI); y *= bessel(kaiser_beta*sqrt(FFMAX(1-w*w, 0))); break; default: av_assert0(0); } tab[i] = y; if (i < tap_count) norm += y; } switch(c->format){ case AV_SAMPLE_FMT_S16P: for(i=0;i<tap_count;i++) ((int16_t*)filter)[ph * alloc + i] = av_clip(lrintf(tab[i] * scale / norm), INT16_MIN, INT16_MAX); if (tap_count % 2 == 0) { for (i = 0; i < tap_count; i++) ((int16_t*)filter)[(phase_count-ph) * alloc + tap_count-1-i] = ((int16_t*)filter)[ph * alloc + i]; } else { for (i = 1; i <= tap_count; i++) ((int16_t*)filter)[(phase_count-ph) * alloc + tap_count-i] = av_clip(lrintf(tab[i] * scale / (norm - tab[0] + tab[tap_count])), INT16_MIN, INT16_MAX); } break; case AV_SAMPLE_FMT_S32P: for(i=0;i<tap_count;i++) ((int32_t*)filter)[ph * alloc + i] = av_clipl_int32(llrint(tab[i] * scale / norm)); if (tap_count % 2 == 0) { for (i = 0; i < tap_count; i++) ((int32_t*)filter)[(phase_count-ph) * alloc + tap_count-1-i] = ((int32_t*)filter)[ph * alloc + i]; } else { for (i = 1; i <= tap_count; i++) ((int32_t*)filter)[(phase_count-ph) * alloc + tap_count-i] = av_clipl_int32(llrint(tab[i] * scale / (norm - tab[0] + tab[tap_count]))); } break; case AV_SAMPLE_FMT_FLTP: for(i=0;i<tap_count;i++) ((float*)filter)[ph * alloc + i] = tab[i] * scale / norm; if (tap_count % 2 == 0) { for (i = 0; i < tap_count; i++) ((float*)filter)[(phase_count-ph) * alloc + tap_count-1-i] = ((float*)filter)[ph * alloc + i]; } else { for (i = 1; i <= tap_count; i++) ((float*)filter)[(phase_count-ph) * alloc + tap_count-i] = tab[i] * scale / (norm - tab[0] + tab[tap_count]); } break; case AV_SAMPLE_FMT_DBLP: for(i=0;i<tap_count;i++) ((double*)filter)[ph * alloc + i] = tab[i] * scale / norm; if (tap_count % 2 == 0) { for (i = 0; i < tap_count; i++) ((double*)filter)[(phase_count-ph) * alloc + tap_count-1-i] = ((double*)filter)[ph * alloc + i]; } else { for (i = 1; i <= tap_count; i++) ((double*)filter)[(phase_count-ph) * alloc + tap_count-i] = tab[i] * scale / (norm - tab[0] + tab[tap_count]); } break; } } #if 0 { #define LEN 1024 int j,k; double sine[LEN + tap_count]; double filtered[LEN]; double maxff=-2, minff=2, maxsf=-2, minsf=2; for(i=0; i<LEN; i++){ double ss=0, sf=0, ff=0; for(j=0; j<LEN+tap_count; j++) sine[j]= cos(i*j*M_PI/LEN); for(j=0; j<LEN; j++){ double sum=0; ph=0; for(k=0; k<tap_count; k++) sum += filter[ph * tap_count + k] * sine[k+j]; filtered[j]= sum / (1<<FILTER_SHIFT); ss+= sine[j + center] * sine[j + center]; ff+= filtered[j] * filtered[j]; sf+= sine[j + center] * filtered[j]; } ss= sqrt(2*ss/LEN); ff= sqrt(2*ff/LEN); sf= 2*sf/LEN; maxff= FFMAX(maxff, ff); minff= FFMIN(minff, ff); maxsf= FFMAX(maxsf, sf); minsf= FFMIN(minsf, sf); if(i%11==0){ av_log(NULL, AV_LOG_ERROR, "i:%4d ss:%f ff:%13.6e-%13.6e sf:%13.6e-%13.6e\n", i, ss, maxff, minff, maxsf, minsf); minff=minsf= 2; maxff=maxsf= -2; } } } #endif av_free(tab); return 0; }
1threat
How to start and stop a MS edge browserwindow from a VB script : So I want to start an MS Edge browser and close it after a few moments. I've tried some things like the Microsoft Internet Controls. But I need a different browser than the IE. Dim pi As New Process pi = Process.Start("shell:Appsfolder\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge", Threading.Thread.Sleep(1000) pi.CloseMainWindow() -- NullReferenceException But I always get a null reference exception even tho I've initialized it. Can someone help? Thanks in advantage
0debug
UITextView with hyperlink text : <p>With a non-editable UITextView, I would like to embed text like this in iOS9+:</p> <blockquote> <p>Just <a href="http://example.com" rel="noreferrer">click here</a> to register</p> </blockquote> <p>I can create a function and manipulate the text but is there a simpler way? </p> <p>I see that I can use NSTextCheckingTypeLink so getting the text clickable without the 'click here' part is straightforward in Interface Builder:</p> <blockquote> <p>Just <a href="http://example.com" rel="noreferrer">http://example.com</a> to register</p> </blockquote> <p>I'm using Xcode 8 and Swift 3 if that's relevant.</p>
0debug
static int smc91c111_can_receive(void *opaque) { smc91c111_state *s = (smc91c111_state *)opaque; if ((s->rcr & RCR_RXEN) == 0 || (s->rcr & RCR_SOFT_RST)) return 1; if (s->allocated == (1 << NUM_PACKETS) - 1) return 0; return 1; }
1threat
Firebase sign out not working in Swift : <p>I am using newest Firebase API (3.2.1) and I am using this code to check if user is signed in:</p> <pre><code>override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if(self.navigationController != nil){ self.navigationController!.setNavigationBarHidden(true, animated: true) } if(FIRAuth.auth() != nil){ self.performSegueWithIdentifier("loginSuccessSegue", sender: self) } } </code></pre> <p>In other words if auth object is present I am switching to other controller. On that controller I have sign out button which is doing sign out like this:</p> <pre><code>do{ try FIRAuth.auth()?.signOut() self.performSegueWithIdentifier("logoutSegue", sender: self) }catch{ print("Error while signing out!") } </code></pre> <p>I do not get error on this operation but when I am switched to login controller, this auth object is present and I get switched back again to controller with data. I also tried checking the current user object in auth and it is present and valid.</p> <p>Anyone knows how an I properly do sign out?</p>
0debug
static int v9fs_synth_name_to_path(FsContext *ctx, V9fsPath *dir_path, const char *name, V9fsPath *target) { V9fsSynthNode *node; V9fsSynthNode *dir_node; if (!strcmp(name, ".") || !strcmp(name, "..")) { errno = EINVAL; return -1; } if (!dir_path) { dir_node = &v9fs_synth_root; } else { dir_node = *(V9fsSynthNode **)dir_path->data; } if (!strcmp(name, "/")) { node = dir_node; goto out; } rcu_read_lock(); QLIST_FOREACH(node, &dir_node->child, sibling) { if (!strcmp(node->name, name)) { break; } } rcu_read_unlock(); if (!node) { errno = ENOENT; return -1; } out: target->data = g_malloc(sizeof(void *)); memcpy(target->data, &node, sizeof(void *)); target->size = sizeof(void *); return 0; }
1threat
GuestExec *qmp_guest_exec(const char *path, bool has_arg, strList *arg, bool has_env, strList *env, bool has_input_data, const char *input_data, bool has_capture_output, bool capture_output, Error **err) { GPid pid; GuestExec *ge = NULL; GuestExecInfo *gei; char **argv, **envp; strList arglist; gboolean ret; GError *gerr = NULL; gint in_fd, out_fd, err_fd; GIOChannel *in_ch, *out_ch, *err_ch; GSpawnFlags flags; bool has_output = (has_capture_output && capture_output); uint8_t *input = NULL; size_t ninput = 0; arglist.value = (char *)path; arglist.next = has_arg ? arg : NULL; if (has_input_data) { input = qbase64_decode(input_data, -1, &ninput, err); if (!input) { return NULL; } } argv = guest_exec_get_args(&arglist, true); envp = has_env ? guest_exec_get_args(env, false) : NULL; flags = G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD; #if GLIB_CHECK_VERSION(2, 33, 2) flags |= G_SPAWN_SEARCH_PATH_FROM_ENVP; #endif if (!has_output) { flags |= G_SPAWN_STDOUT_TO_DEV_NULL | G_SPAWN_STDERR_TO_DEV_NULL; } ret = g_spawn_async_with_pipes(NULL, argv, envp, flags, guest_exec_task_setup, NULL, &pid, has_input_data ? &in_fd : NULL, has_output ? &out_fd : NULL, has_output ? &err_fd : NULL, &gerr); if (!ret) { error_setg(err, QERR_QGA_COMMAND_FAILED, gerr->message); g_error_free(gerr); goto done; } ge = g_new0(GuestExec, 1); ge->pid = gpid_to_int64(pid); gei = guest_exec_info_add(pid); gei->has_output = has_output; g_child_watch_add(pid, guest_exec_child_watch, gei); if (has_input_data) { gei->in.data = input; gei->in.size = ninput; #ifdef G_OS_WIN32 in_ch = g_io_channel_win32_new_fd(in_fd); #else in_ch = g_io_channel_unix_new(in_fd); #endif g_io_channel_set_encoding(in_ch, NULL, NULL); g_io_channel_set_buffered(in_ch, false); g_io_channel_set_flags(in_ch, G_IO_FLAG_NONBLOCK, NULL); g_io_add_watch(in_ch, G_IO_OUT, guest_exec_input_watch, &gei->in); } if (has_output) { #ifdef G_OS_WIN32 out_ch = g_io_channel_win32_new_fd(out_fd); err_ch = g_io_channel_win32_new_fd(err_fd); #else out_ch = g_io_channel_unix_new(out_fd); err_ch = g_io_channel_unix_new(err_fd); #endif g_io_channel_set_encoding(out_ch, NULL, NULL); g_io_channel_set_encoding(err_ch, NULL, NULL); g_io_channel_set_buffered(out_ch, false); g_io_channel_set_buffered(err_ch, false); g_io_channel_set_close_on_unref(out_ch, true); g_io_channel_set_close_on_unref(err_ch, true); g_io_add_watch(out_ch, G_IO_IN | G_IO_HUP, guest_exec_output_watch, &gei->out); g_io_add_watch(err_ch, G_IO_IN | G_IO_HUP, guest_exec_output_watch, &gei->err); } done: g_free(argv); g_free(envp); return ge; }
1threat
void aio_context_release(AioContext *ctx) { qemu_rec_mutex_unlock(&ctx->lock); }
1threat
Deserialize a JSON into a list of C# objects : <p>I'm developing a mobile game project that utilizes Firebase. I've managed to get login/registration, and <em>sending</em> items to the database to work just fine. However, after countless hours of banging my head against the wall, I just can't get the inventory to work. I can fetch the correct JSON data from the database, and it comes out in the following format:</p> <pre><code>{"5449000085757":{"itemLevel":82,"itemName":"Sword of Maximum Epicness","itemType":""},"6419800152996":{"itemLevel":45,"itemName":"Your Average Sword","itemType":""}} </code></pre> <p>These are all just fields for testing purposes of course. What I'm trying to do is create a list of objects, where the list is the "inventory" and the objects are the items. I've tried using Json.NET, Unity's built-in JSON utilities, all kinds of technologies, but just can't find a way. I feel kind of stupid, because obviously it can't be this difficult. No matter what example I've tried, it doesn't work.</p> <p>If possible, could someone provide a quick briefing on how to create that list of objects from JSON, a simple way? I just can't figure this out on my own and it's getting really frustrating.</p>
0debug
deadlock detected when trying to start server : <p>I have a simple application where I am using both django and django-rest-framework.</p> <p>Quite often, when I try to start the local server (<code>python manage.py runserver</code>), I get the following exception:</p> <pre><code>Watching for file changes with StatReloader Exception in thread Thread-1: Traceback (most recent call last): File "/project/venv/lib/python3.7/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/project/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/project/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/project/venv/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/project/venv/lib/python3.7/site-packages/django/contrib/admin/checks.py", line 80, in check_dependencies for engine in engines.all(): File "/project/venv/lib/python3.7/site-packages/django/template/utils.py", line 90, in all return [self[alias] for alias in self] File "/project/venv/lib/python3.7/site-packages/django/template/utils.py", line 90, in &lt;listcomp&gt; return [self[alias] for alias in self] File "/project/venv/lib/python3.7/site-packages/django/template/utils.py", line 81, in __getitem__ engine = engine_cls(params) File "/project/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 25, in __init__ options['libraries'] = self.get_templatetag_libraries(libraries) File "/project/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 43, in get_templatetag_libraries libraries = get_installed_libraries() File "/project/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 108, in get_installed_libraries for name in get_package_libraries(pkg): File "/project/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "/project/venv/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 1006, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 983, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 967, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 677, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 728, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 219, in _call_with_frames_removed File "/project/venv/lib/python3.7/site-packages/rest_framework/templatetags/rest_framework.py", line 15, in &lt;module&gt; from rest_framework.renderers import HTMLFormRenderer File "/project/venv/lib/python3.7/site-packages/rest_framework/renderers.py", line 20, in &lt;module&gt; from django.test.client import encode_multipart File "/project/venv/lib/python3.7/site-packages/django/test/client.py", line 23, in &lt;module&gt; from django.test import signals File "&lt;frozen importlib._bootstrap&gt;", line 980, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 149, in __enter__ File "&lt;frozen importlib._bootstrap&gt;", line 94, in acquire _frozen_importlib._DeadlockError: deadlock detected by _ModuleLock('django.test.signals') at 4420467792 Performing system checks... </code></pre> <p>After a couple of retries, the server starts successfully. Therefore, it is not a show-stopper but it is quite annoying.</p> <p>Since I am quite new to Django, I was wondering if there was a way to prevent such an error.</p>
0debug
How to tag folder in linux, bash : Was looking for solution, but cannot find it. I want to create folder with @tag, which I could find by this tag. Is there any command in linux/bash that can help me solve this problem?
0debug
void memory_global_sync_dirty_bitmap(MemoryRegion *address_space) { AddressSpace *as = memory_region_to_address_space(address_space); FlatRange *fr; FOR_EACH_FLAT_RANGE(fr, &as->current_map) { MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, log_sync); } }
1threat
static int decode_unk6(uint8_t *frame, int width, int height, const uint8_t *src, const uint8_t *src_end) { return -1; }
1threat
Angular2 animated [hidden] element : <p>I have a sidebar that I am showing / hiding using a boolean like this:</p> <p><code>[hidden]='toggleSidebar'</code></p> <p>I have been trying to find the correct way to add a transition to this element, but so far have been only partially successful using this method : <code>[class.show]='!toggleSidebar'</code>. Applying css styles to this class only partially works though.</p> <p>How do I add a slide-in or fade-in animation to an element containing a router-outlet such as this?</p> <pre><code>&lt;aside [hidden]="toggleSidebar"&gt; &lt;router-outlet name="aside"&gt;&lt;/router-outlet&gt; &lt;/aside&gt; </code></pre>
0debug
What is the connection or difference between lemma and synset in wordnet? : <p>I am a complete beginner to NLP and NLTK. </p> <p>I was not able to understand the exact <strong><em>difference between lemmas and synsets in wordnet</em></strong>, because both are producing nearly the same output. for example for the word cake it produce this output.</p> <pre><code>lemmas : [Lemma('cake.n.01.cake'), Lemma('patty.n.01.cake'), Lemma('cake.n.03.cake'), Lemma('coat.v.03.cake')] synsets : [Synset('cake.n.01'), Synset('patty.n.01'), Synset('cake.n.03'), Synset('coat.v.03')] </code></pre> <p>please help me to understand this concept.</p> <p>Thank you.</p>
0debug
Modify struct value inside function Golang : I have struct with setter function package main type Person struct { Name string Age int } func (p *Person) SetName(name string) { p.Name = string } func SomeMethod(human interface{}){ // I call the setter function here, but doesn't seems exist human.SetName("Johnson") } func main(){ p := Person{Name : "Musk"} SomeMethod(&p) } But, I got an error as follows : human.SetName undefined (type interface {} is interface with no methods) seems func SetName doesn't included in SomeMethod func Why is it? Any answer will be highly appreciated !
0debug
how to deallocate memory spaces in Java. ? : <p>I am working on an enhancement project which had an issue, " The process of the android app is slowed proportionally as the usage of app is increased" I figured out the reason for the slow process is accumulation of data in cache memory, which is not cleared after the particular session is closed(i.e the cache memory remains even after the app is closed.). Since the app is developed in Java I couldn't use Destructor to clear the memory space. Can any one suggest the possible way to deallocate the memory space.?</p>
0debug
React testing setup with rails/webpacker : <p>I've added <a href="https://github.com/rails/webpacker" rel="noreferrer">webpacker</a> to my existing rails app, everything is working like a charm.</p> <p>Webpack config is found under</p> <pre><code>config/webpack/shared.js config/webpack/development.js config/webpack/production.js </code></pre> <p>node_modules are installed in</p> <pre><code>vendor/node_modules </code></pre> <p>js pack files are in</p> <pre><code>app/javascript/packs/application.js </code></pre> <p>I've installed react and wrote a little component:</p> <pre><code>app/javascript/discover/example.jsx </code></pre> <p>Now I struggle with how to setup a working test environment. Normally I'd say the usual test setup should include: <code>karma</code>, <code>jasmine</code> or <code>mocha</code>, <code>webpack</code>.</p> <p>Where should the config files live? Where will the test files be stored and to build a <code>karma.config.js</code> to bundle everything together.</p> <p>It would be great to have a sample application that shows how to do all that correctly, but I obviously lack the necessary skills to plug everything together correctly.</p> <p>This is not an easy to answer question, but having such an example application would be extremely helpful to a lot of people that'd want to use webpacker in the future.</p> <p>Thanks for any thoughts on that topic,<br> Jo</p> <p><strong>Some helpful resources:</strong></p> <ol> <li><a href="https://medium.com/@scbarrus/how-to-get-test-coverage-on-react-with-karma-babel-and-webpack-c9273d805063#.g6p5go9gd" rel="noreferrer">https://medium.com/@scbarrus/how-to-get-test-coverage-on-react-with-karma-babel-and-webpack-c9273d805063#.g6p5go9gd</a></li> <li><a href="http://qiita.com/kimagure/items/f2d8d53504e922fe3c5c" rel="noreferrer">http://qiita.com/kimagure/items/f2d8d53504e922fe3c5c</a></li> <li><a href="http://nicolasgallagher.com/how-to-test-react-components-karma-webpack/" rel="noreferrer">http://nicolasgallagher.com/how-to-test-react-components-karma-webpack/</a></li> <li><a href="https://www.codementor.io/reactjs/tutorial/test-reactjs-components-karma-webpack" rel="noreferrer">https://www.codementor.io/reactjs/tutorial/test-reactjs-components-karma-webpack</a></li> </ol>
0debug
Form lexicographically small string among others by removing exactly one character? : Eg string applea, by removing p we get alea smallest of other lexicogra phically strings
0debug
Google chrome is giving me a warning that site is no secure when i try to login : <p>guys am stuck cant login in my newly created site browser is busy giving an insecure warning what can i do the client is on my case "Info Info or Not secure"</p>
0debug
AWS VPC identify private and public subnet : <p>I have a VPC in AWS account and there are 5 subnets associated with that VPC. Subnets are of 2 types - Public and private. How to identify which subnet is public and which is private ? Each subnet has CIDR 10.249.?.? range.</p> <p>Basically when I launch an EMR in that subnet with lists of ec2SubnetIds , it says ***The subnet configuration was invalid: Provided subnet list contains both public and private subnet. Only one type of subnet is allowed.</p> <hr> <p>How to recify this error.</p>
0debug
How to set built-in speaker as main, if are headphones plugged in? Is it possible? (Android) : Is it possible to set built-in speaker as main (sounds will go from its) if are headphones plugged in? How can I do it? Thanks.. (Android)
0debug
Add html inside a value to a javascript object : I'm working with a google sheet: my goal is to parse the html and turn into a json file in order to add some places to a google map (api), since in my google sheet I saved some map locations. So far so good, I was able to clean the html file and obtain a json file with all the value I need. My problem is that now, I want to add some html inside the json file. My single value looks like that: { "a": "Store Name", "b": "Address", "c": "Town/City", "d": "Prov", "e": "Postal Code", "f": "Phone", "g": "Website", }, { "a": "Nutter's Bulk Foods #50", "b": "102-400 Main Street", "c": " N.E.", "d": "Airdrie", "e": "AB", "f": "T4B 2N1", "g": "(403) 948-6354", }, { "a": "King Drug Hinton 1982 Ltd.", "b": "145 Athabasca Avenue", "c": "Hinton", "d": "AB", "e": "T7V 2A4", "f": "(780) 865-2645", "g": "http://www.kingdrug.ca/", }, and so on. I want to add some html inside the single value in order to change my file into: { "a": "King Drug Hinton 1982 Ltd.", "b": "145 Athabasca Avenue", "c": "Hinton", "d": "AB", "e": "T7V 2A4", "f": "<a href='tel:+1780..'>(780) 865-2645</a>", "g": "<a href='http://www.kingdrug.ca/'>http://www.kingdrug.ca/</a>", } And I would like to do it dynamically, in order to save time, so let's say that I want to target the property name "a", retrieve the value "780..." and add an html anchor tag <a> with the <href> equal to the value inside the file. The biggest problem for me is working with a json file, I used to word and iterate with javascript object. Thank you in advance for any useful suggestion.
0debug
static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom) { int64_t total_size = 0; MOV_atom_t a; int i; int err = 0; a.offset = atom.offset; if (atom.size < 0) atom.size = INT64_MAX; while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) { a.size = atom.size; a.type=0L; if(atom.size >= 8) { a.size = get_be32(pb); a.type = get_le32(pb); } total_size += 8; a.offset += 8; dprintf(c->fc, "type: %08x %.4s sz: %"PRIx64" %"PRIx64" %"PRIx64"\n", a.type, (char*)&a.type, a.size, atom.size, total_size); if (a.size == 1) { a.size = get_be64(pb) - 8; a.offset += 8; total_size += 8; } if (a.size == 0) { a.size = atom.size - total_size; if (a.size <= 8) break; } a.size -= 8; if(a.size < 0 || a.size > atom.size - total_size) break; for (i = 0; c->parse_table[i].type != 0L && c->parse_table[i].type != a.type; i++) ; if (c->parse_table[i].type == 0) { url_fskip(pb, a.size); } else { offset_t start_pos = url_ftell(pb); int64_t left; err = (c->parse_table[i].func)(c, pb, a); left = a.size - url_ftell(pb) + start_pos; if (left > 0) url_fskip(pb, left); } a.offset += a.size; total_size += a.size; } if (!err && total_size < atom.size && atom.size < 0x7ffff) { url_fskip(pb, atom.size - total_size); } return err; }
1threat
How to apply python scikit-learn to images/sound/videos for machine learning? : <p>It would be really helpful if someone can explain and give an example of how to apply machine learning algorithms using scikit-learn and python to images,sound or videos. I know how to apply it to csv file just want to learn how it can be extended for multimedia files. Thankyou</p>
0debug
static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor, int point_transform){ int i, mb_x, mb_y; const int nb_components=3; for(mb_y = 0; mb_y < s->mb_height; mb_y++) { for(mb_x = 0; mb_x < s->mb_width; mb_x++) { if (s->restart_interval && !s->restart_count) s->restart_count = s->restart_interval; if(mb_x==0 || mb_y==0 || s->interlaced){ for(i=0;i<nb_components;i++) { uint8_t *ptr; int n, h, v, x, y, c, j, linesize; n = s->nb_blocks[i]; c = s->comp_index[i]; h = s->h_scount[i]; v = s->v_scount[i]; x = 0; y = 0; linesize= s->linesize[c]; for(j=0; j<n; j++) { int pred; ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); if(y==0 && mb_y==0){ if(x==0 && mb_x==0){ pred= 128 << point_transform; }else{ pred= ptr[-1]; } }else{ if(x==0 && mb_x==0){ pred= ptr[-linesize]; }else{ PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor); } } if (s->interlaced && s->bottom_field) ptr += linesize >> 1; *ptr= pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform); if (++x == h) { x = 0; y++; } } } }else{ for(i=0;i<nb_components;i++) { uint8_t *ptr; int n, h, v, x, y, c, j, linesize; n = s->nb_blocks[i]; c = s->comp_index[i]; h = s->h_scount[i]; v = s->v_scount[i]; x = 0; y = 0; linesize= s->linesize[c]; for(j=0; j<n; j++) { int pred; ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor); *ptr= pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform); if (++x == h) { x = 0; y++; } } } } if (s->restart_interval && !--s->restart_count) { align_get_bits(&s->gb); skip_bits(&s->gb, 16); } } } return 0; }
1threat