problem stringlengths 26 131k | labels class label 2 classes |
|---|---|
AngularJS Sentence Builder similar to http://niklr.github.io/angular-query-builder/ : I need angularjs solution (plugin or any fiddle/codepen etc. workaround) which is similar to query builders as below(which are available in github)
http://niklr.github.io/angular-query-builder/
I should be able to form sentence with
operators: if, then, else, and, or, on
fields: xyzproduct, etc..
unit: quantity, value,..
conditions: =, <, <=, >, >=, <>, between
finally i should be able to form a promotion or discount kind of thing.
Output:
> (if xyzproduct quantity between 1 and 100) (then discount 10%)
> (if xyzproduct value > 500) (then discount 20%)
| 0debug |
uint_fast16_t float32_to_uint16_round_to_zero(float32 a STATUS_PARAM)
{
int64_t v;
uint_fast16_t res;
v = float32_to_int64_round_to_zero(a STATUS_VAR);
if (v < 0) {
res = 0;
float_raise( float_flag_invalid STATUS_VAR);
} else if (v > 0xffff) {
res = 0xffff;
float_raise( float_flag_invalid STATUS_VAR);
} else {
res = v;
}
return res;
}
| 1threat |
Unable to show images of Python code? : <p>Is there some unwritten rule that you are not allowed to show images of Python code on Github websites? I tried to upload images in this manner, however, it doesn't work. Images are png and source linked appropriately.</p>
<p><a href="https://eclecticexistential.github.io/" rel="nofollow noreferrer">https://eclecticexistential.github.io/</a></p>
| 0debug |
confusion with the following selection sort code : int i,j,t;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
My question is whether the above code is correct selection sort code or not? Got this code in various book. if it is incorrect then please explain reason. | 0debug |
static int cpu_post_load(void *opaque, int version_id)
{
ARMCPU *cpu = opaque;
int i, v;
for (i = 0, v = 0; i < cpu->cpreg_array_len
&& v < cpu->cpreg_vmstate_array_len; i++) {
if (cpu->cpreg_vmstate_indexes[v] > cpu->cpreg_indexes[i]) {
continue;
}
if (cpu->cpreg_vmstate_indexes[v] < cpu->cpreg_indexes[i]) {
return -1;
}
cpu->cpreg_values[i] = cpu->cpreg_vmstate_values[v];
v++;
}
if (kvm_enabled()) {
if (!write_list_to_kvmstate(cpu)) {
return -1;
}
write_list_to_cpustate(cpu);
} else {
if (!write_list_to_cpustate(cpu)) {
return -1;
}
}
hw_breakpoint_update_all(cpu);
hw_watchpoint_update_all(cpu);
return 0;
}
| 1threat |
By using order by clause,i'm not getting correct order. I need month wise dates : select (TO_CHAR(TRUNC(exec_end),'DD-MON-YY'))
from tbl_dumps
where exec_end >=to_date(sysdate-90) group by TO_CHAR(TRUNC(exec_end),'DD-MON-YY'),
TO_CHAR(TRUNC(exec_end),'MON') order by (TO_CHAR(TRUNC(exec_end),'MON')) desc) | 0debug |
static void qxl_hard_reset(PCIQXLDevice *d, int loadvm)
{
dprint(d, 1, "%s: start%s\n", __FUNCTION__,
loadvm ? " (loadvm)" : "");
qemu_mutex_unlock_iothread();
d->ssd.worker->reset_cursor(d->ssd.worker);
d->ssd.worker->reset_image_cache(d->ssd.worker);
qemu_mutex_lock_iothread();
qxl_reset_surfaces(d);
qxl_reset_memslots(d);
if (!loadvm) {
qxl_reset_state(d);
}
qemu_spice_create_host_memslot(&d->ssd);
qxl_soft_reset(d);
dprint(d, 1, "%s: done\n", __FUNCTION__);
}
| 1threat |
python Traceback about tkinter that I can't fix : from tkinter import *
window_main = Tk()
def window_open():
def chgColor(event):
lst["bg"] = lst.get(lst.curselection())
window_public = Tk()
window_public.title("New Page")
lbl = Label(window_public, text = "Today is a good day and I'm a gooie!")
lbl.grid(padx = 20, pady = 10)
var = StringVar()
lst = Listbox(window_public, height = 5, width = 10, listvariable = var)
lst.grid(padx = 50, pady = 20)
list = ["red", "blue", "yellow", "pink", "green", "white", "black"]
var.set(tuple(list))
lst.bind("<<ListboxSelect>>", chgColor)
window_public.mainloop()
window_main.title("Main")
window_main_btn = Button(window_main, text = "To New Page", command = window_open)
window_main_btn.grid(padx = 50, pady = 20)
window_main.mainloop()
I'm a beginner of python and get stuck in this problem for several days. When I click on the button and get in new page then click on listbox I'll get a traceback. I still can't understand what the traceback's meaning and can't fix it. But I found when I delete codes about window_main, it could run. I need your help!!
| 0debug |
(c#) How would you go about removing whitespace from a string without the use of methods such as .trim or .replace? : I'm also not allowed to use lists.
My initial thought process for this was to take the initial string then to turn that into a char array. Then after copy everything that is not a space to a second char array. Then convert that char array back to a string.
So quickly it would look something like this;
char[] firstArray;
char[] secondArray;
string someString;
for (int i = 0; i < someString.Length; i++)
{
firstArray = someString.ToCharArray();
secondArray = new char[someString.Length];
for (int j = 0; j < firstArray.Length; j++)
{
if (firstArray[j] != ' ')
{
secondArray[j] = firstArray[j];
}
}
someString = secondArray.ToString();
}
But when I initialise the second char array it would contain an extra char with no value if there was a space in it initially, since it was initialised to the same size as the first char array. Would I have to do a similar loop before just to count the amount of non-spaces then initialise secondArray based off that or is there a much simpler way than all of this that I am missing? (Without the use of .trim, .replace(or anything like them) or lists)
Any help would be appreciated. | 0debug |
static void attach(sPAPRDRConnector *drc, DeviceState *d, void *fdt,
int fdt_start_offset, bool coldplug, Error **errp)
{
DPRINTFN("drc: %x, attach", get_index(drc));
if (drc->isolation_state != SPAPR_DR_ISOLATION_STATE_ISOLATED) {
error_setg(errp, "an attached device is still awaiting release");
return;
if (drc->type == SPAPR_DR_CONNECTOR_TYPE_PCI) {
g_assert(drc->allocation_state == SPAPR_DR_ALLOCATION_STATE_USABLE);
g_assert(fdt || coldplug);
if (drc->type == SPAPR_DR_CONNECTOR_TYPE_PCI) {
drc->isolation_state = SPAPR_DR_ISOLATION_STATE_UNISOLATED;
drc->indicator_state = SPAPR_DR_INDICATOR_STATE_ACTIVE;
drc->dev = d;
drc->fdt = fdt;
drc->fdt_start_offset = fdt_start_offset;
drc->configured = coldplug;
drc->signalled = (drc->type != SPAPR_DR_CONNECTOR_TYPE_PCI)
? true : coldplug;
object_property_add_link(OBJECT(drc), "device",
object_get_typename(OBJECT(drc->dev)),
(Object **)(&drc->dev),
NULL, 0, NULL); | 1threat |
Im trying to create UnitTests for a private method : Im trying to create unitTests for the getoutofjail method but i cant workout a way of getting to it as it private and apart from testing there is no need for it to be public. I cant change the signature of the LandedonTile method as it inheriting a the abstract class Tile.
As you probably worked out, it is for a game of Monopoly im trying to make as a mini project. Thanks in advanced for any help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monolopy
{
public abstract class Tile
{
public abstract int Location { get;}
public abstract void LandedOnTile(Player player);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monolopy
{
public class JailTile : Tile
{
public override int Location { get; }
Random dice = new Random();
public JailTile()
{
Location = 3;
}
public override void LandedOnTile(Player player)
{
if (player.inJail)
{
GetOutOfJail(player);
}
else
{
Console.WriteLine(player.name + " is just visiting jail");
}
}
private void GetOutOfJail(Player player)
{
int roll = dice.Next(1, 4);
int turnsInJail = player.timeInJail;
if (turnsInJail == 3)
{
player.inJail = false;
Console.WriteLine(player.name + " has spent 3 turns in jail and is now out");
player.timeInJail = 0;
}
else if (turnsInJail < 3 && roll > 2)
{
player.inJail = false;
Console.WriteLine(player.name + " has rolled a 3 and it out of jail");
player.timeInJail = 0;
}
else
{
Console.WriteLine(player.name + " has rolled a lower than a 3 and is in jail for another turn");
player.timeInJail++;
}
}
}
}
| 0debug |
when to use the relative layout and constrain layout with real time example : <p>Could someone please help me out letting me know when to use the relative layout and when to use the constrain layout with example in android. </p>
| 0debug |
Annotate interface function that must call super : <p>I'm creating interface and some function in it has a body.
It's required, that class that implements this interface must call super in overriding function before executing other code.
How can I do this?</p>
<pre><code>interface Watcher {
fun funWithoutBody()
fun startWatching() {
//do some important stuff which must be called
}
}
</code></pre>
| 0debug |
sharable database between devices : <p>i need a way for a phone to notify all other phones that hold the same application about a change, in my case i am trying to make a hotel booking app , i have managed to create a database and a table called hotels and filled with hotels but the problem is this kind of apps requires a connection between devices, so when i reserve a room in a device , it is also reserved in the other device , i was told i need the work with a server , can anyone give me a good link or something where a newbie like me ( never worked with servers before) to learn a bit thank you in advance</p>
| 0debug |
Unknown column 'email_input' (PHP MySQLi Prepared Statement) : <p>I'm using MySQLiIn the <code>WHERE</code> clause of my statement I am adding parameters on RHS:</p>
<p>Prepared statement:</p>
<p><code>$sql = 'select * from emailstobeverified where email=email_input and verification_code=code_input;';</code></p>
<p>And then I use <code>$stmt->prepare($sql);</code></p>
<p>And I get a PHP error saying:</p>
<p><code>Sql Error: Unknown column 'email_input' in 'where clause'</code></p>
<p>(I thought that the LHS of the boolean expression counts as the column? )</p>
<p>the below query will work:</p>
<p><code>$sql = 'insert into emailstobeverified (email) values (:email);';</code></p>
<p>Here, I can use <code>:email</code> as a parameter, so I tried making <code>email_input</code> have a colon before it: <code>:email_input</code> and used that as the param. However I got a syntax error:</p>
<pre><code>Sql Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ':email_input and verification_code=:code_input' at line 1
</code></pre>
<p>What's the correct syntax for comparing the table column value to some param?</p>
| 0debug |
Using Java Script in email : <p>I am sending am email from a C# application which has html and javascript in it.
And when I checked the received mail the graphs which should be appearing after the execution of javascript code are not appearing.</p>
<p>I am using outlook to view the email
Is there some way to make javascript run in an email on outlook </p>
| 0debug |
Jsoup dont parse xml correctly from a file : in android i want to parse a xml text but jsoup delete <col> tags
this is the part i have the problem.
Original:
<rowh> <col>DTC Code</col> <col>Description</col> </rowh>
Result:
<rowh> DTC Code Description
</rowh>
this is the code i use to see the content
Document jDoc = Jsoup.parse(contentXML);
Log.d("Original", contentXML);
Log.d("Document", jDoc.outerHtml());
i need to count how many <col> tags are inside each <rowh> tag but always return 0 | 0debug |
Clustered Stacked Bar in Python Pandas : <p>I have created a single stacked bar chart but I want to have them clustered. Exactly something like the picture. </p>
<p>Wondering if it's possible. </p>
<p><a href="https://i.stack.imgur.com/SoxmW.png" rel="nofollow">link to picture</a></p>
| 0debug |
How to report console.error with Sentry? : <p>I have application where some critical issues are reported with <code>console.error</code> but are not <code>thrown</code> so application might continue to run - possibly in crippled state.</p>
<p>It's necessary to report also <code>console.error</code> issues, but Sentry (Raven) library send to server only thrown exceptions.</p>
<p>Does someone knows how to solve this nicely ?</p>
<p><em>(ideally without need to rewrite all <code>console.error</code> calls, cause also some vendor libraries might still write output just into console)</em></p>
| 0debug |
Redux + ImmutableJS - how to garbage collect too large store? : <p>I'm using Redux with ImmutableJS. In my SPA (quite complicated administration system), users often load a lot of data into stores (thousands rows for many tables). After opening several pages and having too many data in the store, the app becomes significantly slower, because the ImmutableJS store can contain even millions entries.</p>
<p>How can I "delete" something from the store, so that the data don't slow down the app? I know that this would be against its main principle, but how else would you solve it?</p>
<p>Using a common website with for example jQuery, it would be pretty easy. With every page refresh, everything unnecessary would be garbage collected. Therefore, 2-3 thousands entries for one page would be ok, but when opening a new page, the reducer loads new data, but the old ones are still being referenced to. </p>
<p>And I don't want to force the user to reload the page, of course.</p>
| 0debug |
html layouts vs css layouts : <p>please,
which is better? benefits and disadvantages</p>
<p>Html Layouts </p>
<pre><code><header>
< nav>
< aside>
</code></pre>
<p>or </p>
<p>css layouts (divs with float)</p>
<p>thanks</p>
| 0debug |
What exactly means this expression found in a .NET view? : <p>I am very new in <strong>.NET</strong> and I have the following doubt about these expression that I am finding in some views.</p>
<p>I have a view like this:</p>
<pre><code>@model Vidly_v2.ViewModels.NewCustomerViewModel
@{
/**/
ViewBag.Title = "New";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>New Customer</h2>
@using (Html.BeginForm("Save", "Customers"))
{
<div class="form-group">
@Html.LabelFor(m => m.Customer.Name)
@Html.TextBoxFor(m => m.Customer.Name, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Customer.Birthdate)
@Html.TextBoxFor(m => m.Customer.Birthdate, "{0:d MMM yyyy}", new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Customer.MembershipTypeId)
@Html.DropDownListFor(m => m.Customer.MembershipTypeId, new SelectList(Model.MembershipTypes, "Id", "Name"), "Select Membership Type", new { @class = "form-control" })
</div>
<div class="checkbox">
<label>
@Html.CheckBoxFor(m => m.Customer.IsSubscribedToNewsletter) Subscribed to Newsletter?
</label>
</div>
@Html.HiddenFor(m => m.Customer.Id)
<button type="submit" class="btn btn-primary">Save</button>
}
</code></pre>
<p>As you can see in this vire I am using this <strong>model object</strong>: </p>
<pre><code>@model Vidly_v2.ViewModels.NewCustomerViewModel
</code></pre>
<p>Into this view I use this model object in this way:</p>
<pre><code>@Html.LabelFor(m => m.Customer.Name)
@Html.TextBoxFor(m => m.Customer.Name, new { @class = "form-control" })
</code></pre>
<p>that simply render this HTML code:</p>
<pre><code><label for="Customer_Name">Name</label>
<input class="form-control" data-val="true" data-val-length="The field Name must be a string with a maximum length of 255." data-val-length-max="255" data-val-required="The Name field is required." id="Customer_Name" name="Customer.Name" value="" type="text">
</code></pre>
<p>related to this model object property.</p>
<p>My doubt is: what exactly is and what represents this expression?</p>
<pre><code>m => m.Customer.Name
</code></pre>
<p>I think that <strong>m</strong> means <strong>model object</strong> (correct me if I am doing wrong assertion) but I can't understand the meaning and the exact use of this expression.</p>
| 0debug |
How to know data coming from Json is float or Integer in swift 3? : I am getting data from Json and displaying it in table view how to check whether the number is float or double or integer in swift 3 if it is float how to get the no.of digits after decimal can anyone help me how to implement this in swift 3 ? | 0debug |
uint64_t helper_msub64_q_ssov(CPUTriCoreState *env, uint64_t r1, uint32_t r2,
uint32_t r3, uint32_t n)
{
int64_t t1 = (int64_t)r1;
int64_t t2 = sextract64(r2, 0, 32);
int64_t t3 = sextract64(r3, 0, 32);
int64_t result, mul;
int64_t ovf;
mul = (t2 * t3) << n;
result = t1 - mul;
env->PSW_USB_AV = (result ^ result * 2u) >> 32;
env->PSW_USB_SAV |= env->PSW_USB_AV;
ovf = (result ^ t1) & (t1 ^ mul);
if (mul == 0x8000000000000000LL) {
if (ovf >= 0) {
env->PSW_USB_V = (1 << 31);
env->PSW_USB_SV = (1 << 31);
if (mul >= 0) {
result = INT64_MAX;
result = INT64_MIN;
}
}
if (ovf < 0) {
env->PSW_USB_V = (1 << 31);
env->PSW_USB_SV = (1 << 31);
if (mul < 0) {
result = INT64_MAX;
result = INT64_MIN;
}
}
}
return (uint64_t)result;
} | 1threat |
static void adjust_frame_information(ChannelElement *cpe, int chans)
{
int i, w, w2, g, ch;
int start, maxsfb, cmaxsfb;
for (ch = 0; ch < chans; ch++) {
IndividualChannelStream *ics = &cpe->ch[ch].ics;
start = 0;
maxsfb = 0;
cpe->ch[ch].pulse.num_pulse = 0;
for (w = 0; w < ics->num_windows*16; w += 16) {
for (g = 0; g < ics->num_swb; g++) {
if (cpe->common_window && !ch && cpe->ms_mask[w + g]) {
for (i = 0; i < ics->swb_sizes[g]; i++) {
cpe->ch[0].coeffs[start+i] = (cpe->ch[0].coeffs[start+i] + cpe->ch[1].coeffs[start+i]) / 2.0;
cpe->ch[1].coeffs[start+i] = cpe->ch[0].coeffs[start+i] - cpe->ch[1].coeffs[start+i];
}
}
start += ics->swb_sizes[g];
}
for (cmaxsfb = ics->num_swb; cmaxsfb > 0 && cpe->ch[ch].zeroes[w+cmaxsfb-1]; cmaxsfb--)
;
maxsfb = FFMAX(maxsfb, cmaxsfb);
}
ics->max_sfb = maxsfb;
for (w = 0; w < ics->num_windows; w += ics->group_len[w]) {
for (g = 0; g < ics->max_sfb; g++) {
i = 1;
for (w2 = w; w2 < w + ics->group_len[w]; w2++) {
if (!cpe->ch[ch].zeroes[w2*16 + g]) {
i = 0;
break;
}
}
cpe->ch[ch].zeroes[w*16 + g] = i;
}
}
}
if (chans > 1 && cpe->common_window) {
IndividualChannelStream *ics0 = &cpe->ch[0].ics;
IndividualChannelStream *ics1 = &cpe->ch[1].ics;
int msc = 0;
ics0->max_sfb = FFMAX(ics0->max_sfb, ics1->max_sfb);
ics1->max_sfb = ics0->max_sfb;
for (w = 0; w < ics0->num_windows*16; w += 16)
for (i = 0; i < ics0->max_sfb; i++)
if (cpe->ms_mask[w+i])
msc++;
if (msc == 0 || ics0->max_sfb == 0)
cpe->ms_mode = 0;
else
cpe->ms_mode = msc < ics0->max_sfb * ics0->num_windows ? 1 : 2;
}
}
| 1threat |
static void i6300esb_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
k->config_read = i6300esb_config_read;
k->config_write = i6300esb_config_write;
k->realize = i6300esb_realize;
k->vendor_id = PCI_VENDOR_ID_INTEL;
k->device_id = PCI_DEVICE_ID_INTEL_ESB_9;
k->class_id = PCI_CLASS_SYSTEM_OTHER;
dc->reset = i6300esb_reset;
dc->vmsd = &vmstate_i6300esb;
set_bit(DEVICE_CATEGORY_MISC, dc->categories);
} | 1threat |
static int do_token_in(USBDevice *s, USBPacket *p)
{
int request, value, index;
int ret = 0;
if (p->devep != 0)
return s->info->handle_data(s, p);
request = (s->setup_buf[0] << 8) | s->setup_buf[1];
value = (s->setup_buf[3] << 8) | s->setup_buf[2];
index = (s->setup_buf[5] << 8) | s->setup_buf[4];
switch(s->setup_state) {
case SETUP_STATE_ACK:
if (!(s->setup_buf[0] & USB_DIR_IN)) {
ret = s->info->handle_control(s, p, request, value, index,
s->setup_len, s->data_buf);
if (ret == USB_RET_ASYNC) {
return USB_RET_ASYNC;
}
s->setup_state = SETUP_STATE_IDLE;
if (ret > 0)
return 0;
return ret;
}
return 0;
case SETUP_STATE_DATA:
if (s->setup_buf[0] & USB_DIR_IN) {
int len = s->setup_len - s->setup_index;
if (len > p->len)
len = p->len;
memcpy(p->data, s->data_buf + s->setup_index, len);
s->setup_index += len;
if (s->setup_index >= s->setup_len)
s->setup_state = SETUP_STATE_ACK;
return len;
}
s->setup_state = SETUP_STATE_IDLE;
return USB_RET_STALL;
default:
return USB_RET_STALL;
}
}
| 1threat |
Unicode Characters do not properly show when received on client : <p>I have a string that includes a character <code>string ="\u2663\"</code>
among others.
I send the string over a socket using the printwriter and read with buffered reader: </p>
<p><code>PrintWriter out = new PrintWriter(c.clientSocket.getOutputStream(),true);</code>
<code>out.println(string)</code></p>
<p><code>BufferedReader in = new BufferedReader(new InputStreamReader(mainSocket.getInputStream()));</code>
<code>in.readLine()</code></p>
<p>When the code is run in eclipse, it renders properly but when testing it via executable jar, the unicode character above shows a "?".</p>
<p>I feel like this is an encoding issue but can't seem to get it to work. </p>
| 0debug |
Add a security code to http get request : I am searching a security function like this:
The user can put his paypal address and an amount of money(which he gained in my app) in my application, and I will recieve it with an http request on my server. Now this is really insecure, anyone with the http requesturl can send me payout data for himself. So what I need is something like a code generator that only my app can create this sort of code, and my php script checks if the code doesnt fit, it wont accept the request. I thougt about java encryption, to encrypt the amount of money. but anybody with the skills to generate a java encrypter can also create an url to send a whitedraw request I think?
I saw an app with this function, its called plus500 there you can whitedraw your money to a(your) paypal account, but I'm not that pro finding out how they do this feature securely. | 0debug |
I need advice on creating an app for uploading training videos : <p>I just got myself into iOS mobile development. I am creating an iOS app that allows athletes to access in-depth training videos for most sports and network with each other. I've already created the login and register UI for the product. What functionalities do you think I need to consider in order for me to create the video based and the social networking part of the app. What backend do you think is best for this project and how long do you think it would take to get it up and running?</p>
<p>Thanks in advance.</p>
| 0debug |
How can I switch view controllers with code swift xcode :
let SecondViewController =
self.storyboard?.instantiateViewController(withIdentifier:
"SecondViewController") as! SecondViewController
self.navigationController?.pushViewController(SecondViewController,
animated: true)
For some reason this doesn't work. Any ideas? Thanks! | 0debug |
static void xen_read_physmap(XenIOState *state)
{
XenPhysmap *physmap = NULL;
unsigned int len, num, i;
char path[80], *value = NULL;
char **entries = NULL;
snprintf(path, sizeof(path),
"/local/domain/0/device-model/%d/physmap", xen_domid);
entries = xs_directory(state->xenstore, 0, path, &num);
if (entries == NULL)
return;
for (i = 0; i < num; i++) {
physmap = g_malloc(sizeof (XenPhysmap));
physmap->phys_offset = strtoull(entries[i], NULL, 16);
snprintf(path, sizeof(path),
"/local/domain/0/device-model/%d/physmap/%s/start_addr",
xen_domid, entries[i]);
value = xs_read(state->xenstore, 0, path, &len);
if (value == NULL) {
free(physmap);
continue;
}
physmap->start_addr = strtoull(value, NULL, 16);
free(value);
snprintf(path, sizeof(path),
"/local/domain/0/device-model/%d/physmap/%s/size",
xen_domid, entries[i]);
value = xs_read(state->xenstore, 0, path, &len);
if (value == NULL) {
free(physmap);
continue;
}
physmap->size = strtoull(value, NULL, 16);
free(value);
snprintf(path, sizeof(path),
"/local/domain/0/device-model/%d/physmap/%s/name",
xen_domid, entries[i]);
physmap->name = xs_read(state->xenstore, 0, path, &len);
QLIST_INSERT_HEAD(&state->physmap, physmap, list);
}
free(entries);
}
| 1threat |
Which Smarttv can open a browser on boot ? : Is their a smarttv that can open a browser when it's powered on (In EU)? And how is can you do it (do you need to hack the tv)? | 0debug |
Does the Project Lombok @Data annotation create a constructor of any kind? : <p>I have a class with a <code>@Data</code> annotation, but I'm not sure whether a constructor with arguments is generated or the only generated constructor is the default (no arguments) one from vanilla Java.</p>
| 0debug |
def find_Extra(arr1,arr2,n) :
for i in range(0, n) :
if (arr1[i] != arr2[i]) :
return i
return n | 0debug |
C#: Large File Compression : <p>we have large files with the size ranging from 800 MB to 900 MB. Currently i am using SharpZipLib Library which takes more time to compress and has very less compression ratio. </p>
<p>Please Suggest me some of the libraries which will support high compression ratio and compressed file can be used to send over TCP\IP network </p>
<p>Thanks </p>
| 0debug |
Lombok @SuperBuilder workaround on IntelliJ : <p>I've a class Product:</p>
<pre><code> @Data
@SuperBuilder
public class Product {
private String name;
private String manufacturer;
}
</code></pre>
<p>and an extended class</p>
<pre><code>@Data
@SuperBuilder
public class Frame extends Product{
private String model;
}
</code></pre>
<p>I'm trying to create a Frame object using the builder:</p>
<pre><code> return Frame.builder()
.name("Frame ABC")
.manufacturer("Manufacturer")
.model("Model 1")
.build();
</code></pre>
<p>I'm using IntelliJ 2019.1.1 with lombok plugin but unfortunately the compiler marks as error the .name() and .manufacturer() methods.
I saw this <a href="https://github.com/mplushnikov/lombok-intellij-plugin/issues/513" rel="noreferrer">https://github.com/mplushnikov/lombok-intellij-plugin/issues/513</a> issue opened and I'm wondering if there is a workaround to make my code to work.</p>
| 0debug |
void scsi_req_build_sense(SCSIRequest *req, SCSISense sense)
{
trace_scsi_req_build_sense(req->dev->id, req->lun, req->tag,
sense.key, sense.asc, sense.ascq);
memset(req->sense, 0, 18);
req->sense[0] = 0xf0;
req->sense[2] = sense.key;
req->sense[7] = 10;
req->sense[12] = sense.asc;
req->sense[13] = sense.ascq;
req->sense_len = 18;
}
| 1threat |
What is the best way to count in a for loop? : <p>I find myself in the need of counting through lists with the help of for loops. What I end up doing is this:</p>
<pre><code>L = ['A','B','C','D']
n = 0
for i in L:
print(L[n])
n += 1
</code></pre>
<p>I was wondering if there is a better way for doing this, without having to declare an extra variable <code>n</code> every time?</p>
<p>Please keep in mind that this is just a simplified example. A solution like this would not suffice (although in this example the results are the same):</p>
<pre><code>L = ['A','B','C','D']
for i in L:
print(i)
</code></pre>
| 0debug |
Output offset when using std::cout : <p><strong>Hello dear Community,</strong></p>
<p>I discovered weird behaviour when using std::cout. At line 75 I invoke the function "<strong>traverse(...)</strong>". <strong>traverse(...)</strong> will invoke "<strong>visit(int)</strong>". <strong>visit(int)</strong> will just print the int-parameter that is applied to the function.</p>
<p>I created a breakpoint on line 75 to investigate how the preorder on an binary-tree is working and discovered weird behaviour when it comes to the console-output of <strong>visit(int)</strong>.</p>
<p>If I'm using at line 101, within the <strong>visit(int)</strong>-function:</p>
<pre><code>std::cout << std::endl << "Node: " << i << std::endl;
</code></pre>
<p>It's normally printed. But if I will use:</p>
<pre><code>std::cout << std::endl << "Node: " << i;
</code></pre>
<p>The zero (0) will not be printed if the <strong>visit(int)</strong>-function is executed first. Whilst examining the the debugger I observed the variable <strong>i</strong> that is applied to <strong>visit(i)</strong>. From the beginning: i = 0, <strong>NO</strong> console output is printed, then the second run of visit(i) is executed with i = 2. But instead printing the 2, the 0 will be printed.</p>
<p>It seems that the missing</p>
<pre><code><< std::endl
</code></pre>
<p>will lead to weird behavior of the whole line.</p>
<p>Does anybody expected same issues? Just try it.</p>
<pre><code>/*
* Project: Traversing of a binary-tree with the preorder (recursive).
* Author: https://github.com/OtenMoten
*
* A binary-tree is suitable for managing efficient data.
* "Preorder" means the algorithm will first check the root, then
* the left sub-tree and finally the right sub-tree.
*
* Just check out https://stackoverflow.com/questions/2130416/what-are-the-applications-of-binary-trees
* to read about the use-cases of binary-trees.
*
* Coding Standard:
* "a" = address variable (i.e. int& aTest;)
* "i" = normal variable (i.e. int iTest;)
* "p" = pointer variable (i.e. int* pTest;)
* "x" = array (i.e. int xTest[10][5];)
*
* Created on 6. Februar 2019, 23:05
*/
#include <cstdlib>
#include <stdio.h>
#include <iostream>
using namespace std;
constexpr int MAX_COLUMNS(4);
void print(int, int[][MAX_COLUMNS]);
void visit(int);
void height(int, int[][MAX_COLUMNS], int&, int&);
void traverse(int, int[][MAX_COLUMNS], int[]);
void out(int[]);
int main(int argc, char** argv) {
constexpr int iCoutRows_Alpha = 9;
constexpr int iCoutRows_Beta = 11;
int aCurrentHeight = 0;
int aFinalHeight = 1;
int xDataFromTree[100] = {0};
// Father - Left Son - Right Son - Data
int xTreeAlpha[iCoutRows_Alpha][MAX_COLUMNS] = {
{0, 5, 3, 0}, // Node 0
{4, 0, 0, 101}, // Node 1
{7, 0, 0, 102}, // Node 2
{0, 0, 0, 103}, // Node 3
{5, 1, 7, 0}, // Node 4
{0, 6, 4, 0}, // Node 5
{5, 0, 0, 104}, // Node 6
{4, 8, 2, 0}, // Node 7
{7, 0, 0, 105} // Node 8
};
int xTreeBeta[iCoutRows_Beta][MAX_COLUMNS] = {
{0, 2, 1, 0}, // Node 0
{0, 4, 8, 0}, // Node 1
{0, 5, 3, 0}, // Node 2
{2, 9, 6, 0}, // Node 3
{1, 10, 7, 0}, // Node 4
{2, 0, 0, 107}, // Node 5
{3, 0, 0, 102}, // Node 6
{4, 0, 0, 104}, // Node 7
{1, 0, 0, 101}, // Node 8
{3, 0, 0, 105}, // Node 9
{4, 0, 0, 103} // Node 10
};
std::cout << std::endl;
std::cout << "Preorder-Traversing" << std::endl;
print(iCoutRows_Beta, xTreeBeta);
std::cout << std::endl;
traverse(0, xTreeBeta, xDataFromTree); // Start with the root, node 0.
std::cout << std::endl << std::endl;
height(0, xTreeBeta, aCurrentHeight, aFinalHeight);
std::cout << "Height of the binary-tree = " << aFinalHeight;
out(xDataFromTree);
return 0;
};
void print(int iCountRows, int b[][MAX_COLUMNS]) {
int iColumnA = 0;
int iColumnB = 1;
int iColumnC = 2;
int iColumnD = 3;
std::cout << std::endl;
std::cout << "Binary-tree:";
for (int iii = 0; iii < iCountRows; iii++) {
std::cout << std::endl;
std::cout << "Father - Left - Right - Data";
printf("\n%3d %7d %7d %7d ", b[iii][iColumnA], b[iii][iColumnB], b[iii][iColumnC], b[iii][iColumnD]);
};
};
void visit(int i) {
std::cout << std::endl << "Node: " << i << std::endl;
};
void height(int root, int xBinaryTree[][4], int &aCurrentHeight, int &aFinalHeight) {
aCurrentHeight++; // "aCurrentHeight" is the current layer of the node.
if (aCurrentHeight > aFinalHeight) aFinalHeight = aCurrentHeight; // The final height is >= the current height.
if (xBinaryTree[root][1] != 0) // The current node is NOT a leaf!
{
height(xBinaryTree[root][1], xBinaryTree, aCurrentHeight, aFinalHeight); // Get the height of the left sub-tree.
height(xBinaryTree[root][2], xBinaryTree, aCurrentHeight, aFinalHeight); // Get the height of the right sub-tree.
};
aCurrentHeight--;
};
void traverse(int i, int baum[][4], int inhalt[]) {
int az;
visit(i);
if (baum[i][1] != 0) // aktueller Knoten ist kein Blatt
{
traverse(baum[i][1], baum, inhalt); //linken Sohn
traverse(baum[i][2], baum, inhalt); //rechten Sohn
} else {
az = inhalt[0]; // aktueller Knoten ist Blatt
inhalt[az + 1] = baum[i][3];
inhalt[0] = az + 1;
};
};
void out(int xInputArray[]) {
std::cout << std::endl;
std::cout << "Count of leafs with data = " << xInputArray[0];
std::cout << std::endl << std::endl;
std::cout << "Data is:";
for (int i = 1; i < xInputArray[0] + 1; i++) {
std::cout << std::endl;
std::cout << xInputArray[i];
};
};
</code></pre>
<p><strong>Kind regards
Oten</strong></p>
| 0debug |
How to find the starting and ending address of Stack memory for a program? : <p>Any one can explain how to find the stack starting address and ending address through programming</p>
| 0debug |
static int disas_vfp_insn(DisasContext *s, uint32_t insn)
{
uint32_t rd, rn, rm, op, i, n, offset, delta_d, delta_m, bank_mask;
int dp, veclen;
TCGv_i32 addr;
TCGv_i32 tmp;
TCGv_i32 tmp2;
if (!arm_dc_feature(s, ARM_FEATURE_VFP)) {
return 1;
}
if (!s->cpacr_fpen) {
gen_exception_insn(s, 4, EXCP_UDEF,
syn_fp_access_trap(1, 0xe, s->thumb),
default_exception_el(s));
return 0;
}
if (!s->vfp_enabled) {
if ((insn & 0x0fe00fff) != 0x0ee00a10)
return 1;
rn = (insn >> 16) & 0xf;
if (rn != ARM_VFP_FPSID && rn != ARM_VFP_FPEXC && rn != ARM_VFP_MVFR2
&& rn != ARM_VFP_MVFR1 && rn != ARM_VFP_MVFR0) {
return 1;
}
}
if (extract32(insn, 28, 4) == 0xf) {
return disas_vfp_v8_insn(s, insn);
}
dp = ((insn & 0xf00) == 0xb00);
switch ((insn >> 24) & 0xf) {
case 0xe:
if (insn & (1 << 4)) {
rd = (insn >> 12) & 0xf;
if (dp) {
int size;
int pass;
VFP_DREG_N(rn, insn);
if (insn & 0xf)
return 1;
if (insn & 0x00c00060
&& !arm_dc_feature(s, ARM_FEATURE_NEON)) {
return 1;
}
pass = (insn >> 21) & 1;
if (insn & (1 << 22)) {
size = 0;
offset = ((insn >> 5) & 3) * 8;
} else if (insn & (1 << 5)) {
size = 1;
offset = (insn & (1 << 6)) ? 16 : 0;
} else {
size = 2;
offset = 0;
}
if (insn & ARM_CP_RW_BIT) {
tmp = neon_load_reg(rn, pass);
switch (size) {
case 0:
if (offset)
tcg_gen_shri_i32(tmp, tmp, offset);
if (insn & (1 << 23))
gen_uxtb(tmp);
else
gen_sxtb(tmp);
break;
case 1:
if (insn & (1 << 23)) {
if (offset) {
tcg_gen_shri_i32(tmp, tmp, 16);
} else {
gen_uxth(tmp);
}
} else {
if (offset) {
tcg_gen_sari_i32(tmp, tmp, 16);
} else {
gen_sxth(tmp);
}
}
break;
case 2:
break;
}
store_reg(s, rd, tmp);
} else {
tmp = load_reg(s, rd);
if (insn & (1 << 23)) {
if (size == 0) {
gen_neon_dup_u8(tmp, 0);
} else if (size == 1) {
gen_neon_dup_low16(tmp);
}
for (n = 0; n <= pass * 2; n++) {
tmp2 = tcg_temp_new_i32();
tcg_gen_mov_i32(tmp2, tmp);
neon_store_reg(rn, n, tmp2);
}
neon_store_reg(rn, n, tmp);
} else {
switch (size) {
case 0:
tmp2 = neon_load_reg(rn, pass);
tcg_gen_deposit_i32(tmp, tmp2, tmp, offset, 8);
tcg_temp_free_i32(tmp2);
break;
case 1:
tmp2 = neon_load_reg(rn, pass);
tcg_gen_deposit_i32(tmp, tmp2, tmp, offset, 16);
tcg_temp_free_i32(tmp2);
break;
case 2:
break;
}
neon_store_reg(rn, pass, tmp);
}
}
} else {
if ((insn & 0x6f) != 0x00)
return 1;
rn = VFP_SREG_N(insn);
if (insn & ARM_CP_RW_BIT) {
if (insn & (1 << 21)) {
rn >>= 1;
switch (rn) {
case ARM_VFP_FPSID:
if (IS_USER(s)
&& arm_dc_feature(s, ARM_FEATURE_VFP3)) {
return 1;
}
tmp = load_cpu_field(vfp.xregs[rn]);
break;
case ARM_VFP_FPEXC:
if (IS_USER(s))
return 1;
tmp = load_cpu_field(vfp.xregs[rn]);
break;
case ARM_VFP_FPINST:
case ARM_VFP_FPINST2:
if (IS_USER(s)
|| arm_dc_feature(s, ARM_FEATURE_VFP3)) {
return 1;
}
tmp = load_cpu_field(vfp.xregs[rn]);
break;
case ARM_VFP_FPSCR:
if (rd == 15) {
tmp = load_cpu_field(vfp.xregs[ARM_VFP_FPSCR]);
tcg_gen_andi_i32(tmp, tmp, 0xf0000000);
} else {
tmp = tcg_temp_new_i32();
gen_helper_vfp_get_fpscr(tmp, cpu_env);
}
break;
case ARM_VFP_MVFR2:
if (!arm_dc_feature(s, ARM_FEATURE_V8)) {
return 1;
}
case ARM_VFP_MVFR0:
case ARM_VFP_MVFR1:
if (IS_USER(s)
|| !arm_dc_feature(s, ARM_FEATURE_MVFR)) {
return 1;
}
tmp = load_cpu_field(vfp.xregs[rn]);
break;
default:
return 1;
}
} else {
gen_mov_F0_vreg(0, rn);
tmp = gen_vfp_mrs();
}
if (rd == 15) {
gen_set_nzcv(tmp);
tcg_temp_free_i32(tmp);
} else {
store_reg(s, rd, tmp);
}
} else {
if (insn & (1 << 21)) {
rn >>= 1;
switch (rn) {
case ARM_VFP_FPSID:
case ARM_VFP_MVFR0:
case ARM_VFP_MVFR1:
break;
case ARM_VFP_FPSCR:
tmp = load_reg(s, rd);
gen_helper_vfp_set_fpscr(cpu_env, tmp);
tcg_temp_free_i32(tmp);
gen_lookup_tb(s);
break;
case ARM_VFP_FPEXC:
if (IS_USER(s))
return 1;
tmp = load_reg(s, rd);
tcg_gen_andi_i32(tmp, tmp, 1 << 30);
store_cpu_field(tmp, vfp.xregs[rn]);
gen_lookup_tb(s);
break;
case ARM_VFP_FPINST:
case ARM_VFP_FPINST2:
if (IS_USER(s)) {
return 1;
}
tmp = load_reg(s, rd);
store_cpu_field(tmp, vfp.xregs[rn]);
break;
default:
return 1;
}
} else {
tmp = load_reg(s, rd);
gen_vfp_msr(tmp);
gen_mov_vreg_F0(0, rn);
}
}
}
} else {
op = ((insn >> 20) & 8) | ((insn >> 19) & 6) | ((insn >> 6) & 1);
if (dp) {
if (op == 15) {
rn = ((insn >> 15) & 0x1e) | ((insn >> 7) & 1);
} else {
VFP_DREG_N(rn, insn);
}
if (op == 15 && (rn == 15 || ((rn & 0x1c) == 0x18) ||
((rn & 0x1e) == 0x6))) {
rd = VFP_SREG_D(insn);
} else {
VFP_DREG_D(rd, insn);
}
if (op == 15 &&
(((rn & 0x1c) == 0x10) || ((rn & 0x14) == 0x14) ||
((rn & 0x1e) == 0x4))) {
rm = VFP_SREG_M(insn);
} else {
VFP_DREG_M(rm, insn);
}
} else {
rn = VFP_SREG_N(insn);
if (op == 15 && rn == 15) {
VFP_DREG_D(rd, insn);
} else {
rd = VFP_SREG_D(insn);
}
rm = VFP_SREG_M(insn);
}
veclen = s->vec_len;
if (op == 15 && rn > 3)
veclen = 0;
delta_m = 0;
delta_d = 0;
bank_mask = 0;
if (veclen > 0) {
if (dp)
bank_mask = 0xc;
else
bank_mask = 0x18;
if ((rd & bank_mask) == 0) {
veclen = 0;
} else {
if (dp)
delta_d = (s->vec_stride >> 1) + 1;
else
delta_d = s->vec_stride + 1;
if ((rm & bank_mask) == 0) {
delta_m = 0;
} else {
delta_m = delta_d;
}
}
}
if (op == 15) {
switch (rn) {
case 16:
case 17:
gen_mov_F0_vreg(0, rm);
break;
case 8:
case 9:
gen_mov_F0_vreg(dp, rd);
gen_mov_F1_vreg(dp, rm);
break;
case 10:
case 11:
gen_mov_F0_vreg(dp, rd);
gen_vfp_F1_ld0(dp);
break;
case 20:
case 21:
case 22:
case 23:
case 28:
case 29:
case 30:
case 31:
gen_mov_F0_vreg(dp, rd);
break;
case 4:
case 5:
case 6:
case 7:
if ((dp && !arm_dc_feature(s, ARM_FEATURE_V8)) ||
!arm_dc_feature(s, ARM_FEATURE_VFP_FP16)) {
return 1;
}
if (!extract32(rn, 1, 1)) {
gen_mov_F0_vreg(0, rm);
break;
}
default:
gen_mov_F0_vreg(dp, rm);
break;
}
} else {
gen_mov_F0_vreg(dp, rn);
gen_mov_F1_vreg(dp, rm);
}
for (;;) {
switch (op) {
case 0:
gen_vfp_F1_mul(dp);
gen_mov_F0_vreg(dp, rd);
gen_vfp_add(dp);
break;
case 1:
gen_vfp_mul(dp);
gen_vfp_F1_neg(dp);
gen_mov_F0_vreg(dp, rd);
gen_vfp_add(dp);
break;
case 2:
gen_vfp_F1_mul(dp);
gen_mov_F0_vreg(dp, rd);
gen_vfp_neg(dp);
gen_vfp_add(dp);
break;
case 3:
gen_vfp_mul(dp);
gen_vfp_F1_neg(dp);
gen_mov_F0_vreg(dp, rd);
gen_vfp_neg(dp);
gen_vfp_add(dp);
break;
case 4:
gen_vfp_mul(dp);
break;
case 5:
gen_vfp_mul(dp);
gen_vfp_neg(dp);
break;
case 6:
gen_vfp_add(dp);
break;
case 7:
gen_vfp_sub(dp);
break;
case 8:
gen_vfp_div(dp);
break;
case 10:
case 11:
case 12:
case 13:
if (!arm_dc_feature(s, ARM_FEATURE_VFP4)) {
return 1;
}
if (dp) {
TCGv_ptr fpst;
TCGv_i64 frd;
if (op & 1) {
gen_helper_vfp_negd(cpu_F0d, cpu_F0d);
}
frd = tcg_temp_new_i64();
tcg_gen_ld_f64(frd, cpu_env, vfp_reg_offset(dp, rd));
if (op & 2) {
gen_helper_vfp_negd(frd, frd);
}
fpst = get_fpstatus_ptr(0);
gen_helper_vfp_muladdd(cpu_F0d, cpu_F0d,
cpu_F1d, frd, fpst);
tcg_temp_free_ptr(fpst);
tcg_temp_free_i64(frd);
} else {
TCGv_ptr fpst;
TCGv_i32 frd;
if (op & 1) {
gen_helper_vfp_negs(cpu_F0s, cpu_F0s);
}
frd = tcg_temp_new_i32();
tcg_gen_ld_f32(frd, cpu_env, vfp_reg_offset(dp, rd));
if (op & 2) {
gen_helper_vfp_negs(frd, frd);
}
fpst = get_fpstatus_ptr(0);
gen_helper_vfp_muladds(cpu_F0s, cpu_F0s,
cpu_F1s, frd, fpst);
tcg_temp_free_ptr(fpst);
tcg_temp_free_i32(frd);
}
break;
case 14:
if (!arm_dc_feature(s, ARM_FEATURE_VFP3)) {
return 1;
}
n = (insn << 12) & 0x80000000;
i = ((insn >> 12) & 0x70) | (insn & 0xf);
if (dp) {
if (i & 0x40)
i |= 0x3f80;
else
i |= 0x4000;
n |= i << 16;
tcg_gen_movi_i64(cpu_F0d, ((uint64_t)n) << 32);
} else {
if (i & 0x40)
i |= 0x780;
else
i |= 0x800;
n |= i << 19;
tcg_gen_movi_i32(cpu_F0s, n);
}
break;
case 15:
switch (rn) {
case 0:
break;
case 1:
gen_vfp_abs(dp);
break;
case 2:
gen_vfp_neg(dp);
break;
case 3:
gen_vfp_sqrt(dp);
break;
case 4:
tmp = gen_vfp_mrs();
tcg_gen_ext16u_i32(tmp, tmp);
if (dp) {
gen_helper_vfp_fcvt_f16_to_f64(cpu_F0d, tmp,
cpu_env);
} else {
gen_helper_vfp_fcvt_f16_to_f32(cpu_F0s, tmp,
cpu_env);
}
tcg_temp_free_i32(tmp);
break;
case 5:
tmp = gen_vfp_mrs();
tcg_gen_shri_i32(tmp, tmp, 16);
if (dp) {
gen_helper_vfp_fcvt_f16_to_f64(cpu_F0d, tmp,
cpu_env);
} else {
gen_helper_vfp_fcvt_f16_to_f32(cpu_F0s, tmp,
cpu_env);
}
tcg_temp_free_i32(tmp);
break;
case 6:
tmp = tcg_temp_new_i32();
if (dp) {
gen_helper_vfp_fcvt_f64_to_f16(tmp, cpu_F0d,
cpu_env);
} else {
gen_helper_vfp_fcvt_f32_to_f16(tmp, cpu_F0s,
cpu_env);
}
gen_mov_F0_vreg(0, rd);
tmp2 = gen_vfp_mrs();
tcg_gen_andi_i32(tmp2, tmp2, 0xffff0000);
tcg_gen_or_i32(tmp, tmp, tmp2);
tcg_temp_free_i32(tmp2);
gen_vfp_msr(tmp);
break;
case 7:
tmp = tcg_temp_new_i32();
if (dp) {
gen_helper_vfp_fcvt_f64_to_f16(tmp, cpu_F0d,
cpu_env);
} else {
gen_helper_vfp_fcvt_f32_to_f16(tmp, cpu_F0s,
cpu_env);
}
tcg_gen_shli_i32(tmp, tmp, 16);
gen_mov_F0_vreg(0, rd);
tmp2 = gen_vfp_mrs();
tcg_gen_ext16u_i32(tmp2, tmp2);
tcg_gen_or_i32(tmp, tmp, tmp2);
tcg_temp_free_i32(tmp2);
gen_vfp_msr(tmp);
break;
case 8:
gen_vfp_cmp(dp);
break;
case 9:
gen_vfp_cmpe(dp);
break;
case 10:
gen_vfp_cmp(dp);
break;
case 11:
gen_vfp_F1_ld0(dp);
gen_vfp_cmpe(dp);
break;
case 12:
{
TCGv_ptr fpst = get_fpstatus_ptr(0);
if (dp) {
gen_helper_rintd(cpu_F0d, cpu_F0d, fpst);
} else {
gen_helper_rints(cpu_F0s, cpu_F0s, fpst);
}
tcg_temp_free_ptr(fpst);
break;
}
case 13:
{
TCGv_ptr fpst = get_fpstatus_ptr(0);
TCGv_i32 tcg_rmode;
tcg_rmode = tcg_const_i32(float_round_to_zero);
gen_helper_set_rmode(tcg_rmode, tcg_rmode, cpu_env);
if (dp) {
gen_helper_rintd(cpu_F0d, cpu_F0d, fpst);
} else {
gen_helper_rints(cpu_F0s, cpu_F0s, fpst);
}
gen_helper_set_rmode(tcg_rmode, tcg_rmode, cpu_env);
tcg_temp_free_i32(tcg_rmode);
tcg_temp_free_ptr(fpst);
break;
}
case 14:
{
TCGv_ptr fpst = get_fpstatus_ptr(0);
if (dp) {
gen_helper_rintd_exact(cpu_F0d, cpu_F0d, fpst);
} else {
gen_helper_rints_exact(cpu_F0s, cpu_F0s, fpst);
}
tcg_temp_free_ptr(fpst);
break;
}
case 15:
if (dp)
gen_helper_vfp_fcvtsd(cpu_F0s, cpu_F0d, cpu_env);
else
gen_helper_vfp_fcvtds(cpu_F0d, cpu_F0s, cpu_env);
break;
case 16:
gen_vfp_uito(dp, 0);
break;
case 17:
gen_vfp_sito(dp, 0);
break;
case 20:
if (!arm_dc_feature(s, ARM_FEATURE_VFP3)) {
return 1;
}
gen_vfp_shto(dp, 16 - rm, 0);
break;
case 21:
if (!arm_dc_feature(s, ARM_FEATURE_VFP3)) {
return 1;
}
gen_vfp_slto(dp, 32 - rm, 0);
break;
case 22:
if (!arm_dc_feature(s, ARM_FEATURE_VFP3)) {
return 1;
}
gen_vfp_uhto(dp, 16 - rm, 0);
break;
case 23:
if (!arm_dc_feature(s, ARM_FEATURE_VFP3)) {
return 1;
}
gen_vfp_ulto(dp, 32 - rm, 0);
break;
case 24:
gen_vfp_toui(dp, 0);
break;
case 25:
gen_vfp_touiz(dp, 0);
break;
case 26:
gen_vfp_tosi(dp, 0);
break;
case 27:
gen_vfp_tosiz(dp, 0);
break;
case 28:
if (!arm_dc_feature(s, ARM_FEATURE_VFP3)) {
return 1;
}
gen_vfp_tosh(dp, 16 - rm, 0);
break;
case 29:
if (!arm_dc_feature(s, ARM_FEATURE_VFP3)) {
return 1;
}
gen_vfp_tosl(dp, 32 - rm, 0);
break;
case 30:
if (!arm_dc_feature(s, ARM_FEATURE_VFP3)) {
return 1;
}
gen_vfp_touh(dp, 16 - rm, 0);
break;
case 31:
if (!arm_dc_feature(s, ARM_FEATURE_VFP3)) {
return 1;
}
gen_vfp_toul(dp, 32 - rm, 0);
break;
default:
return 1;
}
break;
default:
return 1;
}
if (op == 15 && (rn >= 8 && rn <= 11)) {
} else if (op == 15 && dp && ((rn & 0x1c) == 0x18 ||
(rn & 0x1e) == 0x6)) {
gen_mov_vreg_F0(0, rd);
} else if (op == 15 && rn == 15) {
gen_mov_vreg_F0(!dp, rd);
} else {
gen_mov_vreg_F0(dp, rd);
}
if (veclen == 0)
break;
if (op == 15 && delta_m == 0) {
while (veclen--) {
rd = ((rd + delta_d) & (bank_mask - 1))
| (rd & bank_mask);
gen_mov_vreg_F0(dp, rd);
}
break;
}
veclen--;
rd = ((rd + delta_d) & (bank_mask - 1))
| (rd & bank_mask);
if (op == 15) {
rm = ((rm + delta_m) & (bank_mask - 1))
| (rm & bank_mask);
gen_mov_F0_vreg(dp, rm);
} else {
rn = ((rn + delta_d) & (bank_mask - 1))
| (rn & bank_mask);
gen_mov_F0_vreg(dp, rn);
if (delta_m) {
rm = ((rm + delta_m) & (bank_mask - 1))
| (rm & bank_mask);
gen_mov_F1_vreg(dp, rm);
}
}
}
}
break;
case 0xc:
case 0xd:
if ((insn & 0x03e00000) == 0x00400000) {
rn = (insn >> 16) & 0xf;
rd = (insn >> 12) & 0xf;
if (dp) {
VFP_DREG_M(rm, insn);
} else {
rm = VFP_SREG_M(insn);
}
if (insn & ARM_CP_RW_BIT) {
if (dp) {
gen_mov_F0_vreg(0, rm * 2);
tmp = gen_vfp_mrs();
store_reg(s, rd, tmp);
gen_mov_F0_vreg(0, rm * 2 + 1);
tmp = gen_vfp_mrs();
store_reg(s, rn, tmp);
} else {
gen_mov_F0_vreg(0, rm);
tmp = gen_vfp_mrs();
store_reg(s, rd, tmp);
gen_mov_F0_vreg(0, rm + 1);
tmp = gen_vfp_mrs();
store_reg(s, rn, tmp);
}
} else {
if (dp) {
tmp = load_reg(s, rd);
gen_vfp_msr(tmp);
gen_mov_vreg_F0(0, rm * 2);
tmp = load_reg(s, rn);
gen_vfp_msr(tmp);
gen_mov_vreg_F0(0, rm * 2 + 1);
} else {
tmp = load_reg(s, rd);
gen_vfp_msr(tmp);
gen_mov_vreg_F0(0, rm);
tmp = load_reg(s, rn);
gen_vfp_msr(tmp);
gen_mov_vreg_F0(0, rm + 1);
}
}
} else {
rn = (insn >> 16) & 0xf;
if (dp)
VFP_DREG_D(rd, insn);
else
rd = VFP_SREG_D(insn);
if ((insn & 0x01200000) == 0x01000000) {
offset = (insn & 0xff) << 2;
if ((insn & (1 << 23)) == 0)
offset = -offset;
if (s->thumb && rn == 15) {
addr = tcg_temp_new_i32();
tcg_gen_movi_i32(addr, s->pc & ~2);
} else {
addr = load_reg(s, rn);
}
tcg_gen_addi_i32(addr, addr, offset);
if (insn & (1 << 20)) {
gen_vfp_ld(s, dp, addr);
gen_mov_vreg_F0(dp, rd);
} else {
gen_mov_F0_vreg(dp, rd);
gen_vfp_st(s, dp, addr);
}
tcg_temp_free_i32(addr);
} else {
int w = insn & (1 << 21);
if (dp)
n = (insn >> 1) & 0x7f;
else
n = insn & 0xff;
if (w && !(((insn >> 23) ^ (insn >> 24)) & 1)) {
return 1;
}
if (n == 0 || (rd + n) > 32 || (dp && n > 16)) {
return 1;
}
if (rn == 15 && w) {
return 1;
}
if (s->thumb && rn == 15) {
addr = tcg_temp_new_i32();
tcg_gen_movi_i32(addr, s->pc & ~2);
} else {
addr = load_reg(s, rn);
}
if (insn & (1 << 24))
tcg_gen_addi_i32(addr, addr, -((insn & 0xff) << 2));
if (dp)
offset = 8;
else
offset = 4;
for (i = 0; i < n; i++) {
if (insn & ARM_CP_RW_BIT) {
gen_vfp_ld(s, dp, addr);
gen_mov_vreg_F0(dp, rd + i);
} else {
gen_mov_F0_vreg(dp, rd + i);
gen_vfp_st(s, dp, addr);
}
tcg_gen_addi_i32(addr, addr, offset);
}
if (w) {
if (insn & (1 << 24))
offset = -offset * n;
else if (dp && (insn & 1))
offset = 4;
else
offset = 0;
if (offset != 0)
tcg_gen_addi_i32(addr, addr, offset);
store_reg(s, rn, addr);
} else {
tcg_temp_free_i32(addr);
}
}
}
break;
default:
return 1;
}
return 0;
}
| 1threat |
WCF как вмешаться в работающий метод и ограничить доступ строго 1 клиентом : Доброго дня. Стоит задача организовать WCF сервер для управления измерительной аппаратурой. В процессе изучения новой для меня темы WCF возникли начальные вопросы:
1. Как организовать аварийное прерывание работы со стороны клиента? Настроил асинхронные вызовы, нажимаю в клиенте кнопку "адски нагрузить сервер" - на стороне сервера в рамках реализации контракта запускаю `
while (!stop) i++;
`
Нажимаю кнопку с предложением серверу перекинуть
`static bool stop = false` в `true` - и безответно. Требуется понимание способов вмешательства в процесс вычислений - как грамотно извне на него повлиять, и в частности - прервать? Писать мультипоточный запуск еще и на стороне сервера и рубить его по запросу от клиента? Или можно проще?
2. Ну и до кучи, требуется ограничить доступ к управляющему аппаратурой серверу строго до 1 клиента. Пляски с бубном вроде найденного здесь же на форуме вараинта
`[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single)]`
и
`<behavior name="Throttled">
<serviceThrottling maxConcurrentCalls="1"
maxConcurrentSessions="1"
maxConcurrentInstances="1" />
</behavior>`
никак не мешают параллельно запущенному окошку клиента управлять сервером, что недопустимо. Рыть в сторону авторизации клиента, или все же есть счастливая строчка, решающая проблему? :) | 0debug |
Xcode 8 - Provisioning Profile vs. Provisioning Profile (Deprecated) : <p>I have just updated to Xcode 8 and I now have two options for app signing, Provisioning Profile and Provisioning Profile (Deprecated).</p>
<p><a href="https://i.stack.imgur.com/skJKj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/skJKj.png" alt="enter image description here"></a></p>
<p>Why is one deprecated, and what is the difference between the two?</p>
| 0debug |
Prevent duplicate objects in classes/instance access with singleton : <p>The use is to provide .instance access, also to prevent duplicate objects of those classes.</p>
<p>Is this a good code implementation of a singleton?</p>
<pre><code>template <typename T> class singleton
{
public:
static T *ms_singleton;
singleton()
{
assert(!ms_singleton);
long offset = (long)(T *) 1 - (long)(singleton <T> *)(T *) 1;
ms_singleton = (T *)((long) this + offset);
}
virtual ~singleton()
{
assert(ms_singleton);
ms_singleton = 0;
}
static T &instance()
{
assert(ms_singleton);
return (*ms_singleton);
}
static T &Instance()
{
assert(ms_singleton);
return (*ms_singleton);
}
static T *instance_ptr()
{
return (ms_singleton);
}
};
template <typename T> T *singleton <T>::ms_singleton = NULL;
</code></pre>
<p>How I use it:</p>
<pre><code>class test1: public singleton<test2>
{
// Something
};
</code></pre>
<p>If not, what is wrong here? What should i rewrite here?</p>
| 0debug |
Convert Razor View to string ASP.NET core : <p>I want to send a view as email body, i'm using sendgrid.
How do i convert view to string ?</p>
<p>I got a code here <a href="https://long2know.com/2017/08/rendering-and-emailing-embedded-razor-views-with-net-core/" rel="nofollow noreferrer">https://long2know.com/2017/08/rendering-and-emailing-embedded-razor-views-with-net-core/</a></p>
<pre><code>
public string RenderToString<TModel>(string viewPath, TModel model)
{
try
{
var viewEngineResult = _viewEngine.GetView("Views/", viewPath, false);
if (!viewEngineResult.Success)
{
throw new InvalidOperationException($"Couldn't find view {viewPath}");
}
var view = viewEngineResult.View;
using (var sw = new StringWriter())
{
var viewContext = new ViewContext()
{
HttpContext = _httpContextAccessor.HttpContext ?? new DefaultHttpContext { RequestServices = _serviceProvider },
ViewData = new ViewDataDictionary<TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model },
Writer = sw
};
view.RenderAsync(viewContext).GetAwaiter().GetResult();
return sw.ToString();
}
}
catch (Exception ex)
{
throw new Exception("Error ending email.", ex);
}
}
</code></pre>
<p>This line say nullreference error</p>
<pre><code>view.RenderAsync(viewContext).GetAwaiter().GetResult();
</code></pre>
| 0debug |
Protocol type cannot conform to protocol because only concrete types can conform to protocols : <p>Within the app, we have two types of Stickers, String and Bitmap. Each sticker pack could contain both types. This is how I declare the models:</p>
<pre><code>// Mark: - Models
protocol Sticker: Codable {
}
public struct StickerString: Sticker, Codable, Equatable {
let fontName: String
let character: String
}
public struct StickerBitmap: Sticker, Codable, Equatable {
let imageName: String
}
</code></pre>
<p>After the user chooses some stickers and used them, we want to save the stickers into <code>UserDefaults</code> so we can show him the "Recently Used" Sticker tab. I'm trying to Decode the saved <code>[Sticker]</code> array:</p>
<pre><code>let recentStickers = try? JSONDecoder().decode([Sticker].self, from: data)
</code></pre>
<p>But I get the following compile error:</p>
<pre><code>Protocol type 'Sticker' cannot conform to 'Decodable' because only concrete types can conform to protocols
</code></pre>
<p>I can't understand why as I declared <code>Sticker</code> as <code>Codable</code> which also implement <code>Decodable</code>. Any help would be highly appreciated! </p>
| 0debug |
iOS Swift uploading PDF file with Alamofire (Multipart) : <p>I'm currently developing an application using iOS 10 and Swift 3 and Alamofire 4</p>
<p>The purpose of this application is to upload a PDF file generated previously.</p>
<p>The PDF generation is working perfectly and the file is created.</p>
<p>However the upload doesn’t work…
I received a success response but the file is not uploaded.</p>
<p><strong>My server response</strong></p>
<pre><code>Multi part Content-Type => multipart/form-data; boundary=alamofire.boundary.56958be35bdb49cb
Multi part Content-Length => 293107
Multi part Content-Boundary => alamofire.boundary.56958be35bdb49cb
responses
SUCCESS: {
uploadedFiles = (
{
details = " Key=Content-Disposition - values=[form-data; name=\"pdfDocuments\"] length=8";
storedFileName = "/var/www/pdf/17/009/22/TMP104150531290406.tmp";
type = PDF;
uploadedDate = 1483999296701;
uploadedFileName = UnknownFile;
}
);
}
end responses
</code></pre>
<p>I’m using multi-part to upload my file as Data as you can see <a href="https://github.com/Alamofire/Alamofire#uploading-data-to-a-server" rel="noreferrer">here</a> </p>
<p>File url is fine. </p>
<p>I have searched on SO but didn’t find any solution working… </p>
<p>Here you can see my <strong>Controller</strong></p>
<pre><code>Alamofire.upload(
multipartFormData: {
multipartFormData in
if let urlString = urlBase2 {
let pdfData = try! Data(contentsOf: urlString.asURL())
var data : Data = pdfData
multipartFormData.append(data as Data, withName:"test.pdf", mimeType:"application/pdf")
for (key, value) in body {
multipartFormData.append(((value as? String)?.data(using: .utf8))!, withName: key)
}
print("Multi part Content -Type")
print(multipartFormData.contentType)
print("Multi part FIN ")
print("Multi part Content-Length")
print(multipartFormData.contentLength)
print("Multi part Content-Boundary")
print(multipartFormData.boundary)
}
},
to: url,
method: .post,
headers: header,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print(" responses ")
print(response)
print("end responses")
onCompletion(true, "Something bad happen...", 200)
}
case .failure(let encodingError):
print(encodingError)
onCompletion(false, "Something bad happen...", 200)
}
})
</code></pre>
<p>Thanks in advance for the help.</p>
<p>Regards</p>
| 0debug |
static void setup_window(AVFormatContext *s)
{
XCBGrabContext *c = s->priv_data;
uint32_t mask = XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK;
uint32_t values[] = { 1,
XCB_EVENT_MASK_EXPOSURE |
XCB_EVENT_MASK_STRUCTURE_NOTIFY };
xcb_rectangle_t rect = { 0, 0, c->width, c->height };
c->window = xcb_generate_id(c->conn);
xcb_create_window(c->conn, XCB_COPY_FROM_PARENT,
c->window,
c->screen->root,
c->x - c->region_border,
c->y - c->region_border,
c->width + c->region_border * 2,
c->height + c->region_border * 2,
0,
XCB_WINDOW_CLASS_INPUT_OUTPUT,
XCB_COPY_FROM_PARENT,
mask, values);
#if CONFIG_LIBXCB_SHAPE
xcb_shape_rectangles(c->conn, XCB_SHAPE_SO_SUBTRACT,
XCB_SHAPE_SK_BOUNDING, XCB_CLIP_ORDERING_UNSORTED,
c->window,
c->region_border, c->region_border,
1, &rect);
#endif
xcb_map_window(c->conn, c->window);
draw_rectangle(s);
}
| 1threat |
How do I omit matplotlib printed output in Python / Jupyter notebook? : <p>When I make a simple plot inside an IPython / Jupyter notebook, there is printed output, presumably generated from matplotlib standard output. For example, if I run the simple script below, the notebook will print a line like: <code><matplotlib.text.Text at 0x115ae9850></code>. </p>
<pre><code>import random
import pandas as pd
%matplotlib inline
A = [random.gauss(10, 5) for i in range(20) ]
df = pd.DataFrame( { 'A': A} )
axis = df.A.hist()
axis.set_title('Histogram', size=20)
</code></pre>
<p>As you can see in the figure below, the output appears even though I didn't <code>print</code> anything. How can I remove or prevent that line?</p>
<p><a href="https://i.stack.imgur.com/rrHbs.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rrHbs.png" alt="Jupyter notebook output"></a></p>
| 0debug |
JavaScript - Creating elements with innerHTML duplicates them. Why? : <p>When creating elements in JavaScript with innerHTML, it duplicates the tags.</p>
<pre><code>let container = document.querySelector(".container");
// This creates two Paragraphs
container.innerHTML = "<p> Paragraph <\p>";
// This only creates one Header 3
container.innerHTML += "<h3> Header 3";
// This doesn't close <strong> correctly and creates two Header 2
container.innerHTML += "<h2><strong> Strong Header<\strong> Not Strong header <\h2> ";
</code></pre>
<p>Here's a good viewable Fiddle: <a href="https://jsfiddle.net/hdvxtujn/10/" rel="nofollow noreferrer">https://jsfiddle.net/hdvxtujn/10/</a></p>
<p>I've figured out, that if i only use an open tag, the element closes itself without duplication.
However, If i close the tag, the element duplicates itself with an empty element.</p>
<p>How come so and how to escape this? I would also like to add <code><strong></code> tag as displayed in the last example.</p>
| 0debug |
How to make a GIF move across the window and respond to a click : <p>In Tkinter, I need to have a GIF image move across a window every 2 seconds, and when it's clicked on to have a splash screen show. I have absolutely no idea how to import an image and have it move / respond to a click, and I can't find a straight answer elsewhere. </p>
<p>Thanks</p>
| 0debug |
static inline void chroma_4mv_motion_lowres(MpegEncContext *s,
uint8_t *dest_cb, uint8_t *dest_cr,
uint8_t **ref_picture,
h264_chroma_mc_func * pix_op,
int mx, int my)
{
const int lowres = s->avctx->lowres;
const int op_index = FFMIN(lowres, 2);
const int block_s = 8 >> lowres;
const int s_mask = (2 << lowres) - 1;
const int h_edge_pos = s->h_edge_pos >> lowres + 1;
const int v_edge_pos = s->v_edge_pos >> lowres + 1;
int emu = 0, src_x, src_y, offset, sx, sy;
uint8_t *ptr;
if (s->quarter_sample) {
mx /= 2;
my /= 2;
}
mx = ff_h263_round_chroma(mx);
my = ff_h263_round_chroma(my);
sx = mx & s_mask;
sy = my & s_mask;
src_x = s->mb_x * block_s + (mx >> lowres + 1);
src_y = s->mb_y * block_s + (my >> lowres + 1);
offset = src_y * s->uvlinesize + src_x;
ptr = ref_picture[1] + offset;
if (s->flags & CODEC_FLAG_EMU_EDGE) {
if ((unsigned) src_x > FFMAX(h_edge_pos - (!!sx) - block_s, 0) ||
(unsigned) src_y > FFMAX(v_edge_pos - (!!sy) - block_s, 0)) {
s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize,
9, 9, src_x, src_y, h_edge_pos, v_edge_pos);
ptr = s->edge_emu_buffer;
emu = 1;
}
}
sx = (sx << 2) >> lowres;
sy = (sy << 2) >> lowres;
pix_op[op_index](dest_cb, ptr, s->uvlinesize, block_s, sx, sy);
ptr = ref_picture[2] + offset;
if (emu) {
s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9,
src_x, src_y, h_edge_pos, v_edge_pos);
ptr = s->edge_emu_buffer;
}
pix_op[op_index](dest_cr, ptr, s->uvlinesize, block_s, sx, sy);
}
| 1threat |
long do_rt_sigreturn(CPUState *env)
{
struct rt_sigframe *frame;
sigset_t host_set;
if (env->regs[13] & 7)
goto badframe;
frame = (struct rt_sigframe *)env->regs[13];
#if 0
if (verify_area(VERIFY_READ, frame, sizeof (*frame)))
goto badframe;
#endif
target_to_host_sigset(&host_set, &frame->uc.tuc_sigmask);
sigprocmask(SIG_SETMASK, &host_set, NULL);
if (restore_sigcontext(env, &frame->uc.tuc_mcontext))
goto badframe;
if (do_sigaltstack(h2g(&frame->uc.tuc_stack), 0, get_sp_from_cpustate(env)) == -EFAULT)
goto badframe;
#if 0
if (ptrace_cancel_bpt(current))
send_sig(SIGTRAP, current, 1);
#endif
return env->regs[0];
badframe:
force_sig(SIGSEGV );
return 0;
}
| 1threat |
What version of org.json is built into Android? : <p>I'm using an open source library that depends on <code>org.json:json:20090211</code>. Evidently there are some API differences between version <code>20090211</code> and whatever version is provided by Android. When I enable ProGuard minimization, I see this warning:</p>
<blockquote>
<p>Warning: com.esri.core.geometry.JSONObjectEnumerator: can't find referenced method 'java.lang.String[] getNames(org.json.JSONObject)' in library class org.json.JSONObject</p>
</blockquote>
<p>That method is present in the current reference implementation of <a href="https://github.com/stleary/JSON-java/blob/master/JSONObject.java" rel="noreferrer"><code>JSONObject</code></a>, so I assume it was added sometime before version <code>20090211</code>, as opposed to removed after it, which means the version included in Android is older. I'd like to diff that version against <code>20090211</code> and see what needs to be done to make the library that depends on <code>20090211</code> compatible with Android.</p>
<p><strong>What version of org.json is included in Android?</strong></p>
<p>(I know I could rename <code>org.json</code> and change the dependency to the renamed version, but I'd like to avoid that if possible. Such a change is unlikely to be accepted upstream.)</p>
| 0debug |
int ff_MPV_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
AVFrame *pic_arg, int *got_packet)
{
MpegEncContext *s = avctx->priv_data;
int i, stuffing_count, ret;
int context_count = s->slice_context_count;
s->picture_in_gop_number++;
if (load_input_picture(s, pic_arg) < 0)
return -1;
if (select_input_picture(s) < 0) {
return -1;
}
if (s->new_picture.f.data[0]) {
if ((ret = ff_alloc_packet2(avctx, pkt, s->mb_width*s->mb_height*(MAX_MB_BYTES+100)+10000)) < 0)
return ret;
if (s->mb_info) {
s->mb_info_ptr = av_packet_new_side_data(pkt,
AV_PKT_DATA_H263_MB_INFO,
s->mb_width*s->mb_height*12);
s->prev_mb_info = s->last_mb_info = s->mb_info_size = 0;
}
for (i = 0; i < context_count; i++) {
int start_y = s->thread_context[i]->start_mb_y;
int end_y = s->thread_context[i]-> end_mb_y;
int h = s->mb_height;
uint8_t *start = pkt->data + (size_t)(((int64_t) pkt->size) * start_y / h);
uint8_t *end = pkt->data + (size_t)(((int64_t) pkt->size) * end_y / h);
init_put_bits(&s->thread_context[i]->pb, start, end - start);
}
s->pict_type = s->new_picture.f.pict_type;
ff_MPV_frame_start(s, avctx);
vbv_retry:
if (encode_picture(s, s->picture_number) < 0)
return -1;
avctx->header_bits = s->header_bits;
avctx->mv_bits = s->mv_bits;
avctx->misc_bits = s->misc_bits;
avctx->i_tex_bits = s->i_tex_bits;
avctx->p_tex_bits = s->p_tex_bits;
avctx->i_count = s->i_count;
avctx->p_count = s->mb_num - s->i_count - s->skip_count;
avctx->skip_count = s->skip_count;
ff_MPV_frame_end(s);
if (CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG)
ff_mjpeg_encode_picture_trailer(s);
if (avctx->rc_buffer_size) {
RateControlContext *rcc = &s->rc_context;
int max_size = rcc->buffer_index * avctx->rc_max_available_vbv_use;
if (put_bits_count(&s->pb) > max_size &&
s->lambda < s->avctx->lmax) {
s->next_lambda = FFMAX(s->lambda + 1, s->lambda *
(s->qscale + 1) / s->qscale);
if (s->adaptive_quant) {
int i;
for (i = 0; i < s->mb_height * s->mb_stride; i++)
s->lambda_table[i] =
FFMAX(s->lambda_table[i] + 1,
s->lambda_table[i] * (s->qscale + 1) /
s->qscale);
}
s->mb_skipped = 0;
if (s->pict_type == AV_PICTURE_TYPE_P) {
if (s->flipflop_rounding ||
s->codec_id == AV_CODEC_ID_H263P ||
s->codec_id == AV_CODEC_ID_MPEG4)
s->no_rounding ^= 1;
}
if (s->pict_type != AV_PICTURE_TYPE_B) {
s->time_base = s->last_time_base;
s->last_non_b_time = s->time - s->pp_time;
}
for (i = 0; i < context_count; i++) {
PutBitContext *pb = &s->thread_context[i]->pb;
init_put_bits(pb, pb->buf, pb->buf_end - pb->buf);
}
goto vbv_retry;
}
assert(s->avctx->rc_max_rate);
}
if (s->flags & CODEC_FLAG_PASS1)
ff_write_pass1_stats(s);
for (i = 0; i < 4; i++) {
s->current_picture_ptr->f.error[i] = s->current_picture.f.error[i];
avctx->error[i] += s->current_picture_ptr->f.error[i];
}
if (s->flags & CODEC_FLAG_PASS1)
assert(avctx->header_bits + avctx->mv_bits + avctx->misc_bits +
avctx->i_tex_bits + avctx->p_tex_bits ==
put_bits_count(&s->pb));
flush_put_bits(&s->pb);
s->frame_bits = put_bits_count(&s->pb);
stuffing_count = ff_vbv_update(s, s->frame_bits);
s->stuffing_bits = 8*stuffing_count;
if (stuffing_count) {
if (s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb) >> 3) <
stuffing_count + 50) {
av_log(s->avctx, AV_LOG_ERROR, "stuffing too large\n");
return -1;
}
switch (s->codec_id) {
case AV_CODEC_ID_MPEG1VIDEO:
case AV_CODEC_ID_MPEG2VIDEO:
while (stuffing_count--) {
put_bits(&s->pb, 8, 0);
}
break;
case AV_CODEC_ID_MPEG4:
put_bits(&s->pb, 16, 0);
put_bits(&s->pb, 16, 0x1C3);
stuffing_count -= 4;
while (stuffing_count--) {
put_bits(&s->pb, 8, 0xFF);
}
break;
default:
av_log(s->avctx, AV_LOG_ERROR, "vbv buffer overflow\n");
}
flush_put_bits(&s->pb);
s->frame_bits = put_bits_count(&s->pb);
}
if (s->avctx->rc_max_rate &&
s->avctx->rc_min_rate == s->avctx->rc_max_rate &&
s->out_format == FMT_MPEG1 &&
90000LL * (avctx->rc_buffer_size - 1) <=
s->avctx->rc_max_rate * 0xFFFFLL) {
int vbv_delay, min_delay;
double inbits = s->avctx->rc_max_rate *
av_q2d(s->avctx->time_base);
int minbits = s->frame_bits - 8 *
(s->vbv_delay_ptr - s->pb.buf - 1);
double bits = s->rc_context.buffer_index + minbits - inbits;
if (bits < 0)
av_log(s->avctx, AV_LOG_ERROR,
"Internal error, negative bits\n");
assert(s->repeat_first_field == 0);
vbv_delay = bits * 90000 / s->avctx->rc_max_rate;
min_delay = (minbits * 90000LL + s->avctx->rc_max_rate - 1) /
s->avctx->rc_max_rate;
vbv_delay = FFMAX(vbv_delay, min_delay);
av_assert0(vbv_delay < 0xFFFF);
s->vbv_delay_ptr[0] &= 0xF8;
s->vbv_delay_ptr[0] |= vbv_delay >> 13;
s->vbv_delay_ptr[1] = vbv_delay >> 5;
s->vbv_delay_ptr[2] &= 0x07;
s->vbv_delay_ptr[2] |= vbv_delay << 3;
avctx->vbv_delay = vbv_delay * 300;
}
s->total_bits += s->frame_bits;
avctx->frame_bits = s->frame_bits;
pkt->pts = s->current_picture.f.pts;
if (!s->low_delay && s->pict_type != AV_PICTURE_TYPE_B) {
if (!s->current_picture.f.coded_picture_number)
pkt->dts = pkt->pts - s->dts_delta;
else
pkt->dts = s->reordered_pts;
s->reordered_pts = pkt->pts;
} else
pkt->dts = pkt->pts;
if (s->current_picture.f.key_frame)
pkt->flags |= AV_PKT_FLAG_KEY;
if (s->mb_info)
av_packet_shrink_side_data(pkt, AV_PKT_DATA_H263_MB_INFO, s->mb_info_size);
} else {
s->frame_bits = 0;
}
assert((s->frame_bits & 7) == 0);
pkt->size = s->frame_bits / 8;
*got_packet = !!pkt->size;
return 0;
}
| 1threat |
how to get different columns by joining two tabl : Problem:
I am trying to join table1 and table2 to get the wk_nmbr for begin_date and end_date.
**table1**
begin_date,
end_date
**table2**
cal_date,
wk_nmbr
**Condition:**
table1.begin_date=table2.cal_date and
table1.end_date=table2.cal_date
**expected result in table 3:**
begin_date,
wk_nmbr_begin,
end_date,
wk_nmbr_end,
| 0debug |
import math
def perimeter_pentagon(a):
perimeter=(5*a)
return perimeter | 0debug |
static int get_siz(Jpeg2000DecoderContext *s)
{
int i;
if (bytestream2_get_bytes_left(&s->g) < 36)
return AVERROR(EINVAL);
s->avctx->profile = bytestream2_get_be16u(&s->g);
s->width = bytestream2_get_be32u(&s->g);
s->height = bytestream2_get_be32u(&s->g);
s->image_offset_x = bytestream2_get_be32u(&s->g);
s->image_offset_y = bytestream2_get_be32u(&s->g);
s->tile_width = bytestream2_get_be32u(&s->g);
s->tile_height = bytestream2_get_be32u(&s->g);
s->tile_offset_x = bytestream2_get_be32u(&s->g);
s->tile_offset_y = bytestream2_get_be32u(&s->g);
s->ncomponents = bytestream2_get_be16u(&s->g);
if (s->ncomponents <= 0 || s->ncomponents > 4) {
av_log(s->avctx, AV_LOG_ERROR, "unsupported/invalid ncomponents: %d\n", s->ncomponents);
return AVERROR(EINVAL);
}
if (s->tile_width<=0 || s->tile_height<=0)
return AVERROR(EINVAL);
if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents)
return AVERROR(EINVAL);
for (i = 0; i < s->ncomponents; i++) {
uint8_t x = bytestream2_get_byteu(&s->g);
s->cbps[i] = (x & 0x7f) + 1;
s->precision = FFMAX(s->cbps[i], s->precision);
s->sgnd[i] = !!(x & 0x80);
s->cdx[i] = bytestream2_get_byteu(&s->g);
s->cdy[i] = bytestream2_get_byteu(&s->g);
if (s->cdx[i] != 1 || s->cdy[i] != 1) {
av_log(s->avctx, AV_LOG_ERROR, "unsupported/ CDxy values %d %d for component %d\n", s->cdx[i], s->cdy[i], i);
if (!s->cdx[i] || !s->cdy[i])
return AVERROR_INVALIDDATA;
}
}
s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width);
s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(Jpeg2000Tile))
return AVERROR(EINVAL);
s->tile = av_mallocz(s->numXtiles * s->numYtiles * sizeof(*s->tile));
if (!s->tile)
return AVERROR(ENOMEM);
for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
Jpeg2000Tile *tile = s->tile + i;
tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
if (!tile->comp)
return AVERROR(ENOMEM);
}
s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x,
s->reduction_factor);
s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,
s->reduction_factor);
switch(s->ncomponents) {
case 1:
if (s->precision > 8)
s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
else
s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
break;
case 3:
switch (s->avctx->profile) {
case FF_PROFILE_JPEG2000_DCINEMA_2K:
case FF_PROFILE_JPEG2000_DCINEMA_4K:
s->avctx->pix_fmt = AV_PIX_FMT_XYZ12;
break;
default:
if (s->precision > 8)
s->avctx->pix_fmt = AV_PIX_FMT_RGB48;
else
s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
break;
}
break;
case 4:
s->avctx->pix_fmt = AV_PIX_FMT_RGBA;
break;
default:
s->avctx->pix_fmt = AV_PIX_FMT_NONE;
break;
}
return 0;
}
| 1threat |
How to properly use ListView and ContetMixin in Django : I am trying to use ListView and ContextMixin to create a view for this but I'm not sure if this is a right way to do it
class ImplementView(generic.ListView):
template_name = 'schedule/implement.html'
context_object_name = 'all_implements'
def get_queryset(self):
return CourseImplementation.objects.all()
def get_context_data(self, **kwargs):
context = super(ImplementView, self).get_context_data(**kwargs)
context['teacherid'] = TeacherCourseImplementation.objects.all()
return context
This is my models.py
class CourseImplementation(models.Model):
courseid = models.ForeignKey(Course, on_delete=models.CASCADE, db_column='courseid', )
roomid = models.ForeignKey('Room', models.DO_NOTHING, db_column='roomid', blank=True, null=True)
note = models.CharField(max_length=10, blank=True, null=True)
class Meta:
managed = False
db_table = 'course_implementation'
def __str__(self):
return self.pk + ' - ' + self.courseid
class TeacherCourseImplementation(models.Model):
teacherid = models.ForeignKey(Teacher, on_delete=models.CASCADE, db_column='teacherid', primary_key=True)
course_impleid = models.ForeignKey(CourseImplementation, on_delete=models.CASCADE, db_column='course_impleid')
p1 = models.IntegerField(blank=True, null=True)
p2 = models.IntegerField(blank=True, null=True)
p3 = models.IntegerField(blank=True, null=True)
p4 = models.IntegerField(blank=True, null=True)
p5 = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'teacher_course_implementation'
unique_together = (('teacherid', 'course_impleid'),)
def __str__(self):
return self.pk + ' - ' + self.teacherid
Can anyone help me on this. Thank you. | 0debug |
Understanding Dagger 2 @Component.Builder annotation : <p>I'm reading <a href="https://proandroiddev.com/dagger-2-component-builder-1f2b91237856" rel="noreferrer">this</a> great tutorial that explains how <code>@Component.Builder</code>works in Dagger 2. The author did a good job and the article is straight forward, but there still are some confusing I need to clarify: the default implementation of Dagger 2 looks something like this:</p>
<p>The component:</p>
<pre><code>@Singleton
@Component(modules = {AppModule.class})
public interface AppComponent {
void inject(MainActivity mainActivity);
SharedPreferences getSharedPrefs();
}
</code></pre>
<p>The module:</p>
<pre><code>@Module
public class AppModule {
Application application;
public AppModule(Application application) {
this.application = application;
}
@Provides
Application providesApplication() {
return application;
}
@Provides
@Singleton
public SharedPreferences providePreferences() {
return application.getSharedPreferences(DATA_STORE,
Context.MODE_PRIVATE);
}
}
</code></pre>
<p>Component instantiating:</p>
<pre><code>DaggerAppComponent appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this)) //this : application
.build();
</code></pre>
<p>According to the article, we can simplify this code even more by avoiding passing arguments to the module constructor using <code>@Component.Builder</code> and <code>@BindsInstance</code> annotations, then the code will look like this:</p>
<p>The component:</p>
<pre><code>@Singleton
@Component(modules = {AppModule.class})
public interface AppComponent {
void inject(MainActivity mainActivity);
SharedPreferences getSharedPrefs();
@Component.Builder
interface Builder {
AppComponent build();
@BindsInstance Builder application(Application application);
}
</code></pre>
<p>}</p>
<p>The module:</p>
<pre><code>@Module
public class AppModule {
@Provides
@Singleton
public SharedPreferences providePreferences(
Application application) {
return application.getSharedPreferences(
"store", Context.MODE_PRIVATE);
}
}
</code></pre>
<p>And the component instantiating:</p>
<pre><code>DaggerAppComponent appComponent = DaggerAppComponent.builder()
.application(this)
.build();
</code></pre>
<p>I almost understand how the above code works, but here is the part I don't understand: how did we get from <code>appModule(new AppModule(this))</code> to <code>application(this)</code> when we are instantiating the component?</p>
<p>I hope the question was clear and thanks.</p>
| 0debug |
easiest way to convert jpeg to pdf using powershell : > Hello,
>
> Anyone can give a sample of the easiest way to convert JPEG in a
> folder to PDF?
>
> Any help is much appreciated.
| 0debug |
static void RENAME(uyvytoyuv420)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,
long width, long height,
long lumStride, long chromStride, long srcStride)
{
long y;
const long chromWidth= -((-width)>>1);
for (y=0; y<height; y++) {
RENAME(extract_even)(src+1, ydst, width);
if(y&1) {
RENAME(extract_even2avg)(src-srcStride, src, udst, vdst, chromWidth);
udst+= chromStride;
vdst+= chromStride;
}
src += srcStride;
ydst+= lumStride;
}
#if COMPILE_TEMPLATE_MMX
__asm__(
EMMS" \n\t"
SFENCE" \n\t"
::: "memory"
);
#endif
}
| 1threat |
Derivate class from a derivate class : Hello i have 3 class (City, Neighborhood and Block)
Here is class definiton of City class
class City:
def __init__(self, id_city, name_city):
self.__id = id_city
self.__name = name_city
Definition of the Neighborhood
class Neighborhood(City):'
def __init__(self, id_neighborhood, name_neighborhood, number_block, *city_args, **kwargs):
City.__init__(self, *city_args, **kwargs)
self.__id = id_neighborhood
self.__name = name_neighborhood
self.__number = number_block
Definition of the Block
class Block(Neighborhood):
def __init__(self, id_block, number_block, number_flats, *neighborhood_args, **kwargs):
Neighborhood.__init__(*neighborhood_args, **kwargs)
self.__id = id_block
self.__number_b = number_block
self.__number_f = number_flats
Now i declare a entities:
city = City(5, "New York")
neighborhood = Neighborhood(1, "Brooklyn", 500, 5, "New York")
block = Block(11, 2, 20 1, "Brooklyn", 500, 5, "New York")
And the error is this:
AttributeError: 'int' object has no attribute '_City__id' | 0debug |
static void multiwrite_user_cb(MultiwriteCB *mcb)
{
int i;
for (i = 0; i < mcb->num_callbacks; i++) {
mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
qemu_free(mcb->callbacks[i].free_qiov);
qemu_free(mcb->callbacks[i].free_buf);
}
}
| 1threat |
Gson: parameter get serialised even though it has @Expose(serialize = false) : <p>I'm writing an SDK for a JSON API and I'm running into a seemingly weird problem. The API is quite strict in it's POST data validation and it does not allow certain parameters to be present when updating resources, like an <code>id</code>. For this reason, I added <code>@Expose(serialize = false)</code> the ID field of my resource class. It seems however, that it still serializes this field, causing the request to be rejected. The resource class roughly is as follows:</p>
<pre><code>public class Organisation extends BaseObject
{
public static final Gson PRETTY_PRINT_JSON = new GsonBuilder()
.setPrettyPrinting()
.create();
@Expose(serialize = false)
@SerializedName("_id")
private String id;
@SerializedName("email")
private String email;
@SerializedName("name")
private String name;
@SerializedName("parent_id")
private String parentId;
public String toJson()
{
return PRETTY_PRINT_JSON.toJson(this);
}
}
</code></pre>
<p>My unit tests create an instance of <code>Organisation</code> via the API, saves the newly created instance to the test class as a class parameter and calls an update method that will test the update implementation of the SDK by updating the new resource. This is where it goes wrong. Even though the <code>toJson()</code> method is called on the new <code>Organisation</code> to serialise it to JSON for the update request, the <code>_id</code> field remains present, causing the API to decline the update. The test code is as follows. Notice the comments in the code.</p>
<pre><code>@Test
public void testCreateUpdateAndDeleteOrganisation() throws RequestException
{
Organisation organisation = new Organisation();
organisation.setParentId(this.ORGANISATION_ID);
organisation.setName("Java Test Organisation");
Organisation newOrganisation = this.MySDK.organisation.create(organisation);
this.testOrganisation(newOrganisation);
this.newOrganisation = newOrganisation;
this.testUpdateOrganisation();
}
public void testUpdateOrganisation() throws RequestException
{
// I tried setting ID to null, but that doesn't work either
// even though I've set Gson to not serialise null values
this.newOrganisation.setId(null);
this.newOrganisation.setName(this.newName);
// For debugging
System.out.println(this.newOrganisation.toJson());
Organisation updatedOrganisation = this.MySDK.organisation.update(this.newOrganisation.getId(), this.newOrganisation);
this.testOrganisation(updatedOrganisation);
assertEquals(newOrganisation.getName(), this.newName);
this.testDeleteOrganisation();
}
</code></pre>
<p>Can anyone spot what I'm doing wrong? I have a feeling it has something to do with the fact that the instance already has/had a value for ID, but that shouldn't matter if I explicity tell it not to serialise it right?</p>
<p>Thanks in advance for the help.</p>
<p>EDIT: At <code>this.MySDK.organisation.update(this.newOrganisation.getId(), this.newOrganisation);</code>, that does not edit the organisation instance. The given ID is merely added to the URL that the SDK will POST to (<code>POST /organisation/{id}</code>)</p>
| 0debug |
void helper_ldl_kernel(uint64_t t0, uint64_t t1)
{
ldl_kernel(t1, t0);
}
| 1threat |
static void boston_lcd_write(void *opaque, hwaddr addr,
uint64_t val, unsigned size)
{
BostonState *s = opaque;
switch (size) {
case 8:
s->lcd_content[(addr + 7) & 0x7] = val >> 56;
s->lcd_content[(addr + 6) & 0x7] = val >> 48;
s->lcd_content[(addr + 5) & 0x7] = val >> 40;
s->lcd_content[(addr + 4) & 0x7] = val >> 32;
case 4:
s->lcd_content[(addr + 3) & 0x7] = val >> 24;
s->lcd_content[(addr + 2) & 0x7] = val >> 16;
case 2:
s->lcd_content[(addr + 1) & 0x7] = val >> 8;
case 1:
s->lcd_content[(addr + 0) & 0x7] = val;
break;
}
qemu_chr_fe_printf(&s->lcd_display,
"\r%-8.8s", s->lcd_content);
}
| 1threat |
How to extract values from a row based on special charater : Please help to achieve below output
COLUMN value:-
Document Name for File: Updated from Q1 - answer to Q1 - answer (Abhi up)); Version: Updated from V5.2 to V5.7;Updated from No to Yes
Required output:-
Document Name for File: Updated from Q1 - answer to Q1 - answer (Abhi up))
Version: Updated from V5.2 to V5.7
Updated from No to Yes
| 0debug |
CSS selector inside a specific class : <p>Hi I wonder if I can select a class specifically by its parents.</p>
<pre><code> <div class="naomi">
<div class="pic01">
<div class="pic02">
<div class="pic05"></div>
</div>
</div>
</div>
<div class="teddy">
<div class="pic01">
<div class="pic05"></div>
</div>
</div>
</code></pre>
<p>is there a way to select class "pic05" only from class "naomi" without going in order inside like this
.naomi .pic01 pic02 .pic05 </p>
<p>Thank you</p>
| 0debug |
is there is function for image view that when we press the image button it should show and if we realise button the previous image should show? : <p>i am developing one walkie talkie app in that i am using walkie talkie image button. when i click on that image it should show the different image and when realise that button it should show the previous image . bellow code walk1 first image and walk2 is second image which should see when image button is clicked </p>
<p>,,,</p>
<pre><code>walk1=findViewById(R.id.walky)
walk2=findViewById(R.id.walky1)
walk1?.setOnLongClickListener {
walk2?.visibility=View.VISIBLE
true // Don't consume event, if return false. Consume event if true.
}
walk2?.setOnClickListener {
walk2?.visibility=View.GONE
}
</code></pre>
<p>,,,
in this code its showing second image but when i realised button its not showing first image when i click again that time its showing </p>
| 0debug |
Can anyone explain this code to me in plain english? Thanks : - the output is
- 1
- 2
- 3
int i, j, ans;
for (i = 1; i <= 3; i++)
{
for (j = i; j > 0; j--)
{
ans = i * j;
System.out.print(ans);
}
System.out.println();
}
| 0debug |
How do I get the amount of numbers in a string? : <p>I currently have a text input in my HTML document and some buttons below it. When pressed, these will run a function <strong>input(some number)</strong>. I have added a feature to the function that prevents the length of the string for the input from being above 5. However, sometimes the string (<strong>currentAnswer</strong>) will be set to something like <em>-768.</em>. When this happens, the function will not let you enter any more numbers, when instead you should be able to enter 2 more digits. So how would I find the length of just the <strong>numbers</strong> in a string? Here is my code:</p>
<pre><code>function input(num) {
currentAnswer = document.getElementById("answerBox").value;
answerLength = currentAnswer.length;
if (answerLength < 5) {
document.getElementById("answerBox").value = currentAnswer + num;
answerLength = answerLength + 1;
}}
</code></pre>
<p>As you can see, I am using <strong>currentAnswer.length</strong> to get the length of the string. But I only want the amount of digits. Can someone please help me?</p>
| 0debug |
throw error inside rxjs Observable : <p>I'm trying to throw an error inside a rxjs Observable</p>
<pre><code> new Observable(subscriber => {
Observable.throw("error1");
return Observable.throw("error2");
})
.subscribe(
() => {},
err => console.error(err)
);
</code></pre>
<p>error 1 is not caught.</p>
<p>error2 gives a compilation error:</p>
<pre><code>Argument of type '(this: Observable<{}>, subscriber: Subscriber<{}>) => ErrorObservable<string>' is not assignable to parameter of type '(this: Observable<{}>, subscriber: Subscriber<{}>) => TeardownLogic'. Type 'ErrorObservable<string>' is not assignable to type 'TeardownLogic'
</code></pre>
<p>what is the proper way to throw an error inside an observable?</p>
| 0debug |
How to disable Vuetify button without changing colors : <p>I'm using Vuetify's <a href="https://vuetifyjs.com/en/components/buttons" rel="noreferrer">v-btn</a> button component with a variety of colors set via the <code>color</code> prop. Once a user clicks the button, I set <code>disabled</code> to <code>true</code> so they can't click it again, but the button loses its color and gets greyed out.</p>
<p>Is there any way to disable the button without changing its color to grey?</p>
| 0debug |
def min_val(listval):
min_val = min(i for i in listval if isinstance(i, int))
return min_val | 0debug |
static uint32_t get_elf_hwcap(void)
{
ARMCPU *cpu = ARM_CPU(thread_cpu);
uint32_t hwcaps = 0;
hwcaps |= ARM_HWCAP_ARM_SWP;
hwcaps |= ARM_HWCAP_ARM_HALF;
hwcaps |= ARM_HWCAP_ARM_THUMB;
hwcaps |= ARM_HWCAP_ARM_FAST_MULT;
#define GET_FEATURE(feat, hwcap) \
do { if (arm_feature(&cpu->env, feat)) { hwcaps |= hwcap; } } while (0)
GET_FEATURE(ARM_FEATURE_V5, ARM_HWCAP_ARM_EDSP);
GET_FEATURE(ARM_FEATURE_VFP, ARM_HWCAP_ARM_VFP);
GET_FEATURE(ARM_FEATURE_IWMMXT, ARM_HWCAP_ARM_IWMMXT);
GET_FEATURE(ARM_FEATURE_THUMB2EE, ARM_HWCAP_ARM_THUMBEE);
GET_FEATURE(ARM_FEATURE_NEON, ARM_HWCAP_ARM_NEON);
GET_FEATURE(ARM_FEATURE_VFP3, ARM_HWCAP_ARM_VFPv3);
GET_FEATURE(ARM_FEATURE_V6K, ARM_HWCAP_ARM_TLS);
GET_FEATURE(ARM_FEATURE_VFP4, ARM_HWCAP_ARM_VFPv4);
GET_FEATURE(ARM_FEATURE_ARM_DIV, ARM_HWCAP_ARM_IDIVA);
GET_FEATURE(ARM_FEATURE_THUMB_DIV, ARM_HWCAP_ARM_IDIVT);
GET_FEATURE(ARM_FEATURE_VFP3, ARM_HWCAP_ARM_VFPD32);
GET_FEATURE(ARM_FEATURE_LPAE, ARM_HWCAP_ARM_LPAE);
#undef GET_FEATURE
return hwcaps;
}
| 1threat |
JS : Search a json object from a list with its partial attribute value : i have a list object which i load from a web service , my list comes in this form :
list = [ {id:"name1 Surname1" , nb:120} ,
{id:"name2", nb:632} ,
{id:"name3Surname3", nb:102} ,
{id:"surname4", nb:896}
]
My searaching stretagei is to going by **"id"**
As you can see i have different formats :
separated name-surname with space , only name , only surname .
My purpose is to search member by id (its name or surname values) ;
My result should be items whose IDS are containing my searched value item .
**For example :**
- If i search for : "name1" -> **result** : name1 Surname1
- If i search for : "name1 Surn" -> **result** : name1 Surname1
- If i search for : "name1 SurAAA" -> **result** : (nothing)
- If i search for : "AAAA Surname1" -> **result** : (nothing)
- If i search for : "name1Surname1" -> **result** : (nothing)
- If i search for : "name" -> **result** : name1 Surname1 , name2 , name3Surname3 , surname4
***To summarize :***
i should search items:
- corresponding for my searched item
- beginning with my searched item
I have tried the **filter** solution , like the following :
findItems(name) {
this.splits = name.toLowerCase().split(' ');
if (this.splits.length >= 1) {
results = this.namesList.filter(item => this.splits.indexOf(item.brand.toLowerCase()) !== -1);
}else {
results = [];
}
}
But this solution is only searching for items corresponding **exactly** to my searched item , and it lacks the **partial search**
**Suggestions ?**
| 0debug |
Why any thread can unlock a semaphore? : I can not understand how Posix allows any thread to unlock (post) on a semaphore. Let's consider following example:
// sem1 and sem2 are a Posix semaphore,
// properly initialized for single process use
// at this point, sem2 is locked, sem1 is unlocked
// x and y are global (non-atomic, non-volatile) integer variables
// thread 1 - is executing right now
rc = sem_wait(&sem); // succeeded, semaphore is 0 now
x = 42;
y = 142;
sem_post(&sem2);
while (true);
// thread 2. waits for sem2 to be unlocked by thread1
sem_wait(&sem2);
sem_post(&sem1);
// thread 3
sem_wait(&sem1); // wakes up when sem1 is unlocked by thread2
#ifdef __cplusplus
std::cout << "x: " << x << ; y: " << y << "\n";
#else
printf("x: %d; y: %d\n", x, y);
#endif
Now, according to everything I've read, this code is 100% kosher for passover. In thread 3, we are guaranteed to see `x` as 42, `y` as 142. We are proteced from any race.
But this is what I can't understand. All those threads can potentially be executed on 3 different cores. And if the chip doesn't have internally strong memory ordering (ARM, PowerPC) or writes are not-atomic (x86 for unaligned data) how can thread2 on Core2 possibly request Core1 (busy with thread1) to properly release the data / complete writes / etc? As far as I know, there are no such commands!
What I am missing here?
| 0debug |
uint64_t cpu_tick_get_count(CPUTimer *timer)
{
uint64_t real_count = timer_to_cpu_ticks(
qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) - timer->clock_offset,
timer->frequency);
TIMER_DPRINTF("%s get_count count=0x%016lx (%s) p=%p\n",
timer->name, real_count,
timer->disabled?"disabled":"enabled", timer);
if (timer->disabled)
real_count |= timer->disabled_mask;
return real_count;
}
| 1threat |
CsvHelper Ignore case for header names : <p>I have some class </p>
<pre><code> public class Import
{
public DateTime Date { get; set; }
public string Category { get; set; }
}
</code></pre>
<p>In csv file header names can be in lowercase.
How I can ignore case while reading file?</p>
<pre><code> var reader = new StreamReader(@"///");
var csv = new CsvReader(reader);
var records = csv.GetRecords<Import>().ToList();
</code></pre>
| 0debug |
Disable WKWebView for opening links to redirect to apps installed on my iPhone : <p>When I'm searching google and click on Etsy.com for exmaple, WKWebView redirect me to Etsy app installed on my iPhone.
How can I disable this behavior? I want WKWebView to redirect me to etsy.com mobile website.
I'm using swift.</p>
| 0debug |
How to find length of a filename? : <p>I wished to find maximum length of filename from a given set of filenames and was using the following code for the purpose:</p>
<pre><code>int Max_FnLen=strlen(files[0]->d_name);
for (i=1;i<count-1;i++)
{
if(strlen(files[i]->d_name)>strlen(files[i-1]->d_name))
{
Max_FnLen=strlen(files[i]->d_name);
}
}
</code></pre>
<p>But it is not giving the desired output can anyone help me with this</p>
<p>Thank You! </p>
| 0debug |
Explode numerical range (e.g. '6-14') in Javascript : <p>I have a string representation of a numerical range</p>
<pre><code>var range = '6-14';
</code></pre>
<p>I want to create an array of integers represented by this range</p>
<pre><code>[6,7,8,9,10,11,12,13,14]
</code></pre>
<p>I could implement this simple enough as a <code>for</code> loop but that seems like a clunky, brute force method. Can this be done in a short or more elegant way?</p>
| 0debug |
static void vga_screen_dump(void *opaque, const char *filename)
{
VGAState *s = (VGAState *)opaque;
if (!(s->ar_index & 0x20))
vga_screen_dump_blank(s, filename);
else if (s->gr[6] & 1)
vga_screen_dump_graphic(s, filename);
else
vga_screen_dump_text(s, filename);
}
| 1threat |
Copy values from an object array into a new array : <p>I have the following array of objects:</p>
<pre><code> names: [
{
"first": "Bob",
"last": "Newhart"
},
{
"first": "Jerry",
"last": "Seinfeld"
},
{
"first": "Oprah",
"last": "Winfrey"
}
]
</code></pre>
<p>I want to convert this into a simple array that looks like this:</p>
<pre><code>names: [ "Bob Newhart", "Jerry Seinfeld", "Oprah Winfrey"]
</code></pre>
<p>What is the proper way to do this in JavaScript?</p>
| 0debug |
how can i convert thid date 03/01/2018 12:00 AM to 2018-03-01 in c# : i am using this code to convert a date 03/01/2018 12:00 AM to 2018-03-01 in c#
DateTime startDate = DateTime.ParseExact(TextBox1.Text.ToString(),"yyyy-mm-dd",System.Globalization.CultureInfo.InvariantCulture);
but it throw exception "string was not recognized as valid datetime" | 0debug |
Template parse errors: 'mat-icon' is not a known element : <p>I'm working with Angular CLI and angular material v.5.2.5
and trying to use </p>
<blockquote>
<p>mat-icon-button</p>
</blockquote>
<p>but such an error produced by the console:</p>
<blockquote>
<p>Uncaught Error: Template parse errors: 'mat-icon' is not a known
element...</p>
</blockquote>
<p>if I use </p>
<blockquote>
<p>mat-raised-button</p>
</blockquote>
<p>everything works fine
cannot figure out how to solve that</p>
<p>index.html</p>
<pre><code> <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Todo</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic"
rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<app-root></app-root>
</body>
</html>
</code></pre>
<p>main.ts</p>
<pre><code> import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
</code></pre>
<p>app.module.ts</p>
<pre><code> import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { MatButtonModule } from '@angular/material/button';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
MatButtonModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>
| 0debug |
static int dxva2_device_create9ex(AVHWDeviceContext *ctx, UINT adapter)
{
DXVA2DevicePriv *priv = ctx->user_opaque;
D3DPRESENT_PARAMETERS d3dpp = dxva2_present_params;
D3DDISPLAYMODEEX modeex = {0};
IDirect3D9Ex *d3d9ex = NULL;
IDirect3DDevice9Ex *exdev = NULL;
HRESULT hr;
pDirect3DCreate9Ex *createD3DEx = (pDirect3DCreate9Ex *)dlsym(priv->d3dlib, "Direct3DCreate9Ex");
if (!createD3DEx)
return AVERROR(ENOSYS);
hr = createD3DEx(D3D_SDK_VERSION, &d3d9ex);
if (FAILED(hr))
return AVERROR_UNKNOWN;
IDirect3D9Ex_GetAdapterDisplayModeEx(d3d9ex, adapter, &modeex, NULL);
d3dpp.BackBufferFormat = modeex.Format;
hr = IDirect3D9Ex_CreateDeviceEx(d3d9ex, adapter, D3DDEVTYPE_HAL, GetDesktopWindow(),
FF_D3DCREATE_FLAGS,
&d3dpp, NULL, &exdev);
if (FAILED(hr)) {
IDirect3D9Ex_Release(d3d9ex);
return AVERROR_UNKNOWN;
}
av_log(ctx, AV_LOG_VERBOSE, "Using D3D9Ex device.\n");
priv->d3d9 = (IDirect3D9 *)d3d9ex;
priv->d3d9device = (IDirect3DDevice9 *)exdev;
return 0;
}
| 1threat |
Java : find all combinations of strings character by character : If I have for instance
CAT,
In JAVA, I want all possible combinations of characters with 1 character change at a time (excluding the combination CAT):
AAT
BAT
DAT
EAT
.
.
.
ZAT
CBT
CCT
CDT
.
.
.
CZT
CAA
CAB
CAC
.
.
.
CAZ
| 0debug |
How to use yarn to install bootstrap 4 - libsass libraries : <p>I'm trying to use yarn for my latest project. How to install bootstrap 4 - libsass libraries using yarn</p>
| 0debug |
static int xen_pt_exp_rom_bar_reg_write(XenPCIPassthroughState *s,
XenPTReg *cfg_entry, uint32_t *val,
uint32_t dev_value, uint32_t valid_mask)
{
XenPTRegInfo *reg = cfg_entry->reg;
XenPTRegion *base = NULL;
PCIDevice *d = (PCIDevice *)&s->dev;
uint32_t writable_mask = 0;
uint32_t throughable_mask = get_throughable_mask(s, reg, valid_mask);
pcibus_t r_size = 0;
uint32_t bar_ro_mask = 0;
r_size = d->io_regions[PCI_ROM_SLOT].size;
base = &s->bases[PCI_ROM_SLOT];
r_size = xen_pt_get_emul_size(base->bar_flag, r_size);
bar_ro_mask = (reg->ro_mask | (r_size - 1)) & ~PCI_ROM_ADDRESS_ENABLE;
writable_mask = ~bar_ro_mask & valid_mask;
cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);
*val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);
return 0;
}
| 1threat |
Change <p> tag by user input forever : <p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="index.php" method="post">
<input type="text" name="content" style="font-size: 25px" placeholder="Name of content"> //The text for p tag
</form>
<p></p> //display the inputted text above right HERE</code></pre>
</div>
</div>
</p>
<p>Hey,</p>
<p>I need to make simple thing. Make an input on a website, and under it, make a <code><p></code> tag. Whatever user inputs to this label/input, it will write that between the <code><p></code> tag. I know, that there is way in javascript, but i need to make it change forever, that means, when i refresh the page, it will be there, the same message forever. Any way to make it? Better to make it NOT using cross-database systém (in PhP)...</p>
<p>Please help</p>
| 0debug |
How to generate alert when clicking Submit button, only when the html form is full using Javascript : <p>I have this html form with many forms of elements. I need to generate the alert "Thank you for your time! Your details have been submitted!" once the submit button is clicked, only when the form is full. When the form is empty I do not want to see this message. So far I've been using onClick event. Can someone please help me on this (I'm trying to implement this using Javascript)</p>
<p>Here's the Javascript code and HTML body</p>
<pre><code><html>
<head>
<title>JS Validation for other types of form input fields</title>
<script type="text/javascript">
function submitClick( ) //function shows message after submitting information
{
alert("Thank you for your time! Your details have been submitted!");
}
function formValidation ( )
{
flag = true;
if (document.myForm.user_name.value == "" )
{
alert ( "Please fill in your Name!" );
flag = false;
}
// Validate letters only as Name
if (!/^[a-zA-Z]*$/g.test(document.myForm.user_name.value))
{
alert("Enter alphabetic characters as Name!");
flag = false;
}
// Validate emails
if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)* (\.\w{2,3})+$/.test(myForm.user_email.value)) //Regular expressions to validate email
{
alert("Enter Valid Email Address!");
flag = false;
}
// Validate Phone number
flag = true;
if (document.myForm.user_phone.value == "" )
{
alert ( "Please fill in your Phone Number!" );
flag = false;
}
if (!/^[0-9]*$/g.test(myForm.user_phone.value))
{
alert("Enter numeric values as Phone Number!");
flag = false;
}
if ((document.myForm.userGender[0].checked == false) && (document.myForm.userGender[1].checked == false ) )
{
alert ( "Please select your gender!" );
flag = false;
}
if (document.myForm.userAge.selectedIndex == 0 )
{
alert ( "Please select your Age from the drop-down list!" );
flag=false;
}
if (document.myForm.termsAndConditions.checked == false )
{
alert ( "Please check the Terms and Conditions box!" );
flag= false;
}
return flag;
}
</script>
</head>
<body bgcolor = "#FFFFFF">
<form name="myForm" method="post" onSubmit=" return formValidation( );">
<h1>Please fill out your details below:</h1>
<p>Name: <input type="text" name="user_name"></p>
<p>Email: <input type="text" name="user_email"></p>
<p>Phone: <input type="text" name="user_phone"></p>
<p>Gender: <input type="radio" name="userGender" value="Male">Male
&nbsp; <input type="radio" name="userGender" value="Female">Female</p>
<p>Age:
<select name="userAge">
<option value="">Please select your age:</option>
<option value="0-17 years">0-17 years</option>
<option value="18-29 years">18-29 years</option>
<option value="30-40 years">30-40 years</option>
<option value="40-64 years">40-64 years</option>
<option value="65+ years">65+ years</option>
</select>
<p>Please tick the checkbox if you agree with our Terms and Conditions:
<input type="checkbox" name="termsAndConditions" value="Yes"> Yes
<p><input type="submit" name="send" value="Submit Details" onClick="submitClick( )"></p>
</form>
</body>
</html>
</code></pre>
| 0debug |
void hmp_info_migrate(Monitor *mon, const QDict *qdict)
{
MigrationInfo *info;
MigrationCapabilityStatusList *caps, *cap;
info = qmp_query_migrate(NULL);
caps = qmp_query_migrate_capabilities(NULL);
if (info->has_status && caps) {
monitor_printf(mon, "capabilities: ");
for (cap = caps; cap; cap = cap->next) {
monitor_printf(mon, "%s: %s ",
MigrationCapability_lookup[cap->value->capability],
cap->value->state ? "on" : "off");
}
monitor_printf(mon, "\n");
}
if (info->has_status) {
monitor_printf(mon, "Migration status: %s\n",
MigrationStatus_lookup[info->status]);
monitor_printf(mon, "total time: %" PRIu64 " milliseconds\n",
info->total_time);
if (info->has_expected_downtime) {
monitor_printf(mon, "expected downtime: %" PRIu64 " milliseconds\n",
info->expected_downtime);
}
if (info->has_downtime) {
monitor_printf(mon, "downtime: %" PRIu64 " milliseconds\n",
info->downtime);
}
if (info->has_setup_time) {
monitor_printf(mon, "setup: %" PRIu64 " milliseconds\n",
info->setup_time);
}
}
if (info->has_ram) {
monitor_printf(mon, "transferred ram: %" PRIu64 " kbytes\n",
info->ram->transferred >> 10);
monitor_printf(mon, "throughput: %0.2f mbps\n",
info->ram->mbps);
monitor_printf(mon, "remaining ram: %" PRIu64 " kbytes\n",
info->ram->remaining >> 10);
monitor_printf(mon, "total ram: %" PRIu64 " kbytes\n",
info->ram->total >> 10);
monitor_printf(mon, "duplicate: %" PRIu64 " pages\n",
info->ram->duplicate);
monitor_printf(mon, "skipped: %" PRIu64 " pages\n",
info->ram->skipped);
monitor_printf(mon, "normal: %" PRIu64 " pages\n",
info->ram->normal);
monitor_printf(mon, "normal bytes: %" PRIu64 " kbytes\n",
info->ram->normal_bytes >> 10);
monitor_printf(mon, "dirty sync count: %" PRIu64 "\n",
info->ram->dirty_sync_count);
if (info->ram->dirty_pages_rate) {
monitor_printf(mon, "dirty pages rate: %" PRIu64 " pages\n",
info->ram->dirty_pages_rate);
}
}
if (info->has_disk) {
monitor_printf(mon, "transferred disk: %" PRIu64 " kbytes\n",
info->disk->transferred >> 10);
monitor_printf(mon, "remaining disk: %" PRIu64 " kbytes\n",
info->disk->remaining >> 10);
monitor_printf(mon, "total disk: %" PRIu64 " kbytes\n",
info->disk->total >> 10);
}
if (info->has_xbzrle_cache) {
monitor_printf(mon, "cache size: %" PRIu64 " bytes\n",
info->xbzrle_cache->cache_size);
monitor_printf(mon, "xbzrle transferred: %" PRIu64 " kbytes\n",
info->xbzrle_cache->bytes >> 10);
monitor_printf(mon, "xbzrle pages: %" PRIu64 " pages\n",
info->xbzrle_cache->pages);
monitor_printf(mon, "xbzrle cache miss: %" PRIu64 "\n",
info->xbzrle_cache->cache_miss);
monitor_printf(mon, "xbzrle cache miss rate: %0.2f\n",
info->xbzrle_cache->cache_miss_rate);
monitor_printf(mon, "xbzrle overflow : %" PRIu64 "\n",
info->xbzrle_cache->overflow);
}
if (info->has_cpu_throttle_percentage) {
monitor_printf(mon, "cpu throttle percentage: %" PRIu64 "\n",
info->cpu_throttle_percentage);
}
qapi_free_MigrationInfo(info);
qapi_free_MigrationCapabilityStatusList(caps);
}
| 1threat |
What is the difference between drawing plots using plot, axes or figure in matplotlib? : <p>I'm kind of confused what is going at the backend when I draw plots in matplotlib, tbh, I'm not clear with the hierarchy of plot, axes and figure. I read the documentation and it was helpful but I'm still confused...</p>
<p>The below code draws the same plot in three different ways - </p>
<pre><code>#creating the arrays for testing
x = np.arange(1, 100)
y = np.sqrt(x)
#1st way
plt.plot(x, y)
#2nd way
ax = plt.subplot()
ax.plot(x, y)
#3rd way
figure = plt.figure()
new_plot = figure.add_subplot(111)
new_plot.plot(x, y)
</code></pre>
<p>Now my question is -</p>
<ol>
<li><p>What is the difference between all the three, I mean what is going under the hood when any of the 3 methods are called? </p></li>
<li><p>Which method should be used when and what are the pros and cons of using any on those? </p></li>
</ol>
| 0debug |
pylint false positive E0401 import errors in vscode while using venv : <p>I created a venv using python3.6 on my mac os in this folder
<code>/Users/kim/Documents/Apps/PythonApps/python36-miros-a3</code></p>
<p>I ran a <code>pip install pylint</code> after I activated the virtual env</p>
<p>My workspace is in <code>/Users/kim/Documents/Apps/WebApps/miros-a3</code></p>
<p>Inside my vscode workspace, I have the following Workspace settings</p>
<pre><code>{
"folders": [
{
"path": "."
}
],
"settings": {
"python.pythonPath": "/Users/kim/Documents/Apps/PythonApps/python36-miros-a3/bin/python3.6",
"python.venvPath": "/Users/kim/Documents/Apps/PythonApps"
}
}
</code></pre>
<p>I have tried setting a custom path for the pylint and also changing the venvpath.</p>
<p>The pylint kept complaining about the import statement saying it does not exist.</p>
<p><a href="https://i.stack.imgur.com/3h7LR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3h7LR.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/9gs8b.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9gs8b.png" alt="enter image description here"></a></p>
<p>As you can see, they are in the same folder, and I can definitely execute my python files.</p>
<p>What can I do to avoid these kind of false positive import errors?</p>
<p>I have also tried the following:</p>
<ol>
<li>go to commandline turn on the virtual env and then type <code>code</code> to activate the vscode as recommended here <a href="https://code.visualstudio.com/docs/setup/mac" rel="noreferrer">https://code.visualstudio.com/docs/setup/mac</a></li>
<li>also tried this <a href="https://donjayamanne.github.io/pythonVSCodeDocs/docs/troubleshooting_linting/" rel="noreferrer">https://donjayamanne.github.io/pythonVSCodeDocs/docs/troubleshooting_linting/</a></li>
</ol>
| 0debug |
static int write_memory(DumpState *s, RAMBlock *block, ram_addr_t start,
int64_t size)
{
int64_t i;
int ret;
for (i = 0; i < size / TARGET_PAGE_SIZE; i++) {
ret = write_data(s, block->host + start + i * TARGET_PAGE_SIZE,
TARGET_PAGE_SIZE);
if (ret < 0) {
return ret;
}
}
if ((size % TARGET_PAGE_SIZE) != 0) {
ret = write_data(s, block->host + start + i * TARGET_PAGE_SIZE,
size % TARGET_PAGE_SIZE);
if (ret < 0) {
return ret;
}
}
return 0;
}
| 1threat |
Switch to linux root account in executing c++ binary with password, POSSIBLE? : To All,
I am trying to copy some files to a root user from a user with very low (almost no privileges). I need to allow someone with access to the low account copy some files onto the higher account. I have thought about using a bin/bash script, but don't want any password in the file to be viewed.
I decided to create a c++ application that has the password of the account I would like pass to the su/setuid commands. I do know the password can be viewed in the binary, but is not a concern. The password not in plain text is sufficient.
My problem is that I cannot figure out how to "login" as the user I need to update files for a service running in that account. I have the user account name, which is localadmin, and the password for that account. But how do I pass these to linux to copy the files to the localadmin account home/subdirectory from the c++ application?
I have tried in c++:
**system("su localadmin");** // This prompts for password, but not sure how to pass the password.
**setuid(0);** // Again, where do I pass the password to get the account privileges? All I get is an "operation not permitted".
I apologize if this is an easy question. Just trying to run the commands as localadmin and be done.
Thanks for any help you can provide. | 0debug |
Why not just use random_device? : <p>I am a bit confused about the c++11 random library.</p>
<p>What I understand: we need two separate concepts:</p>
<ul>
<li>random engine (which can be pseudo (need seed) or real)</li>
<li>distribution: it maps the numbers obtained from the engine to a specific interval, using a specific distribution.</li>
</ul>
<p>What I don't understand is why not just use this:</p>
<pre><code>std::random_device rd;
std::uniform_int_distribution<int> dist(1, 5);
// get random numbers with:
dist(rd);
</code></pre>
<p>As far as I can tell this works well.</p>
<p>Instead, this is what I found on most examples/sites/articles:</p>
<pre><code>std::random_device rd;
std::mt19937 e{rd()}; // or std::default_random_engine e{rd()};
std::uniform_int_distribution<int> dist{1, 5};
// get random numbers with:
dist(e);
</code></pre>
<p>I am not talking about special use, e.g. cryptography, just your basic getting started articles.</p>
<p>My suspicion is because <code>std::mt19937</code> (or <code>std::default_random_engine</code>) accepts a seed, it can be easier to debug by providing the same seed during a debug session.</p>
<p>Also, why not just:</p>
<pre><code>std::mt19937 e{std::random_device{}()};
</code></pre>
| 0debug |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.