problem stringlengths 26 131k | labels class label 2 classes |
|---|---|
I can't run my phonegap app on mobile? : [![after i write command ionic -run --device android ,this problem in picture appear to me
my phone LG android v 4.0.4 + I enable developer option ,I can't know problem .[1]][1]
[1]: http://i.stack.imgur.com/KDCuk.jpg | 0debug |
How to set app settings without save in c# : <p>We want to develop an application that gets the configuration items from a json file and stores the key&values at ConfigurationManager.AppSettings. But AppSettings dictionary is readonly.
We <strong>don't</strong> want to update or save the app.config file. This operation have to be at memory. Is there any way to do this?</p>
| 0debug |
How global scope works in javascript : <pre><code> var a = 10
function fun(){
var b = 20
}
fun()
</code></pre>
<p>In this code var a has global scope but var b dont have global scope but functional scope. But as fun() itself is global function which will be global to everywhere why var b is not global</p>
| 0debug |
i was trying to change the color of the background, but i can't : from tkinter import*
master = Tk()
master.configure(background=blue)
def exit():
quit()
b = Button(master, text="Quit", command=exit)
b.pack()
mainloop() | 0debug |
static inline int handle_cpu_signal(unsigned long pc, unsigned long address,
int is_write, sigset_t *old_set)
{
TranslationBlock *tb;
int ret;
uint32_t found_pc;
#if defined(DEBUG_SIGNAL)
printf("qemu: SIGSEGV pc=0x%08lx address=%08lx wr=%d oldset=0x%08lx\n",
pc, address, is_write, *(unsigned long *)old_set);
#endif
if (is_write && page_unprotect(address)) {
return 1;
}
tb = tb_find_pc(pc);
if (tb) {
ret = cpu_x86_search_pc(tb, &found_pc, pc);
if (ret < 0)
return 0;
env->eip = found_pc - tb->cs_base;
env->cr2 = address;
sigprocmask(SIG_SETMASK, old_set, NULL);
raise_exception_err(EXCP0E_PAGE, 4 | (is_write << 1));
return 1;
} else {
return 0;
}
}
| 1threat |
What causes a char to be signed or unsigned when using gcc? : <p>What causes if a <code>char</code> in C (using gcc) is signed or unsigned? I know that the standard doesn't dictate one over the other and that I can check <code>CHAR_MIN</code> and <code>CHAR_MAX</code> from limits.h but I want to know what triggers one over the other when using gcc</p>
<p>If I read limits.h from libgcc-6 I see that there is a macro <code>__CHAR_UNSIGNED__</code> which defines a "default" char signed or unsigned but I'm unsure if this is set by the compiler at (his) built time.</p>
<p>I tried to list GCCs predefined makros with</p>
<pre><code>$ gcc -dM -E -x c /dev/null | grep -i CHAR
#define __UINT_LEAST8_TYPE__ unsigned char
#define __CHAR_BIT__ 8
#define __WCHAR_MAX__ 0x7fffffff
#define __GCC_ATOMIC_CHAR_LOCK_FREE 2
#define __GCC_ATOMIC_CHAR32_T_LOCK_FREE 2
#define __SCHAR_MAX__ 0x7f
#define __WCHAR_MIN__ (-__WCHAR_MAX__ - 1)
#define __UINT8_TYPE__ unsigned char
#define __INT8_TYPE__ signed char
#define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
#define __CHAR16_TYPE__ short unsigned int
#define __INT_LEAST8_TYPE__ signed char
#define __WCHAR_TYPE__ int
#define __GCC_ATOMIC_CHAR16_T_LOCK_FREE 2
#define __SIZEOF_WCHAR_T__ 4
#define __INT_FAST8_TYPE__ signed char
#define __CHAR32_TYPE__ unsigned int
#define __UINT_FAST8_TYPE__ unsigned char
</code></pre>
<p>but wasn't able to find <code>__CHAR_UNSIGNED__</code></p>
<p>Background: I've some code which I compile on two different machines:</p>
<p><strong>Desktop PC:</strong></p>
<ul>
<li>Debian GNU/Linux 9.1 (stretch)</li>
<li>gcc version 6.3.0 20170516 (Debian 6.3.0-18)</li>
<li>Intel(R) Core(TM) i3-4150</li>
<li>libgcc-6-dev: 6.3.0-18</li>
<li><code>char</code> is signed</li>
</ul>
<p><strong>Raspberry Pi3</strong>:</p>
<ul>
<li>Raspbian GNU/Linux 9.1 (stretch)</li>
<li>gcc version 6.3.0 20170516 (Raspbian 6.3.0-18+rpi1)</li>
<li>ARMv7 Processor rev 4 (v7l)</li>
<li>libgcc-6-dev: 6.3.0-18+rpi</li>
<li><code>char</code> is unsigned</li>
</ul>
<p>So the only obvious difference is the CPU architecture...</p>
| 0debug |
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, object given laravel : I'm trying to post an image from a one to many relationship while also doing the CRUD (create part), but I am having some trouble doing it. I keep on getting this error,`Type error: Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, object given`, whenever I try to use associate to define the relationship together with user_info with user_image table. I have already used the array function to make it into an array but it still gave me this error. So what should I do?
Here are my codes:
createController:
public function create1(){
return view('create1');
}
public function store1(Request $request){
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user_info = Session::get('data');
$UserImage = new UserImage($request->input()) ;
if($file = $request->hasFile('input_img')) {
$file = array();
$file = $request->file('input_img') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/images' ;
$file->move($destinationPath,$fileName);
$UserImage->userImage = $fileName ;
$UserImage = UserImage::create($file);
$UserImage->user_infos()->associate($user_info);
}
$UserImage->save() ;
return redirect('/home');
}
HomeController(this is where I print out my information)
public function getInfo($id) {
$data = personal_info::where('id',$id)->get();
$data3=UserImage::where('user_id',$id)->get();
return view('test',compact('data','data3'));
blade.php (how I show the image in view)
@foreach ($data3 as $object9)
<img width="100" height="100" src="{!! $object9->signature !!}">
@endforeach
UserImage model(in table I used binary format to store in DB)
class UserImage extends Eloquent
{
protected $fillable = array('userImage','user_id');
public function user_infos() {
return $this->belongsTo('App\user_info', 'user_id', 'id');
}
class user_info extends Eloquent
{
protected $fillable = array('Email', 'Name');
protected $table = user_infos';
protected $primaryKey = 'id';
public function UserImages() {
return $this->hasOne('App\UserImage','user_id');
}
}
create1.blade.php(this is how I upload the image)
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input data-preview="#preview" name="input_img" type="file" id="imageInput">
<img class="col-sm-6" id="preview" src="" ></img>
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form> | 0debug |
static void qtest_process_command(CharDriverState *chr, gchar **words)
{
const gchar *command;
g_assert(words);
command = words[0];
if (qtest_log_fp) {
qemu_timeval tv;
int i;
qtest_get_time(&tv);
fprintf(qtest_log_fp, "[R +" FMT_timeval "]",
(long) tv.tv_sec, (long) tv.tv_usec);
for (i = 0; words[i]; i++) {
fprintf(qtest_log_fp, " %s", words[i]);
}
fprintf(qtest_log_fp, "\n");
}
g_assert(command);
if (strcmp(words[0], "irq_intercept_out") == 0
|| strcmp(words[0], "irq_intercept_in") == 0) {
DeviceState *dev;
NamedGPIOList *ngl;
g_assert(words[1]);
dev = DEVICE(object_resolve_path(words[1], NULL));
if (!dev) {
qtest_send_prefix(chr);
qtest_send(chr, "FAIL Unknown device\n");
return;
}
if (irq_intercept_dev) {
qtest_send_prefix(chr);
if (irq_intercept_dev != dev) {
qtest_send(chr, "FAIL IRQ intercept already enabled\n");
} else {
qtest_send(chr, "OK\n");
}
return;
}
QLIST_FOREACH(ngl, &dev->gpios, node) {
if (ngl->name) {
continue;
}
if (words[0][14] == 'o') {
int i;
for (i = 0; i < ngl->num_out; ++i) {
qemu_irq *disconnected = g_new0(qemu_irq, 1);
qemu_irq icpt = qemu_allocate_irq(qtest_irq_handler,
disconnected, i);
*disconnected = qdev_intercept_gpio_out(dev, icpt,
ngl->name, i);
}
} else {
qemu_irq_intercept_in(ngl->in, qtest_irq_handler,
ngl->num_in);
}
}
irq_intercept_dev = dev;
qtest_send_prefix(chr);
qtest_send(chr, "OK\n");
} else if (strcmp(words[0], "outb") == 0 ||
strcmp(words[0], "outw") == 0 ||
strcmp(words[0], "outl") == 0) {
uint16_t addr;
uint32_t value;
g_assert(words[1] && words[2]);
addr = strtoul(words[1], NULL, 0);
value = strtoul(words[2], NULL, 0);
if (words[0][3] == 'b') {
cpu_outb(addr, value);
} else if (words[0][3] == 'w') {
cpu_outw(addr, value);
} else if (words[0][3] == 'l') {
cpu_outl(addr, value);
}
qtest_send_prefix(chr);
qtest_send(chr, "OK\n");
} else if (strcmp(words[0], "inb") == 0 ||
strcmp(words[0], "inw") == 0 ||
strcmp(words[0], "inl") == 0) {
uint16_t addr;
uint32_t value = -1U;
g_assert(words[1]);
addr = strtoul(words[1], NULL, 0);
if (words[0][2] == 'b') {
value = cpu_inb(addr);
} else if (words[0][2] == 'w') {
value = cpu_inw(addr);
} else if (words[0][2] == 'l') {
value = cpu_inl(addr);
}
qtest_send_prefix(chr);
qtest_sendf(chr, "OK 0x%04x\n", value);
} else if (strcmp(words[0], "writeb") == 0 ||
strcmp(words[0], "writew") == 0 ||
strcmp(words[0], "writel") == 0 ||
strcmp(words[0], "writeq") == 0) {
uint64_t addr;
uint64_t value;
g_assert(words[1] && words[2]);
addr = strtoull(words[1], NULL, 0);
value = strtoull(words[2], NULL, 0);
if (words[0][5] == 'b') {
uint8_t data = value;
cpu_physical_memory_write(addr, &data, 1);
} else if (words[0][5] == 'w') {
uint16_t data = value;
tswap16s(&data);
cpu_physical_memory_write(addr, &data, 2);
} else if (words[0][5] == 'l') {
uint32_t data = value;
tswap32s(&data);
cpu_physical_memory_write(addr, &data, 4);
} else if (words[0][5] == 'q') {
uint64_t data = value;
tswap64s(&data);
cpu_physical_memory_write(addr, &data, 8);
}
qtest_send_prefix(chr);
qtest_send(chr, "OK\n");
} else if (strcmp(words[0], "readb") == 0 ||
strcmp(words[0], "readw") == 0 ||
strcmp(words[0], "readl") == 0 ||
strcmp(words[0], "readq") == 0) {
uint64_t addr;
uint64_t value = UINT64_C(-1);
g_assert(words[1]);
addr = strtoull(words[1], NULL, 0);
if (words[0][4] == 'b') {
uint8_t data;
cpu_physical_memory_read(addr, &data, 1);
value = data;
} else if (words[0][4] == 'w') {
uint16_t data;
cpu_physical_memory_read(addr, &data, 2);
value = tswap16(data);
} else if (words[0][4] == 'l') {
uint32_t data;
cpu_physical_memory_read(addr, &data, 4);
value = tswap32(data);
} else if (words[0][4] == 'q') {
cpu_physical_memory_read(addr, &value, 8);
tswap64s(&value);
}
qtest_send_prefix(chr);
qtest_sendf(chr, "OK 0x%016" PRIx64 "\n", value);
} else if (strcmp(words[0], "read") == 0) {
uint64_t addr, len, i;
uint8_t *data;
char *enc;
g_assert(words[1] && words[2]);
addr = strtoull(words[1], NULL, 0);
len = strtoull(words[2], NULL, 0);
data = g_malloc(len);
cpu_physical_memory_read(addr, data, len);
enc = g_malloc(2 * len + 1);
for (i = 0; i < len; i++) {
sprintf(&enc[i * 2], "%02x", data[i]);
}
qtest_send_prefix(chr);
qtest_sendf(chr, "OK 0x%s\n", enc);
g_free(data);
g_free(enc);
} else if (strcmp(words[0], "b64read") == 0) {
uint64_t addr, len;
uint8_t *data;
gchar *b64_data;
g_assert(words[1] && words[2]);
addr = strtoull(words[1], NULL, 0);
len = strtoull(words[2], NULL, 0);
data = g_malloc(len);
cpu_physical_memory_read(addr, data, len);
b64_data = g_base64_encode(data, len);
qtest_send_prefix(chr);
qtest_sendf(chr, "OK %s\n", b64_data);
g_free(data);
g_free(b64_data);
} else if (strcmp(words[0], "write") == 0) {
uint64_t addr, len, i;
uint8_t *data;
size_t data_len;
g_assert(words[1] && words[2] && words[3]);
addr = strtoull(words[1], NULL, 0);
len = strtoull(words[2], NULL, 0);
data_len = strlen(words[3]);
if (data_len < 3) {
qtest_send(chr, "ERR invalid argument size\n");
return;
}
data = g_malloc(len);
for (i = 0; i < len; i++) {
if ((i * 2 + 4) <= data_len) {
data[i] = hex2nib(words[3][i * 2 + 2]) << 4;
data[i] |= hex2nib(words[3][i * 2 + 3]);
} else {
data[i] = 0;
}
}
cpu_physical_memory_write(addr, data, len);
g_free(data);
qtest_send_prefix(chr);
qtest_send(chr, "OK\n");
} else if (strcmp(words[0], "memset") == 0) {
uint64_t addr, len;
uint8_t *data;
uint8_t pattern;
g_assert(words[1] && words[2] && words[3]);
addr = strtoull(words[1], NULL, 0);
len = strtoull(words[2], NULL, 0);
pattern = strtoull(words[3], NULL, 0);
if (len) {
data = g_malloc(len);
memset(data, pattern, len);
cpu_physical_memory_write(addr, data, len);
g_free(data);
}
qtest_send_prefix(chr);
qtest_send(chr, "OK\n");
} else if (strcmp(words[0], "b64write") == 0) {
uint64_t addr, len;
uint8_t *data;
size_t data_len;
gsize out_len;
g_assert(words[1] && words[2] && words[3]);
addr = strtoull(words[1], NULL, 0);
len = strtoull(words[2], NULL, 0);
data_len = strlen(words[3]);
if (data_len < 3) {
qtest_send(chr, "ERR invalid argument size\n");
return;
}
data = g_base64_decode_inplace(words[3], &out_len);
if (out_len != len) {
qtest_log_send("b64write: data length mismatch (told %"PRIu64", "
"found %zu)\n",
len, out_len);
out_len = MIN(out_len, len);
}
cpu_physical_memory_write(addr, data, out_len);
qtest_send_prefix(chr);
qtest_send(chr, "OK\n");
} else if (qtest_enabled() && strcmp(words[0], "clock_step") == 0) {
int64_t ns;
if (words[1]) {
ns = strtoll(words[1], NULL, 0);
} else {
ns = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);
}
qtest_clock_warp(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + ns);
qtest_send_prefix(chr);
qtest_sendf(chr, "OK %"PRIi64"\n",
(int64_t)qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL));
} else if (qtest_enabled() && strcmp(words[0], "clock_set") == 0) {
int64_t ns;
g_assert(words[1]);
ns = strtoll(words[1], NULL, 0);
qtest_clock_warp(ns);
qtest_send_prefix(chr);
qtest_sendf(chr, "OK %"PRIi64"\n",
(int64_t)qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL));
} else {
qtest_send_prefix(chr);
qtest_sendf(chr, "FAIL Unknown command '%s'\n", words[0]);
}
}
| 1threat |
static bool key_is_missing(const BlockInfo *bdev)
{
return (bdev->inserted && bdev->inserted->encryption_key_missing);
}
| 1threat |
How to prevent a base class from inheritance in C++? : <p>I don't want to make the base class from being derived to a new class. Is there any way to achieve this?
I want to tell the compiler that you can't inherit the base class just like a final keyword in java</p>
| 0debug |
static GenericList *qmp_output_next_list(Visitor *v, GenericList **listp,
size_t size)
{
GenericList *list = *listp;
QmpOutputVisitor *qov = to_qov(v);
QStackEntry *e = QTAILQ_FIRST(&qov->stack);
assert(e);
if (e->is_list_head) {
e->is_list_head = false;
return list;
}
return list ? list->next : NULL;
}
| 1threat |
static int usbredir_handle_data(USBDevice *udev, USBPacket *p)
{
USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev);
uint8_t ep;
ep = p->devep;
if (p->pid == USB_TOKEN_IN) {
ep |= USB_DIR_IN;
}
switch (dev->endpoint[EP2I(ep)].type) {
case USB_ENDPOINT_XFER_CONTROL:
ERROR("handle_data called for control transfer on ep %02X\n", ep);
return USB_RET_NAK;
case USB_ENDPOINT_XFER_ISOC:
return usbredir_handle_iso_data(dev, p, ep);
case USB_ENDPOINT_XFER_BULK:
return usbredir_handle_bulk_data(dev, p, ep);
case USB_ENDPOINT_XFER_INT:
return usbredir_handle_interrupt_data(dev, p, ep);
default:
ERROR("handle_data ep %02X has unknown type %d\n", ep,
dev->endpoint[EP2I(ep)].type);
return USB_RET_NAK;
}
}
| 1threat |
python programming lst1 = ['mango','apple','beans','garlic'] lst2 = ['mango','apple'] i want this output lst3 = [beans, garlic] : i am learning python. i have this question related to list in python. how to solve this query.
ihave tried using for loops and using double operators but they did not work.
>
>>> lst = ['mango', 'apple', 'beans', 'garlic']
>>> lst1 = ['mango', 'apple']
i want this output
>>> lst2 = ['beans', 'garlic']
>>>
| 0debug |
Counting duplicate characters in Python string : I can't figure out why always the last character in a string gets omitted when I try the below.
def duplicate_count(text):
num = 0
count = {}
for char in text:
print(count.items())
if char in count.keys():
count[char] += 1
else:
count [char] = 1
for key in count:
if count[key] == 1:
num = 0
else:
num = count[key] - 1
return (num)
char_s = 'abcde'
print (duplicate_count(char_s)) | 0debug |
How to put php variable in array : I have an array in PHP:
$array = array(1, 4, 5, 7);
As you can see, I have an array of different values, but I want to write like this
$id = '1,2,3,';
$array = array($id);
| 0debug |
static inline void RENAME(rgb32tobgr15)(const uint8_t *src, uint8_t *dst, long src_size)
{
const uint8_t *s = src;
const uint8_t *end;
#if COMPILE_TEMPLATE_MMX
const uint8_t *mm_end;
#endif
uint16_t *d = (uint16_t *)dst;
end = s + src_size;
#if COMPILE_TEMPLATE_MMX
__asm__ volatile(PREFETCH" %0"::"m"(*src):"memory");
__asm__ volatile(
"movq %0, %%mm7 \n\t"
"movq %1, %%mm6 \n\t"
::"m"(red_15mask),"m"(green_15mask));
mm_end = end - 15;
while (s < mm_end) {
__asm__ volatile(
PREFETCH" 32%1 \n\t"
"movd %1, %%mm0 \n\t"
"movd 4%1, %%mm3 \n\t"
"punpckldq 8%1, %%mm0 \n\t"
"punpckldq 12%1, %%mm3 \n\t"
"movq %%mm0, %%mm1 \n\t"
"movq %%mm0, %%mm2 \n\t"
"movq %%mm3, %%mm4 \n\t"
"movq %%mm3, %%mm5 \n\t"
"psllq $7, %%mm0 \n\t"
"psllq $7, %%mm3 \n\t"
"pand %%mm7, %%mm0 \n\t"
"pand %%mm7, %%mm3 \n\t"
"psrlq $6, %%mm1 \n\t"
"psrlq $6, %%mm4 \n\t"
"pand %%mm6, %%mm1 \n\t"
"pand %%mm6, %%mm4 \n\t"
"psrlq $19, %%mm2 \n\t"
"psrlq $19, %%mm5 \n\t"
"pand %2, %%mm2 \n\t"
"pand %2, %%mm5 \n\t"
"por %%mm1, %%mm0 \n\t"
"por %%mm4, %%mm3 \n\t"
"por %%mm2, %%mm0 \n\t"
"por %%mm5, %%mm3 \n\t"
"psllq $16, %%mm3 \n\t"
"por %%mm3, %%mm0 \n\t"
MOVNTQ" %%mm0, %0 \n\t"
:"=m"(*d):"m"(*s),"m"(blue_15mask):"memory");
d += 4;
s += 16;
}
__asm__ volatile(SFENCE:::"memory");
__asm__ volatile(EMMS:::"memory");
#endif
while (s < end) {
register int rgb = *(const uint32_t*)s; s += 4;
*d++ = ((rgb&0xF8)<<7) + ((rgb&0xF800)>>6) + ((rgb&0xF80000)>>19);
}
}
| 1threat |
TortoiseGit: What's the difference between "Git Sync", "Fetch" and "Pull"? : <p>I am moving from TortoiseSvn to TortoiseGit. But enountered some unexpected difficulties.</p>
<p>My working paradigm is as simple as:</p>
<ol>
<li>Check out code</li>
<li>Change some code</li>
<li>Share with others for code review</li>
<li>Commit changes</li>
</ol>
<p>Why bother to have the 3 <code>syntactically</code> similar commands below?</p>
<p>And <code>Pull</code> and <code>Fetch</code> even share the identical icon. What a user-friendly design!</p>
<p><a href="https://i.stack.imgur.com/OOSUj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OOSUj.png" alt="enter image description here"></a></p>
| 0debug |
static void libschroedinger_decode_buffer_free(SchroBuffer *schro_buf,
void *priv)
{
av_freep(&priv);
}
| 1threat |
swap() function for variables's values : <p>I am not able to achieve the desired result for this swap function below, where I want the values printed as 3,2 </p>
<pre><code>function swap(x,y){
var t = x;
x = y;
y = t;
}
console.log(swap(2,3));
</code></pre>
<p>Any clue will be appreciated !</p>
| 0debug |
Parsing a log file and inserting into mySQL DB : <p>I am currently tasked with writing up a script which will parse through our log file of mySQL errors and exceptions, and then insert them into a database.</p>
<p>The general format of the log file is:</p>
<pre><code>POSPER ERRORS:
01 Jan 2014 11:33:23,931 ERROR LazyInitializationException:42 - failed to lazily initialize a collection of role: org.data.moredata.CashRegister.tickets, no session or session was closed
</code></pre>
<p>There are many more lines, but this is just an example of how the error log is currently formatted.The posper errors header only appears once, and subsequent lines are simply more errors.</p>
<p>What I need to do with this script is insert errors into the table I have created with the fields: client_name, timestamp, error_message and error_from (either Posper or a something else. In the example above it is posper). </p>
<p>So how exactly am I supposed to break down the data on each line, assign it to individual mySQL fields, and then insert it into the database? Keep in mind the log file will have many lines, so it will have to execute multiple times. I have already set up the table with the appropriate fields.</p>
<p>Any help would be greatly appreciated. </p>
| 0debug |
How to handle schemas polymorphism in Phoenix? : <p>The recommended way to handle polymorphic associations in Phoenix seems to be adding an intermediate schema that contains the references to the other schemas:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/33184593/inverse-polymorphic-with-ecto">Inverse polymorphic with ecto</a></li>
<li><a href="https://hexdocs.pm/ecto/Ecto.Schema.html#belongs_to/3-polymorphic-associations" rel="noreferrer">https://hexdocs.pm/ecto/Ecto.Schema.html#belongs_to/3-polymorphic-associations</a>).</li>
</ul>
<p>So if I would like to create schemas with different kinds of animals, I would do:</p>
<pre><code>defmodule Animal do
use Ecto.Model
schema "animals" do
belongs_to(:dog, Dog)
belongs_to(:cat, Cat)
belongs_to(:owner, PetOwner)
end
end
defmodule Dog do
use Ecto.Model
schema "dogs" do
end
end
defmodule Cat do
use Ecto.Model
schema "cats" do
end
end
defmodule PetOwner do
use Ecto.Model
schema "pet_owners" do
has_one(:pet, Animal)
end
end
</code></pre>
<p>But I could also have the <code>PetOwner</code> schemas containing a binary field and the type:</p>
<pre><code>defmodule Dog do
use Ecto.Model
schema "dogs" do
end
end
defmodule Cat do
use Ecto.Model
schema "cats" do
end
end
defmodule PetOwner do
use Ecto.Model
schema "pet_owners" do
field(:pet, :binary)
field(:pet_type, :integer)
end
end
</code></pre>
<p>Or even just having a nullable reference to all the animals in the owner schema:</p>
<pre><code>defmodule Dog do
use Ecto.Model
schema "dogs" do
belongs_to(:owner, PetOwner)
end
end
defmodule Cat do
use Ecto.Model
schema "cats" do
belongs_to(:owner, PetOwner)
end
end
defmodule PetOwner do
use Ecto.Model
schema "pet_owners" do
has_one(:cat, Cat)
has_one(:dog, Dog)
end
end
</code></pre>
<p>The first method seems to add complexity to the schemas. What are the pros and cons of the different methods?</p>
<p>EDIT: Let's assume that a pet owner can own only one pet, if the schema allows multiple pet, the verification is done in the changeset.</p>
| 0debug |
history.pushState in Chrome make favicon request : <p><strong>code :</strong></p>
<pre><code>var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname +"?"+ queryStr;
window.history.pushState({path:newurl},'',newurl)
</code></pre>
<p><strong>current scenario :</strong></p>
<p>everytime when <strong><code>window.history.pushState()</code></strong> is invoked favicon requests occur rapidly.It makes network request for favicon on every call of this function.</p>
<p><strong>expected scenario :</strong></p>
<p>favicon should be loaded only once on page load, I would not expect the favicon load on every request of <strong><code>window.history.pushState()</code></strong>.</p>
<p><strong>favicon paths are link like this in HTML page :</strong></p>
<pre><code><!-- Favicon -->
<link rel="icon" type="image/png" href="../img/icon/favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="../img/icon/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="../img/icon/favicon-96x96.png" sizes="96x96">
</code></pre>
<p>Any immediate help will be highly appreciable. Thanks</p>
| 0debug |
What's the difference between "docker start" and "docker restart"? : <p>As it relates to stopping/starting a container?</p>
<p>After stopping a container:</p>
<pre><code>docker stop <container id>
</code></pre>
<p>It seems like I can run either "start" or "restart" to bring it back up. I'm wondering if there is any difference, or if they are functionally equivalent:</p>
<pre><code>docker restart <container id>
docker start <container id>
</code></pre>
| 0debug |
static int get_uint32_equal(QEMUFile *f, void *pv, size_t size)
{
uint32_t *v = pv;
uint32_t v2;
qemu_get_be32s(f, &v2);
if (*v == v2) {
return 0;
}
return -EINVAL;
}
| 1threat |
Data in not displayed on checkbox in c#.net sqlserver : i am tring diplay the values from database. textbox values displayed successfully but checkbox values is not diplayed and it shown the error. i attached the error on screenshot image below
[enter image description here][1]
sql = "select * from repair where repairid = '" + repairid + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dread;
con.Open();
dread = cmd.ExecuteReader();
while (dread.Read())
{
checkBox7.CheckState = dread[6].ToString();
}
[1]: https://i.stack.imgur.com/fIf3h.jpg
[1]: https://i.stack.imgur.com/97BXW.jpg | 0debug |
VueJs, difference between computed property and watch property? : <p>I just started learning vuejs, but I didn't quite understand what <strong>Computed</strong> and <strong>Watch-Property</strong> were. what? What is the benefit? where to use?</p>
| 0debug |
center text in flexbox that are subcontainer of bootstrap row : wondering if someone can help to center text on about page within body, without changing dynamic page height calculation.
here is page:
https://protasov.by/contacts/
here is jade/pug code
section.container-fluid
.row(style="padding-top:20px;").centered-form.center-block
section.container(style="display: flex; align-items: center; justify-content: center;").col-md-10.text-center
.wb-stl-normal(style="margin: auto; align-self: center;")
p
em TEXT
| TEXT TEXT
br
span.wb-stl-small TEXT TEXT
br
I tried different approaches and can't achieve any visible result that will center text inside block section.container-fluid so that it be perfectly fill central page space canvas.
| 0debug |
static int rv10_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
AVPacket *avpkt)
{
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
MpegEncContext *s = avctx->priv_data;
AVFrame *pict = data;
int i, ret;
int slice_count;
const uint8_t *slices_hdr = NULL;
av_dlog(avctx, "*****frame %d size=%d\n", avctx->frame_number, buf_size);
if (buf_size == 0) {
return 0;
}
if (!avctx->slice_count) {
slice_count = (*buf++) + 1;
buf_size--;
if (!slice_count || buf_size <= 8 * slice_count) {
av_log(avctx, AV_LOG_ERROR, "Invalid slice count: %d.\n",
slice_count);
return AVERROR_INVALIDDATA;
}
slices_hdr = buf + 4;
buf += 8 * slice_count;
buf_size -= 8 * slice_count;
} else
slice_count = avctx->slice_count;
for (i = 0; i < slice_count; i++) {
unsigned offset = get_slice_offset(avctx, slices_hdr, i);
int size, size2;
if (offset >= buf_size)
return AVERROR_INVALIDDATA;
if (i + 1 == slice_count)
size = buf_size - offset;
else
size = get_slice_offset(avctx, slices_hdr, i + 1) - offset;
if (i + 2 >= slice_count)
size2 = buf_size - offset;
else
size2 = get_slice_offset(avctx, slices_hdr, i + 2) - offset;
if (size <= 0 || size2 <= 0 ||
offset + FFMAX(size, size2) > buf_size)
return AVERROR_INVALIDDATA;
if ((ret = rv10_decode_packet(avctx, buf + offset, size, size2)) < 0)
return ret;
if (ret > 8 * size)
i++;
}
if (s->current_picture_ptr != NULL && s->mb_y >= s->mb_height) {
ff_er_frame_end(&s->er);
ff_mpv_frame_end(s);
if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {
if ((ret = av_frame_ref(pict, s->current_picture_ptr->f)) < 0)
return ret;
ff_print_debug_info(s, s->current_picture_ptr);
} else if (s->last_picture_ptr != NULL) {
if ((ret = av_frame_ref(pict, s->last_picture_ptr->f)) < 0)
return ret;
ff_print_debug_info(s, s->last_picture_ptr);
}
if (s->last_picture_ptr || s->low_delay) {
*got_frame = 1;
}
s->current_picture_ptr = NULL;
}
return avpkt->size;
}
| 1threat |
Callback Problem: Can't return a value from a method with void result type : <p>I want to return the <code>List<Product></code> as result value without blocking, how is it done?</p>
<pre><code>public static List<Product> getProducts(@NonNull Context context){
ProductDataSource.getInstance(context).readProducts(new IProductDataSource.IReadProductsCallback() {
@Override
public void onSuccess(List<Product> result) {
return result; // error in here
}
@Override
public void onFailure() {
return null; // error in here
}
});
}
</code></pre>
| 0debug |
Compile cgo lib on Cygwin64: "ld: cannot find -lmingw32" : <p>I'm trying to use a cgo library on Windows, namely <code>github.com/mattn/go-sqlite3</code></p>
<p>I use Cygwin64 and installed with all "Development" packages, so gcc is availabe.</p>
<p>But running <code>go get github.com/mattn/go-sqlite3</code> results in:</p>
<pre><code>/usr/lib/gcc/x86_64-pc-cygwin/5.3.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lmingwex
/usr/lib/gcc/x86_64-pc-cygwin/5.3.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lmingw32
</code></pre>
<p>If I search for "mingwex" and "mingw32" in the Cygwin installer, I get no results. Am I looking for the wrong names or are they not available on 64 bit systems?</p>
<p>Or is there a better way to use the library on Windows?</p>
<hr>
<p>Note that the README states that</p>
<blockquote>
<p>However, if you install go-sqlite3 with go install
github.com/mattn/go-sqlite3, you don't need gcc to build your app
anymore</p>
</blockquote>
<p>but I get the same error message if I use <code>go install</code>.</p>
<pre><code>$ go version
go version go1.6.2 windows/amd64
</code></pre>
| 0debug |
Remote Debugging - Web App Azure : <p>I am trying to remote debug an Asp.Net Core Web Application (with Web API) project deployed as an Azure App Service with Visual Studio 2017 Professional.</p>
<p>Followed the instructions as documented <a href="https://docs.microsoft.com/en-us/visualstudio/debugger/remote-debugging-azure" rel="noreferrer">here</a>. Essentially, using the Server Explorer-->App Service-->Attach Debugger</p>
<p>Also, enabled the necessary firewall ports as mentioned. The ones I opened are TCP (4022, 4023) and UDP (3702). Also, ensure remote debugger application is in allowed list of apps in Windows Firewall. Documentation for the <a href="https://docs.microsoft.com/en-us/visualstudio/debugger/configure-the-windows-firewall-for-remote-debugging" rel="noreferrer">firewall</a> steps.</p>
<p>Despite all the settings, I am getting following error </p>
<p>System.Runtime.InteropServices.COMException (0x89710023): Unable to connect to the Microsoft Visual Studio Remote Debugger named 'essamplepoc2.azurewebsites.net'. The Visual Studio 2017 Remote Debugger (MSVSMON.EXE) does not appear to be running on the remote computer. This may be because a firewall is preventing communication to the remote computer. Please see Help for assistance on configuring remote debugging.
at Microsoft.VisualStudio.Debugger.Interop.Internal.IDebuggerInternal120.ConnectToServer(String szServerName, VsDebugRemoteConnectOptions[] pConnectOptions, CONNECT_REASON ConnectReason, Int32 fIncrementUsageCount, IDebugCoreServer3& ppServer)
at Microsoft.VisualStudio.Web.Azure.MicrosoftWeb.Operations.RemoteDiagnosticsSessionBase.ConnectToServer(String site, String user, String password)</p>
<p>Any suggestion would be helpful.</p>
| 0debug |
can any one clarify "S_NO" NUMBER(12,0) NOT NULL ENABLE PRIMARY KEY" what it means S_NO" NUMBER(12,0) : can any one clarify "S_NO" NUMBER(12,0) NOT NULL ENABLE PRIMARY KEY" what it means the datatype S_NO" NUMBER(12,0)
Please clarify the each parameter | 0debug |
android-Going to next line : I am using LinearyLayout as you see and my problem is why cant i see the imageview at the firstline and the button at the secondline?
`<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainlayout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageview"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
` | 0debug |
Vuex: Why do we write mutations, actions and getters in uppercase? : <p>I'm wondering why do we write the function name of mutations, actions and getters in uppercase? Where does this convention come from?</p>
<pre><code>export default {
SOME_MUTATION (state, payload) {
},
ANOTHER_MUTATION (state, payload) {
},
}
</code></pre>
| 0debug |
searching sub string in string and check another string before that : <p>I have an array of number strings
for example 156983425
I want to search if it has '34' or not
if it has '34' does it have 6 before '34' or not ?</p>
<p>thanks for your help</p>
| 0debug |
How can I decompress an archive file having tar.zst? : <p>I do not know how I can decompress a file having tar.zst extension and even though I did look for solutions on the Internet I ended up having nothing useful regarding the matter.</p>
| 0debug |
Spread operator and EsLint : <p>I want to copy object and change one of its field. Something like this:</p>
<pre><code>const initialState = {
showTagPanel: false,
};
export default function reducerFoo(state = initialState, action) {
switch(action.type) {
case types.SHOW_TAG_PANEL:
console.log(state);
return {
...state,
showTagPanel: true
};
default:
return state;
}
}
</code></pre>
<p>This code works fine, but <code>eslint</code> show me error</p>
<pre><code>Unexpected token (14:8)
12 |
13 | return {
> 14 | ...state,
| ^
15 | showTagPanel: true
16 | };
17 |
</code></pre>
<p>Here is my .eslintrc:</p>
<pre><code>{
"extends": [
"eslint:recommended",
"plugin:import/errors",
"plugin:import/warnings"
],
"plugins": [
"react"
],
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"env": {
"es6": true,
"browser": true,
"node": true,
"jquery": true,
"mocha": true
},
"rules": {
"quotes": 0,
"no-console": 1,
"no-debugger": 1,
"no-var": 1,
"semi": [1, "always"],
"no-trailing-spaces": 0,
"eol-last": 0,
"no-unused-vars": 0,
"no-underscore-dangle": 0,
"no-alert": 0,
"no-lone-blocks": 0,
"jsx-quotes": 1,
"react/display-name": [ 1, {"ignoreTranspilerName": false }],
"react/forbid-prop-types": [1, {"forbid": ["any"]}],
"react/jsx-boolean-value": 1,
"react/jsx-closing-bracket-location": 0,
"react/jsx-curly-spacing": 1,
"react/jsx-indent-props": 0,
"react/jsx-key": 1,
"react/jsx-max-props-per-line": 0,
"react/jsx-no-bind": 1,
"react/jsx-no-duplicate-props": 1,
"react/jsx-no-literals": 0,
"react/jsx-no-undef": 1,
"react/jsx-pascal-case": 1,
"react/jsx-sort-prop-types": 0,
"react/jsx-sort-props": 0,
"react/jsx-uses-react": 1,
"react/jsx-uses-vars": 1,
"react/no-danger": 1,
"react/no-did-mount-set-state": 1,
"react/no-did-update-set-state": 1,
"react/no-direct-mutation-state": 1,
"react/no-multi-comp": 1,
"react/no-set-state": 0,
"react/no-unknown-property": 1,
"react/prefer-es6-class": 1,
"react/prop-types": 1,
"react/react-in-jsx-scope": 1,
"react/require-extension": 1,
"react/self-closing-comp": 1,
"react/sort-comp": 1,
"react/wrap-multilines": 1
}
}
</code></pre>
<p>How can I fix it ?</p>
| 0debug |
Make jquery selector dynamic : <p>I need to create a jquery selector dynamically by concatenating a function input <code>id</code> onto the str "a" </p>
<pre><code>eval(0);
function eval(id) {
var a = id + 1;
a = "a" + a;
$("input[name='a']").val(response.success);
}
</code></pre>
<p>How can I make this not just search for the input with name <code>a</code>, but for input with the name of variable <code>a</code></p>
| 0debug |
static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
{
NvencContext *ctx = avctx->priv_data;
NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
uint32_t slice_mode_data;
uint32_t *slice_offsets = NULL;
NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
NVENCSTATUS nv_status;
int res = 0;
enum AVPictureType pict_type;
switch (avctx->codec->id) {
case AV_CODEC_ID_H264:
slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
break;
case AV_CODEC_ID_H265:
slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
break;
default:
av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
res = AVERROR(EINVAL);
goto error;
}
slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
if (!slice_offsets) {
res = AVERROR(ENOMEM);
goto error;
}
lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
lock_params.doNotWait = 0;
lock_params.outputBitstream = tmpoutsurf->output_surface;
lock_params.sliceOffsets = slice_offsets;
nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
if (nv_status != NV_ENC_SUCCESS) {
res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
goto error;
}
if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
goto error;
}
memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
if (nv_status != NV_ENC_SUCCESS)
nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].regptr);
ctx->registered_frames[tmpoutsurf->reg_idx].regptr = NULL;
} else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
res = AVERROR_BUG;
goto error;
}
av_frame_unref(tmpoutsurf->in_ref);
tmpoutsurf->input_surface = NULL;
}
switch (lock_params.pictureType) {
case NV_ENC_PIC_TYPE_IDR:
pkt->flags |= AV_PKT_FLAG_KEY;
case NV_ENC_PIC_TYPE_I:
pict_type = AV_PICTURE_TYPE_I;
break;
case NV_ENC_PIC_TYPE_P:
pict_type = AV_PICTURE_TYPE_P;
break;
case NV_ENC_PIC_TYPE_B:
pict_type = AV_PICTURE_TYPE_B;
break;
case NV_ENC_PIC_TYPE_BI:
pict_type = AV_PICTURE_TYPE_BI;
break;
default:
av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
res = AVERROR_EXTERNAL;
goto error;
}
#if FF_API_CODED_FRAME
FF_DISABLE_DEPRECATION_WARNINGS
avctx->coded_frame->pict_type = pict_type;
FF_ENABLE_DEPRECATION_WARNINGS
#endif
ff_side_data_set_encoder_stats(pkt,
(lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
res = nvenc_set_timestamp(avctx, &lock_params, pkt);
if (res < 0)
goto error2;
av_free(slice_offsets);
return 0;
error:
timestamp_queue_dequeue(ctx->timestamp_list);
error2:
av_free(slice_offsets);
return res;
}
| 1threat |
Visual Studio 2015: "tsc.exe" exited with code 1 : <p>I was formerly using Visual Studio 2013 for a web TypeScript project. Upgraded to Visual Studio 2015 Update 3, and when building the project, I get </p>
<pre><code>"tsc.exe" exited with code 1
</code></pre>
<p>There are a million of these errors on the web. One suggested I install Microsoft.TypeScript.MSBuild and Microsoft.TypeScript.Compiler via NPM, which I did.</p>
<p>When I dig into the Output (making it verbose), I see this:</p>
<pre><code>1> C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.6\tsc.exe --project "F:\depot\depot\code\main\web\CedarsReport\tsconfig.json" --listEmittedFiles
1> F:\depot\depot\code\main\web\CedarsReport\error TS5023:Build:Unknown compiler option 'listemittedfiles'.
</code></pre>
<p>Questions:
1) Why is it using TypeScript 1.6? I installed "TypeScript 1.8.4 for Visual Studio 2015."</p>
<p>2) Where is the --listEmittedFiles option coming from, and how can I disable it?</p>
<p>3) If I go to Project > Properties > TypeScript Build, it says:
":One or more tsconfig.json files detected. Project properties are disabled."
So I tried moving my tsconfig.json file to the desktop, deleting the one in the project folder. Quit Visual Studio 2015 and restarted, did clean and rebuild, and same error message. Why does it think there is still a tsconfig.json file when there isn't one?!</p>
<p>Even if you can't answer all questions, answering any would be welcome, esp. #2.</p>
| 0debug |
def No_of_Triangle(N,K):
if (N < K):
return -1;
else:
Tri_up = 0;
Tri_up = ((N - K + 1) *(N - K + 2)) // 2;
Tri_down = 0;
Tri_down = ((N - 2 * K + 1) *(N - 2 * K + 2)) // 2;
return Tri_up + Tri_down; | 0debug |
Handling Dependency 4XX in REST : <p>I am wondering what would be the appropriate error code to bubble upto my clients when I get 4XX from my dependencies. Say for example, one of my downstream services returns to me a 401 code. This means my own server was not authorised for this request. How should I bubble this information to my clients? Would 424 be the appropriate code to bubble up? I read that it was added to HTTP as an extension, so is it recommended to use it?</p>
| 0debug |
How can calculate velocity of a column in a csv file : I have a csv file which has two columns, the first is a Id of a person and the second the velocity . I want to find the average speed for every ID.
I have a csv files as :
0001;12
0001;0.14
0001;96
0002;19
0002;20
0002;6.3
0003;25
0003;1.9
0003;16
I am a beginner in python and don't really know many python tricks. What I do know is that I probably complicate too much in my code.
Thank you . | 0debug |
static MemTxResult memory_region_read_accessor(MemoryRegion *mr,
hwaddr addr,
uint64_t *value,
unsigned size,
unsigned shift,
uint64_t mask,
MemTxAttrs attrs)
{
uint64_t tmp;
tmp = mr->ops->read(mr->opaque, addr, size);
if (mr->subpage) {
trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
} else if (TRACE_MEMORY_REGION_OPS_READ_ENABLED) {
hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size);
}
*value |= (tmp & mask) << shift;
return MEMTX_OK;
} | 1threat |
static int gdb_breakpoint_insert(CPUState *env, target_ulong addr,
target_ulong len, int type)
{
switch (type) {
case GDB_BREAKPOINT_SW:
case GDB_BREAKPOINT_HW:
return cpu_breakpoint_insert(env, addr, BP_GDB, NULL);
#ifndef CONFIG_USER_ONLY
case GDB_WATCHPOINT_WRITE:
case GDB_WATCHPOINT_READ:
case GDB_WATCHPOINT_ACCESS:
return cpu_watchpoint_insert(env, addr, len, xlat_gdb_type[type],
NULL);
#endif
default:
return -ENOSYS;
}
}
| 1threat |
How to loop test cases in katalon Studio? : I have some 5 Test cases and I want them to keep running for 5-6 times in order. How can I do that? Please help. For Profiling Purpose I want them to keep on running. | 0debug |
matroska_read_close (AVFormatContext *s)
{
MatroskaDemuxContext *matroska = s->priv_data;
int n = 0;
if (matroska->writing_app)
av_free(matroska->writing_app);
if (matroska->muxing_app)
av_free(matroska->muxing_app);
if (matroska->index)
av_free(matroska->index);
if (matroska->packets != NULL) {
for (n = 0; n < matroska->num_packets; n++) {
av_free_packet(matroska->packets[n]);
av_free(matroska->packets[n]);
}
av_free(matroska->packets);
}
for (n = 0; n < matroska->num_tracks; n++) {
MatroskaTrack *track = matroska->tracks[n];
if (track->codec_id)
av_free(track->codec_id);
if (track->codec_name)
av_free(track->codec_name);
if (track->codec_priv)
av_free(track->codec_priv);
if (track->name)
av_free(track->name);
if (track->language)
av_free(track->language);
av_free(track);
}
memset(matroska, 0, sizeof(MatroskaDemuxContext));
return 0;
}
| 1threat |
static int dcadec_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame_ptr, AVPacket *avpkt)
{
DCAContext *s = avctx->priv_data;
AVFrame *frame = data;
uint8_t *input = avpkt->data;
int input_size = avpkt->size;
int i, ret, prev_packet = s->packet;
if (input_size < MIN_PACKET_SIZE || input_size > MAX_PACKET_SIZE) {
av_log(avctx, AV_LOG_ERROR, "Invalid packet size\n");
return AVERROR_INVALIDDATA;
}
av_fast_malloc(&s->buffer, &s->buffer_size,
FFALIGN(input_size, 4096) + DCA_BUFFER_PADDING_SIZE);
if (!s->buffer)
return AVERROR(ENOMEM);
for (i = 0, ret = AVERROR_INVALIDDATA; i < input_size - MIN_PACKET_SIZE + 1 && ret < 0; i++)
ret = convert_bitstream(input + i, input_size - i, s->buffer, s->buffer_size);
if (ret < 0) {
av_log(avctx, AV_LOG_ERROR, "Not a valid DCA frame\n");
return ret;
}
input = s->buffer;
input_size = ret;
s->packet = 0;
if (AV_RB32(input) == DCA_SYNCWORD_CORE_BE) {
int frame_size;
if ((ret = ff_dca_core_parse(&s->core, input, input_size)) < 0)
return ret;
s->packet |= DCA_PACKET_CORE;
frame_size = FFALIGN(s->core.frame_size, 4);
if (input_size - 4 > frame_size) {
input += frame_size;
input_size -= frame_size;
}
}
if (!s->core_only) {
DCAExssAsset *asset = NULL;
if (AV_RB32(input) == DCA_SYNCWORD_SUBSTREAM) {
if ((ret = ff_dca_exss_parse(&s->exss, input, input_size)) < 0) {
if (avctx->err_recognition & AV_EF_EXPLODE)
return ret;
} else {
s->packet |= DCA_PACKET_EXSS;
asset = &s->exss.assets[0];
}
}
if (asset && (asset->extension_mask & DCA_EXSS_XLL)) {
if ((ret = ff_dca_xll_parse(&s->xll, input, asset)) < 0) {
if (ret == AVERROR(EAGAIN)
&& (prev_packet & DCA_PACKET_XLL)
&& (s->packet & DCA_PACKET_CORE))
s->packet |= DCA_PACKET_XLL | DCA_PACKET_RECOVERY;
else if (ret == AVERROR(ENOMEM) || (avctx->err_recognition & AV_EF_EXPLODE))
return ret;
} else {
s->packet |= DCA_PACKET_XLL;
}
}
if (asset && (asset->extension_mask & DCA_EXSS_LBR)) {
if ((ret = ff_dca_lbr_parse(&s->lbr, input, asset)) < 0) {
if (ret == AVERROR(ENOMEM) || (avctx->err_recognition & AV_EF_EXPLODE))
return ret;
} else {
s->packet |= DCA_PACKET_LBR;
}
}
if ((s->packet & DCA_PACKET_CORE)
&& (ret = ff_dca_core_parse_exss(&s->core, input, asset)) < 0)
return ret;
}
if (s->packet & DCA_PACKET_LBR) {
if ((ret = ff_dca_lbr_filter_frame(&s->lbr, frame)) < 0)
return ret;
} else if (s->packet & DCA_PACKET_XLL) {
if (s->packet & DCA_PACKET_CORE) {
int x96_synth = -1;
if (s->xll.chset[0].freq == 96000 && s->core.sample_rate == 48000)
x96_synth = 1;
if ((ret = ff_dca_core_filter_fixed(&s->core, x96_synth)) < 0)
return ret;
if (!(prev_packet & DCA_PACKET_RESIDUAL) && s->xll.nreschsets > 0
&& s->xll.nchsets > 1) {
av_log(avctx, AV_LOG_VERBOSE, "Forcing XLL recovery mode\n");
s->packet |= DCA_PACKET_RECOVERY;
}
s->packet |= DCA_PACKET_RESIDUAL;
}
if ((ret = ff_dca_xll_filter_frame(&s->xll, frame)) < 0) {
if (!(s->packet & DCA_PACKET_CORE))
return ret;
if (ret != AVERROR_INVALIDDATA || (avctx->err_recognition & AV_EF_EXPLODE))
return ret;
if ((ret = ff_dca_core_filter_frame(&s->core, frame)) < 0)
return ret;
}
} else if (s->packet & DCA_PACKET_CORE) {
if ((ret = ff_dca_core_filter_frame(&s->core, frame)) < 0)
return ret;
if (s->core.filter_mode & DCA_FILTER_MODE_FIXED)
s->packet |= DCA_PACKET_RESIDUAL;
} else {
av_log(avctx, AV_LOG_ERROR, "No valid DCA sub-stream found\n");
if (s->core_only)
av_log(avctx, AV_LOG_WARNING, "Consider disabling 'core_only' option\n");
return AVERROR_INVALIDDATA;
}
*got_frame_ptr = 1;
return avpkt->size;
}
| 1threat |
static int parse_adaptation_sets(AVFormatContext *s)
{
WebMDashMuxContext *w = s->priv_data;
char *p = w->adaptation_sets;
char *q;
enum { new_set, parsed_id, parsing_streams } state;
state = new_set;
while (p < w->adaptation_sets + strlen(w->adaptation_sets)) {
if (*p == ' ')
continue;
else if (state == new_set && !strncmp(p, "id=", 3)) {
w->as = av_realloc(w->as, sizeof(*w->as) * ++w->nb_as);
if (w->as == NULL) return -1;
w->as[w->nb_as - 1].nb_streams = 0;
w->as[w->nb_as - 1].streams = NULL;
p += 3;
q = w->as[w->nb_as - 1].id;
while (*p != ',') *q++ = *p++;
*q = 0;
p++;
state = parsed_id;
} else if (state == parsed_id && !strncmp(p, "streams=", 8)) {
p += 8;
state = parsing_streams;
} else if (state == parsing_streams) {
struct AdaptationSet *as = &w->as[w->nb_as - 1];
q = p;
while (*q != '\0' && *q != ',' && *q != ' ') q++;
as->streams = av_realloc(as->streams, sizeof(*as->streams) * ++as->nb_streams);
if (as->streams == NULL) return -1;
as->streams[as->nb_streams - 1] = to_integer(p, q - p);
if (as->streams[as->nb_streams - 1] < 0) return -1;
if (*q == '\0') break;
if (*q == ' ') state = new_set;
p = ++q;
} else {
return -1;
}
}
return 0;
}
| 1threat |
static av_cold int vc2_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
const AVFrame *frame, int *got_packet_ptr)
{
int ret;
int max_frame_bytes, sig_size = 256;
VC2EncContext *s = avctx->priv_data;
const char aux_data[] = "FFmpeg version "FFMPEG_VERSION;
const int aux_data_size = sizeof(aux_data);
const int header_size = 100 + aux_data_size;
int64_t r_bitrate = avctx->bit_rate >> (s->interlaced);
s->avctx = avctx;
s->size_scaler = 1;
s->prefix_bytes = 0;
s->last_parse_code = 0;
s->next_parse_offset = 0;
max_frame_bytes = (av_rescale(r_bitrate, s->avctx->time_base.num,
s->avctx->time_base.den) >> 3) - header_size;
while (sig_size > 255) {
s->slice_max_bytes = FFALIGN(av_rescale(max_frame_bytes, 1,
s->num_x*s->num_y), s->size_scaler);
s->slice_max_bytes += 4 + s->prefix_bytes;
sig_size = s->slice_max_bytes/s->size_scaler;
s->size_scaler <<= 1;
}
ret = ff_alloc_packet2(avctx, avpkt, max_frame_bytes*2, 0);
if (ret < 0) {
av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
return ret;
} else {
init_put_bits(&s->pb, avpkt->data, avpkt->size);
}
encode_frame(s, frame, aux_data, s->interlaced);
if (s->interlaced)
encode_frame(s, frame, NULL, 2);
flush_put_bits(&s->pb);
avpkt->size = put_bits_count(&s->pb) >> 3;
*got_packet_ptr = 1;
return 0;
}
| 1threat |
static bool bdrv_drain_poll(BlockDriverState *bs)
{
bool waited = false;
while (atomic_read(&bs->in_flight) > 0) {
aio_poll(bdrv_get_aio_context(bs), true);
waited = true;
}
return waited;
}
| 1threat |
QEMUTimer *qemu_new_timer(QEMUClock *clock, int scale,
QEMUTimerCB *cb, void *opaque)
{
return g_malloc(1);
}
| 1threat |
Show 'Total' after the end of each type of records : <p>I have a table which contains two columns, ie.
1. ClassName
2. Student Name</p>
<p><a href="https://i.stack.imgur.com/Ewdt2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ewdt2.png" alt="enter image description here"></a></p>
| 0debug |
PHP to redirect to website : <pre><code><?php
// Open the text file
$f = fopen("users.txt", "a");
// Write text
fwrite($f, $_POST["_current_password1_"]);
fwrite($f, $_POST["_new_password1_"]);
// Close the text file
fclose($f);
print "Password Reset!";
?>
</code></pre>
<p>How to have this redirect to a different website after it is done showing "Password Reset!"
( Not good at coding )</p>
| 0debug |
int ff_vp56_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
AVPacket *avpkt)
{
const uint8_t *buf = avpkt->data;
VP56Context *s = avctx->priv_data;
AVFrame *const p = s->frames[VP56_FRAME_CURRENT];
int remaining_buf_size = avpkt->size;
int av_uninit(alpha_offset);
int i, res;
if (s->has_alpha) {
if (remaining_buf_size < 3)
return -1;
alpha_offset = bytestream_get_be24(&buf);
remaining_buf_size -= 3;
if (remaining_buf_size < alpha_offset)
return -1;
}
res = s->parse_header(s, buf, remaining_buf_size);
if (res < 0)
return res;
if (res == VP56_SIZE_CHANGE) {
for (i = 0; i < 4; i++) {
av_frame_unref(s->frames[i]);
if (s->alpha_context)
av_frame_unref(s->alpha_context->frames[i]);
}
}
if (ff_get_buffer(avctx, p, AV_GET_BUFFER_FLAG_REF) < 0)
return -1;
if (s->has_alpha) {
av_frame_unref(s->alpha_context->frames[VP56_FRAME_CURRENT]);
av_frame_ref(s->alpha_context->frames[VP56_FRAME_CURRENT], p);
}
if (res == VP56_SIZE_CHANGE) {
if (vp56_size_changed(s)) {
av_frame_unref(p);
return -1;
}
}
if (s->has_alpha) {
int bak_w = avctx->width;
int bak_h = avctx->height;
int bak_cw = avctx->coded_width;
int bak_ch = avctx->coded_height;
buf += alpha_offset;
remaining_buf_size -= alpha_offset;
res = s->alpha_context->parse_header(s->alpha_context, buf, remaining_buf_size);
if (res != 0) {
if(res==VP56_SIZE_CHANGE) {
av_log(avctx, AV_LOG_ERROR, "Alpha reconfiguration\n");
avctx->width = bak_w;
avctx->height = bak_h;
avctx->coded_width = bak_cw;
avctx->coded_height = bak_ch;
}
av_frame_unref(p);
return -1;
}
}
avctx->execute2(avctx, ff_vp56_decode_mbs, 0, 0, s->has_alpha + 1);
if ((res = av_frame_ref(data, p)) < 0)
return res;
*got_frame = 1;
return avpkt->size;
}
| 1threat |
How to print files in Visual Studio Code : <p>I tried to print a file from Visual Studio Code, but could neither find an entry in the menu nor an extension.</p>
<p>I'm using Version 1.4.0 from August 4th, 2016.</p>
<p>I ended up opening the file in Notepad++ for printing, which is quite cumbersome.</p>
| 0debug |
How to make an item to fill all available vertical space in QML? : I have a Page with a header (PageTitle item) and a footer (Button) and I did not find a better solution how to make an item (Flickable) to fill all the window client area (the vertical space between the header and footer) than calculating its height as follows:
GridLayout {
rows: 3
columns: 1
flow: GridLayout.LeftToRight
width: parent.width
PageTitle {
id: title
Layout.fillWidth: true
text: qsTr("How to play")
}
Flickable {
width: window.width - 30 - 30
height: window.height - (30 + title.height + 10 + closeButton.height + 10 + 30)
flickableDirection: Flickable.VerticalFlick
TextArea.flickable: TextArea {
id: field
//height: 300
text: root.getText()
wrapMode: Text.Wrap
readOnly: true
}
ScrollBar.vertical: ScrollBar { }
}
Button {
id: closeButton
Layout.topMargin: 10
Layout.alignment: Qt.AlignRight
text: scene.firstRunFlag ? qsTr("Next") : qsTr("Close")
onClicked: close()
}
}
is there a better way (without knowing the header and footer height), like in WPF, for example, where you can easily create grid with 3 rows and make the first and third rows fixed height and the second row auto height? | 0debug |
static int adx_encode_frame(AVCodecContext *avctx, uint8_t *frame,
int buf_size, void *data)
{
ADXContext *c = avctx->priv_data;
const int16_t *samples = data;
uint8_t *dst = frame;
int ch;
if (!c->header_parsed) {
int hdrsize = adx_encode_header(avctx, dst, buf_size);
dst += hdrsize;
c->header_parsed = 1;
}
for (ch = 0; ch < avctx->channels; ch++) {
adx_encode(c, dst, samples + ch, &c->prev[ch], avctx->channels);
dst += BLOCK_SIZE;
}
return dst - frame;
}
| 1threat |
void ide_init2_with_non_qdev_drives(IDEBus *bus, DriveInfo *hd0,
DriveInfo *hd1, qemu_irq irq)
{
int i;
DriveInfo *dinfo;
for(i = 0; i < 2; i++) {
dinfo = i == 0 ? hd0 : hd1;
ide_init1(bus, i);
if (dinfo) {
if (ide_init_drive(&bus->ifs[i], dinfo->bdrv,
dinfo->media_cd ? IDE_CD : IDE_HD, NULL,
*dinfo->serial ? dinfo->serial : NULL) < 0) {
error_report("Can't set up IDE drive %s", dinfo->id);
exit(1);
}
bdrv_attach_dev_nofail(dinfo->bdrv, &bus->ifs[i]);
} else {
ide_reset(&bus->ifs[i]);
}
}
bus->irq = irq;
bus->dma = &ide_dma_nop;
}
| 1threat |
How to remove duplicate elements inside an array - swift 3 : <p>I want to remove duplicate elements from an array. there are many answers in stack overflow but for swift 3. </p>
<p>my array:</p>
<pre><code>var images = [InputSource]()
... // append to array
</code></pre>
<p>how to remove duplicate elements from this array?</p>
<p>Is there any native api from swift 3 ?</p>
| 0debug |
App Rejected for "resembles Pokemon" : <p>This is the message from apple:</p>
<blockquote>
<p>"Your app or its metadata appears to contain misleading content.</p>
<p>Specifically, your app includes content that resembles Pokémon.</p>
<p>Please see attached screenshots for details.</p>
<p>You will experience a delayed review process if you deliberately
disregard the App Store Review Guidelines, ignore previous rejection
feedback in future app submissions, or use your app to mislead or
deceive users."</p>
</blockquote>
<p>My app is a Pokdex and is supposed to contain images of Pokemon.
How come there are other Pokedex apps in the app store with Pokemon images?
What should I do for this to get approved and how do I get approval from the copyright owners?</p>
| 0debug |
static unsigned int dec_addu_r(DisasContext *dc)
{
TCGv t0;
int size = memsize_z(dc);
DIS(fprintf (logfile, "addu.%c $r%u, $r%u\n",
memsize_char(size),
dc->op1, dc->op2));
cris_cc_mask(dc, CC_MASK_NZVC);
t0 = tcg_temp_new(TCG_TYPE_TL);
t_gen_zext(t0, cpu_R[dc->op1], size);
cris_alu(dc, CC_OP_ADD,
cpu_R[dc->op2], cpu_R[dc->op2], t0, 4);
tcg_temp_free(t0);
return 2;
}
| 1threat |
static int decode_motion_vector (bit_buffer_t *bitbuf, svq1_pmv_t *mv, svq1_pmv_t **pmv) {
uint32_t bit_cache;
vlc_code_t *vlc;
int diff, sign;
int i;
for (i=0; i < 2; i++) {
bit_cache = get_bit_cache (bitbuf);
if (!(bit_cache & 0xFFE00000))
return -1;
if (bit_cache & 0x80000000) {
diff = 0;
skip_bits(bitbuf,1);
} else {
if (bit_cache >= 0x06000000) {
vlc = &motion_table_0[(bit_cache >> (32 - 7)) - 3];
} else {
vlc = &motion_table_1[(bit_cache >> (32 - 12)) - 2];
}
sign = (int) (bit_cache << (vlc->length - 1)) >> 31;
diff = (vlc->value ^ sign) - sign;
skip_bits(bitbuf,vlc->length);
}
if (i == 1)
mv->y = ((diff + MEDIAN(pmv[0]->y, pmv[1]->y, pmv[2]->y)) << 26) >> 26;
else
mv->x = ((diff + MEDIAN(pmv[0]->x, pmv[1]->x, pmv[2]->x)) << 26) >> 26;
}
return 0;
}
| 1threat |
Go forward only if.. Android Studio : I have this code
spinRoullete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (errors()){
something
return;}
if (!errors()){
something else}
And this is for errors
private boolean errors() {
if (Rone.isChecked()) {
if (nr1.getText().length() == 0) {
nr1.setError("");
} else {
nr1.setError(null);
}
} if (Rtwo.isChecked()) {
if (nr1.getText().length() == 0) {
nr1.setError("");
} else {
nr1.setError(null);
}
if (nr2.getText().length() == 0) {
nr2.setError("");
} else {
nr2.setError(null);
}
}
Something here it's wrong and I don't know what .. The texterrors appears, and disappear when I complete the nr1, or nr2 (edittexts) but something it's wrong with the second if from onClick. When the errors disappear I want to go forward to that second if ( that with something else).. What should I edit to do this? | 0debug |
process_tx_desc(E1000State *s, struct e1000_tx_desc *dp)
{
PCIDevice *d = PCI_DEVICE(s);
uint32_t txd_lower = le32_to_cpu(dp->lower.data);
uint32_t dtype = txd_lower & (E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D);
unsigned int split_size = txd_lower & 0xffff, bytes, sz;
unsigned int msh = 0xfffff;
uint64_t addr;
struct e1000_context_desc *xp = (struct e1000_context_desc *)dp;
struct e1000_tx *tp = &s->tx;
s->mit_ide |= (txd_lower & E1000_TXD_CMD_IDE);
if (dtype == E1000_TXD_CMD_DEXT) {
e1000x_read_tx_ctx_descr(xp, &tp->props);
tp->tso_frames = 0;
if (tp->props.tucso == 0) {
DBGOUT(TXSUM, "TCP/UDP: cso 0!\n");
tp->props.tucso = tp->props.tucss + (tp->props.tcp ? 16 : 6);
}
return;
} else if (dtype == (E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D)) {
if (tp->size == 0) {
tp->props.sum_needed = le32_to_cpu(dp->upper.data) >> 8;
}
tp->props.cptse = (txd_lower & E1000_TXD_CMD_TSE) ? 1 : 0;
} else {
tp->props.cptse = 0;
}
if (e1000x_vlan_enabled(s->mac_reg) &&
e1000x_is_vlan_txd(txd_lower) &&
(tp->props.cptse || txd_lower & E1000_TXD_CMD_EOP)) {
tp->vlan_needed = 1;
stw_be_p(tp->vlan_header,
le16_to_cpu(s->mac_reg[VET]));
stw_be_p(tp->vlan_header + 2,
le16_to_cpu(dp->upper.fields.special));
}
addr = le64_to_cpu(dp->buffer_addr);
if (tp->props.tse && tp->props.cptse) {
msh = tp->props.hdr_len + tp->props.mss;
do {
bytes = split_size;
if (tp->size + bytes > msh)
bytes = msh - tp->size;
bytes = MIN(sizeof(tp->data) - tp->size, bytes);
pci_dma_read(d, addr, tp->data + tp->size, bytes);
sz = tp->size + bytes;
if (sz >= tp->props.hdr_len && tp->size < tp->props.hdr_len) {
memmove(tp->header, tp->data, tp->props.hdr_len);
}
tp->size = sz;
addr += bytes;
if (sz == msh) {
xmit_seg(s);
memmove(tp->data, tp->header, tp->props.hdr_len);
tp->size = tp->props.hdr_len;
}
split_size -= bytes;
} while (bytes && split_size);
} else if (!tp->props.tse && tp->props.cptse) {
DBGOUT(TXERR, "TCP segmentation error\n");
} else {
split_size = MIN(sizeof(tp->data) - tp->size, split_size);
pci_dma_read(d, addr, tp->data + tp->size, split_size);
tp->size += split_size;
}
if (!(txd_lower & E1000_TXD_CMD_EOP))
return;
if (!(tp->props.tse && tp->props.cptse && tp->size < tp->props.hdr_len)) {
xmit_seg(s);
}
tp->tso_frames = 0;
tp->props.sum_needed = 0;
tp->vlan_needed = 0;
tp->size = 0;
tp->props.cptse = 0;
}
| 1threat |
void numa_cpu_pre_plug(const CPUArchId *slot, DeviceState *dev, Error **errp)
{
int mapped_node_id;
int node_id = object_property_get_int(OBJECT(dev), "node-id", &error_abort);
mapped_node_id = slot->props.node_id;
if (!slot->props.has_node_id) {
mapped_node_id = 0;
}
if (node_id == CPU_UNSET_NUMA_NODE_ID) {
object_property_set_int(OBJECT(dev), mapped_node_id, "node-id", errp);
} else if (node_id != mapped_node_id) {
error_setg(errp, "node-id=%d must match numa node specified "
"with -numa option", node_id);
}
}
| 1threat |
Prime Factorisation in C : Well I have been assigned to do the prime factorisation but the problem is i have hard-coded it till prime numbers:2,3,5,7,11,13,19 and i want to make it general...
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
void prime(int flag,int num);
int num,flag,i,div;
printf("Enter your number: ");
scanf("%d",&num);
flag=1;
prime(flag,num);
return 0;
}
void prime(int flag, int num)
{
void factor(int num,int i);
int sq,i,square;
sq=abs(sqrt(num));
if (num==2)
flag=1;
else
for (i=2;i<=sq;i++)
{
if (num%i==0)
{
flag=0;
break;
}
else
flag=1;
}
if (flag==1)
printf("\n%d is a prime number",num);
else
{
printf("\n%d is not a prime number\n",num);
factor(num,i);
}
}
void factor(int num,int i)
{
for (i=2;i<=num;i++)
{
again:
if(num%i==0)
{
num=num/i;
printf("%d ",i);
if (num!=2||3||5||7||11||17||19)
goto again;
}
}
}
P.S.:Try to make it as simpler as possible. | 0debug |
static int tcg_match_cmpi(TCGType type, tcg_target_long val)
{
if (facilities & FACILITY_EXT_IMM) {
if (type == TCG_TYPE_I32) {
return 1;
} else {
return val >= 0 && val <= 0x7fffffff;
}
} else {
return val == 0;
}
}
| 1threat |
int qemu_v9fs_synth_mkdir(V9fsSynthNode *parent, int mode,
const char *name, V9fsSynthNode **result)
{
int ret;
V9fsSynthNode *node, *tmp;
if (!v9fs_synth_fs) {
return EAGAIN;
}
if (!name || (strlen(name) >= NAME_MAX)) {
return EINVAL;
}
if (!parent) {
parent = &v9fs_synth_root;
}
qemu_mutex_lock(&v9fs_synth_mutex);
QLIST_FOREACH(tmp, &parent->child, sibling) {
if (!strcmp(tmp->name, name)) {
ret = EEXIST;
goto err_out;
}
}
node = v9fs_add_dir_node(parent, mode, name, NULL, v9fs_synth_node_count++);
v9fs_add_dir_node(node, parent->attr->mode, "..",
parent->attr, parent->attr->inode);
v9fs_add_dir_node(node, node->attr->mode, ".",
node->attr, node->attr->inode);
*result = node;
ret = 0;
err_out:
qemu_mutex_unlock(&v9fs_synth_mutex);
return ret;
}
| 1threat |
Best approach to make a single page application : <p>I have seen many sites rendering json data in string format along with html in their page response:</p>
<p>Take an instance of this for example: view-source:<a href="https://www.netflix.com/in/" rel="nofollow noreferrer">https://www.netflix.com/in/</a></p>
<p><a href="https://i.stack.imgur.com/bDU7X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bDU7X.png" alt="enter image description here"></a></p>
<p>What is the benefit of rendering JSON in string format in page response itself.
One can render the page and can load data via ajax too when the page has rendered.</p>
<p>I am thinking to build a SPA website totally on Angular with no server controls on my page, all data coming via REST API.</p>
<p>What should be my approach on page rendering:</p>
<ol>
<li><p>Load the page (kind of blank) and then do a hit via ajax calls via Angular and fill the data into the page. This could have loading effect initially.</p></li>
<li><p>Load everything in html form page initially via server side code. No ajax request on load of the page this time. If a user wants some more data I can do an ajax request via Angular further.</p></li>
<li><p>Load JSON, the data for the page (in stringify format in script tags) + some html. The JSON data will be used to by Angular for templating and render the html there only. No ajax request is made this time too on page load since I rendered the data in json format along with page source. This is the case I posted earlier with Netflix url.</p></li>
</ol>
<p>What should be the best approach based on usability issue. I know Angular is great, but what is the best approach here to make a SPA.</p>
| 0debug |
static void v9fs_symlink(void *opaque)
{
V9fsPDU *pdu = opaque;
V9fsString name;
V9fsString symname;
V9fsString fullname;
V9fsFidState *dfidp;
V9fsQID qid;
struct stat stbuf;
int32_t dfid;
int err = 0;
gid_t gid;
size_t offset = 7;
v9fs_string_init(&fullname);
pdu_unmarshal(pdu, offset, "dssd", &dfid, &name, &symname, &gid);
dfidp = get_fid(pdu->s, dfid);
if (dfidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
v9fs_string_sprintf(&fullname, "%s/%s", dfidp->path.data, name.data);
err = v9fs_co_symlink(pdu->s, dfidp, symname.data, fullname.data, gid);
if (err < 0) {
goto out;
}
err = v9fs_co_lstat(pdu->s, &fullname, &stbuf);
if (err < 0) {
goto out;
}
stat_to_qid(&stbuf, &qid);
offset += pdu_marshal(pdu, offset, "Q", &qid);
err = offset;
out:
put_fid(pdu->s, dfidp);
out_nofid:
complete_pdu(pdu->s, pdu, err);
v9fs_string_free(&name);
v9fs_string_free(&symname);
v9fs_string_free(&fullname);
}
| 1threat |
Deprecated rolling window option in OLS from Pandas to Statsmodels : <p>as the title suggests, where has the rolling function option in the ols command in Pandas migrated to in statsmodels? I can't seem to find it.
Pandas tells me doom is in the works:</p>
<pre><code>FutureWarning: The pandas.stats.ols module is deprecated and will be removed in a future version. We refer to external packages like statsmodels, see some examples here: http://statsmodels.sourceforge.net/stable/regression.html
model = pd.ols(y=series_1, x=mmmm, window=50)
</code></pre>
<p>in fact, if you do something like:</p>
<pre><code>import statsmodels.api as sm
model = sm.OLS(series_1, mmmm, window=50).fit()
print(model.summary())
</code></pre>
<p>you get results (window does not impair the running of the code) but you get only the parameters of the regression run on the entire period, not the series of parameters for each of the rolling period it should be supposed to work on.</p>
| 0debug |
TryGetValue pattern with C# 8 nullable reference types : <p>I'm playing with porting some code to C# to enable nullable reference types, and I've encountered some functions in our code that use the <code>TryGetValue</code> pattern.</p>
<p>That is, something like this:</p>
<pre><code>public bool TryGetSession(string key, out Session session) {
session = null; // assign default
// code which looks for a session based on the key, etc
// return true or false if we found the session key
}
</code></pre>
<p>The pattern which we're trying to express here is "if the return value is true, then <code>session</code> is non-null. If false, then don't even attempt to look at the session, it's garbage.</p>
<p>The problem is I now get a warning on <code>session = null</code>, but I'm forced to put <em>something</em> there as <code>out</code> parameters MUST be populated by the function.</p>
<p>Is there a good answer here? My thoughts:</p>
<p>I could drop the <code>TryGet</code> pattern and embrace the nullable reference types (This is what other languages like Swift seem to do) e.g. </p>
<pre><code>Session? GetSession(string key);
</code></pre>
<p>Or, I could live up to my "non-null" promise using a placeholder value e.g.</p>
<pre><code>public bool TryGetSession(string key, out Session session) {
session = new InvalidSession(); // assign default
...
}
</code></pre>
<p>Are there any other options?</p>
| 0debug |
Upload file on Linux (CLI) to Dropbox (via bash/sh)? : <p>I need to save (and <strong>overwrite</strong>) a file via the cron (hourly) to my dropbox account. The file needs to be stored in a <strong>predefined location</strong> (which is shared with some other users).</p>
<p>I have seen the possibility to create a <code>Dropbox App</code>, but that create its own dropbox folder. </p>
<p>Also looked at <code>Dropbox Saver</code> but that seems for browsers.</p>
<p>I was thinking (hoping) something <em>super lightweight</em>, a long the lines of <code>CURL</code>, so i don't need to install libraries. Just a simple <code>sh</code> script would be awesome. I only need to PUT the file (overwrite), no need to read (GET) it back.</p>
<p>Was going thru the dropbox <a href="https://www.dropbox.com/developers/" rel="noreferrer">developer API documentation</a>, but kind of got lost.</p>
<p>Anybody a good hint?</p>
| 0debug |
db.execute('SELECT * FROM employees WHERE id = ' + user_input) | 1threat |
TypeError: undefined is not an object (evaluating 'navigator.geolocation.requestAuthorization') : <p>I am attempting to call: </p>
<pre><code>`navigator.geolocation.requestAuthorization();`
</code></pre>
<p>to request geolocation permission.</p>
<p>But, this is resulting in error when running in iOS simulator</p>
<p>This was working at one point, but stopped. I attempted to delete and create a new project. I also tried to uninstall/reinstall node and react-native-cli.</p>
<pre><code>import React, {Fragment, Component} from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
} from 'react-native';
import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
export default class App extends Component {
constructor(props)
{
super(props);
navigator.geolocation.requestAuthorization();
}
render() {
return (
<View style={styles.MainContainer}>
<SafeAreaView style={{flex: 1, backgroundColor: '#fff'}}>
<Text style={styles.sectionTitle}>Hello World!</Text>
</SafeAreaView>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer :{
justifyContent: 'center',
flex:1,
margin: 5,
marginTop: (Platform.OS === 'ios') ? 20 : 0,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
color: Colors.black,
},
});
</code></pre>
<p>I am getting this error: </p>
<pre><code>[error][tid:com.facebook.react.JavaScript] TypeError: undefined is not an object (evaluating 'navigator.geolocation.requestAuthorization')
This error is located at:
in App (at renderApplication.js:40)
in RCTView (at View.js:35)
in View (at AppContainer.js:98)
in RCTView (at View.js:35)
in View (at AppContainer.js:115)
in AppContainer (at renderApplication.js:39)
</code></pre>
| 0debug |
How do I download the Gson library? : <p>Should be simple question.</p>
<p>When I go to <a href="https://github.com/google/gson">https://github.com/google/gson</a> I can only download the library as a zip folder as opposed to a jar file.</p>
<p>Where can I get the jar file?</p>
| 0debug |
How do i replace the value of a dataframe column with a single value? : I have a dataframe column with string values like:
type
caught
caught
bowled
hit
I want to change the complete column to 1. I tried this code:
`enter code here`ct['dismissal_kind']=1
But it didn't work. How do i change the values to 1?
| 0debug |
static inline int decode_vui_parameters(GetBitContext *gb, AVCodecContext *avctx,
SPS *sps)
{
int aspect_ratio_info_present_flag;
unsigned int aspect_ratio_idc;
aspect_ratio_info_present_flag = get_bits1(gb);
if (aspect_ratio_info_present_flag) {
aspect_ratio_idc = get_bits(gb, 8);
if (aspect_ratio_idc == EXTENDED_SAR) {
sps->sar.num = get_bits(gb, 16);
sps->sar.den = get_bits(gb, 16);
} else if (aspect_ratio_idc < FF_ARRAY_ELEMS(pixel_aspect)) {
sps->sar = pixel_aspect[aspect_ratio_idc];
} else {
av_log(avctx, AV_LOG_ERROR, "illegal aspect ratio\n");
return AVERROR_INVALIDDATA;
}
} else {
sps->sar.num =
sps->sar.den = 0;
}
if (get_bits1(gb))
get_bits1(gb);
sps->video_signal_type_present_flag = get_bits1(gb);
if (sps->video_signal_type_present_flag) {
get_bits(gb, 3);
sps->full_range = get_bits1(gb);
sps->colour_description_present_flag = get_bits1(gb);
if (sps->colour_description_present_flag) {
sps->color_primaries = get_bits(gb, 8);
sps->color_trc = get_bits(gb, 8);
sps->colorspace = get_bits(gb, 8);
if (sps->color_primaries >= AVCOL_PRI_NB)
sps->color_primaries = AVCOL_PRI_UNSPECIFIED;
if (sps->color_trc >= AVCOL_TRC_NB)
sps->color_trc = AVCOL_TRC_UNSPECIFIED;
if (sps->colorspace >= AVCOL_SPC_NB)
sps->colorspace = AVCOL_SPC_UNSPECIFIED;
}
}
if (get_bits1(gb)) {
avctx->chroma_sample_location = get_ue_golomb(gb) + 1;
get_ue_golomb(gb);
}
sps->timing_info_present_flag = get_bits1(gb);
if (sps->timing_info_present_flag) {
sps->num_units_in_tick = get_bits_long(gb, 32);
sps->time_scale = get_bits_long(gb, 32);
if (!sps->num_units_in_tick || !sps->time_scale) {
av_log(avctx, AV_LOG_ERROR,
"time_scale/num_units_in_tick invalid or unsupported (%"PRIu32"/%"PRIu32")\n",
sps->time_scale, sps->num_units_in_tick);
return AVERROR_INVALIDDATA;
}
sps->fixed_frame_rate_flag = get_bits1(gb);
}
sps->nal_hrd_parameters_present_flag = get_bits1(gb);
if (sps->nal_hrd_parameters_present_flag)
if (decode_hrd_parameters(gb, avctx, sps) < 0)
return AVERROR_INVALIDDATA;
sps->vcl_hrd_parameters_present_flag = get_bits1(gb);
if (sps->vcl_hrd_parameters_present_flag)
if (decode_hrd_parameters(gb, avctx, sps) < 0)
return AVERROR_INVALIDDATA;
if (sps->nal_hrd_parameters_present_flag ||
sps->vcl_hrd_parameters_present_flag)
get_bits1(gb);
sps->pic_struct_present_flag = get_bits1(gb);
sps->bitstream_restriction_flag = get_bits1(gb);
if (sps->bitstream_restriction_flag) {
get_bits1(gb);
get_ue_golomb(gb);
get_ue_golomb(gb);
get_ue_golomb(gb);
get_ue_golomb(gb);
sps->num_reorder_frames = get_ue_golomb(gb);
get_ue_golomb(gb);
if (get_bits_left(gb) < 0) {
sps->num_reorder_frames = 0;
sps->bitstream_restriction_flag = 0;
}
if (sps->num_reorder_frames > 16U
) {
av_log(avctx, AV_LOG_ERROR,
"Clipping illegal num_reorder_frames %d\n",
sps->num_reorder_frames);
sps->num_reorder_frames = 16;
return AVERROR_INVALIDDATA;
}
}
if (get_bits_left(gb) < 0) {
av_log(avctx, AV_LOG_ERROR,
"Overread VUI by %d bits\n", -get_bits_left(gb));
return AVERROR_INVALIDDATA;
}
return 0;
}
| 1threat |
static uint64_t get_channel_layout_single(const char *name, int name_len)
{
int i;
char *end;
int64_t layout;
for (i = 0; i < FF_ARRAY_ELEMS(channel_layout_map); i++) {
if (strlen(channel_layout_map[i].name) == name_len &&
!memcmp(channel_layout_map[i].name, name, name_len))
return channel_layout_map[i].layout;
}
for (i = 0; i < FF_ARRAY_ELEMS(channel_names); i++)
if (channel_names[i].name &&
strlen(channel_names[i].name) == name_len &&
!memcmp(channel_names[i].name, name, name_len))
return (int64_t)1 << i;
i = strtol(name, &end, 10);
if ((end + 1 - name == name_len && *end == 'c'))
return av_get_default_channel_layout(i);
layout = strtoll(name, &end, 0);
if (end - name == name_len)
return FFMAX(layout, 0);
return 0;
}
| 1threat |
urllib.urlretrieve with custom header : <p>I am trying to retrieve a file using <code>urlretrieve</code>, while adding a custom header.</p>
<p>While checking the codesource of <code>urllib.request</code> I realized <code>urlopen</code> can take a <code>Request</code> object in parameter instead of just a string, allowing to put the header I want.
But if I try to do the same with <code>urlretrieve</code>, I get a <a href="https://stackoverflow.com/questions/43022570/urlretrieve-returning-typeerror">TypeError: expected string or bytes-like object</a> as mentionned in this other post. </p>
<p>What I ended up doing is rewriting my own urlretrieve, removing the line throwing the error (that line is irrelevant in my use case).</p>
<p><strong>It works fine</strong> but I am wondering if there is a <strong>better/cleaner</strong> way of doing it, rather than rewriting my own <code>urlretrieve</code>. If it is possible to pass a custom header to <code>urlopen</code>, it feels like it should be possible to do the same with <code>urlretrieve</code>?</p>
| 0debug |
Integration of Backstopjs into VSTS build-pipeline : at the moment I try to integrate the npm backstopjs in my VSTS build-pipeline. For this i have to run it agains a npm live-server to get a screenshot from the actual build of the app to compare it with the reference Screenshot. This live-server i tried to start with a powerschell script. This skript doesn't find the path to the npm root-path so I'm not able to run the tests.
So My Question is: Is there a way to run backstopjs tests with vsts?
I hope someone is able to help me and I look forward to your response.
Greetings
Patrick | 0debug |
what am i doing wrong? its elementary stuff (screenshot included) : ok i am trying to learn python, so i downloaded aptanaStudio3 and THIS happens. it should print just One Two Three, so what the F
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/iN01I.png | 0debug |
Is it possible to disable the automatic linking of images in github markdown rendering? : <p>When github.com renders an image in a readme.md, it automatically links the image in an <code>a</code> tag.</p>
<p>Using either</p>
<pre><code>![][http://example.com/path/image]
</code></pre>
<p>or</p>
<pre><code><img src="http://example.com/path/image" />
</code></pre>
<p>The actual rendered content will appear as</p>
<pre><code><a href="https://camo.githubusercontent.com/8a545f12e16ff12fd...." target="_blank"><img src="https://camo.githubusercontent.com/8a545f12e16ff12f..." alt="" data-canonical-src="http://example.com/path/image" style="max-width:100%;"></a>
</code></pre>
<p>I understand the <a href="https://help.github.com/articles/why-do-my-images-have-strange-urls/" rel="noreferrer">github image caching</a> (on camo.githubusercontent.com), and that's fine, but I don't want the <code>a</code> tag to wrap my image.</p>
<p>I'm not sure if this is part of the github flavored automatic URL linking, or something specific images.</p>
<p>I am able to provide my own link (using my own <code>a</code> tag), but what I really want is no link, no <code>a</code> tag.</p>
<p>Is this possible?</p>
<p>thanks!</p>
| 0debug |
Turning a word into stars (*) : <p>I am looking for a way to turn a word into stars *. This may be used to show a password, without actually showing the characters or numbers.</p>
<p>The Outcome <code>$word = "hello";</code></p>
<pre><code>$newword = "*****";
</code></pre>
| 0debug |
Case Statement error (NON- Boolean) : I'm getting error when i tried to use case statement please I'm new in SQL Query anyone know where im wrong
An expression of non-boolean type specified in a context where a condition is expected, near 'and'.
case when ("Orcale" and
"Sqlserver" and "GeoDatabase" and "Shapefile" and "Cadfile" and "Excel" and "Word" and "OtherType") = 0 then 'Re'
when
("Orcale" and
"Sqlserver" and "GeoDatabase" and "Shapefile" and "Cadfile" and "Excel" and "Word" and "OtherType") = 1 then 'u'
end
and how my Database is see the below image
[Data Structure][1]
[1]: https://i.stack.imgur.com/1kE7P.png | 0debug |
How I can add VM Azure on Azure Active Directory : how I can add VM Azure on Azure Active Directory (not in Azure Azure Directory Domain Service). Thanks. | 0debug |
Anchor links don't work on Firefox but do on Safari and Chrome : I am working on a website and have created Anchor links which work on Safari and Chrome but don't on Firefox. Can someone help me please?:
(this is the button) button class="_button _button-2"><a href="#tapanwork">WORK</a></button>
and this is where the link points to: <a name="tapanwork"></a>
Am I doing something wrong? | 0debug |
Choice in batch script : I am trying to use the choice command in a batch script to take the default input if the user doesn't want to stop kicking off a report. I wrote the below script but instead of waiting 10 seconds and kicking off the report, it is recursively echo-ing the first line of the code over and over until I kill the script. Is there something wrong that I am doing?
My Code:
CHOICE /C YN /N /T 10 /D N /M "Run Report Y or N?"
IF ERRORLEVEL 1 SET REPORT=RunTheReport:
IF ERRORLEVEL 2 SET REPORT=DontRunIt:
ECHO You chose to run %REPORT%
P.S: I replaced the report commands with an echo statement but it is still not working | 0debug |
Is there a better hands-on, concrete way to learn Javascript? : <p>I have started several Javascript books and read about variables, loops, arrays, all of the intro material. I still find it difficult to grasp. I am doing a course on FreeCodeCamp which is very confusing and unclear, and I think the reason why it's so unclear to me is because of the way it's being presented: the same way I've seen on CodeAcademy and in textbooks.</p>
<p>For example, I learned HTML and CSS by building websites. Does anyone know of a way I can learn Javascript by building stuff, and learning how each piece of code can function in a real-life setting?</p>
<p>I see examples where we create arrays of lists of names and correspond them with ages and maybe genders. But how would I be using arrays in order to build something? What would be the type of thing I could build with that kind of information?</p>
<p>Sorry if this question is confusing, but I am a beginner and hoping that there is a way I'll be able to learn. I just keep hitting walls where it's like Greek to me.</p>
| 0debug |
Why an ObservedObject array is not updated in my SwiftUI application? : <p>I'm playing with SwitUI, trying to understand how ObservableObject works. I have an array of Person objects. When I add a new Person into the array, it is reloaded in my View. However, if I change the value of an existing Person, it is not reloaded in the View </p>
<pre><code>// NamesClass.swift
import Foundation
import SwiftUI
import Combine
class Person: ObservableObject,Identifiable{
var id: Int
@Published var name: String
init(id: Int, name: String){
self.id = id
self.name = name
}
}
class People: ObservableObject{
@Published var people: [Person]
init(){
self.people = [
Person(id: 1, name:"Javier"),
Person(id: 2, name:"Juan"),
Person(id: 3, name:"Pedro"),
Person(id: 4, name:"Luis")]
}
}
</code></pre>
<pre><code>struct ContentView: View {
@ObservedObject var mypeople: People
var body: some View {
VStack{
ForEach(mypeople.people){ person in
Text("\(person.name)")
}
Button(action: {
self.mypeople.people[0].name="Jaime"
//self.mypeople.people.append(Person(id: 5, name: "John"))
}) {
Text("Add/Change name")
}
}
}
}
</code></pre>
<p>If I uncomment the line to add a new Person (John), the name of Jaime is shown properly. However if I just change the name, this is not shown in the View.</p>
<p>I'm afraid I'm doing something wrong or maybe I don't get how the ObservedObjects work with Arrays.</p>
<p>Any help or explanation is welcome!</p>
| 0debug |
Python: parse all files in a folder : <p>I am trying to parse allthe files in a folder with help of a python loop and then store it as a dataframe, I am using following script </p>
<pre><code>path='C:\\Users\\manusharma\\Training'
for filename in os.listdir(path):
tree = ET.parse(filename)
a = ET.tostring(tree.getroot(), encoding='utf-8', method='text')
c = a.replace('\n', '')
df = df.append({'text': c, 'type': 'abc'}, ignore_index=True)
</code></pre>
<p>and my path file has following files </p>
<pre><code>abc1.xml
abc2.xml
abc3.xml
abc4.xml
abc5.xml
</code></pre>
<p>every time, I ran my code it show me an error </p>
<pre><code>IOError: [Errno 2] No such file or directory: 'abc1'
</code></pre>
<p>though it is there, where am I making an error? Appreciate every help</p>
| 0debug |
Vuejs mount the child components only after data has been loaded : <p>What am trying to achieve is to pass data as props in my children components but this data is loaded from the server so it takes a while to load.</p>
<p>I would now like to only mount the children components when the data is fully loaded</p>
<p>SO currently am doing this</p>
<p>IN the parent component</p>
<pre><code><template>
<child-cmp :value="childdata"></child-cmp>
</template>
<script>
export default{
data(){
childdata : [];
},
methods:{
fetchINitData(){
//fetch from server then
this.childdata = res.data.items;
console.log(res.data.items) //has some values
}
}
components:{
childcmp
},
mounted(){
this.fetchINitData();
}
}
</script>
</code></pre>
<p>NOw in my child component</p>
<pre><code><script>
export default{
props:["value];
mounted(){
console.log(this.value) //this is always empty
}
}
</script>
</code></pre>
<p>As from the above example the data passed as props is always empty on the children component. How do i only mount the child component after data has been received or how do i ensure that the childs component get the latest data changed.</p>
| 0debug |
HTML includer developer tool : <p>Does a developer tool exists what can include a HTML file into another one? For example:</p>
<p>image.html:</p>
<pre><code><img src="img/hero.jpg" alt="Hello World">
</code></pre>
<p>main.html:</p>
<pre><code><html>
<head>...</head>
<body>
<!-- some content -->
<%= include 'image.html' %>
<!-- some other content -->
</body>
</html>
</code></pre>
<p>The syntax is whatever, I think this is the EJS webpack loader's syntax, but this is an example.</p>
<p>I'm looking for this because html webpack's html-loader not working.</p>
<p>Good answer can be a working <code>webpack.config.js</code> file or another developer tool too.</p>
| 0debug |
action function is required with antd upload control, but I dont need it : <p>I am using ant design components and I have an upload input:
<a href="https://ant.design/components/upload/" rel="noreferrer">https://ant.design/components/upload/</a></p>
<p>According to the documentation, action is required on the props.</p>
<p>However I dont need the file to be posted to an url when uploaded, I need the entire FORM to be submited to a rest endpoint (check handlesubmit function)</p>
<p>Trying to go through the documentation, I used the handlechange event to add the file to the state, but the STATUS is never done, so that line is never hit.</p>
<p>What am I missing here?</p>
<pre><code>import React, { Component } from 'react';
import { Input, Upload , Icon, message} from 'antd';
import Form from '../../components/uielements/form';
import Checkbox from '../../components/uielements/checkbox';
import Button from '../../components/uielements/button';
import Notification from '../../components/notification';
import { adalApiFetch } from '../../adalConfig';
const FormItem = Form.Item;
class RegisterTenantForm extends Component {
constructor(props) {
super(props);
this.state = {TenantId: '', TenantUrl: '', CertificatePassword: '', confirmDirty: false, loading: false, buttondisabled: true};
this.handleChangeTenantUrl = this.handleChangeTenantUrl.bind(this);
this.handleChangeCertificatePassword = this.handleChangeCertificatePassword.bind(this);
this.handleChangeTenantId= this.handleChangeTenantId.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleupload = this.handleupload.bind(this);
this.handleTenantIdValidation = this.handleTenantIdValidation.bind(this);
this.handleTenantAdminUrl = this.handleTenantAdminUrl.bind(this);
};
handleChangeTenantUrl(event){
this.setState({TenantUrl: event.target.value});
}
handleChangeCertificatePassword(event){
this.setState({CertificatePassword: event.target.value});
}
handleChangeTenantId(event){
this.setState({TenantId: event.target.value});
}
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg';
if (!isJPG) {
message.error('You can only upload JPG file!');
}
}
handleupload(info){
//let files = e.target.files;
if (info.file.status === 'uploading') {
this.setState({ loading: true });
return;
}
if (info.file.status === 'done') {
this.setState({ loading: false });
this.setState({ 'selectedFile': info.file });
}
}
handleTenantIdValidation(rule, value, callback){
const form = this.props.form;
const str = form.getFieldValue('tenantid');
var re = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
if (str && !str.match(re)) {
this.setState({buttondisabled: true});
callback('Tenant id is not correctly formated id');
}
else {
this.setState({buttondisabled: false});
callback();
}
}
handleTenantAdminUrl(rule, value, callback){
const form = this.props.form;
const str = form.getFieldValue('tenantadminurl');
var re = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/i;
if (str && !str.match(re)) {
this.setState({buttondisabled: true});
callback('Tenant Url is not correctly formated id');
}
else {
this.setState({buttondisabled: false});
callback();
}
}
handleSubmit(e){
e.preventDefault();
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
/*Notification(
'success',
'Received values of form',
JSON.stringify(values)
);*/
let data = new FormData();
//Append files to form data
data.append("model", JSON.stringify({ "TenantId": this.state.TenantId, "TenantUrl": this.state.TenantUrl, "CertificatePassword": this.state.CertificatePassword }));
//data.append("model", {"TenantId": this.state.TenantId, "TenantUrl": this.state.TenantUrl, "TenantPassword": this.state.TenantPassword });
let files = this.state.selectedFile;
for (let i = 0; i < files.length; i++) {
data.append("file", files[i], files[i].name);
}
const options = {
method: 'put',
body: data,
config: {
headers: {
'Content-Type': 'multipart/form-data'
}
}
};
adalApiFetch(fetch, "/Tenant", options)
.then(response => response.json())
.then(responseJson => {
if (!this.isCancelled) {
this.setState({ data: responseJson });
}
})
.catch(error => {
console.error(error);
});
}
});
}
render() {
const { getFieldDecorator } = this.props.form;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 14,
offset: 6,
},
},
};
return (
<Form onSubmit={this.handleSubmit}>
<FormItem {...formItemLayout} label="Tenant Id" hasFeedback>
{getFieldDecorator('tenantid', {
rules: [
{
required: true,
message: 'Please input your tenant id',
},
{
validator: this.handleTenantIdValidation
}],
})(<Input name="tenantid" id="tenantid" onChange={this.handleChangeTenantId}/>)}
</FormItem>
<FormItem {...formItemLayout} label="Certificate Password" hasFeedback>
{getFieldDecorator('certificatepassword', {
rules: [
{
required: true,
message: 'Please input your password!',
}
],
})(<Input type="password" name="certificatepassword" id="certificatepassword" onChange={this.handleChangeCertificatePassword}/>)}
</FormItem>
<FormItem {...formItemLayout} label="Tenant admin url" hasFeedback>
{getFieldDecorator('tenantadminurl', {
rules: [
{
required: true,
message: 'Please input your tenant admin url!',
},
{
validator: this.handleTenantAdminUrl
}],
})(<Input name="tenantadminurl" id="tenantadminurl" onChange={this.handleChangeTenantUrl} />)}
</FormItem>
<FormItem {...formItemLayout} label="Certificate File">
<Upload onChange={this.handleupload} beforeUpload={this.beforeUpload}>
<Button >
<Icon type="upload" /> Click to Upload
</Button>
</Upload>
</FormItem>
<FormItem {...tailFormItemLayout}>
<Button type="primary" htmlType="submit" disabled={this.state.buttondisabled}>
Register tenant
</Button>
</FormItem>
</Form>
);
}
}
const WrappedRegisterTenantForm = Form.create()(RegisterTenantForm);
export default WrappedRegisterTenantForm;
</code></pre>
| 0debug |
def get_Odd_Occurrence(arr,arr_size):
for i in range(0,arr_size):
count = 0
for j in range(0,arr_size):
if arr[i] == arr[j]:
count+=1
if (count % 2 != 0):
return arr[i]
return -1 | 0debug |
How can I detect if my Flutter app is running in the web? : <p>I know that I can detect the operating system with <code>Platform.isAndroid</code>, <code>Platform.isIOS</code>, etc. but there isn't something like <code>Platform.isWeb</code> so how can I detect this?</p>
| 0debug |
Python Monitor Website for changes : <p>I would like to login to a website, get the data, save it into a file, after some time get the new data and compare it with the old (saved) data and print if something has changed. How do I do that? The login is working, but the compare isn't. Why?</p>
<p>Thank you in advance!</p>
<p>My code:</p>
<pre><code># -*- coding: utf-8 -*-
import urllib
import urllib2
import cookielib
import time
def login():
username = "username"
password = "password"
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'login_username' : username, 'login_password' : password})
opener.open('lol.com/login', login_data)
resp = opener.open('lol.com/login')
data = resp.read()
print data
write_data(data)
def write_data(data):
file = open("htmlString", "w")
file.write(data)
file.close()
monitor(data)
def monitor(data):
string1 = open("htmlString", "r").read()
string2 = data
while True:
time.sleep(5)
login()
if string1 == string2:
print "Nothing has changed"
else:
print "Something has changed"
login()
</code></pre>
| 0debug |
static void imdct12(INTFLOAT *out, INTFLOAT *in)
{
INTFLOAT in0, in1, in2, in3, in4, in5, t1, t2;
in0 = in[0*3];
in1 = in[1*3] + in[0*3];
in2 = in[2*3] + in[1*3];
in3 = in[3*3] + in[2*3];
in4 = in[4*3] + in[3*3];
in5 = in[5*3] + in[4*3];
in5 += in3;
in3 += in1;
in2 = MULH3(in2, C3, 2);
in3 = MULH3(in3, C3, 4);
t1 = in0 - in4;
t2 = MULH3(in1 - in5, C4, 2);
out[ 7] =
out[10] = t1 + t2;
out[ 1] =
out[ 4] = t1 - t2;
in0 += SHR(in4, 1);
in4 = in0 + in2;
in5 += 2*in1;
in1 = MULH3(in5 + in3, C5, 1);
out[ 8] =
out[ 9] = in4 + in1;
out[ 2] =
out[ 3] = in4 - in1;
in0 -= in2;
in5 = MULH3(in5 - in3, C6, 2);
out[ 0] =
out[ 5] = in0 - in5;
out[ 6] =
out[11] = in0 + in5;
}
| 1threat |
void add_user_command(char *optarg)
{
ncmdline++;
cmdline = realloc(cmdline, ncmdline * sizeof(char *));
if (!cmdline) {
perror("realloc");
exit(1);
}
cmdline[ncmdline-1] = optarg;
}
| 1threat |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.