problem stringlengths 26 131k | labels class label 2 classes |
|---|---|
How to make an interactive text game more efficient? : I am trying to create a text game in C# much like the game "Angband". https://en.wikipedia.org/wiki/Angband_(video_game)
The basic process goes like this:
1. Take user input (WASD or Q to quit).
2. Manipulate the map (2d array) based on the user input.
3. Print out the map.
4. Repeat.
The game works fine, but my problem is that it flickers whenever you try to move the character because it has to go through an entire nested for loop to print out the map each time.
Obviously, I don't like that. Can you guys provide any way to make my game more efficient? I believe a more efficient way to print the map would suffice very well.
Extremely messy source (Bolded is important): https://docs.google.com/document/d/1bOfI6_Ns25IxOtQ5A1_ykpofw8oGWSpfK57yut0Ij_M/edit?usp=sharing
(Maps.lvl_1 is just the the map for level 1)
| 0debug |
Invalid json_decode while decode number with two dots : <p>I have problem with json_decode function - when I try to decode json-string</p>
<pre><code>{"amount": 132..45}
</code></pre>
<p>I didn't receive any errors, I got array</p>
<pre><code>[
'amount => 132
]
</code></pre>
<p>But it doens't expected result - I expect receive error.
Could anyone help me, what's wrong with my json_decode?</p>
| 0debug |
Angular 6 Services and Class Inheritance : <p>Angular 6 now has <a href="https://angular.io/guide/dependency-injection#injectable-providers" rel="noreferrer">injectable providers</a> which is the new recommended way of injecting services, and it works really well except I'm having a problem when using a service which extends another service. So as an example, suppose I have</p>
<pre><code>@Injectable({
providedIn: 'root'
})
export class ParentAppService { ... }
@Injectable({
providedIn: 'root'
})
export class ChildAppService extends ParentAppService { ... }
</code></pre>
<p>The problem is that no matter what I ask for in a component, the parent class is always injected.</p>
<p>So if you ask for</p>
<pre><code>constructor(private childAppService: ChildAppService) { ... }
</code></pre>
<p>you will still be provided an instance of ParentAppService, which isn't expected.</p>
<p>A very simple workaround would be to just register the providers in your module the old fashioned way, and this works:</p>
<pre><code>@NgModule({
providers: [AppService, ChildAppService]
})
</code></pre>
<p>But that's basically the old way of doing things, and doesn't have the benefits of better tree-shaking and cleaner testing like the new providedIn registration process.</p>
<p>So my question is, what's the right way to do this? Is there a better way to register a provider so I can get the desired behavior (maybe specifying a provider token somehow?).</p>
<p>I've setup a super simple stackblitz example to show what's going on. </p>
<p><a href="https://stackblitz.com/edit/angular-lacyab?file=src%2Fapp%2Fapp.component.ts" rel="noreferrer">https://stackblitz.com/edit/angular-lacyab?file=src%2Fapp%2Fapp.component.ts</a></p>
<p>You'll notice it says "Hello I AM APP SERVICE!" even though the component asked to be provided the child service. If in the app module we register the providers the old way (see the commented out code), all of a sudden the proper provider gets injected.</p>
<p>Thanks for your help!</p>
| 0debug |
static ssize_t qio_channel_file_readv(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int **fds,
size_t *nfds,
Error **errp)
{
QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);
ssize_t ret;
retry:
ret = readv(fioc->fd, iov, niov);
if (ret < 0) {
if (errno == EAGAIN ||
errno == EWOULDBLOCK) {
return QIO_CHANNEL_ERR_BLOCK;
}
if (errno == EINTR) {
goto retry;
}
error_setg_errno(errp, errno,
"Unable to read from file");
return -1;
}
return ret;
}
| 1threat |
Random selection in reservoir samplig : My question is related to sample code in 'Alogarithm R' section of this link [https://en.m.wikipedia.org/wiki/Reservoir_sampling][1]
[1]: https://en.m.wikipedia.org/wiki/Reservoir_sampling
// I copied below code snippet from that section
// why this code is replacing elements with gradually decreasing probability? According to the problem each item in the input should have same probability right?
for i = k+1 to n
j := random(1, i)
if j <= k
R[j] := S[i]
For example compare Random function call for below three inputs with my reservoir size 10
1) random (1,15) chances are high for getting random numbers below 10
2) random (1, 100) chances are very low for getting random numbers below 10
3) random (1, 1000) chances are very very low for getting random numbers below 10
So chances of replacing items are very very less as input grows then how can we say that reservoir sampling algorithm is the solution for selecting random samples with equal probability on each Item? Mayou be I am missing some thing please explain.
| 0debug |
segmentation fault compiler error in C : <pre><code>Node* Insert(Node *head,int data)
{
// Complete this method
Node *temp, *temp1;
temp1 = head;
temp = (Node *)malloc(sizeof(Node));
temp->data = data;
temp->next = NULL;
while(temp1->next!=NULL){
temp1 = temp1->next;
}
temp1->next = temp;
return head;
}
</code></pre>
<p>I am trying to write simple code to insert at the end of the array. The method works for GCC compiler, but gives segmentation fault error when compiling using an online compiler on HackerRank. Does the program work differently for different compilers. </p>
| 0debug |
Regular expression to extract only numbers but only if sting doesn't contain any letters : Hello regular expression gurus! I need Your help!
I want to extracts digits from the string that may contain some special character (let's say "+-() ") but not any other characters! I.e.:
"+123 (456) 7-8" -> "1, 2, 3, 4, 5, 6, 7, 8" is extracted
"123a45" -> pattern matching fails, nothing is extracted
"1234 B" -> pattern matching fails, nothing is extracted
Thanks! | 0debug |
int do_migrate(Monitor *mon, const QDict *qdict, QObject **ret_data)
{
MigrationState *s = NULL;
const char *p;
int detach = qdict_get_try_bool(qdict, "detach", 0);
int blk = qdict_get_try_bool(qdict, "blk", 0);
int inc = qdict_get_try_bool(qdict, "inc", 0);
const char *uri = qdict_get_str(qdict, "uri");
if (current_migration &&
current_migration->get_status(current_migration) == MIG_STATE_ACTIVE) {
monitor_printf(mon, "migration already in progress\n");
if (strstart(uri, "tcp:", &p)) {
s = tcp_start_outgoing_migration(mon, p, max_throttle, detach,
blk, inc);
#if !defined(WIN32)
} else if (strstart(uri, "exec:", &p)) {
s = exec_start_outgoing_migration(mon, p, max_throttle, detach,
blk, inc);
} else if (strstart(uri, "unix:", &p)) {
s = unix_start_outgoing_migration(mon, p, max_throttle, detach,
blk, inc);
} else if (strstart(uri, "fd:", &p)) {
s = fd_start_outgoing_migration(mon, p, max_throttle, detach,
blk, inc);
#endif
} else {
monitor_printf(mon, "unknown migration protocol: %s\n", uri);
if (s == NULL) {
monitor_printf(mon, "migration failed\n");
if (current_migration) {
current_migration->release(current_migration);
current_migration = s;
return 0; | 1threat |
Send Email using only Angular JS : <p>I have created a web application using angularJS and firebase. Now, I want to send E-mail to the users once they are authenticated from app. Is there any way to send email using only angular JS?</p>
| 0debug |
Get variable from javascript array : <p>I'm want to get variable "priceWithVatMin" and "priceWithVatMax" from Javascript "array"</p>
<pre><code> <script>
dataLayer = [];
dataLayer.push({'shoptet' : {
"pageType": "productDetail",
"product": {
"id": 2148,
"name": "iPhone 7 Plus 32GB Black",
"currency": "CZK",
"priceWithVatMin": 12899,
"priceWithVatMax": 13599
}
</code></pre>
<p>i want some like write in console this variable e.g -> <code>console.log(?)</code>
Thanks lot :-) </p>
| 0debug |
static int a64_write_trailer(struct AVFormatContext *s)
{
A64MuxerContext *c = s->priv_data;
AVPacket pkt;
if(c->interleaved) a64_write_packet(s, &pkt);
return 0;
}
| 1threat |
Can both the values and keys of a dictionary be integers? : <p>Can both the values and keys of a dictionary be integers in python? Or do I need one of them to be like a string or something?</p>
| 0debug |
SwsFunc yuv2rgb_init_altivec (SwsContext *c)
{
if (!(c->flags & SWS_CPU_CAPS_ALTIVEC))
return NULL;
if ((c->srcW & 0xf) != 0) return NULL;
switch (c->srcFormat) {
case PIX_FMT_YUV410P:
case PIX_FMT_YUV420P:
case PIX_FMT_GRAY8:
case PIX_FMT_NV12:
case PIX_FMT_NV21:
if ((c->srcH & 0x1) != 0)
return NULL;
switch(c->dstFormat){
case PIX_FMT_RGB24:
av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space RGB24\n");
return altivec_yuv2_rgb24;
case PIX_FMT_BGR24:
av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space BGR24\n");
return altivec_yuv2_bgr24;
case PIX_FMT_ARGB:
av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space ARGB\n");
return altivec_yuv2_argb;
case PIX_FMT_ABGR:
av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space ABGR\n");
return altivec_yuv2_abgr;
case PIX_FMT_RGBA:
av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space RGBA\n");
return altivec_yuv2_rgba;
case PIX_FMT_BGRA:
av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space BGRA\n");
return altivec_yuv2_bgra;
default: return NULL;
}
break;
case PIX_FMT_UYVY422:
switch(c->dstFormat){
case PIX_FMT_BGR32:
av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space UYVY -> RGB32\n");
return altivec_uyvy_rgb32;
default: return NULL;
}
break;
}
return NULL;
}
| 1threat |
How to Dynamically hilight some words in html format : i have a List, that Included lots of keywords,
and have another List, that Included lots of text as HTML format.
i want dinamically Anywhere in my text come those keywords , i can hilight that keyword
what best way for this job in spring framework Or java? | 0debug |
Extracting city and state info out of zip codes in Excel : <p>I need to extract city and state info out of the zip codes in my Excel sheet.
I have an Excel sheet which has over 50 thousands of zip codes in a single column, I created another 2 columns next to it as City and State. </p>
<p>Is there any easy way or any common formula to find out corresponding city and state names with these zip codes and populate them in city and state columns?</p>
<p>Thanks..</p>
| 0debug |
static void store_slice_mmx(uint8_t *dst, const uint16_t *src,
int dst_stride, int src_stride,
int width, int height, int log2_scale,
const uint8_t dither[8][8])
{
int y;
for (y = 0; y < height; y++) {
uint8_t *dst1 = dst;
const int16_t *src1 = src;
__asm__ volatile(
"movq (%3), %%mm3 \n"
"movq (%3), %%mm4 \n"
"movd %4, %%mm2 \n"
"pxor %%mm0, %%mm0 \n"
"punpcklbw %%mm0, %%mm3 \n"
"punpckhbw %%mm0, %%mm4 \n"
"psraw %%mm2, %%mm3 \n"
"psraw %%mm2, %%mm4 \n"
"movd %5, %%mm2 \n"
"1: \n"
"movq (%0), %%mm0 \n"
"movq 8(%0), %%mm1 \n"
"paddw %%mm3, %%mm0 \n"
"paddw %%mm4, %%mm1 \n"
"psraw %%mm2, %%mm0 \n"
"psraw %%mm2, %%mm1 \n"
"packuswb %%mm1, %%mm0 \n"
"movq %%mm0, (%1) \n"
"add $16, %0 \n"
"add $8, %1 \n"
"cmp %2, %1 \n"
" jb 1b \n"
: "+r" (src1), "+r"(dst1)
: "r"(dst + width), "r"(dither[y]), "g"(log2_scale), "g"(MAX_LEVEL - log2_scale)
);
src += src_stride;
dst += dst_stride;
}
}
| 1threat |
How to search as a dictionary in C# : <p>I'm try to find the search term in my term collection.</p>
<p>array of term collection :</p>
<pre><code>[0] "windows"
[1] "dual sim"
[2] "32 gb"
[3] "Intel i5"
</code></pre>
<p>Now I search bellow term</p>
<pre><code>search term= "32 gb" return -> 2 (position of array)
search term ="android 32 gb" return -> 2 (position of array)
search term ="android mobile 32 gb" return -> 2 (position of array)
search term= "32 GB" return -> 2 (position of array)
search term= "32gb" return -> not match
search term= "dual sim 32" return -> 1 (position of array)
</code></pre>
<p>So how can do like this in C# .net
Can any search library or search dictionary provide this feature</p>
<p>Please advise/suggestion for same </p>
<p>Thanks! </p>
| 0debug |
How to workaround "the input device is not a TTY" when using grunt-shell to invoke a script that calls docker run? : <p>When issuing <code>grunt shell:test</code>, I'm getting warning "the input device is not a TTY" & don't want to have to use <code>-f</code>:</p>
<pre><code>$ grunt shell:test
Running "shell:test" (shell) task
the input device is not a TTY
Warning: Command failed: /bin/sh -c ./run.sh npm test
the input device is not a TTY
Use --force to continue.
Aborted due to warnings.
</code></pre>
<p>Here's the <code>Gruntfile.js</code> command:</p>
<pre><code>shell: {
test: {
command: './run.sh npm test'
}
</code></pre>
<p>Here's <code>run.sh</code>:</p>
<pre><code>#!/bin/sh
# should use the latest available image to validate, but not LATEST
if [ -f .env ]; then
RUN_ENV_FILE='--env-file .env'
fi
docker run $RUN_ENV_FILE -it --rm --user node -v "$PWD":/app -w /app yaktor/node:0.39.0 $@
</code></pre>
<p>Here's the relevant <code>package.json</code> <code>scripts</code> with command <code>test</code>:</p>
<pre><code>"scripts": {
"test": "mocha --color=true -R spec test/*.test.js && npm run lint"
}
</code></pre>
<p>How can I get <code>grunt</code> to make <code>docker</code> happy with a TTY? Executing <code>./run.sh npm test</code> outside of grunt works fine:</p>
<pre><code>$ ./run.sh npm test
> yaktor@0.59.2-pre.0 test /app
> mocha --color=true -R spec test/*.test.js && npm run lint
[snip]
105 passing (3s)
> yaktor@0.59.2-pre.0 lint /app
> standard --verbose
</code></pre>
| 0debug |
static void multiwrite_help(void)
{
printf(
"\n"
" writes a range of bytes from the given offset source from multiple buffers,\n"
" in a batch of requests that may be merged by qemu\n"
"\n"
" Example:\n"
" 'multiwrite 512 1k 1k ; 4k 1k' \n"
" writes 2 kB at 512 bytes and 1 kB at 4 kB into the open file\n"
"\n"
" Writes into a segment of the currently open file, using a buffer\n"
" filled with a set pattern (0xcdcdcdcd). The pattern byte is increased\n"
" by one for each request contained in the multiwrite command.\n"
" -P, -- use different pattern to fill file\n"
" -C, -- report statistics in a machine parsable format\n"
" -q, -- quiet mode, do not show I/O statistics\n"
"\n");
}
| 1threat |
def largest_neg(list1):
max = list1[0]
for x in list1:
if x < max :
max = x
return max | 0debug |
Array is returning "array ( )" : <p>So, I have this array:</p>
<pre><code>$id = DB::query('SELECT user_id FROM login_tokens WHERE token=:token',
array(':token' => sha1($_COOKIE['SNID'])));
$myusername = DB::query('SELECT username FROM users WHERE id=:id', array(':id'
=> $id));
print_r($myusername);
</code></pre>
<p>but it returns only array ( )</p>
| 0debug |
Flutter persistent navigation bar with named routes? : <p>I've been searching around for a good navigation/router example for Flutter but I have not managed to find one.</p>
<p>What I want to achieve is very simple:</p>
<ol>
<li>Persistent bottom navigation bar that highlights the current top level route</li>
<li>Named routes so I can navigate to any route from anywhere inside the app</li>
<li>Navigator.pop should always take me to the previous view I was in</li>
</ol>
<p>The official Flutter demo for BottomNavigationBar achieves 1 but back button and routing dont't work. Same problem with PageView and TabView. There are many other tutorials that achieve 2 and 3 by implementing MaterialApp routes but none of them seem to have a persistent navigation bar.</p>
<p>Are there any examples of a navigation system that would satisfy all these requirements?</p>
| 0debug |
Using function argument as part of a constant expression - gcc vs clang : <p>Consider the following code snippet:</p>
<pre><code>template <bool> struct B { };
template <typename T>
constexpr bool pred(T t) { return true; }
template <typename T>
auto f(T t) -> decltype(B<pred(t)>{})
{
}
</code></pre>
<ul>
<li><p>clang++ <em>(trunk)</em> compiles the code</p></li>
<li><p>g++ <em>(trunk)</em> fails compilation with the following error:</p>
<pre><code>src:7:34: error: template argument 1 is invalid
auto f(T t) -> decltype(B<pred(t)>{})
^
src:7:34: error: template argument 1 is invalid
src:7:34: error: template argument 1 is invalid
src:7:34: error: template argument 1 is invalid
src:7:34: error: template argument 1 is invalid
src:7:34: error: template argument 1 is invalid
src:7:25: error: invalid template-id
auto f(T t) -> decltype(B<pred(t)>{})
^
src:7:36: error: class template argument deduction failed:
auto f(T t) -> decltype(B<pred(t)>{})
^
src:7:36: error: no matching function for call to 'B()'
src:1:24: note: candidate: 'template<bool <anonymous> > B()-> B<<anonymous> >'
template <bool> struct B { };
^
src:1:24: note: template argument deduction/substitution failed:
src:7:36: note: couldn't deduce template parameter '<anonymous>'
auto f(T t) -> decltype(B<pred(t)>{})
^
</code></pre>
<p><a href="https://godbolt.org/g/Xjjcwc" rel="noreferrer"><strong>live example on godbolt.org</strong></a></p></li>
</ul>
<hr>
<p>Even though g++'s diagnostic is misleading, I assume that the problem here is that <code>t</code> is not a <em>constant expression</em>. Changing the code to...</p>
<pre><code>decltype(B<pred(T{})>{})
</code></pre>
<p>...fixes the compilation error on g++: <a href="https://godbolt.org/g/F4vxAX" rel="noreferrer"><strong>live example on godbolt.org</strong></a></p>
<hr>
<p>What compiler is behaving correctly here? </p>
| 0debug |
How to save continuous 512 bytes into file using fprintf : <p>I want to save continuous 512 memory location values into csv file</p>
<pre><code> memcpy(signals, ascanSamples, ascanSizeInBytes);
fprintf(fptr1, "%f,", *(signals));
</code></pre>
<p>Using fprintf how can i achieve it,.</p>
<p>I tried</p>
<pre><code>fprintf(fptr1, "%f,", 512,512, *(signals)) but it is not working
</code></pre>
| 0debug |
What is the reason for having edges and nodes in a connection in your graphql schema? : <p>I am trying to understand more complex graphql apis that implement the <a href="https://facebook.github.io/relay/graphql/connections.htm" rel="noreferrer">Relay Cursor Connections Specification</a></p>
<p>If you look at the query below that I run on the <a href="https://developer.github.com/early-access/graphql/explorer/" rel="noreferrer">github graphql api explorer</a></p>
<pre><code>{
repository(owner: "getsmarter", name: "moodle-api") {
id
issues(first:2 ) {
edges {
node {
id
body
}
}
nodes {
body
}
pageInfo {
endCursor
hasNextPage
hasPreviousPage
startCursor
}
totalCount
}
}
}
</code></pre>
<p>Notice it has the fields <strong>edges</strong> and <strong>nodes</strong>.</p>
<p>Why does github have an additional field called nodes in their api? Why don’t they just use the edges field since you can get the same data from edges? Is this just for convenience? </p>
| 0debug |
Anyone has a nice example of how to calculate a median for a grouped data in R or Python : if you can also please provide a small example on the usage and how data is processed, thanks in advance. I am trying to calculate the median of any grpued data like age cohort , for instance , how to choose the median value of such datasets | 0debug |
How to find all divs who's class starts with a string in BeautifulSoup? : <p>In BeautifulSoup, if I want to find all div's where whose class is span3, I'd just do:</p>
<pre><code>result = soup.findAll("div",{"class":"span3"})
</code></pre>
<p>However, in my case, I want to find all div's whose class starts with span3, therefore, BeautifulSoup should find:</p>
<pre><code><div id="span3 span49">
<div id="span3 span39">
</code></pre>
<p>And so on...</p>
<p>How do I achieve what I want? I am familiar with regular expressions; however I do not know how to implement them to beautiful soup nor did I find any help by going through BeautifulSoup's documentation.</p>
| 0debug |
static int64_t load_kernel (void)
{
int64_t kernel_entry, kernel_high;
long initrd_size;
ram_addr_t initrd_offset;
int big_endian;
uint32_t *prom_buf;
long prom_size;
int prom_index = 0;
#ifdef TARGET_WORDS_BIGENDIAN
big_endian = 1;
#else
big_endian = 0;
#endif
if (load_elf(loaderparams.kernel_filename, cpu_mips_kseg0_to_phys, NULL,
(uint64_t *)&kernel_entry, NULL, (uint64_t *)&kernel_high,
big_endian, ELF_MACHINE, 1) < 0) {
fprintf(stderr, "qemu: could not load kernel '%s'\n",
loaderparams.kernel_filename);
exit(1);
}
initrd_size = 0;
initrd_offset = 0;
if (loaderparams.initrd_filename) {
initrd_size = get_image_size (loaderparams.initrd_filename);
if (initrd_size > 0) {
initrd_offset = (kernel_high + ~INITRD_PAGE_MASK) & INITRD_PAGE_MASK;
if (initrd_offset + initrd_size > ram_size) {
fprintf(stderr,
"qemu: memory too small for initial ram disk '%s'\n",
loaderparams.initrd_filename);
exit(1);
}
initrd_size = load_image_targphys(loaderparams.initrd_filename,
initrd_offset,
ram_size - initrd_offset);
}
if (initrd_size == (target_ulong) -1) {
fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",
loaderparams.initrd_filename);
exit(1);
}
}
prom_size = ENVP_NB_ENTRIES * (sizeof(int32_t) + ENVP_ENTRY_SIZE);
prom_buf = g_malloc(prom_size);
prom_set(prom_buf, prom_index++, "%s", loaderparams.kernel_filename);
if (initrd_size > 0) {
prom_set(prom_buf, prom_index++, "rd_start=0x%" PRIx64 " rd_size=%li %s",
cpu_mips_phys_to_kseg0(NULL, initrd_offset), initrd_size,
loaderparams.kernel_cmdline);
} else {
prom_set(prom_buf, prom_index++, "%s", loaderparams.kernel_cmdline);
}
prom_set(prom_buf, prom_index++, "memsize");
prom_set(prom_buf, prom_index++, "%i", loaderparams.ram_size);
prom_set(prom_buf, prom_index++, "modetty0");
prom_set(prom_buf, prom_index++, "38400n8r");
prom_set(prom_buf, prom_index++, NULL);
rom_add_blob_fixed("prom", prom_buf, prom_size,
cpu_mips_kseg0_to_phys(NULL, ENVP_ADDR));
return kernel_entry;
}
| 1threat |
ArrayList finding the int value of position in List : java nub here. Stuck on my algorithm, all I am trying to do is print the position where my tradeaway string matches in my playerNames List. I want the index position in my playerNames, so I
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
public static void evaluationOfTrade(List tradeAway, List playerNames){
for(int i=tradeAway.size();i>0;i--){
String playerAway=(String) tradeAway.get(0);
String playerAwaySearch=(String) playerNames.get(i);
if(playerAway.equals(playerNames)){
System.out.println("Player found:"+" "+playerNames.get(i).toString()+" Index is : "+ playerNames.indexOf(playerNames.get(i)));
}
}
}
<!-- end snippet -->
ater. Any help? Been trying to read up on arrayLists all day cant seem to find my answer.
thanks | 0debug |
Why does Fish shell have dark blue as the default color for directories : <p>Is it just me?</p>
<p>I have just installed fish using <code>brew install fish</code> and I'm using iTerm2.</p>
<p><a href="https://i.stack.imgur.com/zEVGG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zEVGG.png" alt="Fish shell dark blue"></a></p>
<p>The color is absolutely unreadable. How do I change it to something nicer?</p>
| 0debug |
static uint64_t mv88w8618_pit_read(void *opaque, target_phys_addr_t offset,
unsigned size)
{
mv88w8618_pit_state *s = opaque;
mv88w8618_timer_state *t;
switch (offset) {
case MP_PIT_TIMER1_VALUE ... MP_PIT_TIMER4_VALUE:
t = &s->timer[(offset-MP_PIT_TIMER1_VALUE) >> 2];
return ptimer_get_count(t->ptimer);
default:
return 0;
}
}
| 1threat |
Function in a switch case loop : <p>Is it possible to put a function inside a switch case loop? Because I've tried this just to explore more of this loop. Though I tried other ways but still I've got the problem existed. Can anyone help me?</p>
<pre><code>#include <stdio.h>
int main(void)
{
int choice;
switch(choice);
{
case 1:
{
int GetData()
{
int num;
printf("Enter the amount of change: ");
scanf("%d%*c", &num);
return (num);
}
int getChange (int change,int fifty,int twenty,int ten,int five)
{
int num = change;
fifty = num/50;
num %= 50;
twenty = num/20;
num %= 20;
ten = num/10;
num %= 10;
five = num/5;
num %= 5;
return (fifty, twenty, ten, five);
}
int main()
{
int change, fifty, twenty, ten, five;
change = GetData();
if ((change < 5) || (change > 95) || (change%5 > 0))
{
printf("Amount must be between 5 and 95 and be a multiple
of 5.");
}
else
{
getChange(change, fifty, twenty, ten, five);
printf("Change for %d cents: \n", change);
if (fifty > 1)
printf("%d Fifty cent piece's.\n", fifty);
if (fifty == 1)
printf("%d Fifty cent piece.\n", fifty);
if (twenty > 1)
printf("%d Twenty cent piece's.\n", twenty);
if (twenty == 1)
printf("%d Twenty cent piece.\n", twenty);
if (ten > 1)
printf("%d Ten cent piece's\n", ten);
if (ten == 1)
printf("%d Ten cent piece.\n", ten);
if (five > 1)
printf("%d Five cent piece's\n", five);
if (five == 1)
printf("%d Five cent piece.\n", five);
}
return(0);
}
</code></pre>
| 0debug |
ValueError: invalid literal for int () with base 10. How to fix for alphanumeric values : I am working with a code which gives me the XY Coordinates and Plot number of map like plot number 20,21,22 etc. But if the map had alpha-numeric values like 20-A,20A or 20 A so here i am stuck because when i input the value like 20-A i got this error "ValueError: invalid literal for int () with base 10". So plz help me how to input alpha-numeric values.
Here is my code.
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import Tkinter as tk
import tkSimpleDialog
#Add path of map file here. The output will be saved in the same path with name map_file_name.extension.csv
path = "maps/21.jpg"
#Set this to true for verbose output in the console
debug = False
#Window for pop ups
root = tk.Tk()
root.withdraw()
root.lift()
root.attributes('-topmost',True)
root.after_idle(root.attributes,'-topmost',False)
#Global and state variables
global_state = 1
xcord_1, ycord_1, xcord_2, ycord_2 = -1,-1,-1,-1
edge1, edge2 = -1,-1
#Defining Plot
img = Image.open(path)
img = img.convert('RGB')
img = np.array(img)
if(debug):
print "Image Loaded; dimensions = "
print img.shape
#This let us bind the mouse function the plot
ax = plt.gca()
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
fig = plt.gcf()
#Selecting tight layout
fig.tight_layout()
#Plotting Image
imgplot = ax.imshow(img)
#Event listener + State changer
def onclick(event):
global xcord_1,xcord_2,ycord_1,ycord_2,edge1,edge2, imgplot,fig, ax, path
if(debug):
print "Single Click Detected"
print "State = " + str(global_state)
if event.dblclick:
if(debug):
print "Double Click Detection"
global global_state
if(global_state==0):
xcord_1 = event.xdata
ycord_1 = event.ydata
edge1 = (tkSimpleDialog.askstring("2nd", "No of 2nd Selected Plot"))
#Draw here
if edge1 is None: #Incase user cancels the pop up. Go to initial state
global_state = 1
pass
else:
edge1 = int(edge1)
global_state = 1
difference = edge2-edge1
dif_state = 1;
#So difference is always positive. Dif_state keeps track of plot at which side has the larger number
if difference <0:
dif_state = -1;
difference *= -1
#Corner Case; labelling a single plot
if(difference == 0):
import csv
fields = [int(xcord_1),int(ycord_1),edge1]
plt.scatter(int(xcord_1),int(ycord_1),marker='$' + str(edge1) + '$', s=150)
with open(path+'.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow(fields)
else:
if(debug):
print "P1 : (" + str(xcord_1) + ", " + str(ycord_1) + " )"
print "P2 : (" + str(xcord_2) + ", " + str(ycord_2) + " )"
for a in range(0,difference+1):
#Plotting the labels
plt.scatter(int(xcord_1+(a*(float(xcord_2-xcord_1)/difference))),int(ycord_1+a*((float(ycord_2-ycord_1)/difference))),marker='$'+str(edge1+dif_state*a)+'$',s=150)
#Saving in CSV
import csv
fields = [int(xcord_1+(a*(float(xcord_2-xcord_1)/difference))),int(ycord_1+a*((float(ycord_2-ycord_1)/difference))),str(edge1+dif_state*a)]
with open(path+'.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow(fields)
if debug:
print (int(xcord_1+(a*(float(xcord_2-xcord_1)/difference))),int(ycord_1+a*((float(ycord_2-ycord_1)/difference))))
plt.show()
elif(global_state == 1):
xcord_2 = event.xdata
ycord_2 = event.ydata
print "Recorded"
edge2 = (tkSimpleDialog.askstring("1st", "No of Selected Plot"))
print type(edge2)
if edge2 is None:
root.withdraw()
pass
else:
edge2 = int(edge2)
global_state = 0
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
| 0debug |
Is it possible to run command of cmd using php? : <p>Is it possible to run cmd command using php? i.e: I can see ip configuration as follows:
step1: open cmd
step2: run ipconfig/all</p>
<p>If I want to do this using php as like below what should I do:
I will input ipconfig/all in a text field then click a button named 'RUN' then I will get ip configuration as like as cmd command results.</p>
| 0debug |
def neg_count(list):
neg_count= 0
for num in list:
if num <= 0:
neg_count += 1
return neg_count | 0debug |
i m write the below jquery first ajax call return state list but second ajax call will not written any result of city : <script>
$(document).ready(function(){
$("#cnt_id").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "a1.php",
data: dataString,
cache: false,
success: function(html)
{
$("#state").html(html);
}
});
});
$("#state2").on('change',function()
{
var id=$(this).val();
//document.innerHTML(id+"country_id");
var cnt_id=$("#country_id").val();
var dataString = 'state_id=' + id + 'country_id=' + cnt_id;
$.ajax
({
type: "POST",
url: "a1.php",
data: dataString,
//async:true;
cache: false,
success: function(html)
{
$("#city").html(html);
}
});
});
});
</script> | 0debug |
Why my app doesnt pass to the next activity : <p>im trying to pass from the main activity to the second activity and also pass a number and it doesn't work
can someone show my what my mistake is </p>
<p>p.s
can anyone tell me how to do i make a loop that stops for the user to press the button to add text in the EditText and then reset the EditText and wait for him again to insert another text until an array is filled</p>
<p>thank you!!</p>
<pre><code>public class MainActivity extends AppCompatActivity {
public static int numOfSails;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
Button nextButton = (Button) findViewById(R.id.next_button);
EditText sailsNumET = (EditText) findViewById(R.id.sails_num);
numOfSails = Integer.parseInt(sailsNumET.toString());
nextButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
Intent addingIntent = new Intent(MainActivity.this,AddingActivity.class);
addingIntent.putExtra("nos",numOfSails);
startActivity(addingIntent);
}
});
}catch(NumberFormatException e){
}
}
}
</code></pre>
<p>and in the second activity this is the code</p>
<pre><code>public class AddingActivity extends AppCompatActivity {
public ArrayList<Sail> sails = new ArrayList<Sail>();
public static int numOfSails;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adding_main);
final Button addButton = (Button) findViewById(R.id.add_button);
final EditText minusInGallonsET = (EditText) findViewById(R.id.gallons_num);
final TextView counterET = (TextView) findViewById(R.id.counter_id);
Bundle bundle = getIntent().getExtras();
this.numOfSails = bundle.getInt("nos",0);
for (int i = 0 ; i< numOfSails; i++){
sails.add(new Sail());
}
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int counter = 0;
for (Sail s : sails){
s.setFuelInGallons(Integer.parseInt(minusInGallonsET.toString()));
s.setSailNum(counter);
counter++;
counterET.setText(counter);
}
}
});
}
}
</code></pre>
| 0debug |
Debugging Broken DAGs : <p>When the airflow webserver shows up errors like <code>Broken DAG: [<path/to/dag>] <error></code>, how and where can we find the full stacktrace for these exceptions?</p>
<p>I tried these locations:</p>
<p><code>/var/log/airflow/webserver</code> -- had no logs in the timeframe of execution, other logs were in binary and decoding with <code>strings</code> gave no useful information.</p>
<p><code>/var/log/airflow/scheduler</code> -- had some logs but were in binary form, tried to read them and looked to be mostly sqlalchemy logs probably for airflow's database.</p>
<p><code>/var/log/airflow/worker</code> -- shows up the logs for running DAGs, (same as the ones you see on the airflow page)</p>
<p>and then also under <code>/var/log/airflow/rotated</code> -- couldn't find the stacktrace I was looking for.</p>
<p>I am using airflow v1.7.1.3</p>
| 0debug |
char *qmp_memchar_read(const char *device, int64_t size,
bool has_format, enum DataFormat format,
Error **errp)
{
CharDriverState *chr;
uint8_t *read_data;
size_t count;
char *data;
chr = qemu_chr_find(device);
if (!chr) {
error_setg(errp, "Device '%s' not found", device);
return NULL;
}
if (qemu_is_chr(chr, "memory")) {
error_setg(errp,"%s is not memory char device", device);
return NULL;
}
if (size <= 0) {
error_setg(errp, "size must be greater than zero");
return NULL;
}
count = qemu_chr_cirmem_count(chr);
if (count == 0) {
return g_strdup("");
}
size = size > count ? count : size;
read_data = g_malloc0(size + 1);
cirmem_chr_read(chr, read_data, size);
if (has_format && (format == DATA_FORMAT_BASE64)) {
data = g_base64_encode(read_data, size);
} else {
data = (char *)read_data;
}
return data;
} | 1threat |
void g_free(void *mem)
{
free(mem);
}
| 1threat |
static uint64_t log16(uint64_t a){
int i;
int out=0;
assert(a >= (1<<16));
a<<=16;
for(i=19;i>=0;i--){
if(a<(exp16_table[i]<<16)) continue;
out |= 1<<i;
a = ((a<<16) + exp16_table[i]/2)/exp16_table[i];
}
return out;
}
| 1threat |
static void do_subtitle_out(AVFormatContext *s,
OutputStream *ost,
InputStream *ist,
AVSubtitle *sub,
int64_t pts)
{
static uint8_t *subtitle_out = NULL;
int subtitle_out_max_size = 1024 * 1024;
int subtitle_out_size, nb, i;
AVCodecContext *enc;
AVPacket pkt;
if (pts == AV_NOPTS_VALUE) {
av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
if (exit_on_error)
exit_program(1);
return;
}
enc = ost->enc_ctx;
if (!subtitle_out) {
subtitle_out = av_malloc(subtitle_out_max_size);
}
if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
nb = 2;
else
nb = 1;
for (i = 0; i < nb; i++) {
ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
if (!check_recording_time(ost))
return;
sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
sub->end_display_time -= sub->start_display_time;
sub->start_display_time = 0;
ost->frames_encoded++;
subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
subtitle_out_max_size, sub);
if (subtitle_out_size < 0) {
av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
exit_program(1);
}
av_init_packet(&pkt);
pkt.data = subtitle_out;
pkt.size = subtitle_out_size;
pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
if (i == 0)
pkt.pts += 90 * sub->start_display_time;
else
pkt.pts += 90 * sub->end_display_time;
}
output_packet(s, &pkt, ost);
}
}
| 1threat |
How do you properly install libcurl for use in visual studio 2017? : <p>I am just starting out in c++ and cannot figure out how to add libraries, in particular libcurl. I tried a bunch of tutorials but most were for 2013/10 or didn't work. Can anyone please explain (Preferably in standard/non technical English) how I can add the library? I have already tried adding it in the include section of the program and in the additional dependencies menu.</p>
<p>Note this is a re-post I asked virtually the same question around 3 days ago to which I received no replies. Not sure if that is because its very easy and I should have figured it out my self, or if it just got buried in a flood of questions, or some other reason. In any case sorry for the re-post.</p>
| 0debug |
Declare classes using 'class' or 'function' : <p>Right now, I know 2 different ways to declare a class. </p>
<p>Using <code>function</code>: </p>
<pre><code>function test (constructor) {
this.value = value;
}
test.prototype.method () {
}
</code></pre>
<p>Using <code>class</code>:</p>
<pre><code>class test {
constructor(parameters) {
this.value = value;
}
method () {
}
}
</code></pre>
<p>What is the difference (if any) between the two, and which should I use when?</p>
| 0debug |
Python: Quotient unequal to a variable with the same value : <p>Am working on a small math-checker using Python and everything works well except of divisions.
Problem: The quotient with two decimals (2/3 = 0.67), float, is equal to an input (0.67). But the if-statement I use to compare a user's input with the result says it isn't equal. </p>
<p>Assumption: the problem is related to float. </p>
<p>My code:</p>
<pre><code>result = float(value0 / value1)
result = round(result,2)
value3 = input("Number 1")
value3 = float(value3)
if result != value3:
print "Wrong!"
print result
elif result == value:
print "Right!"
</code></pre>
<p>Of course I could create a function with a different approach, but I am curious to understand why it doesn't work.</p>
<p>If there's a similar thread, please post the link and close this one. Thanks for any help.</p>
| 0debug |
static void dss_sp_unpack_coeffs(DssSpContext *p, const uint8_t *src)
{
GetBitContext gb;
DssSpFrame *fparam = &p->fparam;
int i;
int subframe_idx;
uint32_t combined_pitch;
uint32_t tmp;
uint32_t pitch_lag;
for (i = 0; i < DSS_SP_FRAME_SIZE; i += 2) {
p->bits[i] = src[i + 1];
p->bits[i + 1] = src[i];
}
init_get_bits(&gb, p->bits, DSS_SP_FRAME_SIZE * 8);
for (i = 0; i < 2; i++)
fparam->filter_idx[i] = get_bits(&gb, 5);
for (; i < 8; i++)
fparam->filter_idx[i] = get_bits(&gb, 4);
for (; i < 14; i++)
fparam->filter_idx[i] = get_bits(&gb, 3);
for (subframe_idx = 0; subframe_idx < 4; subframe_idx++) {
fparam->sf_adaptive_gain[subframe_idx] = get_bits(&gb, 5);
fparam->sf[subframe_idx].combined_pulse_pos = get_bits_long(&gb, 31);
fparam->sf[subframe_idx].gain = get_bits(&gb, 6);
for (i = 0; i < 7; i++)
fparam->sf[subframe_idx].pulse_val[i] = get_bits(&gb, 3);
}
for (subframe_idx = 0; subframe_idx < 4; subframe_idx++) {
unsigned int C72_binomials[PULSE_MAX] = {
72, 2556, 59640, 1028790, 13991544, 156238908, 1473109704,
3379081753
};
unsigned int combined_pulse_pos =
fparam->sf[subframe_idx].combined_pulse_pos;
int index = 6;
if (combined_pulse_pos < C72_binomials[PULSE_MAX - 1]) {
if (p->pulse_dec_mode) {
int pulse, pulse_idx;
pulse = PULSE_MAX - 1;
pulse_idx = 71;
combined_pulse_pos =
fparam->sf[subframe_idx].combined_pulse_pos;
for (i = 0; i < 7; i++) {
for (;
combined_pulse_pos <
dss_sp_combinatorial_table[pulse][pulse_idx];
--pulse_idx)
;
combined_pulse_pos -=
dss_sp_combinatorial_table[pulse][pulse_idx];
pulse--;
fparam->sf[subframe_idx].pulse_pos[i] = pulse_idx;
}
}
} else {
p->pulse_dec_mode = 0;
fparam->sf[subframe_idx].pulse_pos[6] = 0;
for (i = 71; i >= 0; i--) {
if (C72_binomials[index] <= combined_pulse_pos) {
combined_pulse_pos -= C72_binomials[index];
fparam->sf[subframe_idx].pulse_pos[6 - index] = i;
if (!index)
break;
--index;
}
--C72_binomials[0];
if (index) {
int a;
for (a = 0; a < index; a++)
C72_binomials[a + 1] -= C72_binomials[a];
}
}
}
}
combined_pitch = get_bits(&gb, 24);
fparam->pitch_lag[0] = (combined_pitch % 151) + 36;
combined_pitch /= 151;
for (i = 1; i < SUBFRAMES; i++) {
fparam->pitch_lag[i] = combined_pitch % 48;
combined_pitch /= 48;
}
pitch_lag = fparam->pitch_lag[0];
for (i = 1; i < SUBFRAMES; i++) {
if (pitch_lag > 162) {
fparam->pitch_lag[i] += 162 - 23;
} else {
tmp = pitch_lag - 23;
if (tmp < 36)
tmp = 36;
fparam->pitch_lag[i] += tmp;
}
pitch_lag = fparam->pitch_lag[i];
}
}
| 1threat |
How do I customize ASP.Net Core model binding errors? : <p>I would like to return only standardized error responses from my Web API (Asp.net Core 2.1), but I can't seem to figure out how to handle model binding errors.</p>
<p>The project is just created from the "ASP.NET Core Web Application" > "API" template. I've got a simple action defined as: </p>
<pre><code>[Route("[controller]")]
[ApiController]
public class MyTestController : ControllerBase
{
[HttpGet("{id}")]
public ActionResult<TestModel> Get(Guid id)
{
return new TestModel() { Greeting = "Hello World!" };
}
}
public class TestModel
{
public string Greeting { get; set; }
}
</code></pre>
<p>If I make a request to this action with an invalid Guid (eg, <code>https://localhost:44303/MyTest/asdf</code>), I get back the following response:</p>
<pre><code>{
"id": [
"The value 'asdf' is not valid."
]
}
</code></pre>
<p>I've got the following code in <code>Startup.Configure</code>:</p>
<pre><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
JsonErrorMiddleware.CreateSingleton(env);
if (!env.IsDevelopment())
{
app.UseHsts();
}
app
.UseHttpsRedirection()
.UseStatusCodePages(async ctx => { await JsonErrorMiddleware.Instance.Invoke(ctx.HttpContext); })
.UseExceptionHandler(new ExceptionHandlerOptions() { ExceptionHandler = JsonErrorMiddleware.Instance.Invoke })
.UseMvc()
}
</code></pre>
<p><code>JsonErrorMiddleware</code> is simply a class that converts errors to the correct shape I want to return and puts them into the response. It is not getting called at all for the model binding errors (no <code>Exception</code> is thrown and <code>UseStatusCodePages</code> is not called).</p>
<p>How do I hook into the model binding to provide a standardized error response across all actions in my project?</p>
<p>I've read a bunch of articles, but they all seem to either discuss global exception handling or validation errors.</p>
| 0debug |
uint64_t helper_fsel (uint64_t arg1, uint64_t arg2, uint64_t arg3)
{
CPU_DoubleU farg1;
farg1.ll = arg1;
if ((!float64_is_neg(farg1.d) || float64_is_zero(farg1.d)) && !float64_is_nan(farg1.d))
return arg2;
else
return arg3;
}
| 1threat |
Is this a correct implementation of realloc()? : I want to be able to have a user enter what they wish to do. There will be other options but for now I am working on "insert". The other two options will be "search" and "delete".
int main() {
char *input = malloc(sizeof(char) * 6);
printf("%s", "WELCOME TO USER'S SKIP LIST!\n\nWhat do you wish to do? ");
scanf("%6s", input);
if (strcmp(input, "insert") == 0) {
printf("%s", "What is the item? ");
input = realloc(input, (size_t)scanf("%s", input));
}
}
I initially allocate enough memory for `input` to have 6 characters. This is because the other two options will also only have 6 characters. After they enter `insert` they will have to enter an item that will have any number of characters, so I want to reallocate memory for `input` based on what they enter for an item. So if they enter `Nintendo Switch` there will be a reallocation for 15 characters. Is my implementation of `realloc()` the correct way of doing this?
| 0debug |
C++ I am trying to delete link list but it get errors when i tried to delete head or node in the middle : I know where is wrong but I don't know how to change it. Help, please! The only working is this **(CurrentNode->next == NULL)** if else case the other doesn't. What can I do?
```void Restaurant::deletereservation()
{
string name;
cout << "Enter name of customer that you want to delete: " << endl
<< "Name: ";
cin.ignore(80, '\n');
getline(cin, name);
ReservationNode *nodeIn = head;
ReservationNode *CurrentNode = head->next;
while ((CurrentNode != NULL) && (CurrentNode->Name != name))
{
nodeIn = CurrentNode;
CurrentNode = CurrentNode->next;
}
if (CurrentNode->Name != name){
cout << "Error!!!" << name << " is not found.Cant be deleted if there is no such person." << endl;
}
else{
if (nodeIn == head){
CurrentNode = head->next;
CurrentNode = head;
delete nodeIn;
}
else if(CurrentNode->next == NULL){
nodeIn ->next = NULL;
delete CurrentNode;
}
else{
nodeIn -> next = CurrentNode->next;
delete CurrentNode;
}
}
}```
| 0debug |
void OPPROTO op_check_addo_64 (void)
{
if (likely(!(((uint64_t)T2 ^ (uint64_t)T1 ^ UINT64_MAX) &
((uint64_t)T2 ^ (uint64_t)T0) & (1ULL << 63)))) {
xer_ov = 0;
} else {
xer_so = 1;
xer_ov = 1;
}
RETURN();
}
| 1threat |
static void hls_transform_unit(HEVCContext *s, int x0, int y0,
int xBase, int yBase, int cb_xBase, int cb_yBase,
int log2_cb_size, int log2_trafo_size,
int trafo_depth, int blk_idx)
{
HEVCLocalContext *lc = &s->HEVClc;
if (lc->cu.pred_mode == MODE_INTRA) {
int trafo_size = 1 << log2_trafo_size;
ff_hevc_set_neighbour_available(s, x0, y0, trafo_size, trafo_size);
s->hpc.intra_pred(s, x0, y0, log2_trafo_size, 0);
if (log2_trafo_size > 2) {
trafo_size = trafo_size << (s->sps->hshift[1] - 1);
ff_hevc_set_neighbour_available(s, x0, y0, trafo_size, trafo_size);
s->hpc.intra_pred(s, x0, y0, log2_trafo_size - 1, 1);
s->hpc.intra_pred(s, x0, y0, log2_trafo_size - 1, 2);
} else if (blk_idx == 3) {
trafo_size = trafo_size << s->sps->hshift[1];
ff_hevc_set_neighbour_available(s, xBase, yBase,
trafo_size, trafo_size);
s->hpc.intra_pred(s, xBase, yBase, log2_trafo_size, 1);
s->hpc.intra_pred(s, xBase, yBase, log2_trafo_size, 2);
}
}
if (lc->tt.cbf_luma ||
SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], x0, y0) ||
SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], x0, y0)) {
int scan_idx = SCAN_DIAG;
int scan_idx_c = SCAN_DIAG;
if (s->pps->cu_qp_delta_enabled_flag && !lc->tu.is_cu_qp_delta_coded) {
lc->tu.cu_qp_delta = ff_hevc_cu_qp_delta_abs(s);
if (lc->tu.cu_qp_delta != 0)
if (ff_hevc_cu_qp_delta_sign_flag(s) == 1)
lc->tu.cu_qp_delta = -lc->tu.cu_qp_delta;
lc->tu.is_cu_qp_delta_coded = 1;
ff_hevc_set_qPy(s, x0, y0, cb_xBase, cb_yBase, log2_cb_size);
}
if (lc->cu.pred_mode == MODE_INTRA && log2_trafo_size < 4) {
if (lc->tu.cur_intra_pred_mode >= 6 &&
lc->tu.cur_intra_pred_mode <= 14) {
scan_idx = SCAN_VERT;
} else if (lc->tu.cur_intra_pred_mode >= 22 &&
lc->tu.cur_intra_pred_mode <= 30) {
scan_idx = SCAN_HORIZ;
}
if (lc->pu.intra_pred_mode_c >= 6 &&
lc->pu.intra_pred_mode_c <= 14) {
scan_idx_c = SCAN_VERT;
} else if (lc->pu.intra_pred_mode_c >= 22 &&
lc->pu.intra_pred_mode_c <= 30) {
scan_idx_c = SCAN_HORIZ;
}
}
if (lc->tt.cbf_luma)
hls_residual_coding(s, x0, y0, log2_trafo_size, scan_idx, 0);
if (log2_trafo_size > 2) {
if (SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], x0, y0))
hls_residual_coding(s, x0, y0, log2_trafo_size - 1, scan_idx_c, 1);
if (SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], x0, y0))
hls_residual_coding(s, x0, y0, log2_trafo_size - 1, scan_idx_c, 2);
} else if (blk_idx == 3) {
if (SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], xBase, yBase))
hls_residual_coding(s, xBase, yBase, log2_trafo_size, scan_idx_c, 1);
if (SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], xBase, yBase))
hls_residual_coding(s, xBase, yBase, log2_trafo_size, scan_idx_c, 2);
}
}
}
| 1threat |
deleting elements in array of pointer (C++) : <p>Suppose I have an array of pointers like</p>
<pre><code>Person** p = new Person*[5]
// p is filled with five person pointer (say p[2] = *John where John is an object of person
// now we want to remove p[2]
delete p[2];
p[2] = p[3];
p[3] = p[4];
p[4] = nullptr;
</code></pre>
<p>The program cannot be compiled unless I remove the line of delete and nullptr.
Why will this happen? If I do not delete p[2], there should be problem as I cannot access john again?</p>
| 0debug |
static void blk_mig_cleanup(void)
{
BlkMigDevState *bmds;
BlkMigBlock *blk;
bdrv_drain_all();
unset_dirty_tracking();
blk_mig_lock();
while ((bmds = QSIMPLEQ_FIRST(&block_mig_state.bmds_list)) != NULL) {
QSIMPLEQ_REMOVE_HEAD(&block_mig_state.bmds_list, entry);
bdrv_op_unblock_all(bmds->bs, bmds->blocker);
error_free(bmds->blocker);
bdrv_unref(bmds->bs);
g_free(bmds->aio_bitmap);
g_free(bmds);
}
while ((blk = QSIMPLEQ_FIRST(&block_mig_state.blk_list)) != NULL) {
QSIMPLEQ_REMOVE_HEAD(&block_mig_state.blk_list, entry);
g_free(blk->buf);
g_free(blk);
}
blk_mig_unlock();
}
| 1threat |
def maximize_elements(test_tup1, test_tup2):
res = tuple(tuple(max(a, b) for a, b in zip(tup1, tup2))
for tup1, tup2 in zip(test_tup1, test_tup2))
return (res) | 0debug |
static always_inline void mpeg_motion_lowres(MpegEncContext *s,
uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
int field_based, int bottom_field, int field_select,
uint8_t **ref_picture, h264_chroma_mc_func *pix_op,
int motion_x, int motion_y, int h)
{
uint8_t *ptr_y, *ptr_cb, *ptr_cr;
int mx, my, src_x, src_y, uvsrc_x, uvsrc_y, uvlinesize, linesize, sx, sy, uvsx, uvsy;
const int lowres= s->avctx->lowres;
const int block_s= 8>>lowres;
const int s_mask= (2<<lowres)-1;
const int h_edge_pos = s->h_edge_pos >> lowres;
const int v_edge_pos = s->v_edge_pos >> lowres;
linesize = s->current_picture.linesize[0] << field_based;
uvlinesize = s->current_picture.linesize[1] << field_based;
if(s->quarter_sample){
motion_x/=2;
motion_y/=2;
}
if(field_based){
motion_y += (bottom_field - field_select)*((1<<lowres)-1);
}
sx= motion_x & s_mask;
sy= motion_y & s_mask;
src_x = s->mb_x*2*block_s + (motion_x >> (lowres+1));
src_y =(s->mb_y*2*block_s>>field_based) + (motion_y >> (lowres+1));
if (s->out_format == FMT_H263) {
uvsx = ((motion_x>>1) & s_mask) | (sx&1);
uvsy = ((motion_y>>1) & s_mask) | (sy&1);
uvsrc_x = src_x>>1;
uvsrc_y = src_y>>1;
}else if(s->out_format == FMT_H261){
mx = motion_x / 4;
my = motion_y / 4;
uvsx = (2*mx) & s_mask;
uvsy = (2*my) & s_mask;
uvsrc_x = s->mb_x*block_s + (mx >> lowres);
uvsrc_y = s->mb_y*block_s + (my >> lowres);
} else {
mx = motion_x / 2;
my = motion_y / 2;
uvsx = mx & s_mask;
uvsy = my & s_mask;
uvsrc_x = s->mb_x*block_s + (mx >> (lowres+1));
uvsrc_y =(s->mb_y*block_s>>field_based) + (my >> (lowres+1));
}
ptr_y = ref_picture[0] + src_y * linesize + src_x;
ptr_cb = ref_picture[1] + uvsrc_y * uvlinesize + uvsrc_x;
ptr_cr = ref_picture[2] + uvsrc_y * uvlinesize + uvsrc_x;
if( (unsigned)src_x > h_edge_pos - (!!sx) - 2*block_s
|| (unsigned)src_y >(v_edge_pos >> field_based) - (!!sy) - h){
ff_emulated_edge_mc(s->edge_emu_buffer, ptr_y, s->linesize, 17, 17+field_based,
src_x, src_y<<field_based, h_edge_pos, v_edge_pos);
ptr_y = s->edge_emu_buffer;
if(!(s->flags&CODEC_FLAG_GRAY)){
uint8_t *uvbuf= s->edge_emu_buffer+18*s->linesize;
ff_emulated_edge_mc(uvbuf , ptr_cb, s->uvlinesize, 9, 9+field_based,
uvsrc_x, uvsrc_y<<field_based, h_edge_pos>>1, v_edge_pos>>1);
ff_emulated_edge_mc(uvbuf+16, ptr_cr, s->uvlinesize, 9, 9+field_based,
uvsrc_x, uvsrc_y<<field_based, h_edge_pos>>1, v_edge_pos>>1);
ptr_cb= uvbuf;
ptr_cr= uvbuf+16;
}
}
if(bottom_field){
dest_y += s->linesize;
dest_cb+= s->uvlinesize;
dest_cr+= s->uvlinesize;
}
if(field_select){
ptr_y += s->linesize;
ptr_cb+= s->uvlinesize;
ptr_cr+= s->uvlinesize;
}
sx <<= 2 - lowres;
sy <<= 2 - lowres;
pix_op[lowres-1](dest_y, ptr_y, linesize, h, sx, sy);
if(!(s->flags&CODEC_FLAG_GRAY)){
uvsx <<= 2 - lowres;
uvsy <<= 2 - lowres;
pix_op[lowres](dest_cb, ptr_cb, uvlinesize, h >> s->chroma_y_shift, uvsx, uvsy);
pix_op[lowres](dest_cr, ptr_cr, uvlinesize, h >> s->chroma_y_shift, uvsx, uvsy);
}
} | 1threat |
iscsi_aio_writev(BlockDriverState *bs, int64_t sector_num,
QEMUIOVector *qiov, int nb_sectors,
BlockDriverCompletionFunc *cb,
void *opaque)
{
IscsiLun *iscsilun = bs->opaque;
struct iscsi_context *iscsi = iscsilun->iscsi;
IscsiAIOCB *acb;
size_t size;
uint32_t num_sectors;
uint64_t lba;
#if !defined(LIBISCSI_FEATURE_IOVECTOR)
struct iscsi_data data;
#endif
int ret;
acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
trace_iscsi_aio_writev(iscsi, sector_num, nb_sectors, opaque, acb);
acb->iscsilun = iscsilun;
acb->qiov = qiov;
acb->canceled = 0;
acb->bh = NULL;
acb->status = -EINPROGRESS;
acb->buf = NULL;
size = nb_sectors * BDRV_SECTOR_SIZE;
#if !defined(LIBISCSI_FEATURE_IOVECTOR)
data.size = MIN(size, acb->qiov->size);
if (acb->qiov->niov == 1) {
data.data = acb->qiov->iov[0].iov_base;
} else {
acb->buf = g_malloc(data.size);
qemu_iovec_to_buf(acb->qiov, 0, acb->buf, data.size);
data.data = acb->buf;
}
#endif
acb->task = malloc(sizeof(struct scsi_task));
if (acb->task == NULL) {
error_report("iSCSI: Failed to allocate task for scsi WRITE16 "
"command. %s", iscsi_get_error(iscsi));
qemu_aio_release(acb);
return NULL;
}
memset(acb->task, 0, sizeof(struct scsi_task));
acb->task->xfer_dir = SCSI_XFER_WRITE;
acb->task->cdb_size = 16;
acb->task->cdb[0] = 0x8a;
lba = sector_qemu2lun(sector_num, iscsilun);
*(uint32_t *)&acb->task->cdb[2] = htonl(lba >> 32);
*(uint32_t *)&acb->task->cdb[6] = htonl(lba & 0xffffffff);
num_sectors = size / iscsilun->block_size;
*(uint32_t *)&acb->task->cdb[10] = htonl(num_sectors);
acb->task->expxferlen = size;
#if defined(LIBISCSI_FEATURE_IOVECTOR)
ret = iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
iscsi_aio_write16_cb,
NULL,
acb);
#else
ret = iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
iscsi_aio_write16_cb,
&data,
acb);
#endif
if (ret != 0) {
scsi_free_scsi_task(acb->task);
g_free(acb->buf);
qemu_aio_release(acb);
return NULL;
}
#if defined(LIBISCSI_FEATURE_IOVECTOR)
scsi_task_set_iov_out(acb->task, (struct scsi_iovec*) acb->qiov->iov, acb->qiov->niov);
#endif
iscsi_set_events(iscsilun);
return &acb->common;
}
| 1threat |
Extract text element separated by hash & comma and store it in separate variable using python : I have text file having this content
```
group11#,['631', '1051']#,ADD/H/U_LS_FR_U#,group12#,['1', '1501']#,ADD/H/U_LS_FR_U#,group13#,['31', '28']#,ADD/H/UC_DT_SS#,group14#,['18', '27', '1017', '1073']#,AN/H/UC_HR_BAN#,group15#,['13']#,AD/H/U_LI_NW#,group16#,['1031']#,AN/HE/U_LE_NW_IES#
```
Requirment is to pull each element separated by **#,** and to store it in separate variable. And text file above is not having fixed length. So if there are 200 #, separated values then, those should be stored in 200 varaiables.
So the expected output would be
```
a = group11, b = 631, 1051, c = ADD/H/U_LS_FR_U, d = group12, e = 1, 1501, f = ADD/H/U_LS_FR_U and so on
```
Not sure how to achive this?
I've started with
```
with open("filename.txt", "r") as f:
data = f.readlines()
``` | 0debug |
How change backcolor of controlBar in <video> : anyone know how change background-color of ControlBar in <video> tag.
Same attach image.[Same this][1]
[1]: http://i.stack.imgur.com/BnHel.jpg | 0debug |
static int s337m_probe(AVProbeData *p)
{
uint64_t state = 0;
int markers[3] = { 0 };
int i, sum, max, data_type, data_size, offset;
uint8_t *buf;
for (buf = p->buf; buf < p->buf + p->buf_size; buf++) {
state = (state << 8) | *buf;
if (!IS_LE_MARKER(state))
continue;
if (IS_16LE_MARKER(state)) {
data_type = AV_RL16(buf + 1);
data_size = AV_RL16(buf + 3);
buf += 4;
} else {
data_type = AV_RL24(buf + 1);
data_size = AV_RL24(buf + 4);
buf += 6;
}
if (s337m_get_offset_and_codec(NULL, state, data_type, data_size, &offset, NULL))
continue;
i = IS_16LE_MARKER(state) ? 0 : IS_20LE_MARKER(state) ? 1 : 2;
markers[i]++;
buf += offset;
state = 0;
}
sum = max = 0;
for (i = 0; i < FF_ARRAY_ELEMS(markers); i++) {
sum += markers[i];
if (markers[max] < markers[i])
max = i;
}
if (markers[max] > 3 && markers[max] * 4 > sum * 3)
return AVPROBE_SCORE_EXTENSION + 1;
return 0;
}
| 1threat |
static inline void gen_op_evsrwu(TCGv_i32 ret, TCGv_i32 arg1, TCGv_i32 arg2)
{
TCGv_i32 t0;
int l1, l2;
l1 = gen_new_label();
l2 = gen_new_label();
t0 = tcg_temp_local_new_i32();
tcg_gen_andi_i32(t0, arg2, 0x3F);
tcg_gen_brcondi_i32(TCG_COND_GE, t0, 32, l1);
tcg_gen_shr_i32(ret, arg1, t0);
tcg_gen_br(l2);
gen_set_label(l1);
tcg_gen_movi_i32(ret, 0);
gen_set_label(l2);
tcg_temp_free_i32(t0);
}
| 1threat |
How to change the meaning of SIGTERM in C programme : I've recently have a problem with signals. I'd like to write a program in C which would print anything after the signal is send to the process. For egzample: I'm sending SIGTERM for my process (which is simply running programme) , and the programme prints out for egzample "killing the process denied" instead of killing the process. So how to do that? How to force process to catch and change the meaning of such signal. Also I have a question if there is any possibility to kill init process (I know it's kind of stiupid question , but I was wondering how linux is dealing with such signal, and how would it technically look like if I type :"sudo kill -9 1") | 0debug |
SBT project refresh failed [IntelliJ, Scala, SBT] : <p>Whenever I try to enable auto-import in IntelliJ it always gives me this error:</p>
<pre><code>SBT 'Example' project refresh failed
Error while importing SBT project:
...
[warn] ==== public: tried
[warn] https://repo1.maven.org/maven2/org/scalatest/scalatest_2.12/2.2.6/scalatest_2.12-2.2.6.pom
[info] Resolving org.scala-lang#scala-compiler;2.12.0 ...
[info] Resolving org.scala-lang#scala-reflect;2.12.0 ...
[info] Resolving org.scala-lang.modules#scala-xml_2.12;1.0.5 ...
[info] Resolving jline#jline;2.14.1 ...
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: UNRESOLVED DEPENDENCIES ::
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: org.scalatest#scalatest_2.12;2.2.6: not found
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn]
[warn] Note: Unresolved dependencies path:
[warn] org.scalatest:scalatest_2.12:2.2.6 (/Users/sarahbaka/Desktop/Scala/Example/build.sbt#L7-8)
[warn] +- default:example_2.12:1.0
[trace] Stack trace suppressed: run 'last *:update' for the full output.
[trace] Stack trace suppressed: run 'last *:ssExtractDependencies' for the full output.
[error] (*:update) sbt.ResolveException: unresolved dependency: org.scalatest#scalatest_2.12;2.2.6: not found
[error] (*:ssExtractDependencies) sbt.ResolveException: unresolved dependency: org.scalatest#scalatest_2.12;2.2.6: not found
[error] Total time: 4 s, completed 08-Nov-2016 22:24:34</pre><br/>
</code></pre>
<p>I already installed the JetBrains Scala plugin, then opened a directory with an SBT build and reset/restarted my cache (File -> Invalidate Caches / Restart). But it still doesn't work! Does anyone know why?</p>
| 0debug |
scrape all songs using cheerio : I'm trying to write nodejs code, that take an argument from user as a singer name , and then go to into the specified singer name in this website 'https://www.billboard.com/charts/rap-song' , and print all of their songs' name
for example if i run: `Node Singer.js Drake`, it will go to drake page, and print all his songs,
I don't know how to do that, can someone help me plz
var request = require('request');
var cheerio = require('cheerio');
const args = process.argv;
request('https://www.billboard.com/charts/rap-song', function(error,response,html){
if(!error && response.statusCode == 200){
var $ = cheerio.load(html);
$('a.chart-row__artist').each(function(i, element) {
if(i%2==1 && i<20){
console.log($(this).text());
}
});
}
}); | 0debug |
Arraylist for subclasses : <p>I have a Vehicle superclass and then I have some subclasses to that one. I am trying to have an array list that adds objects from all of the subclasses into the same list, but I'm coming up short.</p>
<p>I currently have the list in my program class but I have moved it around a bit.</p>
<p>This is the code I have in Program:</p>
<pre><code>ArrayList<Vehicles> Inventorie = new ArrayList<>();
public void setInventorie(Car newCar) {
Inventorie.add(newCar);
}
</code></pre>
<p>And this the code I have in Car:</p>
<pre><code>public void addCar(){
System.out.println("Make: ");
Make = scan.nextLine();
System.out.println("RegNr");
regNr = scan.nextInt();
System.out.println("Year");
year = scan.nextInt();
setValue();
Car c1 = new Car(make, regNr, Year);
Program.setInventorie(c1);
}
</code></pre>
<p>In Car I am getting "Non-static method 'setInventorie(Project1.Vehicles)' cannot be referenced from static context."</p>
<p>I also had to comment out the main method or the compiler couldn't resolve the symbol Inventorie (name of array list).</p>
<p>Tried to explain my problem as best as I could, hope someone can help.
And yes, I am new to this so it might seem really stupid but it's the best I could do.</p>
<p>Thanks</p>
| 0debug |
void term_printf(const char *fmt, ...)
{
char buf[4096];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
qemu_chr_write(monitor_hd, buf, strlen(buf));
va_end(ap);
}
| 1threat |
Using jQuery DataTables with Rollup.js : <p>Ok I'm using the tool rollup for the first time and I love how small it is making the code. Tree shaking is great. However, I'm having some trouble getting it to include everything correctly. I tried having a single entry point, exp.js, where I export things from various files like this:</p>
<pre><code>export {
dashboardCharts
} from './dashboard.js';
</code></pre>
<p>my rollup.config.js looks like </p>
<pre><code>export default {
// tell rollup our main entry point
input: [
'assets/js/exp.js',
],
output: {
name: 'helloworld',
file: 'build/js/main.js',
format: 'iife'
// format: 'umd'
},
plugins: [
resolve({
// pass custom options to the resolve plugin
customResolveOptions: {
moduleDirectory: 'node_modules'
}
}),
multiEntry()
// terser(),
],
};
</code></pre>
<p>The file dashboard.js includes the datatables library, so datatables gets included in the bundle main.js. However, datatables tests whether it should take the commonjs path or not by testing </p>
<pre><code>else if ( typeof exports === 'object' ) {
// CommonJS
module.exports = function (root, $) {
</code></pre>
<p>and I'm trying to execute this in the browser, so I don't want the commonjs path. Rollup's top level scope is declared like</p>
<pre><code>var helloworld = (function (exports) {
</code></pre>
<p>so exports ends up being an empty object, the browser tries to execute the commonjs path and we get a "module is not defined" error. </p>
<p>I feel like I'm really close, but I'm missing a simple solution here. I also tried doing a umd format instead of iife, but it didn't help. Is there a different version of datatables I should be using?</p>
| 0debug |
int bdrv_open_image(BlockDriverState **pbs, const char *filename,
QDict *options, const char *bdref_key, int flags,
bool allow_none, Error **errp)
{
QDict *image_options;
int ret;
char *bdref_key_dot;
const char *reference;
assert(pbs);
assert(*pbs == NULL);
bdref_key_dot = g_strdup_printf("%s.", bdref_key);
qdict_extract_subqdict(options, &image_options, bdref_key_dot);
g_free(bdref_key_dot);
reference = qdict_get_try_str(options, bdref_key);
if (!filename && !reference && !qdict_size(image_options)) {
if (allow_none) {
ret = 0;
} else {
error_setg(errp, "A block device must be specified for \"%s\"",
bdref_key);
ret = -EINVAL;
}
goto done;
}
ret = bdrv_open(pbs, filename, reference, image_options, flags, NULL, errp);
done:
qdict_del(options, bdref_key);
return ret;
} | 1threat |
void cpu_io_recompile(CPUState *cpu, uintptr_t retaddr)
{
#if defined(TARGET_MIPS) || defined(TARGET_SH4)
CPUArchState *env = cpu->env_ptr;
#endif
TranslationBlock *tb;
uint32_t n, cflags;
target_ulong pc, cs_base;
uint32_t flags;
tb_lock();
tb = tb_find_pc(retaddr);
if (!tb) {
cpu_abort(cpu, "cpu_io_recompile: could not find TB for pc=%p",
(void *)retaddr);
}
n = cpu->icount_decr.u16.low + tb->icount;
cpu_restore_state_from_tb(cpu, tb, retaddr);
n = n - cpu->icount_decr.u16.low;
n++;
#if defined(TARGET_MIPS)
if ((env->hflags & MIPS_HFLAG_BMASK) != 0 && n > 1) {
env->active_tc.PC -= (env->hflags & MIPS_HFLAG_B16 ? 2 : 4);
cpu->icount_decr.u16.low++;
env->hflags &= ~MIPS_HFLAG_BMASK;
}
#elif defined(TARGET_SH4)
if ((env->flags & ((DELAY_SLOT | DELAY_SLOT_CONDITIONAL))) != 0
&& n > 1) {
env->pc -= 2;
cpu->icount_decr.u16.low++;
env->flags &= ~(DELAY_SLOT | DELAY_SLOT_CONDITIONAL);
}
#endif
if (n > CF_COUNT_MASK) {
cpu_abort(cpu, "TB too big during recompile");
}
cflags = n | CF_LAST_IO;
cflags |= curr_cflags();
pc = tb->pc;
cs_base = tb->cs_base;
flags = tb->flags;
tb_phys_invalidate(tb, -1);
if (tb->cflags & CF_NOCACHE) {
if (tb->orig_tb) {
tb_phys_invalidate(tb->orig_tb, -1);
}
tb_free(tb);
}
tb_gen_code(cpu, pc, cs_base, flags, cflags);
cpu_loop_exit_noexc(cpu);
}
| 1threat |
How to Remove Specific Value From Cache : I Want to Remove Specific Cache Value From Particular Cache.
e.g
Cache.Insert("TestCacheKey", "111", null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.High,null);
Cache.Insert("TestCacheKey", "222", null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
Cache.Insert("TestCacheKey", "333", null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
So, i have some data added in cache key i.e "TestCacheKey". Now, i want to delete specific value i.e "111" from that key i.e "TestCacheKey".
After Delete Specific value and when i retrieve that cache i just get only two records i.e "222" & "333" value
So, how can i achieve this to delete specific value from cache.
Help Please
| 0debug |
static int ram_save_host_page(RAMState *rs, PageSearchStatus *pss,
bool last_stage,
ram_addr_t dirty_ram_abs)
{
int tmppages, pages = 0;
size_t pagesize = qemu_ram_pagesize(pss->block);
do {
tmppages = ram_save_target_page(rs, pss, last_stage, dirty_ram_abs);
if (tmppages < 0) {
return tmppages;
}
pages += tmppages;
pss->offset += TARGET_PAGE_SIZE;
dirty_ram_abs += TARGET_PAGE_SIZE;
} while (pss->offset & (pagesize - 1));
pss->offset -= TARGET_PAGE_SIZE;
return pages;
}
| 1threat |
The equivalent of an array of struct in Android Studio and how to implement it : <p>I am making a quiz app and i couldn't figure out how to store my questions and answers without using SQLite or datashare
I'm used to c++ so I'm searching for the equivalent of making a struct and using an array to store my data </p>
<pre><code>struct item {
string Question;
string Answer1;
string Answer2;
};
item data[] ;
</code></pre>
<p>how can i make an equivalent of this in Android Studio, store data in it and import from it to a textView for example ?? </p>
| 0debug |
static int decode_b_mbs(VC9Context *v)
{
int x, y, current_mb = 0 , last_mb = v->height_mb*v->width_mb,
i ;
int direct_b_bit = 0, skip_mb_bit = 0;
int ac_pred;
int b_mv1 = 0, b_mv2 = 0, b_mv_type = 0;
int mquant, mqdiff;
int tt_block;
for (y=0; y<v->height_mb; y++)
{
for (x=0; x<v->width_mb; x++)
{
if (v->direct_mb_plane[current_mb])
direct_b_bit = get_bits(&v->gb, 1);
if (1 )
{
#if 0
skip_mb_bit = get_bits(&v->gb, n);
#endif
}
if (!direct_b_bit)
{
if (skip_mb_bit)
{
#if 0
b_mv_type = get_bits(&v->gb, n);
#endif
}
else
{
#if 0
b_mv1 = get_bits(&v->gb, n);
#endif
if (1 )
{
b_mv_type = 0;
}
}
}
if (!skip_mb_bit)
{
if (b_mv1 != last_mb)
{
GET_MQUANT();
if (1 )
ac_pred = get_bits(&v->gb, 1);
}
else
{
if (1 )
{
b_mv2 = 0;
}
if (1 )
{
if (1 )
ac_pred = get_bits(&v->gb, 1);
GET_MQUANT();
}
}
}
#if 0
if (v->ttmbf)
v->ttmb = get_bits(&v->gb, n);
#endif
}
for (i=0; i<6; i++)
{
}
current_mb++;
}
return 0;
}
| 1threat |
break or return from when expressions : <p>What I would like to do:</p>
<pre><code>when(transaction.state) {
Transaction.Type.EXPIRED,
//about 10 more types
Transaction.Type.BLOCKED -> {
if (transaction.type == Transaction.Type.BLOCKED && transaction.closeAnyway) {
close(transaction)
break //close if type is blocked and has 'closeAnyway' flag
}
//common logic
}
//other types
}
</code></pre>
<p>I cannot write <code>break</code>:</p>
<blockquote>
<p>'break' and 'continue' are not allowed in 'when' statements. Consider using labels to continue/break from the outer loop.</p>
</blockquote>
<p>Is it a way to <code>return/break</code> from <code>when</code> statements? Or what is the best way to solve it?</p>
| 0debug |
int avpriv_mpeg4audio_get_config(MPEG4AudioConfig *c, const uint8_t *buf,
int bit_size, int sync_extension)
{
GetBitContext gb;
int specific_config_bitindex;
if(bit_size<=0)
return AVERROR_INVALIDDATA;
init_get_bits(&gb, buf, bit_size);
c->object_type = get_object_type(&gb);
c->sample_rate = get_sample_rate(&gb, &c->sampling_index);
c->chan_config = get_bits(&gb, 4);
if (c->chan_config < FF_ARRAY_ELEMS(ff_mpeg4audio_channels))
c->channels = ff_mpeg4audio_channels[c->chan_config];
c->sbr = -1;
c->ps = -1;
if (c->object_type == AOT_SBR || (c->object_type == AOT_PS &&
!(show_bits(&gb, 3) & 0x03 && !(show_bits(&gb, 9) & 0x3F)))) {
if (c->object_type == AOT_PS)
c->ps = 1;
c->ext_object_type = AOT_SBR;
c->sbr = 1;
c->ext_sample_rate = get_sample_rate(&gb, &c->ext_sampling_index);
c->object_type = get_object_type(&gb);
if (c->object_type == AOT_ER_BSAC)
c->ext_chan_config = get_bits(&gb, 4);
} else {
c->ext_object_type = AOT_NULL;
c->ext_sample_rate = 0;
}
specific_config_bitindex = get_bits_count(&gb);
if (c->object_type == AOT_ALS) {
skip_bits(&gb, 5);
if (show_bits_long(&gb, 24) != MKBETAG('\0','A','L','S'))
skip_bits_long(&gb, 24);
specific_config_bitindex = get_bits_count(&gb);
if (parse_config_ALS(&gb, c))
return -1;
}
if (c->ext_object_type != AOT_SBR && sync_extension) {
while (get_bits_left(&gb) > 15) {
if (show_bits(&gb, 11) == 0x2b7) {
get_bits(&gb, 11);
c->ext_object_type = get_object_type(&gb);
if (c->ext_object_type == AOT_SBR && (c->sbr = get_bits1(&gb)) == 1) {
c->ext_sample_rate = get_sample_rate(&gb, &c->ext_sampling_index);
if (c->ext_sample_rate == c->sample_rate)
c->sbr = -1;
}
if (get_bits_left(&gb) > 11 && get_bits(&gb, 11) == 0x548)
c->ps = get_bits1(&gb);
break;
} else
get_bits1(&gb);
}
}
if (!c->sbr)
c->ps = 0;
if ((c->ps == -1 && c->object_type != AOT_AAC_LC) || c->channels & ~0x01)
c->ps = 0;
return specific_config_bitindex;
}
| 1threat |
How to use dynamic resource names in Terraform? : <p>I would like to use the same terraform template for several dev and production environments. </p>
<p>My approach:
As I understand it, the resource name needs to be unique, and terraform stores the state of the resource internally. I therefore tried to use variables for the resource names - but it seems to be not supported. I get an error message:</p>
<pre><code>$ terraform plan
var.env1
Enter a value: abc
Error asking for user input: Error parsing address 'aws_sqs_queue.SqsIntegrationOrderIn${var.env1}': invalid resource address "aws_sqs_queue.SqsIntegrationOrderIn${var.env1}"
</code></pre>
<p>My terraform template:</p>
<pre><code>variable "env1" {}
provider "aws" {
region = "ap-southeast-2"
}
resource "aws_sqs_queue" "SqsIntegrationOrderIn${var.env1}" {
name = "Integration_Order_In__${var.env1}"
message_retention_seconds = 86400
receive_wait_time_seconds = 5
}
</code></pre>
<p>I think, either my approach is wrong, or the syntax. Any ideas?</p>
| 0debug |
Null Pointer Exc: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference : <p>I have MainActivity:
public class MainActivity extends Activity {</p>
<pre><code>private ArrayList<Antrenament> listaAntr = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Antrenament a1 = new Antrenament("forta","12/06/2019",50,"Andrei");
listaAntr.add(a1);
Button bAdd = (Button) findViewById(R.id.buttonAdd);
Button bLista = (Button) findViewById(R.id.buttonList);
bAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AdaugareAntrenament.class);
intent.putParcelableArrayListExtra("listaant",listaAntr);
startActivityForResult(intent,1);
}
});
bLista.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ListaAntr.class);
intent.putParcelableArrayListExtra("listaant",listaAntr);
startActivityForResult(intent,1);
}
});
Intent intent2 = getIntent();
listaAntr = intent2.getParcelableArrayListExtra("listaantr");
}
</code></pre>
<p>}</p>
<p>I want to send the list of objects Antrenament name listaAntr to AdaugareAntrenament activity, where I want to create a new Antrenament object, add it to the list and then send back the list to mainactivity. This updated list I want to send afterward to ListaAntr Activity, from mainactivity.</p>
<p>AdaugareAntrenament activity:</p>
<p>public class AdaugareAntrenament extends Activity {</p>
<pre><code> ArrayList<Antrenament> listaAntr1=new ArrayList<>();
//private Button add;
EditText etcateg, etdurata, etinstr,etdata;
List<String> listacateg=new ArrayList<>();
Spinner spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adaugare_antrenament);
Intent intent = getIntent();
listaAntr1 = intent.getParcelableArrayListExtra("listaant");
Button add = findViewById(R.id.buttonSave);
etdurata=findViewById(R.id.editTextDurata);
etinstr=findViewById(R.id.editTextInstructor);
etdata=findViewById(R.id.editTextData);
spinner=findViewById(R.id.spinner);
listacateg=new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.categ)));
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,listacateg);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String categorie,instructor,data;
int durata;
durata = Integer.parseInt(etdurata.getText().toString());
instructor = etinstr.getText().toString().trim();
data = etdata.getText().toString().trim();
categorie = spinner.getSelectedItem().toString().trim();
if(TextUtils.isEmpty(instructor)) {
etinstr.setError("Introduceti numele instructorului");
return;
}
if(TextUtils.isEmpty(data)) {
etdata.setError("Introduceti data programarii");
return;
}
Antrenament antr = new Antrenament(categorie, data, durata, instructor);
listaAntr1.add(antr);
Intent intent=new Intent(getApplicationContext(), MainActivity.class);
intent.putParcelableArrayListExtra("listaantr",listaAntr1);
}
});
}
</code></pre>
<p>For the moment I get that error when I try to create the Antrenament object.. but this after some changes, because my code doesn't even send the updated list back to main activity.</p>
<p>Current error: </p>
<pre><code> java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
at com.example.ancaa.rezolvarerestanta20181.AdaugareAntrenament$1.onClick(AdaugareAntrenament.java:78)
</code></pre>
<p>The error points to the line : </p>
<pre><code> listaAntr1.add(antr);
</code></pre>
<p>and ListaAntr Activity: </p>
<p>public class ListaAntr extends Activity {</p>
<pre><code>public ArrayList<Antrenament> listaAntr = new ArrayList<>();
public ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_antr);
lv = (ListView)findViewById(R.id.lista);
Intent intent = getIntent();
listaAntr = intent.getParcelableArrayListExtra("listaantr");
ArrayAdapter<Antrenament> adapter=new ArrayAdapter<Antrenament>(this,android.R.layout.simple_list_item_1,listaAntr);
lv.setAdapter(adapter);
}
</code></pre>
<p>}</p>
<p>Here the content of the arraylist should be shown as a listview.</p>
| 0debug |
void HELPER(cdsg)(CPUS390XState *env, uint64_t addr,
uint32_t r1, uint32_t r3)
{
uintptr_t ra = GETPC();
Int128 cmpv = int128_make128(env->regs[r1 + 1], env->regs[r1]);
Int128 newv = int128_make128(env->regs[r3 + 1], env->regs[r3]);
Int128 oldv;
bool fail;
if (parallel_cpus) {
#ifndef CONFIG_ATOMIC128
cpu_loop_exit_atomic(ENV_GET_CPU(env), ra);
#else
int mem_idx = cpu_mmu_index(env, false);
TCGMemOpIdx oi = make_memop_idx(MO_TEQ | MO_ALIGN_16, mem_idx);
oldv = helper_atomic_cmpxchgo_be_mmu(env, addr, cmpv, newv, oi, ra);
fail = !int128_eq(oldv, cmpv);
#endif
} else {
uint64_t oldh, oldl;
check_alignment(env, addr, 16, ra);
oldh = cpu_ldq_data_ra(env, addr + 0, ra);
oldl = cpu_ldq_data_ra(env, addr + 8, ra);
oldv = int128_make128(oldl, oldh);
fail = !int128_eq(oldv, cmpv);
if (fail) {
newv = oldv;
}
cpu_stq_data_ra(env, addr + 0, int128_gethi(newv), ra);
cpu_stq_data_ra(env, addr + 8, int128_getlo(newv), ra);
}
env->cc_op = fail;
env->regs[r1] = int128_gethi(oldv);
env->regs[r1 + 1] = int128_getlo(oldv);
}
| 1threat |
static void *file_ram_alloc(RAMBlock *block,
ram_addr_t memory,
const char *path,
Error **errp)
{
char *filename;
char *sanitized_name;
char *c;
void *area;
int fd;
uint64_t hpagesize;
Error *local_err = NULL;
hpagesize = gethugepagesize(path, &local_err);
if (local_err) {
error_propagate(errp, local_err);
goto error;
}
block->mr->align = hpagesize;
if (memory < hpagesize) {
error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
"or larger than huge page size 0x%" PRIx64,
memory, hpagesize);
goto error;
}
if (kvm_enabled() && !kvm_has_sync_mmu()) {
error_setg(errp,
"host lacks kvm mmu notifiers, -mem-path unsupported");
goto error;
}
sanitized_name = g_strdup(memory_region_name(block->mr));
for (c = sanitized_name; *c != '\0'; c++) {
if (*c == '/')
*c = '_';
}
filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
sanitized_name);
g_free(sanitized_name);
fd = mkstemp(filename);
if (fd < 0) {
error_setg_errno(errp, errno,
"unable to create backing store for hugepages");
g_free(filename);
goto error;
}
unlink(filename);
g_free(filename);
memory = ROUND_UP(memory, hpagesize);
if (ftruncate(fd, memory)) {
perror("ftruncate");
}
area = qemu_ram_mmap(fd, memory, hpagesize, block->flags & RAM_SHARED);
if (area == MAP_FAILED) {
error_setg_errno(errp, errno,
"unable to map backing store for hugepages");
close(fd);
goto error;
}
if (mem_prealloc) {
os_mem_prealloc(fd, area, memory);
}
block->fd = fd;
return area;
error:
return NULL;
}
| 1threat |
Python - determine change in value fro one period to the next : Thanks in advance for your help. I am new to Python (and coding in general), and am trying to do the several things, with the imported CSV file below. The problem that I am having a problem is capturing (in a list) the change in revenue from one row to the next for example, the change in revenue from 10/18 to 11/18. Ideally, I would have a final list with ["month", "change vs previous"].
Here is my existing code:
import os
import csv
csvpath = os.path.join("C:/test2", "budget_data.csv")
num_rows=0
total_rev=0
with open(csvpath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter= ",")
print(csvreader)
csv_header =next(csvreader)
print(f"CSV Header: {csv_header}")
for row in csvreader:
num_rows=num_rows+1
total_rev += int(row[1])
print("")
print("There are "+ str(num_rows) +" months of data!")
print("Total Revenue is "+str(total_rev)+" dollars!")
| 0debug |
Watermark text repeated diagonally css/html : <p>How can I achieve the following watermark text ("howbloggerz") with css/html?</p>
<p><a href="https://i.stack.imgur.com/wunyF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wunyF.png" alt="enter image description here"></a></p>
| 0debug |
static void gen_rdhwr(DisasContext *ctx, int rt, int rd)
{
TCGv t0;
#if !defined(CONFIG_USER_ONLY)
check_insn(ctx, ISA_MIPS32R2);
#endif
t0 = tcg_temp_new();
switch (rd) {
case 0:
gen_helper_rdhwr_cpunum(t0, cpu_env);
gen_store_gpr(t0, rt);
break;
case 1:
gen_helper_rdhwr_synci_step(t0, cpu_env);
gen_store_gpr(t0, rt);
break;
case 2:
gen_helper_rdhwr_cc(t0, cpu_env);
gen_store_gpr(t0, rt);
break;
case 3:
gen_helper_rdhwr_ccres(t0, cpu_env);
gen_store_gpr(t0, rt);
break;
case 29:
#if defined(CONFIG_USER_ONLY)
tcg_gen_ld_tl(t0, cpu_env,
offsetof(CPUMIPSState, active_tc.CP0_UserLocal));
gen_store_gpr(t0, rt);
break;
#else
if ((ctx->hflags & MIPS_HFLAG_CP0) ||
(ctx->hflags & MIPS_HFLAG_HWRENA_ULR)) {
tcg_gen_ld_tl(t0, cpu_env,
offsetof(CPUMIPSState, active_tc.CP0_UserLocal));
gen_store_gpr(t0, rt);
} else {
generate_exception_end(ctx, EXCP_RI);
}
break;
#endif
default:
MIPS_INVAL("rdhwr");
generate_exception_end(ctx, EXCP_RI);
break;
}
tcg_temp_free(t0);
}
| 1threat |
static void xtensa_cpu_initfn(Object *obj)
{
CPUState *cs = CPU(obj);
XtensaCPU *cpu = XTENSA_CPU(obj);
XtensaCPUClass *xcc = XTENSA_CPU_GET_CLASS(obj);
CPUXtensaState *env = &cpu->env;
static bool tcg_inited;
cs->env_ptr = env;
env->config = xcc->config;
cpu_exec_init(cs, &error_abort);
if (tcg_enabled() && !tcg_inited) {
tcg_inited = true;
xtensa_translate_init();
}
}
| 1threat |
void ff_ac3_bit_alloc_calc_psd(int8_t *exp, int start, int end, int16_t *psd,
int16_t *band_psd)
{
int bin, j, k, end1, v;
for(bin=start;bin<end;bin++) {
psd[bin]=(3072 - (exp[bin] << 7));
}
j=start;
k=bin_to_band_tab[start];
do {
v = psd[j++];
end1 = FFMIN(band_start_tab[k+1], end);
for (; j < end1; j++) {
int adr = FFMIN(FFABS(v - psd[j]) >> 1, 255);
v = FFMAX(v, psd[j]) + ff_ac3_log_add_tab[adr];
}
band_psd[k]=v;
k++;
} while (end > band_start_tab[k]);
}
| 1threat |
Bulk files rename : <p>I have 10000 files (php, html, css, and png). They are interconnected, in other words that the site engine. How do I can to do a bulk rename files so that the website worked properly? I understand that in addition to rename files and folders, I need to rename the paths inside the files. But how to do it bulk?</p>
| 0debug |
static int coroutine_fn blkreplay_co_discard(BlockDriverState *bs,
int64_t sector_num, int nb_sectors)
{
uint64_t reqid = request_id++;
int ret = bdrv_co_discard(bs->file->bs, sector_num, nb_sectors);
block_request_create(reqid, bs, qemu_coroutine_self());
qemu_coroutine_yield();
return ret;
}
| 1threat |
I am converting existing GCM to Firebase Messaging in my project but I am getting this error, Can you help me? Thanks in Advance : 12-23 11:27:22.729 4443-4443/com.example.tabswithswipe E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList[[zip file "/data/app/com.example.tabswithswipe-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.example.tabswithswipe-2, /vendor/lib, /system/lib]]
at android.app.ActivityThread.installProvider(ActivityThread.java:5100)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4680)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4613)
at android.app.ActivityThread.access$1300(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1424)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList[[zip file "/data/app/com.example.tabswithswipe-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.example.tabswithswipe-2, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53)
at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
at android.app.ActivityThread.installProvider(ActivityThread.java:5085)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4680)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4613)
at android.app.ActivityThread.access$1300(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1424)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
| 0debug |
SQL command error for multiple value condition in other table column; : We want to add a new column which values are depending by lots of condiction
For example, there are lots of bin numbers refer to different country like this bin number table
Start_Bin End_Bin Country_Code
4976999 4971000 US
4986999 4990000 UK
4920000 4929999 US
And we want to create a new column of country code on a table which's condiction is base on this table
This is our sql code, which is not allowed by sql server :(
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
ALTER Table temp.we_are_foreigners__table ADD COLUMNS CASE
WHEN (CAST(temp.we_are_foreigners__table.accountno AS int) >= CAST(temp.visa_country_classify_table.start_binnumber AS int) AND CAST(temp.we_are_foreigners__table.accountno AS int) <= CAST(temp.visa_country_classify_table.end_binnumber AS int) ) THEN temp.mastercard_country_classify_table.country_code
WHEN (CAST(temp.we_are_foreigners__table.accountno AS int) >= CAST(temp.mastercard_country_classify_table.start_binnumber AS int) AND CAST(temp.we_are_foreigners__table.accountno AS int) <= CAST(temp.mastercard_country_classify_table.end_binnumber AS int) ) THEN temp.mastercard_country_classify_table.country_code
END As Country_String
from temp.visa_country_classify_table, temp.mastercard_country_classify_table, temp.we_are_foreigners__table;
<!-- end snippet -->
What's the proper SQL command of doing this, what's the problem? | 0debug |
Is there any software can help assure the quality in c++ code? : <p><strong>Is there any software can help assure the quality in c++ code?</strong></p>
<p>the software can check the code and report some bad code with warnings.</p>
<p><strong>For example:</strong></p>
<p>the length of function should less than 50 lines.</p>
<p>the input variable of function should less than 5.</p>
<p>the name of variable is not obey the camel-case.</p>
<p>thanks!</p>
| 0debug |
static inline void flash_sync_area(Flash *s, int64_t off, int64_t len)
{
int64_t start, end, nb_sectors;
QEMUIOVector iov;
if (!s->bdrv || bdrv_is_read_only(s->bdrv)) {
return;
}
assert(!(len % BDRV_SECTOR_SIZE));
start = off / BDRV_SECTOR_SIZE;
end = (off + len) / BDRV_SECTOR_SIZE;
nb_sectors = end - start;
qemu_iovec_init(&iov, 1);
qemu_iovec_add(&iov, s->storage + (start * BDRV_SECTOR_SIZE),
nb_sectors * BDRV_SECTOR_SIZE);
bdrv_aio_writev(s->bdrv, start, &iov, nb_sectors, bdrv_sync_complete, NULL);
}
| 1threat |
Creating a markdown table with key bindings in Spacemacs : What is the best way to create a markdown table with key bindings in Spacemacs (evil mode)?
The table should show single keystrokes (letters, numbers, punctuation) with and without modifiers, the function bound to them, and the first line of the function description.
To clarify, this question is not about markdown or layout, but about how to automate this for a large number of key bindings. | 0debug |
JavaScript - Find multiple objects by IDs existing in prefined list from an array of objects without using the for loop : <p>I have a JavaScript array of objects:</p>
<pre><code>var my_array = [
{
"id" : 1,
"aas_name" : "aaa"
},
{
"id" : 2,
"aas_name" : "bbb"
},
{
"id" : 3,
"aas_name" : "ccc"
},
...
...
...
,
{
"id" : 10,
"aas_name" : "jjj"
}
]
</code></pre>
<p>I would like to find all objects in the <code>my_array</code>, each of which has the id value that exists in a pre-defined array [1, 3, 8] for instance without having to use the <code>for... loop</code> and ES6 arrow function style.</p>
<pre><code>var result = [
{
"id" : 1,
"aas_name" : "aaa"
},
{
"id" : 3,
"aas_name" : "ccc"
},
{
"id" : 8,
"aas_name" : "hhh"
}
]
</code></pre>
| 0debug |
static void vc1_decode_i_blocks(VC1Context *v)
{
int k, j;
MpegEncContext *s = &v->s;
int cbp, val;
uint8_t *coded_val;
int mb_pos;
switch(v->y_ac_table_index){
case 0:
v->codingset = (v->pqindex <= 8) ? CS_HIGH_RATE_INTRA : CS_LOW_MOT_INTRA;
break;
case 1:
v->codingset = CS_HIGH_MOT_INTRA;
break;
case 2:
v->codingset = CS_MID_RATE_INTRA;
break;
}
switch(v->c_ac_table_index){
case 0:
v->codingset2 = (v->pqindex <= 8) ? CS_HIGH_RATE_INTER : CS_LOW_MOT_INTER;
break;
case 1:
v->codingset2 = CS_HIGH_MOT_INTER;
break;
case 2:
v->codingset2 = CS_MID_RATE_INTER;
break;
}
s->y_dc_scale = s->y_dc_scale_table[v->pq];
s->c_dc_scale = s->c_dc_scale_table[v->pq];
s->mb_x = s->mb_y = 0;
s->mb_intra = 1;
s->first_slice_line = 1;
for(s->mb_y = 0; s->mb_y < s->mb_height; s->mb_y++) {
for(s->mb_x = 0; s->mb_x < s->mb_width; s->mb_x++) {
ff_init_block_index(s);
ff_update_block_index(s);
s->dsp.clear_blocks(s->block[0]);
mb_pos = s->mb_x + s->mb_y * s->mb_width;
s->current_picture.mb_type[mb_pos] = MB_TYPE_INTRA;
s->current_picture.qscale_table[mb_pos] = v->pq;
s->current_picture.motion_val[1][s->block_index[0]][0] = 0;
s->current_picture.motion_val[1][s->block_index[0]][1] = 0;
cbp = get_vlc2(&v->s.gb, ff_msmp4_mb_i_vlc.table, MB_INTRA_VLC_BITS, 2);
v->s.ac_pred = get_bits1(&v->s.gb);
for(k = 0; k < 6; k++) {
val = ((cbp >> (5 - k)) & 1);
if (k < 4) {
int pred = vc1_coded_block_pred(&v->s, k, &coded_val);
val = val ^ pred;
*coded_val = val;
}
cbp |= val << (5 - k);
vc1_decode_i_block(v, s->block[k], k, val, (k<4)? v->codingset : v->codingset2);
s->dsp.vc1_inv_trans_8x8(s->block[k]);
if(v->pq >= 9 && v->overlap) {
for(j = 0; j < 64; j++) s->block[k][j] += 128;
}
}
vc1_put_block(v, s->block);
if(v->pq >= 9 && v->overlap) {
if(s->mb_x) {
s->dsp.vc1_h_overlap(s->dest[0], s->linesize);
s->dsp.vc1_h_overlap(s->dest[0] + 8 * s->linesize, s->linesize);
if(!(s->flags & CODEC_FLAG_GRAY)) {
s->dsp.vc1_h_overlap(s->dest[1], s->uvlinesize);
s->dsp.vc1_h_overlap(s->dest[2], s->uvlinesize);
}
}
s->dsp.vc1_h_overlap(s->dest[0] + 8, s->linesize);
s->dsp.vc1_h_overlap(s->dest[0] + 8 * s->linesize + 8, s->linesize);
if(!s->first_slice_line) {
s->dsp.vc1_v_overlap(s->dest[0], s->linesize);
s->dsp.vc1_v_overlap(s->dest[0] + 8, s->linesize);
if(!(s->flags & CODEC_FLAG_GRAY)) {
s->dsp.vc1_v_overlap(s->dest[1], s->uvlinesize);
s->dsp.vc1_v_overlap(s->dest[2], s->uvlinesize);
}
}
s->dsp.vc1_v_overlap(s->dest[0] + 8 * s->linesize, s->linesize);
s->dsp.vc1_v_overlap(s->dest[0] + 8 * s->linesize + 8, s->linesize);
}
if(v->s.loop_filter) vc1_loop_filter_iblk(s, s->current_picture.qscale_table[mb_pos]);
if(get_bits_count(&s->gb) > v->bits) {
ff_er_add_slice(s, 0, 0, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END));
av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i\n", get_bits_count(&s->gb), v->bits);
return;
}
}
ff_draw_horiz_band(s, s->mb_y * 16, 16);
s->first_slice_line = 0;
}
ff_er_add_slice(s, 0, 0, s->mb_width - 1, s->mb_height - 1, (AC_END|DC_END|MV_END));
}
| 1threat |
static uint64_t subpage_ram_read(void *opaque, target_phys_addr_t addr,
unsigned size)
{
ram_addr_t raddr = addr;
void *ptr = qemu_get_ram_ptr(raddr);
switch (size) {
case 1: return ldub_p(ptr);
case 2: return lduw_p(ptr);
case 4: return ldl_p(ptr);
default: abort();
}
}
| 1threat |
SQL: count occurences for each row : i have an SQL table called `Codes` with a column `code` of type String.
I also have another table called `Items` with a column `codestring` also of type String. This entry always contains a string with some of the codes of the above table seperated by spaces.
Now i want to get all codes and their number of Items containing the respective code. Can i do that? | 0debug |
need MSSQL query to get multiple choice answer if matches : **example :**
Table - Question_Answers
+------+--------+
| q_id | ans_id |
+------+--------+
| 1 | 2 |
| 1 | 4 |
| 2 | 1 |
| 3 | 1 |
| 3 | 2 |
| 3 | 3 |
+------+--------+
User_Submited_Answers
| q_id | sub_ans_id |
+------+------------+
| 1 | 2 |
| 1 | 4 |
| 2 | 1 |
| 3 | 1 |
| 3 | 2 |
| 3 | 4 |
+------+------------+
****need a MSSQL query if this rows matches count 1 else 0****
| 0debug |
av_cold void ff_psy_end(FFPsyContext *ctx)
{
if (ctx->model->end)
ctx->model->end(ctx);
av_freep(&ctx->bands);
av_freep(&ctx->num_bands);
av_freep(&ctx->group);
av_freep(&ctx->ch);
}
| 1threat |
Is there any way to push a commit without a ref? : <p>Is there any way to push a git commit to a repository without modifying any refs on the remote repository? Or does it have to be attached to a ref?</p>
| 0debug |
How can I remain in a same line by pressing enter button in c++ : I am working on a programe but now I am stick with a problem and the problem is I want to enter two numbers but with the cursor in same line when ever I enter any number and press enter it moves to the next line but I want it on the same line.please help me!! | 0debug |
Fatal Exception: Invalid index 0,out of 0 : <p>I'm trying to retrieve the json data with JsonArrayRequest and then add it to a list. Here's my code</p>
<pre><code>public class QuestionDetailFragment extends Fragment {
RecyclerView cRecyclerView;
private static final String url = "http://10.0.2.2:80/forumtest/readquestion.php?format=json";
private List<String> userList = new ArrayList<>();
RequestQueue requestQueue;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.question_details_layout, container, false);
readQuestionDetails();
Log.d("check", "data:" + userList.get(0));
return view;
}
private void readQuestionDetails() {
Log.d("Volley", "Called222!");
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, url, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
for (int i=0;i<response.length();i++) {
JSONObject jsonObject = response.getJSONObject(i);
userList.add(jsonObject.getString("user"));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("tag",e.getMessage());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.getMessage());
}
});
requestQueue.add(jsonArrayRequest);
}
}
</code></pre>
<p>I've used <strong><em>Log.d("user`,"data:",user.get(0));</em></strong> just to make sure that the data has been added to the list. This is my logcat after running the code</p>
<pre><code> 03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: FATAL EXCEPTION: main
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: Process: com.rekoj.softwarica, PID: 2767
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: at java.util.ArrayList.get(ArrayList.java:308)
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: at com.rekoj.softwarica.Forum.QuestionDetailFragment.onCreateView(QuestionDetailFragment.java:50)
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-08 20:45:25.750 2767-2767/com.rekoj.softwarica E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
03-08 20:50:25.802 2767-2767/? I/Process: Sending signal. PID: 2767 SIG: 9
</code></pre>
| 0debug |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.