problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
db.execute('SELECT * FROM employees WHERE id = ' + user_input)
| 1threat
|
static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
int64_t align, QEMUIOVector *qiov, int flags)
{
BlockDriver *drv = bs->drv;
int ret;
int64_t sector_num = offset >> BDRV_SECTOR_BITS;
unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
if (flags & BDRV_REQ_COPY_ON_READ) {
mark_request_serialising(req, bdrv_get_cluster_size(bs));
}
wait_serialising_requests(req);
if (flags & BDRV_REQ_COPY_ON_READ) {
int pnum;
ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);
if (ret < 0) {
goto out;
}
if (!ret || pnum != nb_sectors) {
ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
goto out;
}
}
if (!(bs->zero_beyond_eof && bs->growable)) {
ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
} else {
int64_t len, total_sectors, max_nb_sectors;
len = bdrv_getlength(bs);
if (len < 0) {
ret = len;
goto out;
}
total_sectors = DIV_ROUND_UP(len, BDRV_SECTOR_SIZE);
max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num),
align >> BDRV_SECTOR_BITS);
if (max_nb_sectors > 0) {
ret = drv->bdrv_co_readv(bs, sector_num,
MIN(nb_sectors, max_nb_sectors), qiov);
} else {
ret = 0;
}
if (ret == 0 && total_sectors < sector_num + nb_sectors) {
uint64_t offset = MAX(0, total_sectors - sector_num);
uint64_t bytes = (sector_num + nb_sectors - offset) *
BDRV_SECTOR_SIZE;
qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
}
}
out:
return ret;
}
| 1threat
|
Is `namedtuple` really as efficient in memory usage as tuples? My test says NO : <p>It is stated in the Python documentation that one of the advantages of <code>namedtuple</code> is that it is as <em>memory-efficient</em> as tuples. </p>
<p>To validate this, I used iPython with <a href="https://github.com/ianozsvald/ipython_memory_usage" rel="noreferrer">ipython_memory_usage</a>. The test is shown in the images below:</p>
<p><a href="https://i.stack.imgur.com/Xl2oi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Xl2oi.png" alt=""></a>
<a href="https://i.stack.imgur.com/RESLQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RESLQ.png" alt=""></a></p>
<p>The test shows that:</p>
<ul>
<li><code>10000000</code> instances of <code>namedtuple</code> used about <code>850 MiB</code> of RAM</li>
<li><code>10000000</code> <code>tuple</code> instances used around <code>73 MiB</code> of RAM</li>
<li><code>10000000</code> <code>dict</code> instances used around <code>570 MiB</code> of RAM</li>
</ul>
<p>So <code>namedtuple</code> used <strong>much more</strong> memory than <code>tuple</code>! Even <strong>more</strong> than <code>dict</code>!!</p>
<p>What do you think? Where did I go wrong?</p>
| 0debug
|
how to print php response json response in android : how to print php response json response in android thanks in advance im fresher in this field i needs help plz help me im fresher and i have no idea about this code thanks in advanced thank you im android devloper but i have no idea about json parsing plz help me
{
"details": [
{
"p_id": "19",
"cat_id": "1",
"p_name": "Papad",
"p_namecode": "[01]Papad",
"p_image":
"p_price": "20",
"p_quantity": "2",
"p_code": "25",
"p_discount": "10",
"p_packing": "2",
"p_type": "small",
"p_status": "1",
"p": [
{
"q_id": "16",
"p_id": "19",
"q_weight": "25-gm",
"q_price": "150",
"q_beg": "50 bunch",
"q_status": "1"
},
{
"q_id": "17",
"p_id": "19",
"q_weight": "50-gm",
"q_price": "200",
"q_beg": "50-bunch",
"q_status": "1"
}
]
},
{
"p_id": "23",
"cat_id": "1",
"p_name": "Palak Papad",
"p_namecode": "[03]Palak",
"p_image":
"p_price": "200",
"p_quantity": "5",
"p_code": "02",
"p_discount": "15",
"p_packing": "4",
"p_type": "small",
"p_status": "1",
"p": [
{
"q_id": "19",
"p_id": "23",
"q_weight": "50- gm",
"q_price": "15",
"q_beg": "50 bunch",
"q_status": "1"
},
{
"q_id": "20",
"p_id": "23",
"q_weight": "1-kg",
"q_price": "30",
"q_beg": "50 bunch",
"q_status": "1"
}
]
}
],
"success": true,
"message": "Category and Sub Category"
}
| 0debug
|
Angular 2 - Submodule routing and nested <router-outlet> : <p>I'm looking for a solution with Angular 2 for the scenario explained below:</p>
<p><a href="https://i.stack.imgur.com/JOXsO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/JOXsO.png" alt="enter image description here"></a></p>
<p>In this scenario, the top-nav contains links to load submodules and sub-nav has links to update the submodule's contents.</p>
<p>The URLs should map as:</p>
<ul>
<li>/home => loads the home page in main component router outlet</li>
<li>/submodule => loads the submodule in the main component router outlet and by default should show the submodule's home page and sub navbar</li>
<li>/submodule/feature => loads the feature inside the submodule's router outlet</li>
</ul>
<p>The app module (and app component) contains a top navbar to navigate to different submodules and the app component template could look like this</p>
<pre><code><top-navbar></top-navbar>
<router-outlet></router-outlet>
</code></pre>
<p>But here is the complexity. I need my submodules to have similar layout with a second level nav bar and their own router outlet to load their own components. </p>
<pre><code><sub-navbar></sub-navbar>
<router-outlet name='sub'></router-outlet>
</code></pre>
<p>I tried every options and search everywhere but couldn't find a solution to have a default template (like app component) in the sub-module with router outlet and also load the contents of submodule in the inner router outlet without losing the sub-nav.</p>
<p>I would appreciate any input or ideas</p>
| 0debug
|
How to group by two field? : I have the following table:
listId | accountId | ammount |
1 1 20
1 1 20
2 2 30
2 2 30
I need to `sum(ammount)` and group by `listId, accountId` to get result:
listId | accountId | ammount |
1 1 40
2 2 60
But this does not work for me: `SUM(ammount) ... GROUP BY listId, accountId`
| 0debug
|
connection.query('SELECT * FROM users WHERE username = ' + input_string)
| 1threat
|
PCIBus *pci_gt64120_init(qemu_irq *pic)
{
GT64120State *s;
PCIDevice *d;
(void)&pci_host_data_writeb;
(void)&pci_host_data_writew;
(void)&pci_host_data_writel;
(void)&pci_host_data_readb;
(void)&pci_host_data_readw;
(void)&pci_host_data_readl;
s = qemu_mallocz(sizeof(GT64120State));
s->pci = qemu_mallocz(sizeof(GT64120PCIState));
s->pci->bus = pci_register_bus(NULL, "pci",
pci_gt64120_set_irq, pci_gt64120_map_irq,
pic, 144, 4);
s->ISD_handle = cpu_register_io_memory(gt64120_read, gt64120_write, s);
d = pci_register_device(s->pci->bus, "GT64120 PCI Bus", sizeof(PCIDevice),
0, gt64120_read_config, gt64120_write_config);
pci_config_set_vendor_id(d->config, PCI_VENDOR_ID_MARVELL);
pci_config_set_device_id(d->config, PCI_DEVICE_ID_MARVELL_GT6412X);
d->config[0x04] = 0x00;
d->config[0x05] = 0x00;
d->config[0x06] = 0x80;
d->config[0x07] = 0x02;
d->config[0x08] = 0x10;
d->config[0x09] = 0x00;
pci_config_set_class(d->config, PCI_CLASS_BRIDGE_HOST);
d->config[0x10] = 0x08;
d->config[0x14] = 0x08;
d->config[0x17] = 0x01;
d->config[0x1B] = 0x1c;
d->config[0x1F] = 0x1f;
d->config[0x23] = 0x14;
d->config[0x24] = 0x01;
d->config[0x27] = 0x14;
d->config[0x3D] = 0x01;
gt64120_reset(s);
register_savevm("GT64120 PCI Bus", 0, 1, gt64120_save, gt64120_load, d);
return s->pci->bus;
}
| 1threat
|
How to include correctly -Wl,-rpath,$ORIGIN linker argument in a Makefile? : <p>I'm preparing a c++ app on linux (Ubuntu 16.04) with the use of a few poco libraries which I have dynamically linked. I have project folder that consists of : include, bin, lib , src and build folders and the relevant Makefile. So far I used the following Makefile which got the libraries from /usr/local/lib</p>
<pre><code>CC := g++
# Folders
SRCDIR := src
BUILDDIR := build
TARGETDIR := bin
# Targets
EXECUTABLE := C++_APP
TARGET := $(TARGETDIR)/$(EXECUTABLE)
SRCEXT := cpp
SOURCES := $(shell find $(SRCDIR) -type f -name *.$(SRCEXT))
OBJECTS := $(patsubst $(SRCDIR)/%,$(BUILDDIR)/%,$(SOURCES:.$(SRCEXT)=.o))
CFLAGS := -c -Wall
INC := -I include -I /usr/local/include
LIB := -L /usr/local/lib -lPocoFoundation -lPocoNet -lPocoUtil
$(TARGET): $(OBJECTS)
@echo " Linking..."
@echo " $(CC) $^ -o $(TARGET) $(LIB)"; $(CC) $^ -o $(TARGET) $(LIB)
$(BUILDDIR)/%.o: $(SRCDIR)/%.$(SRCEXT)
@mkdir -p $(BUILDDIR)
@echo " $(CC) $(CFLAGS) $(INC) -c -o $@ $<"; $(CC) $(CFLAGS) $(INC) -c -o $@ $<
clean:
@echo " Cleaning...";
@echo " $(RM) -r $(BUILDDIR) $(TARGET)"; $(RM) -r $(BUILDDIR) $(TARGET)
.PHONY: clean
</code></pre>
<p>Now I'd like during running the linker to search for libraries only in project lib folder without changing LD_LIBRARY_PATH or editing ld.so.conf. So I searched and I found that this can be achieved by the linker argument -Wl,rpath,$ORIGIN. So I assume that I need to add the following statement </p>
<pre><code>LDFLAGS := -Wl,-rpath,$ORIGIN/../lib
</code></pre>
<p>and change the the LIB statement as following:</p>
<pre><code>LIB := -L $ORIGIN/../lib -lPocoFoundation -lPocoNet -lPocoUtil
</code></pre>
<p>However it still get the libraries from the default directory (usr/local/lib) , since I tested it with no library on the project lib folder. What have I done wrong?</p>
| 0debug
|
expression pattern of type 'Int' cannot match values of type 'uint?' (aka 'Optional<UInt32>') : <p>I am getting below error during Objective-C to Swift code change. Thanks</p>
<pre><code>class func shareLevelUp(toFacebook level: uint, from vc: UIViewController?) {
let report = GymStatusReport.statusReportForLevel(level)
switch report.level {
case 1:
// something
case 2:
// something
case 3:
// something
case 4:
// something
default:
return
}
}
</code></pre>
<p>expression pattern of type 'Int' cannot match values of type 'uint?' (aka 'Optional')</p>
| 0debug
|
static double get_audio_clock(VideoState *is)
{
double pts;
int hw_buf_size, bytes_per_sec;
pts = is->audio_clock;
hw_buf_size = audio_write_get_buf_size(is);
bytes_per_sec = 0;
if (is->audio_st) {
bytes_per_sec = is->audio_st->codec->sample_rate *
2 * is->audio_st->codec->channels;
}
if (bytes_per_sec)
pts -= (double)hw_buf_size / bytes_per_sec;
return pts;
}
| 1threat
|
How to use the sed command : <p>I have a <strong>text</strong> file lets say with the name of "example" and has this data :</p>
<pre><code>data:data:data
data:data:data
data:data:data
data:data:data
</code></pre>
<p>I want to Display the file substituting all instances of the : character with 5 spaces using the SED command I have tried everything but its not working.
how will i do it ?
thanks</p>
| 0debug
|
SNI Dynamic Certificate : <p>I'm pulling my hair out here.
Websites like <a href="http://wix.com" rel="noreferrer">wix.com</a>, <a href="http://squarespace.com" rel="noreferrer">squarespace.com</a> ...etc; can generate websites on the fly and still use SSL on every one of the millions of custom domains.</p>
<p>I try to do the same thing, <strong>but I can't figure out how they do it</strong>!?</p>
<p>The logical solution would be on Apache:</p>
<pre><code><IfModule mod_ssl.c>
<VirtualHost *:443>
ServerAlias *
UseCanonicalName Off
DocumentRoot /var/www/html
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/%0/server.crt
SSLCertificateKeyFile /etc/apache2/ssl/%0/server.key
</VirtualHost></IfModule>
</code></pre>
<p>But when I restart apache I get an error: <strong>SSLCertificateFile: file '/etc/apache2/ssl/%0/server.crt' does not exist or is empty</strong></p>
<p>Even when I create a dummy folder /ssl/%0/ with some dummy certificates... it still used the (wrong) dummy certificates.</p>
<p>I know some will get on their high horses and yell that you cannot resolve the server name BEFORE the TLS handshake.
But according to this <a href="https://community.letsencrypt.org/t/apache-module-mod-vhost-alias-le/9476/8" rel="noreferrer">post</a> and other ones: %0 can be resolved with <a href="http://httpd.apache.org/docs/current/mod/mod_vhost_alias.html" rel="noreferrer">mod_vhost_alias</a> because the server name is sent with SNI... </p>
<p>I know this works: a second approach would be to create a virtualhost for every custom domain:</p>
<pre><code> <VirtualHost *:443>
ServerName site111.ca
ServerAlias www.site111.ca
DocumentRoot /var/www/html
SSLEngine on
SSLCertificateFile "/var/app/s3/ssl/site111.ca/certificate.crt"
SSLCertificateKeyFile "/var/app/s3/ssl/site111.ca/certificate.key"
SSLCertificateChainFile "/var/app/s3/ssl/site111.ca/certificate.chain"
</VirtualHost><VirtualHost *:443>
ServerName site222.ca
ServerAlias www.site222.ca
DocumentRoot /var/www/html
SSLEngine on
SSLCertificateFile "/var/app/s3/ssl/site222.ca/certificate.crt"
SSLCertificateKeyFile "/var/app/s3/ssl/site222.ca/certificate.key"
SSLCertificateChainFile "/var/app/s3/ssl/site222.ca/certificate.chain"
</code></pre>
<p></p>
<p>I could create a dirty system where I add one virtual host per new domain and reload apache every day Eeewwww... and again: Apache cap the number of virtual hosts to 256 :/</p>
<p>How do they do it!? Is there other technology that can help me? Nginx, Nodejs?
Thank you for your time.</p>
| 0debug
|
int qcow2_grow_l1_table(BlockDriverState *bs, int min_size)
{
BDRVQcowState *s = bs->opaque;
int new_l1_size, new_l1_size2, ret, i;
uint64_t *new_l1_table;
int64_t new_l1_table_offset;
uint8_t data[12];
new_l1_size = s->l1_size;
if (min_size <= new_l1_size)
return 0;
if (new_l1_size == 0) {
new_l1_size = 1;
}
while (min_size > new_l1_size) {
new_l1_size = (new_l1_size * 3 + 1) / 2;
}
#ifdef DEBUG_ALLOC2
printf("grow l1_table from %d to %d\n", s->l1_size, new_l1_size);
#endif
new_l1_size2 = sizeof(uint64_t) * new_l1_size;
new_l1_table = qemu_mallocz(align_offset(new_l1_size2, 512));
memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ALLOC_TABLE);
new_l1_table_offset = qcow2_alloc_clusters(bs, new_l1_size2);
if (new_l1_table_offset < 0) {
qemu_free(new_l1_table);
return new_l1_table_offset;
}
BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_WRITE_TABLE);
for(i = 0; i < s->l1_size; i++)
new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
ret = bdrv_pwrite(bs->file, new_l1_table_offset, new_l1_table, new_l1_size2);
if (ret != new_l1_size2)
goto fail;
for(i = 0; i < s->l1_size; i++)
new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ACTIVATE_TABLE);
cpu_to_be32w((uint32_t*)data, new_l1_size);
cpu_to_be64w((uint64_t*)(data + 4), new_l1_table_offset);
ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, l1_size), data,sizeof(data));
if (ret != sizeof(data)) {
goto fail;
}
qemu_free(s->l1_table);
qcow2_free_clusters(bs, s->l1_table_offset, s->l1_size * sizeof(uint64_t));
s->l1_table_offset = new_l1_table_offset;
s->l1_table = new_l1_table;
s->l1_size = new_l1_size;
return 0;
fail:
qemu_free(new_l1_table);
qcow2_free_clusters(bs, new_l1_table_offset, new_l1_size2);
return ret < 0 ? ret : -EIO;
}
| 1threat
|
Need to create a ~2,000 flat files with specific structure in MS SQL : The .control files I need to create contains a specific structure that will be used to fax certain documents to specific destinations. Here is a sample:
;Sender Information
#SENDER_NAME LA Medical Care
#SENDER_EMAIL LAFakers@gmail.com
#SENDER_BUSINESS_FAX_NUMBER 213-555-4321
;RANDLE, JULIUS's Information
#RECIPIENT
#RECIP_NAME RANDLE, JULIUS
#DESTINATION 1-323-555-6789
#ATTACHMENT Report_Randle1.pdf
For every flat file, the sender information will be the same but the recipient information is what needs to be dynamic. I have a table that can provide the RECIP_NAME, DESTINATION, and ATTACHMENT parameters. Any ideas on how to start this query? Thank you.
| 0debug
|
static int socket_accept(int sock)
{
struct sockaddr_un addr;
socklen_t addrlen;
int ret;
addrlen = sizeof(addr);
do {
ret = accept(sock, (struct sockaddr *)&addr, &addrlen);
} while (ret == -1 && errno == EINTR);
g_assert_no_errno(ret);
close(sock);
return ret;
}
| 1threat
|
I want a div to show only when user clicks on a button : <form id="search" action="#" method="post" style="float: left">
<div id="input" style="float: left; margin-left: 10px;" ><input type="text" name="search-terms" id="search-terms" placeholder="Search websites and categories..." style="width: 300px;"></div>
<div id="label" style="float: left;margin-right: 10px;"><button type="submit" onclick="searchbox()" for="search-terms" id="search-label" class="glyphicon glyphicon-search"></button></div>
</form>
when user clicks on div id "label", I want to toggle the display property of div "input". which is working fine. I have used following code to implement the functionality.
function searchbox(){
if($("#input").css('display') == 'none'){
$('#input').css('display','block');
} else {
$('#input').css('display','none');
}
}
But I want to to submit the form data via post. But that functionality is not working, neither by pressing enter key nor when submit button is clicked.
Please help me with this.
| 0debug
|
How can I make react-bootstrap's Dropdown open on mouse hover? : <p>Ok the question is simple. I need to make the dropdown open when mouse hover rather than on click.</p>
<p>Currently my code is as follow.</p>
<pre><code> <Nav>
<NavDropdown
onMouseEnter = {()=> isOpen=true}
open={isOpen}
noCaret
id="language-switcher-container"
>
<MenuItem>Only one Item</MenuItem>
</NavDropdown>
</Nav>
</code></pre>
<p>as you can see, I tried onMouseEnter but no effect. Can someone solve this issue? What attribute should I pass in to achive this.</p>
<p>The API page is here <a href="https://react-bootstrap.github.io/components.html#btn-dropdowns" rel="noreferrer">react-bootstrap API page</a></p>
| 0debug
|
How git manage to store the files branch wise? : <p>Suppose, In my repository, I have two branches i.e Master and development. I've created the development branch from master and now I added some new files to the development branch and after committing those changes on local, I switched to the <strong>Master branch</strong>. Now, here we don't see the new files which we had added on the development branch but when I switch back to the development branch, I'll able to see the new files. <strong>How git manage to store the files branch wise?</strong></p>
| 0debug
|
void virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
{
uint32_t type;
struct iovec *in_iov = req->elem.in_sg;
struct iovec *iov = req->elem.out_sg;
unsigned in_num = req->elem.in_num;
unsigned out_num = req->elem.out_num;
if (req->elem.out_num < 1 || req->elem.in_num < 1) {
error_report("virtio-blk missing headers");
exit(1);
}
if (unlikely(iov_to_buf(iov, out_num, 0, &req->out,
sizeof(req->out)) != sizeof(req->out))) {
error_report("virtio-blk request outhdr too short");
exit(1);
}
iov_discard_front(&iov, &out_num, sizeof(req->out));
if (in_num < 1 ||
in_iov[in_num - 1].iov_len < sizeof(struct virtio_blk_inhdr)) {
error_report("virtio-blk request inhdr too short");
exit(1);
}
req->in_len = iov_size(in_iov, in_num);
req->in = (void *)in_iov[in_num - 1].iov_base
+ in_iov[in_num - 1].iov_len
- sizeof(struct virtio_blk_inhdr);
iov_discard_back(in_iov, &in_num, sizeof(struct virtio_blk_inhdr));
type = virtio_ldl_p(VIRTIO_DEVICE(req->dev), &req->out.type);
switch (type & ~(VIRTIO_BLK_T_OUT | VIRTIO_BLK_T_BARRIER)) {
case VIRTIO_BLK_T_IN:
{
bool is_write = type & VIRTIO_BLK_T_OUT;
req->sector_num = virtio_ldq_p(VIRTIO_DEVICE(req->dev),
&req->out.sector);
if (is_write) {
qemu_iovec_init_external(&req->qiov, iov, out_num);
trace_virtio_blk_handle_write(req, req->sector_num,
req->qiov.size / BDRV_SECTOR_SIZE);
} else {
qemu_iovec_init_external(&req->qiov, in_iov, in_num);
trace_virtio_blk_handle_read(req, req->sector_num,
req->qiov.size / BDRV_SECTOR_SIZE);
}
if (!virtio_blk_sect_range_ok(req->dev, req->sector_num,
req->qiov.size)) {
virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
virtio_blk_free_request(req);
return;
}
block_acct_start(blk_get_stats(req->dev->blk),
&req->acct, req->qiov.size,
is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
if (mrb->num_reqs > 0 && (mrb->num_reqs == VIRTIO_BLK_MAX_MERGE_REQS ||
is_write != mrb->is_write ||
!req->dev->conf.request_merging)) {
virtio_blk_submit_multireq(req->dev->blk, mrb);
}
assert(mrb->num_reqs < VIRTIO_BLK_MAX_MERGE_REQS);
mrb->reqs[mrb->num_reqs++] = req;
mrb->is_write = is_write;
break;
}
case VIRTIO_BLK_T_FLUSH:
virtio_blk_handle_flush(req, mrb);
break;
case VIRTIO_BLK_T_SCSI_CMD:
virtio_blk_handle_scsi(req);
break;
case VIRTIO_BLK_T_GET_ID:
{
VirtIOBlock *s = req->dev;
const char *serial = s->conf.serial ? s->conf.serial : "";
size_t size = MIN(strlen(serial) + 1,
MIN(iov_size(in_iov, in_num),
VIRTIO_BLK_ID_BYTES));
iov_from_buf(in_iov, in_num, 0, serial, size);
virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
virtio_blk_free_request(req);
break;
}
default:
virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
virtio_blk_free_request(req);
}
}
| 1threat
|
JavaScript giving nonsense errors : <p>So, me and a few friends are making a text adventure in JavaScript. in it, there is a possibility of the player using a heal spell, which runs the following code:</p>
<pre><code>function heal() {
alert('You chant some ominous-sounding words, and your wounds heal');
alert('Hit points restored!');
hitPoints += 60;
blobsOfDoom -= 30;
burn();
MonsAtt();
Choose Spell();
}
</code></pre>
<h2>Error Messages:</h2>
<h3>Firefox:</h3>
<pre><code>/*
Exception: SyntaxError: missing ; before statement
@Scratchpad/1:2703
*/
</code></pre>
<h3>Chrome:</h3>
<p><code>SyntaxError: Unexpected identifier</code>.</p>
<p>Why is this error showing up? How do I fix it?</p>
| 0debug
|
Conversion of numbers from one form to other : I have a data frame "df" with a column "Amount", which contains values in millions like 2.3, 17, 1.47 and so on. I want to create a new column "Amount1" in "df" which converts each value in "Amount" to the form like 2300000, 17000000, 1470000 and so on. How would I accomplish this task?
| 0debug
|
Is it possible to use Webpack-Hot-Middleware with NGINX on server side? : <p>I am working on a project for a client and I need to use webpack's Hot Module Replacement feature. I am using an express (node) application behind NGINX. I am using many javascript frameworks to design the application, React happens to be one of them. </p>
<p>I will be using the HMR feature. </p>
<p>I have a webpack.config.js like this :</p>
<pre><code>var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var merge = require('webpack-merge');
var validate = require('webpack-validator');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var styleLintPlugin = require('stylelint-webpack-plugin');
//breaking up into smaller modules
//commons module
//first
var start = {
context : __dirname ,
//entry point defination
entry : {
app : ['./require.js','webpack-hot-middleware/client?https:127.0.0.1:8195'],
vendor : ['angular','angular-animate','angular-messages','angular-aria','angular-route','angular-material','react','react-dom',''webpack-hot-middleware/client?https:127.0.0.1:8195'']
},
//output defination
output : {
path : './public/dist',
publicPath: 'https://127.0.0.1:8195/public/dist/',
filename : 'app.bundle.js'
},
module: { preLoaders: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loaders: ['eslint']
}
],
loaders: [
{test: /\.js$/, loader: 'ng-annotate!babel?presets[]=es2015!jshint', exclude: /node_modules/},
{
test: /\.css$/,
exclude: /(node_modules|bower_components)/,
loader: ExtractTextPlugin.extract("style-loader", "css")
},
{
test: /\.less$/,
exclude: /(node_modules|bower_components)/,
loader: ExtractTextPlugin.extract("style", "css!less")
},
{
test: /\.scss$/,
exclude: /(node_modules|bower_components)/,
loader: ExtractTextPlugin.extract("style", "css!sass")
},
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loaders: ['react-hot', 'babel'],
},
{
test: /\.woff2$/,
loader: 'url'
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin(/* chunkName= */"vendor", /* filename= */"vendor.bundle.js"),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
new ExtractTextPlugin("styling.css", {allChunks: true}),
new ExtractTextPlugin("styling.css", {allChunks: true}),
new ExtractTextPlugin("styling.css", {allChunks: true}),
//new webpack.optimize.UglifyJsPlugin({
//compress: {
// warnings: false
// },
//}),
// new webpack.optimize.DedupePlugin(),
// new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
//target: 'web'
};
var config;
// Detect how npm is run and branch based on that
//choose modules
//all modules
switch(process.env.npm_lifecycle_event) {
case 'build':
config = merge(start);
break;
default:
config = merge(start);
}
//export config
module.exports = validate(config);
</code></pre>
<p>My app.js file includes : </p>
<pre><code>app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//webpack development server integration
app.use(require("webpack-dev-middleware")(compiler, {
noInfo: false, stats: { colors: true,
chunks: true,
'errors-only': true }, headers: { "X-Custom-Header": "yes" }, publicPath: webpackConfig.output.publicPath
}));
app.use(require("webpack-hot-middleware")(compiler, {
log: console.log
}));
</code></pre>
<p>My NGINX file includes </p>
<pre><code>location / {
...
proxy_pass https://127.0.0.1:8195;
...
...
}
</code></pre>
<p>When I open <a href="https://127.0.0.1:8195" rel="noreferrer">https://127.0.0.1:8195</a>. Then files are created and served up. Express listens on 8195 port.
But when I open the <a href="https://domain-name.com" rel="noreferrer">https://domain-name.com</a>, the files aren't served but NGINX doesn't show 502 error. </p>
| 0debug
|
Finiding count of files using C language using sytem calls with specific extension : Using bash I can find count the count of specific extensions of a file like jpg,mp4 etc..,. How can I achieve this using C language system calls? Any help to achieve this using C language system calls?
ls -lR /path/to/dir/*.jpg | wc -l
| 0debug
|
static void decode_lpc(int32_t *coeffs, int mode, int length)
{
int i;
if (length < 2)
return;
if (mode == 1) {
unsigned a1 = *coeffs++;
for (i = 0; i < length - 1 >> 1; i++) {
*coeffs += a1;
coeffs[1] += *coeffs;
a1 = coeffs[1];
coeffs += 2;
}
if (length - 1 & 1)
*coeffs += a1;
} else if (mode == 2) {
unsigned a1 = coeffs[1];
unsigned a2 = a1 + *coeffs;
coeffs[1] = a2;
if (length > 2) {
coeffs += 2;
for (i = 0; i < length - 2 >> 1; i++) {
unsigned a3 = *coeffs + a1;
unsigned a4 = a3 + a2;
*coeffs = a4;
a1 = coeffs[1] + a3;
a2 = a1 + a4;
coeffs[1] = a2;
coeffs += 2;
}
if (length & 1)
*coeffs += a1 + a2;
}
} else if (mode == 3) {
unsigned a1 = coeffs[1];
unsigned a2 = a1 + *coeffs;
coeffs[1] = a2;
if (length > 2) {
unsigned a3 = coeffs[2];
unsigned a4 = a3 + a1;
unsigned a5 = a4 + a2;
coeffs[2] = a5;
coeffs += 3;
for (i = 0; i < length - 3; i++) {
a3 += *coeffs;
a4 += a3;
a5 += a4;
*coeffs = a5;
coeffs++;
}
}
}
}
| 1threat
|
How to feed input to an exe via bat file on DOS : Suppose I have a program kn.exe made in Visual Basic which takes in three numbers in text boxes and calculates an index out of them when one clicks the command "Calculate", and displays the calculated number (index) in another text box.
Can I write a .bat file for DOS which will have one or several sets of those three numbers and will execute kn.exe, calculate the index and display it (still better if it can write it somewhere)?
It can either execute kn.exe once and feed the several sets of three numbers, or it can start kn.exe for each set of three numbers. Thanks for any help.
| 0debug
|
static int libopenjpeg_copy_unpacked8(AVCodecContext *avctx, const AVFrame *frame, opj_image_t *image)
{
int compno;
int x;
int y;
int width;
int height;
int *image_line;
int frame_index;
const int numcomps = image->numcomps;
for (compno = 0; compno < numcomps; ++compno) {
if (image->comps[compno].w > frame->linesize[compno]) {
av_log(avctx, AV_LOG_ERROR, "Error: frame's linesize is too small for the image\n");
return 0;
}
}
for (compno = 0; compno < numcomps; ++compno) {
width = avctx->width / image->comps[compno].dx;
height = avctx->height / image->comps[compno].dy;
for (y = 0; y < height; ++y) {
image_line = image->comps[compno].data + y * image->comps[compno].w;
frame_index = y * frame->linesize[compno];
for (x = 0; x < width; ++x)
image_line[x] = frame->data[compno][frame_index++];
for (; x < image->comps[compno].w; ++x) {
image_line[x] = image_line[x - 1];
}
}
for (; y < image->comps[compno].h; ++y) {
image_line = image->comps[compno].data + y * image->comps[compno].w;
for (x = 0; x < image->comps[compno].w; ++x) {
image_line[x] = image_line[x - image->comps[compno].w];
}
}
}
return 1;
}
| 1threat
|
Should I use block element or inline element? : I want to show like this.<br>
> [![enter image description here][1]][1]
[1]: http://i.stack.imgur.com/s973o.png
What should i used?
Obviously one external div with blue background.<br>
But what inside?<br>
**Two span or<br>
Two p elements or<br>
Two div**<br>
This is just the case.<br>
I want generalise answer **how to structure page properly**.<br>
Please also refer some article or reference about it
| 0debug
|
static void do_safe_dpy_refresh(CPUState *cpu, run_on_cpu_data opaque)
{
DisplayChangeListener *dcl = opaque.host_ptr;
dcl->ops->dpy_refresh(dcl);
}
| 1threat
|
writing an "if" function that returns 3 possible vairable results based on the formula in a combination of 3 cells : I'm trying to write a formula that will do the following - if a1>b1 then (c2-d2)*f2, if a1<b1 but a1>c1, then (c3-d3)*f2, if a1<c1, then 0.
| 0debug
|
post data from a form in json format : I have two html pages : 1.html and 2.html
I want to post data from a form in 1.html to 2.html
I want to store data from form in 1.html in json and then post it to 2.html without going to 2.html when I click on submit button and parse json in 2.html and use them.
1.html :
<body>
<form action="2.html" method="POST">
<input type="text" name="material" value="material" readonly>
<input type="text" name="Unit" value="Unit" readonly>
<button type="submit" id="add">add</button>
</form>
</body>
can anyone help? i need it soon. thanks
| 0debug
|
Here im getting error when i pass my DB name i.e Test if i pass Sid its working plz help me :
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getOracleConnection();
Statement stmt = null;
ResultSet rs = null;
stmt = conn.createStatement();
//only for Oracle
rs = stmt.executeQuery("select object_name from user_objects where object_type = 'TABLE'");
while (rs.next()) {
String tableName = rs.getString(1);
System.out.println("tableName=" + tableName);
}
stmt.close();
conn.close();
}
/*private static Connection getHSQLConnection() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
return DriverManager.getConnection(url, "sa", "");
}*/
/* public static Connection getMySqlConnection() throws Exception {
String driver = "org.gjt.mm.mysql.Driver";
String url = "jdbc:mysql://localhost/demo2s";
String username = "oost";
String password = "oost";
*/
/* Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
*/
public static Connection getOracleConnection() throws Exception {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:Test";
String username = "system";
String password = "root12345";
Class.forName(driver); // load Oracle driver
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
}
here I'm going to get the list of tables from Test database but I'm getting the error like listener refused connection, Listener refused the connection with the following error: ORA-12505, TNS: listener does not currently know of SID given in connect descriptor But when I change Test to Orcl then its working fine but I want to select table from particular Database, Plz can anyone help me where I did wrong
| 0debug
|
How to insert scale bar in a map in matplotlib : <p>Any ideas on how can I insert a scale bar in a map in matplotlib that shows the length scale? something like the one I have attached.</p>
<p>Or maybe any ideas on measuring and showing distances automatically (not drawing an arrow and writing the distance manually!)?</p>
<p>Thanks :)<a href="https://i.stack.imgur.com/tODjr.png"><img src="https://i.stack.imgur.com/tODjr.png" alt="enter image description here"></a></p>
| 0debug
|
Getting error while running application on real device : I am developing quiz application where user can solve quiz in particular time but when I am running application on emulator it runs without error but at the time of running application on real device it throws following error.
**Error:-**
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2683)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2744)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1493)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6195)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:874)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:764)
Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at com.gaurav.javascripttutorial.subactivities.QuizMainActivity.onCreate(QuizMainActivity.java:52)
**Code:-**
public class QuizMainActivity extends AppCompatActivity {
private ProgressBar countDownTimer;
private TextView timer;
public int counter;
List<Question> quesList;
int score=0;
int qid=0;
Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;
Button butNext;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_main_activity);
/**
* Quiz coding
*/
DbHelper db=new DbHelper(this);
quesList=db.getAllQuestions();
currentQ=quesList.get(qid);
txtQuestion=(TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.radio0);
rdb=(RadioButton)findViewById(R.id.radio1);
rdc=(RadioButton)findViewById(R.id.radio2);
butNext=(Button)findViewById(R.id.nextButton);
setQuestionView();
butNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getANSWER().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}
if(qid<22){
currentQ=quesList.get(qid);
setQuestionView();
}else{
Intent intent = new Intent(QuizMainActivity.this, QuizResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
/**
* Timer Coding
*/
countDownTimer = (ProgressBar) findViewById(R.id.progressBar);
timer = (TextView) findViewById(R.id.timer);
new CountDownTimer(1200000,1000){
@Override
public void onTick(long millisUntilFinished) {
int progress = (int) (millisUntilFinished/120000)+1;
countDownTimer.setProgress(countDownTimer.getMax()-progress);
if (counter == 1080){
Toast.makeText(QuizMainActivity.this, "Only 2 minutes remaining, Please review the answers.", Toast.LENGTH_SHORT).show();
}
counter++;
Log.d("Counter number", ""+counter);
}
@Override
public void onFinish() {
Toast.makeText(QuizMainActivity.this, "Sorry! Time is over, Try again", Toast.LENGTH_LONG).show();
finish();
}
}.start();
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
private void setQuestionView()
{
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
qid++;
}
}
**When program runs and error throws the cursor denote to the following line of a code:-**
currentQ=quesList.get(qid);
| 0debug
|
how to match /foo/:id/bar?any_query_string_I_want with regex : <p>This is a page URL and the :id param changes based on the resource and the query string can be all over the map.</p>
<p>How can I match /foo/:id/bar?anything</p>
<p>thanks in advance</p>
| 0debug
|
failed to deploy Travis CI `Python` : I got the below error when tried to run the build in `travis`. I'm new to travis and following some websites to create the builds for `Python` project.
```=========================== 2 passed in 0.02 seconds ===========================
The command "coverage run -m pytest test.py" exited with 0.
3.23s$ coverage html -d docs/report/coverage/
The command "coverage html -d docs/report/coverage/" exited with 0.
after_success
0.17s$ coveralls
dpl_0
1.25s$ rvm $(travis_internal_ruby) --fuzzy do ruby -S gem install dpl
invalid option "--token="
failed to deploy
```
Any insights will be helpful and i saw `secure` keyword in `.travis.yml` page and may i know what is it and it's use. How to generate the `secure` key in windows?
| 0debug
|
how can i adjust my plot to make it easier to read? : import numpy as np
import matplotlib.pyplot as plt
def barchart(Gbar, Vbar, Wbar, Rbar, Dbar, Nebar, Tbar, Abar):
N = 10
G = Gbar
ind = np.arange(N) # the x locations for the groups
width = 0.12 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind, G, width, color='b')
V = Vbar
rects2 = ax.bar(ind + width, V, width, color='g')
W = Wbar
rects3 = ax.bar(ind + width*2, W, width, color='y')
R = Rbar
rects4 = ax.bar(ind + width*3, R, width, color='r')
D = Dbar
rects5 = ax.bar(ind + width * 4, D, width, color='orange')
N = Nebar
rects6 = ax.bar(ind + width * 5, N, width, color='black')
T = Tbar
rects7 = ax.bar(ind + width * 6, T, width, color='purple')
Ab = Abar
rects8 = ax.bar(ind + width * 7, Ab, width, color='cyan')
# add some text for labels, title and axes ticks
ax.set_ylabel('Char edit distance')
ax.set_xticks(ind + width/2)
ax.set_xticklabels(('A1', 'A2', 'A3', 'A4', 'A5', 'B1', 'B2',
'B3', 'B4', 'C1'))
ax.legend((rects1[0], rects2[0], rects3[0], rects4[0], rects5[0],rects6[0],rects7[0],rects8[0]),
('Google', 'Voicebase', 'Watson', 'Remeeting', 'Deepgram','Nexiwave','Temi','Ababa'))
def autolabel(rects):
"""
Attach a text label above each bar displaying its height
"""
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
'%d' % int(height), ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
autolabel(rects3)
autolabel(rects4)
autolabel(rects5)
autolabel(rects6)
autolabel(rects7)
autolabel(rects8)
plt.savefig('plot.png')
plt.show()
[![Plot][1]][1]
[1]: https://i.stack.imgur.com/aS3ck.png
The plot is as you can see is not easy to read how can i adjust it to make it look better and move the columns a bit further .(Note that the image attached is part of the entire image but should be more than enough to get an idea about my issue)
| 0debug
|
Strange behaviour of printf (C) : i'm trying to discover all capabilities of printf and I have tried this :
printf("Test:%+*0d", 10, 20);
that print : **Test:%+100d**
I have use first the flag +, then the width * and the re-use the flag 0.
Why it's make this output ?
I purposely use printf in a bad way but I wonder why it shows me the number 100
| 0debug
|
static void virtio_set_status(struct subchannel_id schid,
unsigned long dev_addr)
{
unsigned char status = dev_addr;
if (run_ccw(schid, CCW_CMD_WRITE_STATUS, &status, sizeof(status))) {
virtio_panic("Could not write status to host!\n");
}
}
| 1threat
|
def count_digs(tup):
return sum([len(str(ele)) for ele in tup ])
def sort_list(test_list):
test_list.sort(key = count_digs)
return (str(test_list))
| 0debug
|
How can I post array keys that have special charachters? : I have a form that contains some special characters as the keys.
Below is an example:
<input type="text" name="skills[React.js]" placeholder="Years" class="form-control">
<input type="text" name="skills[Responsive-Web-Design-(RWD)]" placeholder="Years" class="form-control">
When I post the form I get 0:value, 1:value
Instead of React.js:value, Responsive-Web-Design-(RWD): value
Does anyone might know any workarounds?
Any help would be really appreciated!
| 0debug
|
Python A part of code is not being exicuted : Hi I have this class which gives me output of "I am in level 1" but doesn't out "i am in level 2" so i assume get_full_name(self) part isn't being executed any help ?
class UserTest(TestCase):
user = UserFactory()
def test_user_login_client(self):
self.client.login(username=self.user.email, password=self.user.password)
print "i am in level 1"
def get_full_name(self):
print "i am in level 2"
full_name = user.full_name()
return full_name
| 0debug
|
static void select_vgahw (const char *p)
{
const char *opts;
assert(vga_interface_type == VGA_NONE);
if (strstart(p, "std", &opts)) {
if (vga_available()) {
vga_interface_type = VGA_STD;
} else {
error_report("standard VGA not available");
exit(1);
}
} else if (strstart(p, "cirrus", &opts)) {
if (cirrus_vga_available()) {
vga_interface_type = VGA_CIRRUS;
} else {
error_report("Cirrus VGA not available");
exit(1);
}
} else if (strstart(p, "vmware", &opts)) {
if (vmware_vga_available()) {
vga_interface_type = VGA_VMWARE;
} else {
error_report("VMWare SVGA not available");
exit(1);
}
} else if (strstart(p, "virtio", &opts)) {
if (virtio_vga_available()) {
vga_interface_type = VGA_VIRTIO;
} else {
error_report("Virtio VGA not available");
exit(1);
}
} else if (strstart(p, "xenfb", &opts)) {
vga_interface_type = VGA_XENFB;
} else if (strstart(p, "qxl", &opts)) {
if (qxl_vga_available()) {
vga_interface_type = VGA_QXL;
} else {
error_report("QXL VGA not available");
exit(1);
}
} else if (strstart(p, "tcx", &opts)) {
if (tcx_vga_available()) {
vga_interface_type = VGA_TCX;
} else {
error_report("TCX framebuffer not available");
exit(1);
}
} else if (strstart(p, "cg3", &opts)) {
if (cg3_vga_available()) {
vga_interface_type = VGA_CG3;
} else {
error_report("CG3 framebuffer not available");
exit(1);
}
} else if (!strstart(p, "none", &opts)) {
invalid_vga:
error_report("unknown vga type: %s", p);
exit(1);
}
while (*opts) {
const char *nextopt;
if (strstart(opts, ",retrace=", &nextopt)) {
opts = nextopt;
if (strstart(opts, "dumb", &nextopt))
vga_retrace_method = VGA_RETRACE_DUMB;
else if (strstart(opts, "precise", &nextopt))
vga_retrace_method = VGA_RETRACE_PRECISE;
else goto invalid_vga;
} else goto invalid_vga;
opts = nextopt;
}
}
| 1threat
|
void build_legacy_cpu_hotplug_aml(Aml *ctx, MachineState *machine,
uint16_t io_base)
{
Aml *dev;
Aml *crs;
Aml *pkg;
Aml *field;
Aml *method;
Aml *if_ctx;
Aml *else_ctx;
int i, apic_idx;
Aml *sb_scope = aml_scope("_SB");
uint8_t madt_tmpl[8] = {0x00, 0x08, 0x00, 0x00, 0x00, 0, 0, 0};
Aml *cpu_id = aml_arg(1);
Aml *apic_id = aml_arg(0);
Aml *cpu_on = aml_local(0);
Aml *madt = aml_local(1);
Aml *cpus_map = aml_name(CPU_ON_BITMAP);
Aml *zero = aml_int(0);
Aml *one = aml_int(1);
MachineClass *mc = MACHINE_GET_CLASS(machine);
CPUArchIdList *apic_ids = mc->possible_cpu_arch_ids(machine);
PCMachineState *pcms = PC_MACHINE(machine);
method = aml_method(CPU_MAT_METHOD, 2, AML_NOTSERIALIZED);
aml_append(method,
aml_store(aml_derefof(aml_index(cpus_map, apic_id)), cpu_on));
aml_append(method,
aml_store(aml_buffer(sizeof(madt_tmpl), madt_tmpl), madt));
aml_append(method, aml_store(cpu_id, aml_index(madt, aml_int(2))));
aml_append(method, aml_store(apic_id, aml_index(madt, aml_int(3))));
aml_append(method, aml_store(cpu_on, aml_index(madt, aml_int(4))));
aml_append(method, aml_return(madt));
aml_append(sb_scope, method);
method = aml_method(CPU_STATUS_METHOD, 1, AML_NOTSERIALIZED);
aml_append(method,
aml_store(aml_derefof(aml_index(cpus_map, apic_id)), cpu_on));
if_ctx = aml_if(cpu_on);
{
aml_append(if_ctx, aml_return(aml_int(0xF)));
}
aml_append(method, if_ctx);
else_ctx = aml_else();
{
aml_append(else_ctx, aml_return(zero));
}
aml_append(method, else_ctx);
aml_append(sb_scope, method);
method = aml_method(CPU_EJECT_METHOD, 2, AML_NOTSERIALIZED);
aml_append(method, aml_sleep(200));
aml_append(sb_scope, method);
method = aml_method(CPU_SCAN_METHOD, 0, AML_NOTSERIALIZED);
{
Aml *while_ctx, *if_ctx2, *else_ctx2;
Aml *bus_check_evt = aml_int(1);
Aml *remove_evt = aml_int(3);
Aml *status_map = aml_local(5);
Aml *byte = aml_local(2);
Aml *idx = aml_local(0);
Aml *is_cpu_on = aml_local(1);
Aml *status = aml_local(3);
aml_append(method, aml_store(aml_name(CPU_STATUS_MAP), status_map));
aml_append(method, aml_store(zero, byte));
aml_append(method, aml_store(zero, idx));
while_ctx = aml_while(aml_lless(idx, aml_sizeof(cpus_map)));
aml_append(while_ctx,
aml_store(aml_derefof(aml_index(cpus_map, idx)), is_cpu_on));
if_ctx = aml_if(aml_and(idx, aml_int(0x07), NULL));
{
aml_append(if_ctx, aml_shiftright(byte, one, byte));
}
aml_append(while_ctx, if_ctx);
else_ctx = aml_else();
{
aml_append(else_ctx, aml_store(aml_derefof(aml_index(status_map,
aml_shiftright(idx, aml_int(3), NULL))), byte));
}
aml_append(while_ctx, else_ctx);
aml_append(while_ctx, aml_store(aml_and(byte, one, NULL), status));
if_ctx = aml_if(aml_lnot(aml_equal(is_cpu_on, status)));
{
aml_append(if_ctx, aml_store(status, aml_index(cpus_map, idx)));
if_ctx2 = aml_if(aml_equal(status, one));
{
aml_append(if_ctx2,
aml_call2(AML_NOTIFY_METHOD, idx, bus_check_evt));
}
aml_append(if_ctx, if_ctx2);
else_ctx2 = aml_else();
{
aml_append(else_ctx2,
aml_call2(AML_NOTIFY_METHOD, idx, remove_evt));
}
}
aml_append(if_ctx, else_ctx2);
aml_append(while_ctx, if_ctx);
aml_append(while_ctx, aml_increment(idx));
aml_append(method, while_ctx);
}
aml_append(sb_scope, method);
QEMU_BUILD_BUG_ON(ACPI_CPU_HOTPLUG_ID_LIMIT > 256);
g_assert(pcms->apic_id_limit <= ACPI_CPU_HOTPLUG_ID_LIMIT);
dev = aml_device("PCI0." stringify(CPU_HOTPLUG_RESOURCE_DEVICE));
aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A06")));
aml_append(dev,
aml_name_decl("_UID", aml_string("CPU Hotplug resources"))
);
aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));
crs = aml_resource_template();
aml_append(crs,
aml_io(AML_DECODE16, io_base, io_base, 1, ACPI_GPE_PROC_LEN)
);
aml_append(dev, aml_name_decl("_CRS", crs));
aml_append(sb_scope, dev);
aml_append(sb_scope, aml_operation_region(
"PRST", AML_SYSTEM_IO, aml_int(io_base), ACPI_GPE_PROC_LEN));
field = aml_field("PRST", AML_BYTE_ACC, AML_NOLOCK, AML_PRESERVE);
aml_append(field, aml_named_field("PRS", 256));
aml_append(sb_scope, field);
for (i = 0; i < apic_ids->len; i++) {
int apic_id = apic_ids->cpus[i].arch_id;
assert(apic_id < ACPI_CPU_HOTPLUG_ID_LIMIT);
dev = aml_processor(i, 0, 0, "CP%.02X", apic_id);
method = aml_method("_MAT", 0, AML_NOTSERIALIZED);
aml_append(method,
aml_return(aml_call2(CPU_MAT_METHOD, aml_int(apic_id), aml_int(i))
));
aml_append(dev, method);
method = aml_method("_STA", 0, AML_NOTSERIALIZED);
aml_append(method,
aml_return(aml_call1(CPU_STATUS_METHOD, aml_int(apic_id))));
aml_append(dev, method);
method = aml_method("_EJ0", 1, AML_NOTSERIALIZED);
aml_append(method,
aml_return(aml_call2(CPU_EJECT_METHOD, aml_int(apic_id),
aml_arg(0)))
);
aml_append(dev, method);
aml_append(sb_scope, dev);
}
method = aml_method(AML_NOTIFY_METHOD, 2, AML_NOTSERIALIZED);
for (i = 0; i < apic_ids->len; i++) {
int apic_id = apic_ids->cpus[i].arch_id;
if_ctx = aml_if(aml_equal(aml_arg(0), aml_int(apic_id)));
aml_append(if_ctx,
aml_notify(aml_name("CP%.02X", apic_id), aml_arg(1))
);
aml_append(method, if_ctx);
}
aml_append(sb_scope, method);
pkg = pcms->apic_id_limit <= 255 ? aml_package(pcms->apic_id_limit) :
aml_varpackage(pcms->apic_id_limit);
for (i = 0, apic_idx = 0; i < apic_ids->len; i++) {
int apic_id = apic_ids->cpus[i].arch_id;
for (; apic_idx < apic_id; apic_idx++) {
aml_append(pkg, aml_int(0));
}
aml_append(pkg, aml_int(apic_ids->cpus[i].cpu ? 1 : 0));
apic_idx = apic_id + 1;
}
aml_append(sb_scope, aml_name_decl(CPU_ON_BITMAP, pkg));
g_free(apic_ids);
aml_append(ctx, sb_scope);
method = aml_method("\\_GPE._E02", 0, AML_NOTSERIALIZED);
aml_append(method, aml_call0("\\_SB." CPU_SCAN_METHOD));
aml_append(ctx, method);
}
| 1threat
|
git clone error: gnutls_handshake() failed: An unexpected TLS packet was received : <p>I am running Ubuntu 18.04 LTS on armv7l. I am running git clone inside a proxy (I got the proxy variables set properly), but now I get this;</p>
<p><code>fatal: unable to access '<my_git>.git/': gnutls_handshake() failed: An unexpected TLS packet was received.</code></p>
<p>It used to work in Ubuntu 16.04. I have checked <a href="https://askubuntu.com/questions/186847/error-gnutls-handshake-failed-when-connecting-to-https-servers">this solution</a> but it does not work for me. All I am trying to do is to git clone. </p>
| 0debug
|
Is there another way to "setConnection" on an Eloquent Model? : <p>I am currently handling a "multi db on the fly swap connections" sort of project.</p>
<p>So what I end up doing is the following:</p>
<pre><code>$connectionName = uniqid();
\Config::set('database.connections.' . $connectionName, [/** db options **/]);
\Artisan::call('migrate', ['--database' => $connectionName]);
</code></pre>
<p>or </p>
<pre><code>$connectionName = uniqid();
\Config::set('database.connections.' . $connectionName,[/** db options **/]);
$user = new User();
$user->setConnection($connectionName);
$user->first_name = 'Daisy';
$user->last_name = 'Demo';
$user->is_not_being_ignored_by_santa_this_year = 0;
$user->email = //and so so on
$user->save();
</code></pre>
<p>For the Artisan call I sort of understand why Laravel needs to refer to a connection in a string, saved in a config array. </p>
<p>However on the Eloquent Model itself I find it somehow cumbersome to have to write my DB connection into a config array. So it can be picked up by the "Singleton approach" \Config::get().. in the Model. </p>
<p>Is there something more elegant, where I can inject a configuration directly without having to write it into some super global ?</p>
<p>Or am I missing something ?</p>
| 0debug
|
int qcrypto_hash_bytesv(QCryptoHashAlgorithm alg,
const struct iovec *iov,
size_t niov,
uint8_t **result,
size_t *resultlen,
Error **errp)
{
int i, ret;
gnutls_hash_hd_t dig;
if (alg >= G_N_ELEMENTS(qcrypto_hash_alg_map)) {
error_setg(errp,
"Unknown hash algorithm %d",
alg);
return -1;
}
ret = gnutls_hash_init(&dig, qcrypto_hash_alg_map[alg]);
if (ret < 0) {
error_setg(errp,
"Unable to initialize hash algorithm: %s",
gnutls_strerror(ret));
return -1;
}
for (i = 0; i < niov; i++) {
ret = gnutls_hash(dig, iov[i].iov_base, iov[i].iov_len);
if (ret < 0) {
error_setg(errp,
"Unable process hash data: %s",
gnutls_strerror(ret));
goto error;
}
}
ret = gnutls_hash_get_len(qcrypto_hash_alg_map[alg]);
if (ret <= 0) {
error_setg(errp,
"Unable to get hash length: %s",
gnutls_strerror(ret));
goto error;
}
if (*resultlen == 0) {
*resultlen = ret;
*result = g_new0(uint8_t, *resultlen);
} else if (*resultlen != ret) {
error_setg(errp,
"Result buffer size %zu is smaller than hash %d",
*resultlen, ret);
goto error;
}
gnutls_hash_deinit(dig, *result);
return 0;
error:
gnutls_hash_deinit(dig, NULL);
return -1;
}
| 1threat
|
How to fix "Equations for ‘lefgNLista’ have different numbers of arguments" : I'm trying to learn list in Haskell but I have a error that me and my friends don't understand
I've been trying with the definition of the arguments, but to be honest I don't understand too much of haskell yet.
lefgNLista:: [Int]->[Int]->Int
lefgNLista []=[]
lefgNLista (fre1:fre2) fre3 = if fre1 == fre3 then 1+lefgNLista else fre1 : lefgNLista fre2
Also try with this but another error pop up
lefgNLista []=[]=0
I expect the function count the amount of N numbers in the list, e.g.
lefgNLista [1,3,5,7,8,8,2,3,8] 8
result 3
| 0debug
|
I am doing a (StrIns) funcion that mix 2 words but the program is not working at all : this is my code
________________________________________________________________________
#include <stdio.h>
#include <stdlib.h>
char strins(char[],char[],int,int,int);
int main(void)
{
char zk1[1000];
char zk2[1000];
int pos=0;
int n1=0;
int n2=0;
printf("plz enter the first string : ");
gets(zk1);
n1=sizeof(zk1)/sizeof(int);
printf("plz enter the second string : ");
gets(zk2);
n2=sizeof(zk2)/sizeof(int);
printf("plz enter the position");
scanf("%d",&pos);
strins(zk1,zk2,pos,n1,n2);
return 0;
}
char strins(char zk1[],char zk2[],int pos,int n1,int n2)
{
char zk3[]={(char)malloc(sizeof(zk1)+sizeof(zk2))};
int ctr=0;
for(int i=0;i<pos;i++)
{
zk3[i]=zk1[i];
ctr++;
}
for(int i=0;i<n2;i++)
{
zk3[pos]=zk2[i];
ctr++;
}
for(int i=pos;i<n1;i++)
{
zk3[ctr]=zk1[i];
}
free(zk3);
return *zk3;
}
__________________________________________________________________________
there are no compiler errors
__________________________________________________________________________
but when I run the program and write the tow words and the position the program stops
____________________________________________________________________________
and write this error :: process returned 255
___________________________________________________________________________
thanks for helping me
| 0debug
|
How to find if all brackets are balanced (C) : <p>So I have an array full of brackets, for example :</p>
<p>1) (()())())((())(())</p>
<p>2) ()((()()))</p>
<p>Any open bracket ( '(' ) should also be closed by another one (')')</p>
<p>So for example 1) -></p>
<p>(()())())((())(()) -> (....)..)((..)(..) -> ())(()() -> .)(.. , so the answer is no because from here we can see that not all of the brackets are balanced</p>
<p>For example 2) -></p>
<p>()((()())) -> .((..)) -> (()) -> (..) -> () -> .. , so here the answer is yes because all brackets are balanced. In this case, I would also like to print the positions of all couples of brackets that are balanced, for example :</p>
<p>1,2 & 5,6 & 7,8 & 3,10 & 4,9</p>
<p>~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~</p>
| 0debug
|
How can I grant the account permission to list enabled APIs? : <p>During a build on Cloud Build, I get the following warning:</p>
<p><code>Step #2: WARNING: Unable to verify that the Appengine Flexible API is enabled for project [xxxxx]. You may not have permission to list enabled services on this project. If it is not enabled, this may cause problems in running your deployment. Please ask the project owner to ensure that the Appengine Flexible API has been enabled and that this account has permission to list enabled APIs.</code></p>
<p>I'd like to get rid of this warning to get a clean build log.</p>
<p>Since the build succeeds, the problem must not be with Appengine Flexible API being disabled.</p>
<p>No; the problem must be that the account does not have permission to list enabled APIs. How can I fix that (either in the Console or at the command line)?</p>
| 0debug
|
Why there is no Source Code Management tab in a Jenkins pipeline job? : <p>I've just installed the pipeline plugin (on Jenkins 2.1). When I create a new job the <em>Source Code Management</em> tab is missing (and a few others).
According to <a href="https://jenkins.io/2.0/#ux" rel="noreferrer">the article describing the Pipeline feature</a> at it should look like:
<a href="https://i.stack.imgur.com/pSjSa.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pSjSa.png" alt="Source Code Management tab"></a></p>
<p>However this is how it looks like in my case:
<a href="https://i.stack.imgur.com/HZluW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HZluW.png" alt="enter image description here"></a></p>
<p>Where are the missing tabs, especially the <em>Source Code Management</em> one? Is it simply some missing config/plugin or a bug?</p>
<p>I'm on Jenkins 2.1</p>
| 0debug
|
What is the different between force push and normal push in git : <p>I want to know what is the different between force push and normal push and at what kind of situations i should do force push in git?Is it a good practice to do force push into master branch?</p>
| 0debug
|
javascript variable's weird behaviour : <p>Case 1 - If I console.log(variable) before the variable declaration I get undefined. eg;</p>
<pre><code> // code
console.log(a);
var a ;
// output
undefined
</code></pre>
<p>Case 2 - If I console.log(variable) without variable declaration I get Uncaught ReferenceError: variable is not defined. </p>
<pre><code>// code
console.log(a);
// output
Uncaught ReferenceError: a is not defined
</code></pre>
<p>But incase of functions we can call a function before or after function definition it never give any issue. eg;</p>
<pre><code> console.log(example());
function example(){
return 'test done';
}
console.log(example());
// output without any issue
</code></pre>
<p>Now My question is, what is the difference between <strong>undefined</strong> and <strong>not defined</strong>.</p>
| 0debug
|
Validating possibilities for HasMap access : Im asking myself what could be the more elegant way of validating a HasMap access.
Map<String, String> m = new HashMap<>();
if(m.hasNext()){
...}
else
System.out.println("Error.");
or
Map<String, String> m = new HashMap<>();
try{
m.getNext();
catch(Exception e){
...}
| 0debug
|
Create a number with several digit in C++ : <p>I have 3 digits (1,4,6) and I want to create a number with 2 digits from my digits like 11,14,16,41,44,46,61,64,66.</p>
<p>What command should I use in c++ ?</p>
| 0debug
|
Swift 1.2 -> Swift 2 : <p>I'm coding an app for my Kids. I have background in Java but havn't professionally coded in a decade. I don't thoroughly understand how the following line works but it worked in Swift 1.2:</p>
<pre><code>leaderboardRequest.loadScoresWithCompletionHandler({ (scores:[AnyObject]!, error:NSError!) -> Void in
if (error != nil)
{
</code></pre>
<p>I need help translating this into working Swift 2.0 code. Could someone please post a translation of working Swift 2.0 code for the following method:</p>
<pre><code>func getHighscores(leaderboardID: String) {
let leaderboardRequest = GKLeaderboard() as GKLeaderboard!
leaderboardRequest.identifier = leaderboardID
if leaderboardRequest != nil
{
leaderboardRequest.loadScoresWithCompletionHandler({ (scores:[AnyObject]!, error:NSError!) -> Void in
if (error != nil)
{
//println("error in alltimeHighscoreForLevel")
print(error.description)
self.updateLocalHighscore()
}
else
{
if(leaderboardRequest != nil){
if(leaderboardRequest.scores != nil ) {
if(leaderboardRequest.scores!.count > 0){
self.updateHighestForLevel(leaderboardRequest)
}
}
}
}
})
}
}
</code></pre>
| 0debug
|
How to pass method name as a parmeter? : <p>I'm looking for a way to make my code shorter. Since a big part of my code is repeatable, is there any way to pass a sub method name as a parmeter?</p>
<p>Here is a some bigger part to make my problem some more clear:</p>
<pre><code>Random rnd = new Random(Guid.NewGuid().GetHashCode());
int[] ArrayRandom = new int[200000];
for (int j = 0; j < ArrayRandom.Length; j++) ArrayRandom[j] = rnd.Next(int.MaxValue);
Console.WriteLine("\nInsertionSort\nARRAY SIZE:\t TIME [ms]:");
for (int u = 50000; u <= 200000; u += 10000)
{
int[] TestArray = new int[u];
Array.Copy(ArrayRandom, TestArray, u);
double ElapsedSeconds;
long ElapsedTime = 0, MinTime = long.MaxValue, MaxTime = long.MinValue, IterationElapsedTime;
for (int n = 0; n < (NIter + 1 + 1); ++n)
{
long StartingTime = Stopwatch.GetTimestamp();
InsertionSort(TestArray);
long EndingTime = Stopwatch.GetTimestamp();
IterationElapsedTime = EndingTime - StartingTime;
ElapsedTime += IterationElapsedTime;
if (IterationElapsedTime < MinTime) MinTime = IterationElapsedTime;
if (IterationElapsedTime > MaxTime) MaxTime = IterationElapsedTime;
}
ElapsedTime -= (MinTime + MaxTime);
ElapsedSeconds = ElapsedTime * (1000.0 / (NIter * Stopwatch.Frequency));
Console.WriteLine("{0,-12}\t{1}", u, ElapsedSeconds.ToString("F4"));
}
Console.WriteLine("\nSelectionSort\nARRAY SIZE:\t TIME [ms]:");
for (int u = 50000; u <= 200000; u += 10000)
{
int[] TestArray = new int[u];
Array.Copy(ArrayRandom, TestArray, u);
double ElapsedSeconds;
long ElapsedTime = 0, MinTime = long.MaxValue, MaxTime = long.MinValue, IterationElapsedTime;
for (int n = 0; n < (NIter + 1 + 1); ++n)
{
long StartingTime = Stopwatch.GetTimestamp();
SelectionSort(TestArray);
long EndingTime = Stopwatch.GetTimestamp();
IterationElapsedTime = EndingTime - StartingTime;
ElapsedTime += IterationElapsedTime;
if (IterationElapsedTime < MinTime) MinTime = IterationElapsedTime;
if (IterationElapsedTime > MaxTime) MaxTime = IterationElapsedTime;
}
ElapsedTime -= (MinTime + MaxTime);
ElapsedSeconds = ElapsedTime * (1000.0 / (NIter * Stopwatch.Frequency));
Console.WriteLine("{0,-12}\t{1}", u, ElapsedSeconds.ToString("F4"));
}
Console.WriteLine("\nCoctailSort\nARRAY SIZE:\t TIME [ms]:");
for (int u = 50000; u <= 200000; u += 10000)
{
int[] TestArray = new int[u];
Array.Copy(ArrayRandom, TestArray, u);
double ElapsedSeconds;
long ElapsedTime = 0, MinTime = long.MaxValue, MaxTime = long.MinValue, IterationElapsedTime;
for (int n = 0; n < (NIter + 1 + 1); ++n)
{
long StartingTime = Stopwatch.GetTimestamp();
CocktailSort(TestArray);
long EndingTime = Stopwatch.GetTimestamp();
IterationElapsedTime = EndingTime - StartingTime;
ElapsedTime += IterationElapsedTime;
if (IterationElapsedTime < MinTime) MinTime = IterationElapsedTime;
if (IterationElapsedTime > MaxTime) MaxTime = IterationElapsedTime;
}
ElapsedTime -= (MinTime + MaxTime);
ElapsedSeconds = ElapsedTime * (1000.0 / (NIter * Stopwatch.Frequency));
Console.WriteLine("{0,-12}\t{1}", u, ElapsedSeconds.ToString("F4"));
}
Console.WriteLine("\nHeapSort\nARRAY SIZE:\t TIME [ms]:");
for (int u = 50000; u <= 200000; u += 10000)
{
int[] TestArray = new int[u];
Array.Copy(ArrayRandom, TestArray, u);
double ElapsedSeconds;
long ElapsedTime = 0, MinTime = long.MaxValue, MaxTime = long.MinValue, IterationElapsedTime;
for (int n = 0; n < (NIter + 1 + 1); ++n)
{
long StartingTime = Stopwatch.GetTimestamp();
HeapSort(TestArray);
long EndingTime = Stopwatch.GetTimestamp();
IterationElapsedTime = EndingTime - StartingTime;
ElapsedTime += IterationElapsedTime;
if (IterationElapsedTime < MinTime) MinTime = IterationElapsedTime;
if (IterationElapsedTime > MaxTime) MaxTime = IterationElapsedTime;
}
ElapsedTime -= (MinTime + MaxTime);
ElapsedSeconds = ElapsedTime * (1000.0 / (NIter * Stopwatch.Frequency));
Console.WriteLine("{0,-12}\t{1}", u, ElapsedSeconds.ToString("F4"));
}
</code></pre>
<p>As You see, that what is changing is a sort method name. Basicly I want to change, this:</p>
<pre><code>Console.WriteLine("\nInsertionSort\nARRAY SIZE:\t TIME [ms]:");
for (int u = 50000; u <= 200000; u += 10000)
{
int[] TestArray = new int[u];
Array.Copy(ArrayRandom, TestArray, u);
double ElapsedSeconds;
long ElapsedTime = 0, MinTime = long.MaxValue, MaxTime = long.MinValue, IterationElapsedTime;
for (int n = 0; n < (NIter + 1 + 1); ++n)
{
long StartingTime = Stopwatch.GetTimestamp();
InsertionSort(TestArray);
long EndingTime = Stopwatch.GetTimestamp();
IterationElapsedTime = EndingTime - StartingTime;
ElapsedTime += IterationElapsedTime;
if (IterationElapsedTime < MinTime) MinTime = IterationElapsedTime;
if (IterationElapsedTime > MaxTime) MaxTime = IterationElapsedTime;
}
ElapsedTime -= (MinTime + MaxTime);
ElapsedSeconds = ElapsedTime * (1000.0 / (NIter * Stopwatch.Frequency));
Console.WriteLine("{0,-12}\t{1}", u, ElapsedSeconds.ToString("F4"));
}
</code></pre>
<p>into somthing like this:</p>
<pre><code>MethotImLookingFor(AnySort(TestArray));
</code></pre>
| 0debug
|
Mockito on Android, Context.getString(id) and NullPointerException : <p>I've just started learning a Mockito testing framework, I followed official tutorial from: <a href="https://developer.android.com/training/testing/unit-testing/local-unit-tests.html" rel="noreferrer">developer.android.com</a></p>
<p>The code is:</p>
<pre><code>private static final String FAKE_STRING = "HELLO WORLD";
@Mock
Context mMockContext;
@Test
public void readStringFromContext_LocalizedString() {
// Given a mocked Context injected into the object under test...
when(mMockContext.getString(R.string.hello_world))
.thenReturn(FAKE_STRING);
ClassUnderTest myObjectUnderTest = new ClassUnderTest(mMockContext);
// ...when the string is returned from the object under test...
String result = myObjectUnderTest.getHelloWorldString();
// ...then the result should be the expected one.
assertThat(result, is(FAKE_STRING));
}
</code></pre>
<p>I wrote following ClassUnderTest:</p>
<pre><code>public class ClassUnderTest {
private Context context;
public ClassUnderTest(Context context)
{
this.context=context;
}
public String getHelloWorldString()
{
return context.getString(R.string.hello_world);
}
</code></pre>
<p>}</p>
<p>and after running I'm getting NullPointerException:</p>
<pre><code> java.lang.NullPointerException
at android.content.Context.getHelloWorldString(Context.java:293)
at com.darekk.draggablelistview.unit_tests.MockitoTest.readStringFromContext_LocalizedString(MockitoTest.java:46)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:59)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:262)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1619)
</code></pre>
<p>When I replace android Context with my own class it works.</p>
<p>Platform: IntelliJ IDEA Community Edition 15.0.6</p>
<p>I really appreciate any help.</p>
| 0debug
|
static ssize_t virtio_net_receive(NetClientState *nc, const uint8_t *buf, size_t size)
{
VirtIONet *n = qemu_get_nic_opaque(nc);
VirtIONetQueue *q = virtio_net_get_subqueue(nc);
VirtIODevice *vdev = VIRTIO_DEVICE(n);
struct iovec mhdr_sg[VIRTQUEUE_MAX_SIZE];
struct virtio_net_hdr_mrg_rxbuf mhdr;
unsigned mhdr_cnt = 0;
size_t offset, i, guest_offset;
if (!virtio_net_can_receive(nc)) {
return -1;
}
if (!virtio_net_has_buffers(q, size + n->guest_hdr_len - n->host_hdr_len)) {
return 0;
}
if (!receive_filter(n, buf, size))
return size;
offset = i = 0;
while (offset < size) {
VirtQueueElement elem;
int len, total;
const struct iovec *sg = elem.in_sg;
total = 0;
if (virtqueue_pop(q->rx_vq, &elem) == 0) {
if (i == 0)
return -1;
error_report("virtio-net unexpected empty queue: "
"i %zd mergeable %d offset %zd, size %zd, "
"guest hdr len %zd, host hdr len %zd "
"guest features 0x%" PRIx64,
i, n->mergeable_rx_bufs, offset, size,
n->guest_hdr_len, n->host_hdr_len,
vdev->guest_features);
exit(1);
}
if (elem.in_num < 1) {
error_report("virtio-net receive queue contains no in buffers");
exit(1);
}
if (i == 0) {
assert(offset == 0);
if (n->mergeable_rx_bufs) {
mhdr_cnt = iov_copy(mhdr_sg, ARRAY_SIZE(mhdr_sg),
sg, elem.in_num,
offsetof(typeof(mhdr), num_buffers),
sizeof(mhdr.num_buffers));
}
receive_header(n, sg, elem.in_num, buf, size);
offset = n->host_hdr_len;
total += n->guest_hdr_len;
guest_offset = n->guest_hdr_len;
} else {
guest_offset = 0;
}
len = iov_from_buf(sg, elem.in_num, guest_offset,
buf + offset, size - offset);
total += len;
offset += len;
if (!n->mergeable_rx_bufs && offset < size) {
#if 0
error_report("virtio-net truncated non-mergeable packet: "
"i %zd mergeable %d offset %zd, size %zd, "
"guest hdr len %zd, host hdr len %zd",
i, n->mergeable_rx_bufs,
offset, size, n->guest_hdr_len, n->host_hdr_len);
#endif
return size;
}
virtqueue_fill(q->rx_vq, &elem, total, i++);
}
if (mhdr_cnt) {
virtio_stw_p(vdev, &mhdr.num_buffers, i);
iov_from_buf(mhdr_sg, mhdr_cnt,
0,
&mhdr.num_buffers, sizeof mhdr.num_buffers);
}
virtqueue_flush(q->rx_vq, i);
virtio_notify(vdev, q->rx_vq);
return size;
}
| 1threat
|
jsp?Action=someaction not working but jsp?action=someaction works : <p>In my web application, I use jsp and servlets. To redirect to a page, I use the following URL Pattern with some action.</p>
<p><strong>This does not work.</strong></p>
<p>1.<a href="http://100.320.22.1423:1023/hello/SomePage.jsp?Action=Det&FunctionId=ID123" rel="nofollow noreferrer">http://100.320.22.1423:1023/hello/SomePage.jsp?Action=Det&FunctionId=ID123</a></p>
<p>These work. As you can see, the only difference between 1 and 2 are 'Action' starts with capital and simple letters. I encountered these problems afrer updating my browers ( both Chrome and firefox )</p>
<p>2.<a href="http://100.320.22.1423:1023/hello/SomePage.jsp?action=Det&FunctionId=ID123" rel="nofollow noreferrer">http://100.320.22.1423:1023/hello/SomePage.jsp?action=Det&FunctionId=ID123</a>
3.<a href="http://100.320.22.1423:10023/hello/SomePage.jsp?FunctionId=ID123&Action=Det" rel="nofollow noreferrer">http://100.320.22.1423:10023/hello/SomePage.jsp?FunctionId=ID123&Action=Det</a></p>
<p>Any suggestion or reasons why this happens?</p>
<p>Thanks in advance.</p>
| 0debug
|
Simple insertion sort : Why this code waits for user to input 10 integers when size of array input by user is 8 ? It gives segmentation fault when 10 integers are used.`
#include<iostream>
using namespace std;
int main()
{
int x,a[x];
cout<<"enter the size of array"<<endl;
cin>>x;
cout<<"enter the elements"<<endl;
for(int j=0;j<x;j++)
cin>>a[j];
for(int i=1;i<x;i++){
for(int k=0;k<i;k++){
if(a[i]<a[k])
swap(a[i],a[k]);
else continue;
}
}
for(int m=0;m<x;m++)
cout<<a[m];
}
| 0debug
|
void av_free(void *ptr)
{
#if CONFIG_MEMALIGN_HACK
if (ptr)
free((char *)ptr - ((char *)ptr)[-1]);
#elif HAVE_ALIGNED_MALLOC
_aligned_free(ptr);
#else
free(ptr);
#endif
}
| 1threat
|
c ++ code test if a inn value is in one of the hundred years (Ex: 1900, 1800 , 200) : <p>Does anyone know of a good code I can use for test if a value is one of the hundred years? </p>
<p>Example: 1200 or 2000 or 2100 or 300.</p>
<p>A easy one, so I dont have to write inn every year like this. </p>
<p>The reason is that i want to do something else with this numbers in a if statement. </p>
<p>Thanks for answers.</p>
| 0debug
|
static enum AVPixelFormat get_format(HEVCContext *s, const HEVCSPS *sps)
{
#define HWACCEL_MAX (CONFIG_HEVC_DXVA2_HWACCEL + CONFIG_HEVC_D3D11VA_HWACCEL + CONFIG_HEVC_VAAPI_HWACCEL + CONFIG_HEVC_VDPAU_HWACCEL)
enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmt = pix_fmts;
switch (sps->pix_fmt) {
case AV_PIX_FMT_YUV420P:
case AV_PIX_FMT_YUVJ420P:
#if CONFIG_HEVC_DXVA2_HWACCEL
*fmt++ = AV_PIX_FMT_DXVA2_VLD;
#endif
#if CONFIG_HEVC_D3D11VA_HWACCEL
*fmt++ = AV_PIX_FMT_D3D11VA_VLD;
#endif
#if CONFIG_HEVC_VAAPI_HWACCEL
*fmt++ = AV_PIX_FMT_VAAPI;
#endif
#if CONFIG_HEVC_VDPAU_HWACCEL
*fmt++ = AV_PIX_FMT_VDPAU;
#endif
break;
case AV_PIX_FMT_YUV420P10:
#if CONFIG_HEVC_DXVA2_HWACCEL
*fmt++ = AV_PIX_FMT_DXVA2_VLD;
#endif
#if CONFIG_HEVC_D3D11VA_HWACCEL
*fmt++ = AV_PIX_FMT_D3D11VA_VLD;
#endif
#if CONFIG_HEVC_VAAPI_HWACCEL
*fmt++ = AV_PIX_FMT_VAAPI;
#endif
break;
}
*fmt++ = sps->pix_fmt;
*fmt = AV_PIX_FMT_NONE;
return ff_get_format(s->avctx, pix_fmts);
}
| 1threat
|
PermissionError: [Errno 13] Permission denied Flask.run() : <p>I am running MacOS X with python 3. The folder and files have 755 but I have also tested it in 777 with no luck. My question is if I have the right permissions why does it not let me run without sudo. Or are my settings incorrect?</p>
<pre><code>cris-mbp:ProjectFolder cris$ python3 zbo.py
Traceback (most recent call last):
File "zbo.py", line 9, in <module>
app.run(host="127.0.0.1",port=81,debug=True)
File "/usr/local/lib/python3.5/site-packages/flask/app.py", line 843, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python3.5/site-packages/werkzeug/serving.py", line 677, in run_simple
s.bind((hostname, port))
PermissionError: [Errno 13] Permission denied
cris-mbp:ProjectFolder cris$ sudo python3 zbo.py
* Running on http://127.0.0.1:81/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger pin code: 106-133-233
</code></pre>
| 0debug
|
static void encode_subband(SnowContext *s, SubBand *b, DWTELEM *src, DWTELEM *parent, int stride, int orientation){
encode_subband_c0run(s, b, src, parent, stride, orientation);
}
| 1threat
|
golang append syntax error: missing statement after label : <pre><code> fmt.Print("Text to send: ")
text, _ := readerConsole.ReadString('\n')
sizen := (int)(unsafe.Sizeof(text))
fmt.Print(sizen)
var bs []byte
binary.BigEndian.PutUint32(bs, sizen)
b := []byte(text)
a: = append(bs, b...)
</code></pre>
<p>Go formatter says error
"syntax error: missing statement after label" on append</p>
| 0debug
|
Installing python 3.6.4 : I'm trying to install python 3.6.4 on my new laptop with windows 8, but when I launch the IDLE, it shows me an error :
"The program can't start because api-crt-runtime-|1-1-0.dll is missing from your computer".
Can someone help me fix it??
| 0debug
|
How add my application content with description and preview to Google search results? : <p>I found this article: <a href="https://search.googleblog.com/2016/08/a-new-way-to-search-for-content-in-your.html" rel="nofollow noreferrer">A new way to search for content in your apps</a> and I'm really excited for this opportunity. I want to show my application content in google search results, like this:</p>
<p><a href="https://i.stack.imgur.com/ZVsJU.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZVsJU.gif" alt="Google In Apps Search"></a></p>
<p>But this article doesn't have any information about how to implement this features in your app.</p>
<p>I use <strong>App Indexing API</strong> in my application, as described in articles:</p>
<ul>
<li><a href="https://firebase.google.com/docs/app-indexing/android/activity" rel="nofollow noreferrer">Add the App Indexing
API</a></li>
<li><a href="https://developer.android.com/studio/write/app-link-indexing.html" rel="nofollow noreferrer">Add URL and App Indexing
Support</a></li>
</ul>
<p>This is my code:</p>
<pre><code>...
private GoogleApiClient mClient;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_main);
mClient = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public Action getAction() {
Thing object = new Thing.Builder()
.setName("Test Content")
.setDescription("Test Description")
.setUrl(Uri.parse("myapp://com.example/"))
.build();
return new Action.Builder(Action.TYPE_VIEW).setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
@Override
public void onStart() {
super.onStart();
mClient.connect();
AppIndex.AppIndexApi.start(mClient, getAction());
}
@Override
public void onStop() {
AppIndex.AppIndexApi.end(mClient, getAction());
mClient.disconnect();
super.onStop();
}
...
</code></pre>
<p>And this is result:</p>
<p><a href="https://i.stack.imgur.com/9Irt1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9Irt1.jpg" alt="Search result"></a></p>
<p>Google show my application's <em>Test Content</em> but without description and preview image. <strong>Is there any ways to add description and preview image in Google Search Results?</strong> (like Youtube or Twitter)</p>
| 0debug
|
How to do the AutoIncrement ID in php ajex : i am crating a simple crud system . i can increment the ID it working well stating from 0001 . but i need start from CS0001 i don't know how to do the task
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "loyalhospital";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT MAX(cast(patientno as decimal)) id FROM patient ";
if($result = mysqli_query($conn,$query))
{
$row = mysqli_fetch_assoc($result);
$count = $row['id'];
$count = $count+1;
$code_no = str_pad($count, 6, "CS0", STR_PAD_LEFT);
echo json_encode($code_no);
}
?>
after add the data ID is not incremented when i run the code output displyed like this **CS04**
| 0debug
|
av_cold void ff_vp8dsp_init_armv6(VP8DSPContext *dsp)
{
dsp->vp8_luma_dc_wht = ff_vp8_luma_dc_wht_armv6;
dsp->vp8_luma_dc_wht_dc = ff_vp8_luma_dc_wht_dc_armv6;
dsp->vp8_idct_add = ff_vp8_idct_add_armv6;
dsp->vp8_idct_dc_add = ff_vp8_idct_dc_add_armv6;
dsp->vp8_idct_dc_add4y = ff_vp8_idct_dc_add4y_armv6;
dsp->vp8_idct_dc_add4uv = ff_vp8_idct_dc_add4uv_armv6;
dsp->vp8_v_loop_filter16y = ff_vp8_v_loop_filter16_armv6;
dsp->vp8_h_loop_filter16y = ff_vp8_h_loop_filter16_armv6;
dsp->vp8_v_loop_filter8uv = ff_vp8_v_loop_filter8uv_armv6;
dsp->vp8_h_loop_filter8uv = ff_vp8_h_loop_filter8uv_armv6;
dsp->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16_inner_armv6;
dsp->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16_inner_armv6;
dsp->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_armv6;
dsp->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_armv6;
dsp->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter16_simple_armv6;
dsp->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter16_simple_armv6;
dsp->put_vp8_epel_pixels_tab[0][0][0] = ff_put_vp8_pixels16_armv6;
dsp->put_vp8_epel_pixels_tab[0][0][2] = ff_put_vp8_epel16_h6_armv6;
dsp->put_vp8_epel_pixels_tab[0][2][0] = ff_put_vp8_epel16_v6_armv6;
dsp->put_vp8_epel_pixels_tab[0][2][2] = ff_put_vp8_epel16_h6v6_armv6;
dsp->put_vp8_epel_pixels_tab[1][0][0] = ff_put_vp8_pixels8_armv6;
dsp->put_vp8_epel_pixels_tab[1][0][1] = ff_put_vp8_epel8_h4_armv6;
dsp->put_vp8_epel_pixels_tab[1][0][2] = ff_put_vp8_epel8_h6_armv6;
dsp->put_vp8_epel_pixels_tab[1][1][0] = ff_put_vp8_epel8_v4_armv6;
dsp->put_vp8_epel_pixels_tab[1][1][1] = ff_put_vp8_epel8_h4v4_armv6;
dsp->put_vp8_epel_pixels_tab[1][1][2] = ff_put_vp8_epel8_h6v4_armv6;
dsp->put_vp8_epel_pixels_tab[1][2][0] = ff_put_vp8_epel8_v6_armv6;
dsp->put_vp8_epel_pixels_tab[1][2][1] = ff_put_vp8_epel8_h4v6_armv6;
dsp->put_vp8_epel_pixels_tab[1][2][2] = ff_put_vp8_epel8_h6v6_armv6;
dsp->put_vp8_epel_pixels_tab[2][0][0] = ff_put_vp8_pixels4_armv6;
dsp->put_vp8_epel_pixels_tab[2][0][1] = ff_put_vp8_epel4_h4_armv6;
dsp->put_vp8_epel_pixels_tab[2][0][2] = ff_put_vp8_epel4_h6_armv6;
dsp->put_vp8_epel_pixels_tab[2][1][0] = ff_put_vp8_epel4_v4_armv6;
dsp->put_vp8_epel_pixels_tab[2][1][1] = ff_put_vp8_epel4_h4v4_armv6;
dsp->put_vp8_epel_pixels_tab[2][1][2] = ff_put_vp8_epel4_h6v4_armv6;
dsp->put_vp8_epel_pixels_tab[2][2][0] = ff_put_vp8_epel4_v6_armv6;
dsp->put_vp8_epel_pixels_tab[2][2][1] = ff_put_vp8_epel4_h4v6_armv6;
dsp->put_vp8_epel_pixels_tab[2][2][2] = ff_put_vp8_epel4_h6v6_armv6;
dsp->put_vp8_bilinear_pixels_tab[0][0][0] = ff_put_vp8_pixels16_armv6;
dsp->put_vp8_bilinear_pixels_tab[0][0][1] = ff_put_vp8_bilin16_h_armv6;
dsp->put_vp8_bilinear_pixels_tab[0][0][2] = ff_put_vp8_bilin16_h_armv6;
dsp->put_vp8_bilinear_pixels_tab[0][1][0] = ff_put_vp8_bilin16_v_armv6;
dsp->put_vp8_bilinear_pixels_tab[0][1][1] = ff_put_vp8_bilin16_hv_armv6;
dsp->put_vp8_bilinear_pixels_tab[0][1][2] = ff_put_vp8_bilin16_hv_armv6;
dsp->put_vp8_bilinear_pixels_tab[0][2][0] = ff_put_vp8_bilin16_v_armv6;
dsp->put_vp8_bilinear_pixels_tab[0][2][1] = ff_put_vp8_bilin16_hv_armv6;
dsp->put_vp8_bilinear_pixels_tab[0][2][2] = ff_put_vp8_bilin16_hv_armv6;
dsp->put_vp8_bilinear_pixels_tab[1][0][0] = ff_put_vp8_pixels8_armv6;
dsp->put_vp8_bilinear_pixels_tab[1][0][1] = ff_put_vp8_bilin8_h_armv6;
dsp->put_vp8_bilinear_pixels_tab[1][0][2] = ff_put_vp8_bilin8_h_armv6;
dsp->put_vp8_bilinear_pixels_tab[1][1][0] = ff_put_vp8_bilin8_v_armv6;
dsp->put_vp8_bilinear_pixels_tab[1][1][1] = ff_put_vp8_bilin8_hv_armv6;
dsp->put_vp8_bilinear_pixels_tab[1][1][2] = ff_put_vp8_bilin8_hv_armv6;
dsp->put_vp8_bilinear_pixels_tab[1][2][0] = ff_put_vp8_bilin8_v_armv6;
dsp->put_vp8_bilinear_pixels_tab[1][2][1] = ff_put_vp8_bilin8_hv_armv6;
dsp->put_vp8_bilinear_pixels_tab[1][2][2] = ff_put_vp8_bilin8_hv_armv6;
dsp->put_vp8_bilinear_pixels_tab[2][0][0] = ff_put_vp8_pixels4_armv6;
dsp->put_vp8_bilinear_pixels_tab[2][0][1] = ff_put_vp8_bilin4_h_armv6;
dsp->put_vp8_bilinear_pixels_tab[2][0][2] = ff_put_vp8_bilin4_h_armv6;
dsp->put_vp8_bilinear_pixels_tab[2][1][0] = ff_put_vp8_bilin4_v_armv6;
dsp->put_vp8_bilinear_pixels_tab[2][1][1] = ff_put_vp8_bilin4_hv_armv6;
dsp->put_vp8_bilinear_pixels_tab[2][1][2] = ff_put_vp8_bilin4_hv_armv6;
dsp->put_vp8_bilinear_pixels_tab[2][2][0] = ff_put_vp8_bilin4_v_armv6;
dsp->put_vp8_bilinear_pixels_tab[2][2][1] = ff_put_vp8_bilin4_hv_armv6;
dsp->put_vp8_bilinear_pixels_tab[2][2][2] = ff_put_vp8_bilin4_hv_armv6;
}
| 1threat
|
statement that executing code over and over : <p>I do not know how to do code that is executing over and over again. I would like to achieve something like this:
(< stands for input, > stands for output)</p>
<pre><code>message=input()
print('Write down the text.')
</code></pre>
<pre><code>>Write down the text.
<qwerty
>qwerty
>Write down the text.
<asd
>asd
</code></pre>
| 0debug
|
Linked list not working in c++ : <p>So i'm trying to get the linked list and this is my code so far. Everything look fine when i'm adding a node at the front of my list, but when i try to add my first node at the back, my code compile but return me -1. I'm not sure what's wrong with it but I know it's in the insertBack() function. And by the way, if there's anything else wrong let me know, it's my first try on linked list!
Thanks!</p>
<pre><code>#include "LinkedList.h"
#include <iostream>
#include <stddef.h>
LinkedList::LinkedList()
{
head=NULL;
length=0;
}
void LinkedList::InsertFront(int item)
{
Node *temp = new Node;
temp->data = item;
temp->next = head;
head = temp;
length++;
}
void LinkedList::InsertBack(int item)
{
Node *temp1 = new Node;
temp1 = head;
while(temp1->next != NULL)
{
temp1 = temp1->next;
}
Node *temp = new Node;
temp->data = item;
temp->next = NULL;
temp1->next = temp;
length++;
}
void LinkedList::MakeEmpty()
{
Node *temp;
while(head!= NULL)
{
temp = head;
head = head->next;
delete temp;
}
length;
}
void LinkedList::ShowItems()
{
Node *temp = head;
while(temp != NULL)
{
std::cout<<temp->data<<std::endl;
temp = temp->next;
}
}
LinkedList::~LinkedList()
{
MakeEmpty();
}
</code></pre>
| 0debug
|
what is most efficient way to use sidebar menu? : So if i have to make have a sidebar menu like schools website, in which active clicked link is highlighted after the page loads.it uses individual pages like
<a target="_top" href="default.asp">HTML HOME</a>
<a target="_top" href="html_intro.asp">HTML Introduction</a>
<a target="_top" href="html_editors.asp">HTML Editors</a>
<a target="_top" href="html_basic.asp">HTML Basic</a>
<a target="_top" href="html_elements.asp">HTML Elements</a>
but the one i built on my own is created with php so what happens in that one is the title or name of menu item is changed to lowercase and saved in database in same row called class which is used for active link highlighting. so what happens when sidebar link is clicked is only content of summary div's content
(which is right to sidebar) is changed while sidebar and navigation bar stays same. so it stays on the same page and retrieves data from database and puts in summary div.
<body class='noPadding'>
<div class='bigNav'> <!-- top navbar -->
<img src="images/logo2.png"/>
</div>
<?php
if(isset($_GET['subject'])){
$subject=$_GET['subject'];
?>
<div class='container'>
<div class='leftLayout' style='padding-top:70px;background-color:#EBEBEB'>
<ul class="fullFit">
<?php
$query="SELECT * FROM `study` WHERE `subject`='$subject'";
$run=mysqli_query($conn,$query);
while($row=mysqli_fetch_array($run)){
$topic=$row['topic'];
$class=$row['class']; ?>
<li class="<?php echo $class?>">
<a href='<?php echo $sitename ?>/web.php?subject=<?php echo $subject?>&topic=<?php echo $class?>'>
<?php echo $topic?>
</a>
</li>
<?php } ?>
</ul>
</div>
<?php
if(isset($_GET['topic'])) {
$active_id=$_GET['topic'];
$topic=$_GET['topic'];
$query="SELECT summary FROM `study` WHERE `class`='$active_id'";
$run=mysqli_query($conn,$query);
$row=mysqli_fetch_array($run);
$summary=$row[0];
?>
<div class='summary'> <?php echo $summary ?> </div>
<?php } ?>
</div>
<script>
$(document).ready(function(){
$(".<?php echo $active_id ?>").addClass("current");
});
</script>
<?php } ?>
</body>
And also if i have to make individual pages instead like many websites including W3schools does,do i have to create a new file each time and include navigation bar and sidebar(which are supposed to stay same on every link) in each file?
how do they manage it?
| 0debug
|
uint32_t HELPER(lpxbr)(CPUS390XState *env, uint32_t f1, uint32_t f2)
{
CPU_QuadU v1;
CPU_QuadU v2;
v2.ll.upper = env->fregs[f2].ll;
v2.ll.lower = env->fregs[f2 + 2].ll;
v1.q = float128_abs(v2.q);
env->fregs[f1].ll = v1.ll.upper;
env->fregs[f1 + 2].ll = v1.ll.lower;
return set_cc_nz_f128(v1.q);
}
| 1threat
|
How To Deserialize Generic Types with Moshi? : <p>Suppose we have this JSON:</p>
<pre><code>[
{
"__typename": "Car",
"id": "123",
"name": "Toyota Prius",
"numDoors": 4
},
{
"__typename": "Boat",
"id": "4567",
"name": "U.S.S. Constitution",
"propulsion": "SAIL"
}
]
</code></pre>
<p>(there could be many more elements to the list; this just shows two)</p>
<p>I have <code>Car</code> and <code>Boat</code> POJOs that use a <code>Vehicle</code> base class for the common fields:</p>
<pre><code>public abstract class Vehicle {
public final String id;
public final String name;
}
public class Car extends Vehicle {
public final Integer numDoors;
}
public class Boat extends Vehicle {
public final String propulsion;
}
</code></pre>
<p>The result of parsing this JSON should be a <code>List<Vehicle></code>. The problem is that no JSON parser is going to know, out of the box, that <code>__typename</code> is how to distinguish a <code>Boat</code> from a <code>Car</code>.</p>
<p>With Gson, I can create a <code>JsonDeserializer<Vehicle></code> that can examine the <code>__typename</code> field, identify whether this is a <code>Car</code> or <code>Boat</code>, then use <code>deserialize()</code> on the supplied <code>JsonDeserializationContext</code> to parse the particular JSON object into the appropriate type. This works fine.</p>
<p>However, the particular thing that I am building ought to support pluggable JSON parsers, and I thought that I would try Moshi as an alternative parser. However, this particular problem is not covered well in the Moshi documentation at the present time, and I am having difficulty figuring out how best to address it.</p>
<p>The closest analogue to <code>JsonDeserializer<T></code> <a href="http://square.github.io/moshi/1.x/moshi/com/squareup/moshi/JsonAdapter.html" rel="noreferrer">is <code>JsonAdapter<T></code></a>. However, <code>fromJson()</code> gets passed a <code>JsonReader</code>, which has a destructive API. To find out what the <code>__typename</code> is, I would have to be able to parse everything by hand from the <code>JsonReader</code> events. While I could call <a href="http://square.github.io/moshi/1.x/moshi/com/squareup/moshi/Moshi.html#adapter-java.lang.reflect.Type-" rel="noreferrer"><code>adapter()</code> on the <code>Moshi</code> instance</a> to try to invoke existing Moshi parsing logic once I know the proper concrete type, I will have consumed data off of the <code>JsonReader</code> and broken its ability to provide the complete object description anymore.</p>
<p>Another analogue of <code>JsonDeserializer<Vehicle></code> would be a <a href="https://github.com/square/moshi#another-example" rel="noreferrer"><code>@FromJson</code>-annotated method</a> that returns a <code>Vehicle</code>. However, I cannot identify a simple thing to pass into the method. The only thing that I can think of is to create yet another POJO representing the union of all possible fields:</p>
<pre><code>public class SemiParsedKindOfVehicle {
public final String id;
public final String name;
public final Integer numDoors;
public final String propulsion;
public final String __typename;
}
</code></pre>
<p>Then, in theory, if I have <code>@FromJson Vehicle rideLikeTheWind(SemiParsedKindOfVehicle rawVehicle)</code> on a class that I register as a type adapter with <code>Moshi</code>, Moshi might be able to parse my JSON objects into <code>SemiParsedKindOfVehicle</code> instances and call <code>rideLikeTheWind()</code>. In there, I would look up the <code>__typename</code>, identify the type, and completely build the <code>Car</code> or <code>Boat</code> myself, returning that object.</p>
<p>While doable, this is a fair bit more complex than the Gson approach, and my <code>Car</code>/<code>Boat</code> scenario is on the simple end of the possible data structures that I will need to deal with.</p>
<p>Is there another approach to handling this with Moshi that I am missing?</p>
| 0debug
|
static int compat_read(AVFilterContext *ctx, AVFilterBufferRef **pbuf, int nb_samples)
{
AVFilterBufferRef *buf;
AVFrame *frame;
int ret;
if (!pbuf)
return ff_poll_frame(ctx->inputs[0]);
frame = av_frame_alloc();
if (!frame)
return AVERROR(ENOMEM);
if (!nb_samples)
ret = av_buffersink_get_frame(ctx, frame);
else
ret = av_buffersink_get_samples(ctx, frame, nb_samples);
if (ret < 0)
goto fail;
if (ctx->inputs[0]->type == AVMEDIA_TYPE_VIDEO) {
buf = avfilter_get_video_buffer_ref_from_arrays(frame->data, frame->linesize,
AV_PERM_READ,
frame->width, frame->height,
frame->format);
} else {
buf = avfilter_get_audio_buffer_ref_from_arrays(frame->extended_data,
frame->linesize[0], AV_PERM_READ,
frame->nb_samples,
frame->format,
frame->channel_layout);
}
if (!buf) {
ret = AVERROR(ENOMEM);
goto fail;
}
avfilter_copy_frame_props(buf, frame);
buf->buf->priv = frame;
buf->buf->free = compat_free_buffer;
*pbuf = buf;
return 0;
fail:
av_frame_free(&frame);
return ret;
}
| 1threat
|
void ff_put_h264_qpel16_mc21_msa(uint8_t *dst, const uint8_t *src,
ptrdiff_t stride)
{
avc_luma_midv_qrt_16w_msa(src - (2 * stride) - 2,
stride, dst, stride, 16, 0);
}
| 1threat
|
Determining the correct order in which jars should be compiled? : <p>we are given a set of jars, with dependencies over each other. How can we determine the correct ordering in which jars should be compiled?</p>
<p>A->B and C</p>
<p>B-> D and E</p>
<p>D->E and C</p>
<p>E->F</p>
<p>F->C</p>
| 0debug
|
Why does c++ stick to this kind of symbol system? : <p>The system I mean is the one where anything you want to reference has to be prototyped or defined either above your current line or in a referenced header, not sure if this has a name. </p>
<p>I'm cool with headers but sometimes the necessity of forward prototypes forces me into writing really disjointed and hard to manage snippets. </p>
<p>I get why it was a thing once upon a time but is there any reason modern c++ can't bring us the convenience of allowing definitions in any order, anywhere like the plethora of newer managed languages?</p>
| 0debug
|
How to fix this? undefined method `links' for #<Mechanize::Image:0x120a7e38> (NoMethodError) : My spider script is stuck at this error:
mySpiderScript.rb:119:in ` block (3 levels) in <main>': undefined method `links' for #<Mechanize::Image:0x120a7e38> (NoMethodError)
Some code:
page2 = agent2.get('http://www.mywebsite.net')
page2.links.each do |link2| #line 119
name = link2.href.to_s
How do I fix this so that the script keeps running?
| 0debug
|
void qemu_spice_init(void)
{
QemuOpts *opts = QTAILQ_FIRST(&qemu_spice_opts.head);
const char *password, *str, *x509_dir, *addr,
*x509_key_password = NULL,
*x509_dh_file = NULL,
*tls_ciphers = NULL;
char *x509_key_file = NULL,
*x509_cert_file = NULL,
*x509_cacert_file = NULL;
int port, tls_port, len, addr_flags;
spice_image_compression_t compression;
spice_wan_compression_t wan_compr;
qemu_thread_get_self(&me);
if (!opts) {
return;
}
port = qemu_opt_get_number(opts, "port", 0);
tls_port = qemu_opt_get_number(opts, "tls-port", 0);
if (!port && !tls_port) {
fprintf(stderr, "neither port nor tls-port specified for spice.");
exit(1);
}
if (port < 0 || port > 65535) {
fprintf(stderr, "spice port is out of range");
exit(1);
}
if (tls_port < 0 || tls_port > 65535) {
fprintf(stderr, "spice tls-port is out of range");
exit(1);
}
password = qemu_opt_get(opts, "password");
if (tls_port) {
x509_dir = qemu_opt_get(opts, "x509-dir");
if (NULL == x509_dir) {
x509_dir = ".";
}
len = strlen(x509_dir) + 32;
str = qemu_opt_get(opts, "x509-key-file");
if (str) {
x509_key_file = g_strdup(str);
} else {
x509_key_file = g_malloc(len);
snprintf(x509_key_file, len, "%s/%s", x509_dir, X509_SERVER_KEY_FILE);
}
str = qemu_opt_get(opts, "x509-cert-file");
if (str) {
x509_cert_file = g_strdup(str);
} else {
x509_cert_file = g_malloc(len);
snprintf(x509_cert_file, len, "%s/%s", x509_dir, X509_SERVER_CERT_FILE);
}
str = qemu_opt_get(opts, "x509-cacert-file");
if (str) {
x509_cacert_file = g_strdup(str);
} else {
x509_cacert_file = g_malloc(len);
snprintf(x509_cacert_file, len, "%s/%s", x509_dir, X509_CA_CERT_FILE);
}
x509_key_password = qemu_opt_get(opts, "x509-key-password");
x509_dh_file = qemu_opt_get(opts, "x509-dh-file");
tls_ciphers = qemu_opt_get(opts, "tls-ciphers");
}
addr = qemu_opt_get(opts, "addr");
addr_flags = 0;
if (qemu_opt_get_bool(opts, "ipv4", 0)) {
addr_flags |= SPICE_ADDR_FLAG_IPV4_ONLY;
} else if (qemu_opt_get_bool(opts, "ipv6", 0)) {
addr_flags |= SPICE_ADDR_FLAG_IPV6_ONLY;
}
spice_server = spice_server_new();
spice_server_set_addr(spice_server, addr ? addr : "", addr_flags);
if (port) {
spice_server_set_port(spice_server, port);
}
if (tls_port) {
spice_server_set_tls(spice_server, tls_port,
x509_cacert_file,
x509_cert_file,
x509_key_file,
x509_key_password,
x509_dh_file,
tls_ciphers);
}
if (password) {
spice_server_set_ticket(spice_server, password, 0, 0, 0);
}
if (qemu_opt_get_bool(opts, "sasl", 0)) {
#if SPICE_SERVER_VERSION >= 0x000900
if (spice_server_set_sasl_appname(spice_server, "qemu") == -1 ||
spice_server_set_sasl(spice_server, 1) == -1) {
fprintf(stderr, "spice: failed to enable sasl\n");
exit(1);
}
#else
fprintf(stderr, "spice: sasl is not available (spice >= 0.9 required)\n");
exit(1);
#endif
}
if (qemu_opt_get_bool(opts, "disable-ticketing", 0)) {
auth = "none";
spice_server_set_noauth(spice_server);
}
#if SPICE_SERVER_VERSION >= 0x000801
if (qemu_opt_get_bool(opts, "disable-copy-paste", 0)) {
spice_server_set_agent_copypaste(spice_server, false);
}
#endif
compression = SPICE_IMAGE_COMPRESS_AUTO_GLZ;
str = qemu_opt_get(opts, "image-compression");
if (str) {
compression = parse_compression(str);
}
spice_server_set_image_compression(spice_server, compression);
wan_compr = SPICE_WAN_COMPRESSION_AUTO;
str = qemu_opt_get(opts, "jpeg-wan-compression");
if (str) {
wan_compr = parse_wan_compression(str);
}
spice_server_set_jpeg_compression(spice_server, wan_compr);
wan_compr = SPICE_WAN_COMPRESSION_AUTO;
str = qemu_opt_get(opts, "zlib-glz-wan-compression");
if (str) {
wan_compr = parse_wan_compression(str);
}
spice_server_set_zlib_glz_compression(spice_server, wan_compr);
str = qemu_opt_get(opts, "streaming-video");
if (str) {
int streaming_video = parse_stream_video(str);
spice_server_set_streaming_video(spice_server, streaming_video);
}
spice_server_set_agent_mouse
(spice_server, qemu_opt_get_bool(opts, "agent-mouse", 1));
spice_server_set_playback_compression
(spice_server, qemu_opt_get_bool(opts, "playback-compression", 1));
qemu_opt_foreach(opts, add_channel, NULL, 0);
if (0 != spice_server_init(spice_server, &core_interface)) {
fprintf(stderr, "failed to initialize spice server");
exit(1);
};
using_spice = 1;
migration_state.notify = migration_state_notifier;
add_migration_state_change_notifier(&migration_state);
#ifdef SPICE_INTERFACE_MIGRATION
spice_migrate.sin.base.sif = &migrate_interface.base;
spice_migrate.connect_complete.cb = NULL;
qemu_spice_add_interface(&spice_migrate.sin.base);
#endif
qemu_spice_input_init();
qemu_spice_audio_init();
g_free(x509_key_file);
g_free(x509_cert_file);
g_free(x509_cacert_file);
}
| 1threat
|
static void read_storage_element1_info(SCLPDevice *sclp, SCCB *sccb)
{
ReadStorageElementInfo *storage_info = (ReadStorageElementInfo *) sccb;
sclpMemoryHotplugDev *mhd = get_sclp_memory_hotplug_dev();
assert(mhd);
if ((mhd->standby_mem_size >> mhd->increment_size) >= 0x10000) {
sccb->h.response_code = cpu_to_be16(SCLP_RC_SCCB_BOUNDARY_VIOLATION);
return;
}
storage_info->max_id = cpu_to_be16(mhd->standby_mem_size ? 1 : 0);
storage_info->assigned = cpu_to_be16(mhd->standby_mem_size >>
mhd->increment_size);
storage_info->standby = cpu_to_be16(mhd->standby_mem_size >>
mhd->increment_size);
sccb->h.response_code = cpu_to_be16(SCLP_RC_STANDBY_READ_COMPLETION);
}
| 1threat
|
How can I do this? with bootstrap and css : I am trying to add a margin-top to a button in bootstrap but only if its inside the <form> tag and only if it has a class called formbutton, how can I do this? I have looked all over and nothing.
| 0debug
|
C++ Logging or a logger class that will print the log message with a custom prefix : I have a C++ project that has multiple classes. I want to streamline my logging process so that I can create some custom ostream object 'log' so that wherever I want to print a log message, I can write "log << my-message". The catch is that each of my class has a name (stored as a string) and I want the ostream object to prefix the name of the class before the log message. So the output would look like
name-of-class: my-message
How can I do this in C++?
I tried create a Logger class with a name variable, and then instantiating an object of that class in each of my classes, which will then set the class' name as the Logger object's name. But this approach cannot scale because once I concatenate multiple log messages, the name gets printed each time.
I also tried using variadic templates/functions, but then I wasn't able to pass in arguments such as std::hex, std::endl etc.
| 0debug
|
one of our colleagues executed rm -rf /* command to one of our development servers : HELP!!! one of our colleagues executed `rm -rf /*` command to one of our development servers via SSH and most of our development sites were there.
Is there any way to recover or rescue all those files? Please help. this is very very urgent. our head still doesn't know it happened.
| 0debug
|
Fastest way to read new email from gmail : <p>What is the fastest way to read is any new gmail message?
I want to refresh it in about 1 second delay. I'm using GMAIL.</p>
| 0debug
|
void s390x_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
MMUAccessType access_type,
int mmu_idx, uintptr_t retaddr)
{
S390CPU *cpu = S390_CPU(cs);
CPUS390XState *env = &cpu->env;
if (retaddr) {
cpu_restore_state(cs, retaddr);
}
program_interrupt(env, PGM_SPECIFICATION, ILEN_LATER);
}
| 1threat
|
Retrieving xml nodes in c# using linq : i have xml like
<century>
<question>What is silvia</question>
<answer>silvia is artificial intelligence</answer>
<question>What is your name</question>
<answer>my name is RAMESH</answer>
</century>
ihave multiple questions and answers.How to retrieve answer based on question using linq ?
Thanks advance
| 0debug
|
void helper_fcmp_eq_FT(CPUSH4State *env, float32 t0, float32 t1)
{
int relation;
set_float_exception_flags(0, &env->fp_status);
relation = float32_compare(t0, t1, &env->fp_status);
if (unlikely(relation == float_relation_unordered)) {
update_fpscr(env, GETPC());
} else {
env->sr_t = (relation == float_relation_equal);
}
}
| 1threat
|
static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
uint8_t *buf, int buf_size, int64_t wait_end)
{
RTSPState *rt = s->priv_data;
RTSPStream *rtsp_st;
int n, i, ret, timeout_cnt = 0;
struct pollfd *p = rt->p;
int *fds = NULL, fdsnum, fdsidx;
if (!p) {
p = rt->p = av_malloc_array(2 * (rt->nb_rtsp_streams + 1), sizeof(struct pollfd));
if (!p)
return AVERROR(ENOMEM);
if (rt->rtsp_hd) {
p[rt->max_p].fd = ffurl_get_file_handle(rt->rtsp_hd);
p[rt->max_p++].events = POLLIN;
}
for (i = 0; i < rt->nb_rtsp_streams; i++) {
rtsp_st = rt->rtsp_streams[i];
if (rtsp_st->rtp_handle) {
if (ret = ffurl_get_multi_file_handle(rtsp_st->rtp_handle,
&fds, &fdsnum)) {
av_log(s, AV_LOG_ERROR, "Unable to recover rtp ports\n");
return ret;
}
if (fdsnum != 2) {
av_log(s, AV_LOG_ERROR,
"Number of fds %d not supported\n", fdsnum);
return AVERROR_INVALIDDATA;
}
for (fdsidx = 0; fdsidx < fdsnum; fdsidx++) {
p[rt->max_p].fd = fds[fdsidx];
p[rt->max_p++].events = POLLIN;
}
av_free(fds);
}
}
}
for (;;) {
if (ff_check_interrupt(&s->interrupt_callback))
return AVERROR_EXIT;
if (wait_end && wait_end - av_gettime_relative() < 0)
return AVERROR(EAGAIN);
n = poll(p, rt->max_p, POLL_TIMEOUT_MS);
if (n > 0) {
int j = rt->rtsp_hd ? 1 : 0;
timeout_cnt = 0;
for (i = 0; i < rt->nb_rtsp_streams; i++) {
rtsp_st = rt->rtsp_streams[i];
if (rtsp_st->rtp_handle) {
if (p[j].revents & POLLIN || p[j+1].revents & POLLIN) {
ret = ffurl_read(rtsp_st->rtp_handle, buf, buf_size);
if (ret > 0) {
*prtsp_st = rtsp_st;
return ret;
}
}
j+=2;
}
}
#if CONFIG_RTSP_DEMUXER
if (rt->rtsp_hd && p[0].revents & POLLIN) {
return parse_rtsp_message(s);
}
#endif
} else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
return AVERROR(ETIMEDOUT);
} else if (n < 0 && errno != EINTR)
return AVERROR(errno);
}
}
| 1threat
|
Run a background task from a controller action in asp.net core 2 : <p>I am developing a web application with a REST Api using C# with asp.net core 2.0</p>
<p>What I want to achieve is when the client send a request to an endpoint I will run a background task separated from the client request context which will be ended if the task started successfully.</p>
<p>I know there is HostedService but the problem is that the HostedService starts when the server starts, and as far as I know there is no way to start the HostedService manually from a controller.</p>
<p>Here is a simple code that demonstrate the question.</p>
<pre><code>[Authorize(AuthenticationSchemes = "UsersScheme")]
public class UsersController : Controller
{
[HttpPost]
public async Task<JsonResult> StartJob([FromForm] string UserId, [FromServices] IBackgroundJobService backgroundService) {
//check user account
(bool isStarted, string data) result = backgroundService.Start();
return JsonResult(result);
}
}
</code></pre>
| 0debug
|
static uint32_t qpi_mem_readl(void *opaque, target_phys_addr_t addr)
{
CPUState *env;
env = cpu_single_env;
if (!env)
return 0;
return env->eflags & (IF_MASK | IOPL_MASK);
}
| 1threat
|
static int get_blocksize(BlockDriverState *bdrv)
{
uint8_t cmd[10];
uint8_t buf[8];
uint8_t sensebuf[8];
sg_io_hdr_t io_header;
int ret;
memset(cmd, 0, sizeof(cmd));
memset(buf, 0, sizeof(buf));
cmd[0] = READ_CAPACITY_10;
memset(&io_header, 0, sizeof(io_header));
io_header.interface_id = 'S';
io_header.dxfer_direction = SG_DXFER_FROM_DEV;
io_header.dxfer_len = sizeof(buf);
io_header.dxferp = buf;
io_header.cmdp = cmd;
io_header.cmd_len = sizeof(cmd);
io_header.mx_sb_len = sizeof(sensebuf);
io_header.sbp = sensebuf;
io_header.timeout = 6000;
ret = bdrv_ioctl(bdrv, SG_IO, &io_header);
if (ret < 0)
return -1;
return (buf[4] << 24) | (buf[5] << 16) | (buf[6] << 8) | buf[7];
}
| 1threat
|
How to shoot a moving object with hitboxes? IndexError: list index out of range Python 3.5.2 : I'm new to coding and I'm recreating space invaders for a school project. I've ran into a problem trying to get the bullet to hit one of the enemies to add and add score. I get the error "IndexError: list index out of range".
Here's a simplified version of my game that recreates the problem:
import pygame, sys
from pygame.locals import *
import math
pygame.init()
FPS=30
fpsClock = pygame.time.Clock()
screen = pygame.display.set_mode((628, 602),0,32)
FILL=(0,162,232)
BLACK=(0,0,0)
font=pygame.font.Font('freesansbold.ttf',22)
mothership=pygame.image.load('mothership.png').convert()
mothership.set_colorkey(FILL)
bullet=pygame.image.load('bullet.png').convert()
player=pygame.image.load('player.png').convert()
player.set_colorkey(FILL)
def drawbullet(bulletx,bullety):
screen.blit(bullet,(bulletx,bullety))
def drawplayer():
screen.blit(player,(playerx,playery))
def drawmothership(mothershipx,mothershipy):
screen.blit(mothership,(mothershipx,mothershipy))
bulletx=[]
bullety=[]
score=0
mothershipx=-30
mothershipy=200
playerx=84
playery=483
firing=False
while True:
screen.fill(BLACK)
drawplayer()
drawmothership(mothershipx,mothershipy)
mothershipx=mothershipx+7
message=''+str(score)+''
text=font.render(message,True,FILL)
screen.blit(text,(143,59))
if mothershipx>=628:
mothershipx=-30
for l in range(len(bulletx)):
drawbullet(bulletx[l],bullety[l])
bullety[l]=bullety[l]-10
if math.hypot((bulletx[1]-mothershipx),(bullety[1]-mothershipy))<100:
score=score+10
pygame.display.update()
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
keys=pygame.key.get_pressed()
if keys[K_LEFT] and playerx>0:
playerx=playerx-5
if keys[K_RIGHT] and playerx<583:
playerx=playerx+5
if event.type==KEYDOWN:
if event.key==K_SPACE:
firing=True
firinglocationx=playerx+20
bulletx.append(firinglocationx)
bullety.append(483)
fpsClock.tick(FPS)
Any help would be appreciated, thanks.
| 0debug
|
iOS 10 compatibility to iOS 9 apps : <p>I have launched my iOS app written in swift 2.2 and supports iOS 9 and watch OS 2.2 in app store. iOS 10 is going to be released tomorrow. How will the app work on iOS 10 environment if any users upgrade to it till the app updates on iOS 10 support are pushed to app store?</p>
<p>I know swift 3 has syntax level changes in methods and a lot. Could anyone please suggest me what the best solution is ? </p>
| 0debug
|
static int deband_8_coupling_c(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
{
DebandContext *s = ctx->priv;
ThreadData *td = arg;
AVFrame *in = td->in;
AVFrame *out = td->out;
const int start = (s->planeheight[0] * jobnr ) / nb_jobs;
const int end = (s->planeheight[0] * (jobnr+1)) / nb_jobs;
int x, y, p;
for (y = start; y < end; y++) {
const int pos = y * s->planewidth[0];
for (x = 0; x < s->planewidth[p]; x++) {
const int x_pos = s->x_pos[pos + x];
const int y_pos = s->y_pos[pos + x];
int avg[4], cmp[4] = { 0 }, src[4];
for (p = 0; p < s->nb_components; p++) {
const uint8_t *src_ptr = (const uint8_t *)in->data[p];
const int src_linesize = in->linesize[p];
const int thr = s->thr[p];
const int w = s->planewidth[p] - 1;
const int h = s->planeheight[p] - 1;
const int ref0 = src_ptr[av_clip(y + y_pos, 0, h) * src_linesize + av_clip(x + x_pos, 0, w)];
const int ref1 = src_ptr[av_clip(y + -y_pos, 0, h) * src_linesize + av_clip(x + x_pos, 0, w)];
const int ref2 = src_ptr[av_clip(y + -y_pos, 0, h) * src_linesize + av_clip(x + -x_pos, 0, w)];
const int ref3 = src_ptr[av_clip(y + y_pos, 0, h) * src_linesize + av_clip(x + -x_pos, 0, w)];
const int src0 = src_ptr[y * src_linesize + x];
src[p] = src0;
avg[p] = get_avg(ref0, ref1, ref2, ref3);
if (s->blur) {
cmp[p] = FFABS(src0 - avg[p]) < thr;
} else {
cmp[p] = (FFABS(src0 - ref0) < thr) &&
(FFABS(src0 - ref1) < thr) &&
(FFABS(src0 - ref2) < thr) &&
(FFABS(src0 - ref3) < thr);
}
}
for (p = 0; p < s->nb_components; p++)
if (!cmp[p])
break;
if (p == s->nb_components) {
for (p = 0; p < s->nb_components; p++) {
const int dst_linesize = out->linesize[p];
out->data[p][y * dst_linesize + x] = avg[p];
}
} else {
for (p = 0; p < s->nb_components; p++) {
const int dst_linesize = out->linesize[p];
out->data[p][y * dst_linesize + x] = src[p];
}
}
}
}
return 0;
}
| 1threat
|
Hide NavigationBar when scrolling tableView in CollectionView? : <p>I have collectionViewController and collectionViewCell include TableView.CollectionView is horizontal layout.I want hide navigationbar when scroll the tableView. Is there any idea about that.</p>
| 0debug
|
Why this program is giving the output at -25 in spite of variables being unsigned integer : <p>1.The code defines the variables as unsigned integer however the output is shown negative.</p>
<pre><code>#include<stdio.h>
#include<limits.h>
#include<stdint.h>
int main(){
uint32_t a= 25,b=50;
a = a-b;
printf("\n%d\n",a);
return 0;
}
</code></pre>
| 0debug
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.