problem stringlengths 26 131k | labels class label 2 classes |
|---|---|
int ff_dirac_golomb_read_32bit(DiracGolombLUT *lut_ctx, const uint8_t *buf,
int bytes, uint8_t *_dst, int coeffs)
{
int i, b, c_idx = 0;
int32_t *dst = (int32_t *)_dst;
DiracGolombLUT *future[4], *l = &lut_ctx[2*LUT_SIZE + buf[0]];
INIT_RESIDUE(res);
for (b = 1; b <= bytes; b++) {
future[0] = &lut_ctx[buf[b]];
future[1] = future[0] + 1*LUT_SIZE;
future[2] = future[0] + 2*LUT_SIZE;
future[3] = future[0] + 3*LUT_SIZE;
if ((c_idx + 1) > coeffs)
return c_idx;
if (res_bits && l->sign) {
int32_t coeff = 1;
APPEND_RESIDUE(res, l->preamble);
for (i = 0; i < (res_bits >> 1) - 1; i++) {
coeff <<= 1;
coeff |= (res >> (RSIZE_BITS - 2*i - 2)) & 1;
}
dst[c_idx++] = l->sign * (coeff - 1);
}
memcpy(&dst[c_idx], l->ready, LUT_BITS*sizeof(int32_t));
c_idx += l->ready_num;
APPEND_RESIDUE(res, l->leftover);
l = future[l->need_s ? 3 : !res_bits ? 2 : res_bits & 1];
}
return c_idx;
} | 1threat |
PHP Parse error: syntax error, unexpected 'endwhile' (T_ENDWHILE) in /wp-content/themes/awaken/page.php on line 26 : <p>i have error log </p>
<blockquote>
<p>PHP Parse error: syntax error, unexpected 'endwhile' (T_ENDWHILE) in
/wp-content/themes/awaken/page.php
on line 26</p>
</blockquote>
<p>my page.php </p>
<pre><code>get_header(); ?>
<div class="row">
<?php is_rtl() ? $rtl = 'awaken-rtl' : $rtl = ''; ?>
<div class="col-xs-12 col-sm-12 col-md-8 <?php echo $rtl ?>">
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php if ( get_theme_mod( 'display_page_comments', 1 ) ) { // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || '0' != get_comments_number() ) : comments_template(); endif; } ?>
<?php endwhile; // end of the loop. ?>
</main><!-- #main -->
</div><!-- #primary -->
</div><!-- .bootstrap cols -->
<div class="col-xs-12 col-sm-6 col-md-4">
<?php get_sidebar(); ?>
</div><!-- .bootstrap cols -->
</div><!-- .row -->
<?php get_footer(); ?>
</code></pre>
<p>Please help!
i have a 503 error, and think it's a problem</p>
| 0debug |
SQL Granting already existing rights to users / revoking them : <p>I have to answer some questions based on the statements below. Initially, user A is the owner of relation R, and no other user holds privileges on R. The following are executed:</p>
<pre><code>By A: GRANT INSERT ON R TO B WITH GRANT OPTION;
By B: GRANT INSERT ON R TO C WITH GRANT OPTION;
By C: GRANT INSERT ON R TO D WITH GRANT OPTION;
By D: GRANT INSERT ON R TO B WITH GRANT OPTION;
By B: REVOKE INSERT ON R FROM C CASCADE;
</code></pre>
<p>The questions are: What happens when D grants privileges to B, but they already exist? And what users still have the privileges after the last line is executed?</p>
| 0debug |
How can I proof a difficult big o notation? : <p>I can easily understand how to proof a simple big o notation like n<sup>5</sup> + 3n<sup>3</sup> ∈ O(n<sup>5</sup>).</p>
<p>But how can I proof something more complex like 3<sup>n</sup> or 2<sup>n</sup> ∉ O(n<sup>k</sup>)?</p>
| 0debug |
Why does the methods doesn't compile : <p>I have a multi catch exception block with a methods that doesn't compile , there's no inhertance relation between the two classes
I still not able to define the rule behind this error ,this my code :</p>
<pre><code>class MyException extends RuntimeException {
public void log() {
System.out.println("Logging MyException");
}
}
class MyException2 extends RuntimeException {
public void log() {
System.out.println("Logging MyException2");
}
}
public class Test {
public static void main(String[] args) {
try {
throw new MyException();
} catch(MyException | MyException2 ex){
ex.log(); // this doesn't compile !
}
}
}
</code></pre>
| 0debug |
Can a C function modify the value of its input arguments in the calling function? : <p>Can a C function modify the value of its input arguments in the calling function?</p>
<p>Could you provide an example.</p>
| 0debug |
What is the most feasible way to store large array data while being able to access it from a web browser? : <p>I have come across many ways to do this, but, either a third party resource is needed or the solution is not practical to implement.</p>
<p>What I need to store is an immense amount of data (an array with 700 nested arrays and 10 entries in each array). Some methods I've thought of are listed below together with their drawbacks:</p>
<ol>
<li>Using JSON:<br>
It's just a lot of work on the browser. The browser will freeze when I loop through the array.</li>
<li>Using an SQL database
I won't be able to run my webpage in any computer. I will have to install PHP and SQL in every computer I wish to run my webpage in.</li>
<li>Using a C++ program to handle the heavy work
This will only work with chrome, where I can use the file system API.</li>
</ol>
<p>Note: the webpage won't be uploaded to the internet.</p>
<p>What would be best to do in this situation?</p>
| 0debug |
During local development with Kubernetes/minikube, how should I connect to postgres database running on localhost? : <p>I've set up an application stack running on Google Kubernetes Engine + Google Cloud SQL. When developing locally, I would like my application to connect to a postgres database server running <em>outside</em> the cluster to simulate the production environment.</p>
<p>It seems that the way to do this is by defining an external endpoint as described here: <a href="https://stackoverflow.com/questions/43354167/minikube-expose-mysql-running-on-localhost-as-service">Minikube expose MySQL running on localhost as service</a></p>
<p>Unfortunately, I am not able to specify "127.0.0.1" as the Endpoint IP address:</p>
<pre><code>kubectl apply -f kubernetes/local/postgres-service.yaml
service "postgres-db" unchanged
The Endpoints "postgres-db" is invalid: subsets[0].addresses[0].ip:
Invalid value: "127.0.0.1": may not be in the loopback range (127.0.0.0/8)
</code></pre>
<p>So I am forced to bind postgres to my actual machine address.</p>
<p>It seems like there MUST be a way to map a port from my localhost into the local kubernetes cluster, but so far I can't find a way to do it. </p>
<p>Anybody know the trick? Or alternatively, can someone suggest an alternative solution which doesn't involve running postgres inside the cluster?</p>
| 0debug |
int64_t av_gcd(int64_t a, int64_t b)
{
if (b)
return av_gcd(b, a % b);
else
return a;
}
| 1threat |
triangle.java Uses or overrides a deprecated API : Finding area and perimeter of triangle of a triangle using stream in java:
On Compiling the below program shows
Note: triangle.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Please find what error in this program!
import java.io.*;
class triangle
{
double s,h,area,perimeter;
void get()throws IOException
{
System.out.println("Enter value of side of an equilateral triangle");
DataInputStream dis=new DataInputStream(System.in);
s=Double.parseDouble(dis.readLine());
System.out.println("Enter height");
h=Double.parseDouble(dis.readLine());
}
void area()
{
area=0.5*s*h;
}
void perimeter()
{
perimeter=3*s;
}
void display()
{
System.out.println("Area="+area);
System.out.println("Perimeter="+perimeter);
}
public static void main(String args[])throws IOException
{
triangle t=new triangle();
t.get();
t.area();
t.perimeter();
t.display();
}
} | 0debug |
ram_addr_t qemu_ram_addr_from_host(void *ptr)
{
RAMBlock *prev;
RAMBlock **prevp;
RAMBlock *block;
uint8_t *host = ptr;
#ifdef CONFIG_KQEMU
if (kqemu_phys_ram_base) {
return host - kqemu_phys_ram_base;
}
#endif
prev = NULL;
prevp = &ram_blocks;
block = ram_blocks;
while (block && (block->host > host
|| block->host + block->length <= host)) {
if (prev)
prevp = &prev->next;
prev = block;
block = block->next;
}
if (!block) {
fprintf(stderr, "Bad ram pointer %p\n", ptr);
abort();
}
return block->offset + (host - block->host);
}
| 1threat |
static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc,
VncBasicInfo *info,
Error **errp)
{
SocketAddress *addr = NULL;
addr = qio_channel_socket_get_remote_address(ioc, errp);
if (!addr) {
return;
}
vnc_init_basic_info(addr, info, errp);
qapi_free_SocketAddress(addr);
}
| 1threat |
OnClick Listner Not Working : Don't know why when I click on button its not performing any operation.Can't locate any error in onclick listner.It suppose to give me option for choose image from gallery when I click on choose button rather when I click on Choose button it doesnt do any thing also not give any error.
Java code :
package com.vshine.neuron;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.vshine.neuron.testing.R;
import org.w3c.dom.Text;
import java.io.IOException;
public class imageupload extends AppCompatActivity implements View.OnClickListener {
Button btn1 , btn2;
TextView tv;
EditText edt;
ImageView img;
private final static int IMG_REQUEST =1;
private Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imageupload);
btn1 = findViewById(R.id.btnupload);
btn2 = findViewById(R.id.btnchose);
//tv = findViewById(R.id.textview);
edt = findViewById(R.id.edit);
img = findViewById(R.id.imgview);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.btnchose:
break;
}
}
private void selectImage()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,IMG_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==IMG_REQUEST && resultCode==RESULT_OK && data !=null)
{
Uri path = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),path);
img.setImageBitmap(bitmap);
img.setVisibility(View.VISIBLE);
edt.setVisibility(View.VISIBLE);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here Is the XML Code for layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.vshine.neuron.imageupload">
<!--<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="lang and lat"
android:textSize="20dp"
android:id="@+id/textview"/>-->
<ImageView
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="@+id/imgview"
android:visibility="gone"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter a Name"
android:visibility="gone"
android:id="@+id/edit"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upload"
android:id="@+id/btnupload"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose image"
android:id="@+id/btnchose"/>
</LinearLayout>
| 0debug |
static int sdl_init_out (HWVoiceOut *hw, struct audsettings *as)
{
SDLVoiceOut *sdl = (SDLVoiceOut *) hw;
SDLAudioState *s = &glob_sdl;
SDL_AudioSpec req, obt;
int endianness;
int err;
audfmt_e effective_fmt;
struct audsettings obt_as;
req.freq = as->freq;
req.format = aud_to_sdlfmt (as->fmt);
req.channels = as->nchannels;
req.samples = conf.nb_samples;
req.callback = sdl_callback;
req.userdata = sdl;
if (sdl_open (&req, &obt)) {
return -1;
}
err = sdl_to_audfmt(obt.format, &effective_fmt, &endianness);
if (err) {
sdl_close (s);
return -1;
}
obt_as.freq = obt.freq;
obt_as.nchannels = obt.channels;
obt_as.fmt = effective_fmt;
obt_as.endianness = endianness;
audio_pcm_init_info (&hw->info, &obt_as);
hw->samples = obt.samples;
s->initialized = 1;
s->exit = 0;
SDL_PauseAudio (0);
return 0;
}
| 1threat |
window.location.href = 'http://attack.com?user=' + user_input; | 1threat |
Automate mailto process : <p>How can I automate the mailto process, instead of a new compose window pop up in one of the mail clients is it possible to have the email send in the background, thus not having the user to click send.</p>
<p>Overall I want to receive a email from one of the customers that contains there choice "Approved" or "Rejected" and have them simply press on either button and the email be sent automatically and then maybe after they have clicked on the button have it redirect them to a page stating what decision they made etc. </p>
<p>If it's not possible to automatically send a email from there inbox without there permission so to speak as it'll be automated is there a way to capture or get there email along with there choice and have that send to orders@macwearembroideryclothing.com </p>
<p>Approve & Reject button code:</p>
<pre><code><a href="mailto:orders@macwearembroideryclothing.com?subject=Review&body=Rejected" style="background: #222222; border: 15px solid #222222; padding: 0 10px;color: #ffffff; font-family: sans-serif; font-size: 13px; line-height: 1.1; text-align: center; text-decoration: none; display: block; border-radius: 3px; font-weight: bold;" class="button-a">
<a href="mailto:orders@macwearembroideryclothing.com?subject=Review&body=Approved" style="background: #222222; border: 15px solid #222222; padding: 0 10px;color: #ffffff; font-family: sans-serif; font-size: 13px; line-height: 1.1; text-align: center; text-decoration: none; display: block; border-radius: 3px; font-weight: bold;" class="button-a">
</code></pre>
<p>Gmail Client:</p>
<p><a href="https://i.stack.imgur.com/ZLqMo.png" rel="nofollow noreferrer">HTML Email Before button click</a></p>
<p><a href="https://i.stack.imgur.com/N0dYa.png" rel="nofollow noreferrer">After approve button has been pressed </a></p>
| 0debug |
eb deploy does not update the code : <p>I am trying to deploy an application version but <code>eb deploy</code> command fails with: </p>
<blockquote>
<p>ERROR: Update environment operation is complete, but with errors. For
more information, see troubleshooting documentation.</p>
</blockquote>
<p>I checked the logs, made some changes to the code, committed and deployed again and guess what, it failed again. The logs indicate the same error, disregarding my changes. The error occurs in a file in this directory <code>/var/app/ondeck/app/</code>, when I go check, I can see the previous version is there. </p>
<p>I tried deploying using the Elastic Beanstalk dashboard, but somehow the instance is not receiving the new version. Can someone help me with this? Thanks.</p>
| 0debug |
static ssize_t nbd_send_reply(QIOChannel *ioc, NBDReply *reply)
{
uint8_t buf[NBD_REPLY_SIZE];
reply->error = system_errno_to_nbd_errno(reply->error);
TRACE("Sending response to client: { .error = %" PRId32
", handle = %" PRIu64 " }",
reply->error, reply->handle);
stl_be_p(buf, NBD_REPLY_MAGIC);
stl_be_p(buf + 4, reply->error);
stq_be_p(buf + 8, reply->handle);
return write_sync(ioc, buf, sizeof(buf), NULL);
}
| 1threat |
How to binding dropdown in html5 page using jquery? : <p>I need to know the code for binding drop down in HTML5 using Jquery.</p>
| 0debug |
static int local_symlink(FsContext *fs_ctx, const char *oldpath,
const char *newpath, FsCred *credp)
{
int err = -1;
int serrno = 0;
if (fs_ctx->fs_sm == SM_MAPPED) {
int fd;
ssize_t oldpath_size, write_size;
fd = open(rpath(fs_ctx, newpath), O_CREAT|O_EXCL|O_RDWR,
SM_LOCAL_MODE_BITS);
if (fd == -1) {
return fd;
}
oldpath_size = strlen(oldpath) + 1;
do {
write_size = write(fd, (void *)oldpath, oldpath_size);
} while (write_size == -1 && errno == EINTR);
if (write_size != oldpath_size) {
serrno = errno;
close(fd);
err = -1;
goto err_end;
}
close(fd);
credp->fc_mode = credp->fc_mode|S_IFLNK;
err = local_set_xattr(rpath(fs_ctx, newpath), credp);
if (err == -1) {
serrno = errno;
goto err_end;
}
} else if ((fs_ctx->fs_sm == SM_PASSTHROUGH) ||
(fs_ctx->fs_sm == SM_NONE)) {
err = symlink(oldpath, rpath(fs_ctx, newpath));
if (err) {
return err;
}
err = lchown(rpath(fs_ctx, newpath), credp->fc_uid, credp->fc_gid);
if (err == -1) {
if (fs_ctx->fs_sm != SM_NONE) {
serrno = errno;
goto err_end;
} else
err = 0;
}
}
return err;
err_end:
remove(rpath(fs_ctx, newpath));
errno = serrno;
return err;
}
| 1threat |
static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
int parse_extradata)
{
AVCodecContext *const avctx = h->avctx;
H264SliceContext *sl;
int buf_index;
unsigned context_count;
int next_avc;
int nals_needed = 0;
int nal_index;
int idr_cleared=0;
int ret = 0;
h->nal_unit_type= 0;
if(!h->slice_context_count)
h->slice_context_count= 1;
h->max_contexts = h->slice_context_count;
if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
h->current_slice = 0;
if (!h->first_field)
h->cur_pic_ptr = NULL;
ff_h264_reset_sei(h);
if (h->nal_length_size == 4) {
if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
h->is_avc = 0;
}else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
h->is_avc = 1;
if (avctx->active_thread_type & FF_THREAD_FRAME)
nals_needed = get_last_needed_nal(h, buf, buf_size);
{
buf_index = 0;
context_count = 0;
next_avc = h->is_avc ? 0 : buf_size;
nal_index = 0;
for (;;) {
int consumed;
int dst_length;
int bit_length;
const uint8_t *ptr;
int nalsize = 0;
int err;
if (buf_index >= next_avc) {
nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
if (nalsize < 0)
break;
next_avc = buf_index + nalsize;
} else {
buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
if (buf_index >= buf_size)
break;
if (buf_index >= next_avc)
continue;
sl = &h->slice_ctx[context_count];
ptr = ff_h264_decode_nal(h, sl, buf + buf_index, &dst_length,
&consumed, next_avc - buf_index);
if (!ptr || dst_length < 0) {
ret = -1;
goto end;
bit_length = get_bit_length(h, buf, ptr, dst_length,
buf_index + consumed, next_avc);
if (h->avctx->debug & FF_DEBUG_STARTCODE)
av_log(h->avctx, AV_LOG_DEBUG,
"NAL %d/%d at %d/%d length %d\n",
h->nal_unit_type, h->nal_ref_idc, buf_index, buf_size, dst_length);
if (h->is_avc && (nalsize != consumed) && nalsize)
av_log(h->avctx, AV_LOG_DEBUG,
"AVC: Consumed only %d bytes instead of %d\n",
consumed, nalsize);
buf_index += consumed;
nal_index++;
if (avctx->skip_frame >= AVDISCARD_NONREF &&
h->nal_ref_idc == 0 &&
h->nal_unit_type != NAL_SEI)
continue;
again:
if (parse_extradata) {
switch (h->nal_unit_type) {
case NAL_IDR_SLICE:
case NAL_SLICE:
case NAL_DPA:
case NAL_DPB:
case NAL_DPC:
av_log(h->avctx, AV_LOG_WARNING,
"Ignoring NAL %d in global header/extradata\n",
h->nal_unit_type);
case NAL_AUXILIARY_SLICE:
h->nal_unit_type = NAL_FF_IGNORE;
err = 0;
switch (h->nal_unit_type) {
case NAL_IDR_SLICE:
if ((ptr[0] & 0xFC) == 0x98) {
av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
h->next_outputed_poc = INT_MIN;
ret = -1;
goto end;
if (h->nal_unit_type != NAL_IDR_SLICE) {
av_log(h->avctx, AV_LOG_ERROR,
"Invalid mix of idr and non-idr slices\n");
ret = -1;
goto end;
if(!idr_cleared) {
if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
ret = AVERROR_INVALIDDATA;
goto end;
idr(h);
idr_cleared = 1;
h->has_recovery_point = 1;
case NAL_SLICE:
init_get_bits(&sl->gb, ptr, bit_length);
if ( nals_needed >= nal_index
|| (!(avctx->active_thread_type & FF_THREAD_FRAME) && !context_count))
h->au_pps_id = -1;
if ((err = ff_h264_decode_slice_header(h, sl)))
break;
if (h->sei_recovery_frame_cnt >= 0) {
if (h->frame_num != h->sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
h->valid_recovery_point = 1;
if ( h->recovery_frame < 0
|| av_mod_uintp2(h->recovery_frame - h->frame_num, h->sps.log2_max_frame_num) > h->sei_recovery_frame_cnt) {
h->recovery_frame = av_mod_uintp2(h->frame_num + h->sei_recovery_frame_cnt, h->sps.log2_max_frame_num);
if (!h->valid_recovery_point)
h->recovery_frame = h->frame_num;
h->cur_pic_ptr->f->key_frame |=
(h->nal_unit_type == NAL_IDR_SLICE);
if (h->nal_unit_type == NAL_IDR_SLICE ||
h->recovery_frame == h->frame_num) {
h->recovery_frame = -1;
h->cur_pic_ptr->recovered = 1;
if (h->nal_unit_type == NAL_IDR_SLICE)
h->frame_recovered |= FRAME_RECOVERED_IDR;
#if 1
h->cur_pic_ptr->recovered |= h->frame_recovered;
#else
h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
#endif
if (h->current_slice == 1) {
if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
decode_postinit(h, nal_index >= nals_needed);
if (h->avctx->hwaccel &&
(ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
goto end;
#if FF_API_CAP_VDPAU
if (CONFIG_H264_VDPAU_DECODER &&
h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU)
ff_vdpau_h264_picture_start(h);
#endif
if (sl->redundant_pic_count == 0) {
if (avctx->hwaccel) {
ret = avctx->hwaccel->decode_slice(avctx,
&buf[buf_index - consumed],
consumed);
if (ret < 0)
goto end;
#if FF_API_CAP_VDPAU
} else if (CONFIG_H264_VDPAU_DECODER &&
h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU) {
ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
start_code,
sizeof(start_code));
ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
&buf[buf_index - consumed],
consumed);
#endif
context_count++;
break;
case NAL_DPA:
case NAL_DPB:
case NAL_DPC:
avpriv_request_sample(avctx, "data partitioning");
break;
case NAL_SEI:
init_get_bits(&h->gb, ptr, bit_length);
ret = ff_h264_decode_sei(h);
if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
goto end;
break;
case NAL_SPS:
init_get_bits(&h->gb, ptr, bit_length);
if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
break;
if (h->is_avc ? nalsize : 1) {
av_log(h->avctx, AV_LOG_DEBUG,
"SPS decoding failure, trying again with the complete NAL\n");
if (h->is_avc)
av_assert0(next_avc - buf_index + consumed == nalsize);
if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
break;
init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
8*(next_avc - buf_index + consumed - 1));
if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
break;
init_get_bits(&h->gb, ptr, bit_length);
ff_h264_decode_seq_parameter_set(h, 1);
break;
case NAL_PPS:
init_get_bits(&h->gb, ptr, bit_length);
ret = ff_h264_decode_picture_parameter_set(h, bit_length);
if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
goto end;
break;
case NAL_AUD:
case NAL_END_SEQUENCE:
case NAL_END_STREAM:
case NAL_FILLER_DATA:
case NAL_SPS_EXT:
case NAL_AUXILIARY_SLICE:
break;
case NAL_FF_IGNORE:
break;
default:
av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
h->nal_unit_type, bit_length);
if (context_count == h->max_contexts) {
ret = ff_h264_execute_decode_slices(h, context_count);
if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
goto end;
context_count = 0;
if (err < 0 || err == SLICE_SKIPED) {
if (err < 0)
av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
} else if (err == SLICE_SINGLETHREAD) {
if (context_count > 1) {
ret = ff_h264_execute_decode_slices(h, context_count - 1);
if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
goto end;
context_count = 0;
sl = &h->slice_ctx[0];
goto again;
if (context_count) {
ret = ff_h264_execute_decode_slices(h, context_count);
if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
goto end;
ret = 0;
end:
if (h->cur_pic_ptr && !h->droppable) {
ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
h->picture_structure == PICT_BOTTOM_FIELD);
return (ret < 0) ? ret : buf_index; | 1threat |
webkit box orient styling disappears from styling : <p>In my Angular app (I'm on version 4.3.1) I'm adding a CSS ellipsis after multiple lines.<br>
For this, I use the following css code in Sass.</p>
<pre><code>.ellipsis {
-webkit-box-orient: vertical;
display: block;
display: -webkit-box;
-webkit-line-clamp: 2;
overflow: hidden;
text-overflow: ellipsis;
}
</code></pre>
<p>For some reason, the box-orient line simply gets removed from the styling by the transpile, causing the ellipsis to not work. This seems to happen in Angular and Ionic apps.</p>
| 0debug |
a='01101' this has to be converted to ['0','1','1','0','1'] ?? IN PYTHON : <blockquote>
<p>convert a <em>binary string</em> into list in <strong>python</strong><br>
example '10011' is to be converted as <strong>list</strong> ['1','0','0','1','1'] ?</p>
</blockquote>
| 0debug |
void ff_hpeldsp_init_x86(HpelDSPContext *c, int flags)
{
int cpu_flags = av_get_cpu_flags();
if (INLINE_MMX(cpu_flags))
hpeldsp_init_mmx(c, flags, cpu_flags);
if (EXTERNAL_MMXEXT(cpu_flags))
hpeldsp_init_mmxext(c, flags, cpu_flags);
if (EXTERNAL_AMD3DNOW(cpu_flags))
hpeldsp_init_3dnow(c, flags, cpu_flags);
if (EXTERNAL_SSE2(cpu_flags))
hpeldsp_init_sse2(c, flags, cpu_flags);
}
| 1threat |
int av_find_best_stream(AVFormatContext *ic,
enum AVMediaType type,
int wanted_stream_nb,
int related_stream,
AVCodec **decoder_ret,
int flags)
{
int i, nb_streams = ic->nb_streams, stream_number = 0;
int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
unsigned *program = NULL;
AVCodec *decoder = NULL, *best_decoder = NULL;
if (related_stream >= 0 && wanted_stream_nb < 0) {
AVProgram *p = find_program_from_stream(ic, related_stream);
if (p) {
program = p->stream_index;
nb_streams = p->nb_stream_indexes;
}
}
for (i = 0; i < nb_streams; i++) {
AVStream *st = ic->streams[program ? program[i] : i];
AVCodecContext *avctx = st->codec;
if (avctx->codec_type != type)
continue;
if (wanted_stream_nb >= 0 && stream_number++ != wanted_stream_nb)
continue;
if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
continue;
if (decoder_ret) {
decoder = avcodec_find_decoder(st->codec->codec_id);
if (!decoder) {
if (ret < 0)
ret = AVERROR_DECODER_NOT_FOUND;
continue;
}
}
if (best_count >= st->codec_info_nb_frames)
continue;
best_count = st->codec_info_nb_frames;
ret = program ? program[i] : i;
best_decoder = decoder;
if (program && i == nb_streams - 1 && ret < 0) {
program = NULL;
nb_streams = ic->nb_streams;
i = 0;
}
}
if (decoder_ret)
*decoder_ret = best_decoder;
return ret;
}
| 1threat |
START_TEST(qint_from_int64_test)
{
QInt *qi;
const int64_t value = 0x1234567890abcdefLL;
qi = qint_from_int(value);
fail_unless((int64_t) qi->value == value);
QDECREF(qi);
}
| 1threat |
How to bulk insert in SQL using Dapper in C# : <p>I am using C# Dapper with MYSQL. </p>
<p>I have a list of classes that i want to insert into MySQL table. </p>
<p>I used to do it using TVP in MS SQL, how do we do it in MySQL.</p>
| 0debug |
How to fix this issue "no suitable node (scheduling constraints not satisfied on 1 node)" in docker swarm while deploying registry? : <p>I have a docker swarm in a virtual machine with 2 core 4GB ram Centos.</p>
<p>In the swarm when I deploy docker private registry (registry 2.6.4) it shows service status as <strong>pending</strong> forever.
I used
<strong><code>docker service ps <<registry_name>></code></strong></p>
<p>And when i inspect using <strong><code>docker inspect <<task_id>></code></strong> in message I got this
<strong><em>"no suitable node (scheduling constraints not satisfied on 1 node)".</em></strong></p>
<p>I tried service restart and redeployment.</p>
<p>How to fix this?</p>
| 0debug |
I have tried many times and search a lot but I can't solve it.referenced CSS failure?why? : enter code here// a small demo to exercise
var express = require("express");
var app = express();
var bodyparser = require("body-parser");
app.use("/public/", express.static("./public/"));
app.use("/node_modules/",express("./node_modules/"));
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
//app.set
app.engine("html", require("express-art-template"));
app.get("/index", function (request, response) {
response.render("index.html");
});
app.listen(9000, function () {
console.log("server is running!!");
});
I met a problem. The below picture is what problem I met.
[![enter image description here][1]][1]
Here is my index.html
[![enter image description here][2]][2]
Here is my resources folders
[![enter image description here][3]][3]
[1]: https://i.stack.imgur.com/eyWLm.png
[2]: https://i.stack.imgur.com/G0pLT.png
[3]: https://i.stack.imgur.com/3pcfL.png | 0debug |
int socket_listen(SocketAddressLegacy *addr, Error **errp)
{
int fd;
switch (addr->type) {
case SOCKET_ADDRESS_LEGACY_KIND_INET:
fd = inet_listen_saddr(addr->u.inet.data, 0, false, errp);
break;
case SOCKET_ADDRESS_LEGACY_KIND_UNIX:
fd = unix_listen_saddr(addr->u.q_unix.data, false, errp);
break;
case SOCKET_ADDRESS_LEGACY_KIND_FD:
fd = monitor_get_fd(cur_mon, addr->u.fd.data->str, errp);
break;
case SOCKET_ADDRESS_LEGACY_KIND_VSOCK:
fd = vsock_listen_saddr(addr->u.vsock.data, errp);
break;
default:
abort();
}
return fd;
}
| 1threat |
3D scatterplots in Python with hue colormap and legend : <p>I have been searching for 3D plots in python with seaborn and haven't seen any. I would like to 3D plot a dataset that I originally plotted using seaborn pairplot. Can anyone help me with these 2 issues:</p>
<ol>
<li>I am not able to get same color palette as sns pairplot, e.g. how to get the color palette from figure 2 and apply to the points on figure 1?</li>
<li>The legend does not stick to the plot or does not show up as nice on pairplot, e.g. When I do <code>plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=4)</code> I see the following error: anaconda2/lib/python2.7/site-packages/matplotlib/axes/_axes.py:545: UserWarning: No labelled objects found. Use label='...' kwarg on individual plots. warnings.warn("No labelled objects found. "</li>
</ol>
<p>Thanks in advance !
My references: <a href="https://stackoverflow.com/questions/1985856/how-to-make-a-3d-scatter-plot-in-python">How to make a 3D scatter plot in Python?</a>
<a href="https://pythonspot.com/3d-scatterplot/" rel="noreferrer">https://pythonspot.com/3d-scatterplot/</a>
<a href="https://jakevdp.github.io/PythonDataScienceHandbook/04.12-three-dimensional-plotting.html" rel="noreferrer">https://jakevdp.github.io/PythonDataScienceHandbook/04.12-three-dimensional-plotting.html</a></p>
<p>Here's a MWE:</p>
<pre><code>import re, seaborn as sns, numpy as np, pandas as pd, random
from pylab import *
from matplotlib.pyplot import plot, show, draw, figure, cm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
sns.set_style("whitegrid", {'axes.grid' : False})
fig = plt.figure(figsize=(6,6))
ax = Axes3D(fig) # Method 1
# ax = fig.add_subplot(111, projection='3d') # Method 2
x = np.random.uniform(1,20,size=20)
y = np.random.uniform(1,100,size=20)
z = np.random.uniform(1,100,size=20)
ax.scatter(x, y, z, c=x, marker='o')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/Zjfde.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Zjfde.png" alt="3D plot"></a></p>
<pre><code>#Seaborn pair plot
df_3d = pd.DataFrame()
df_3d['x'] = x
df_3d['y'] = y
df_3d['z'] = z
sns.pairplot(df_3d, hue='x')
</code></pre>
<p><a href="https://i.stack.imgur.com/RSv7d.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RSv7d.png" alt="Seaborn pairplot"></a></p>
| 0debug |
Realtime with Rails 3.2 : <p>I need to add realtime notifications to my Rails app (Rails 3.2, Ruby 1.93, Phusion Passenger). I have another app using Rails 5 that uses Action Cable to deal with realtime notifications and now I'm looking for a similar solution that works with Rails 3.2. Any suggestion on how to do it?</p>
<p>Thanks in advance!</p>
| 0debug |
MATLAB: How to loop through each (x,y) pair in MATLAB? : <p>So I want to create a loop in MATLAB where I can retrieve the x,y pairs. </p>
<p>So far, I have two arrays:</p>
<pre><code>x = [x1 x2 x2 x1 x1];
y = [y1 y1 y2 y2 y1];
</code></pre>
<p>I would like to create a for loop where I can retrieve pairs (x1,y1), then (x2, y1), then (x2, y2), (x1, y2), and lastly (x1,y1) once again. </p>
| 0debug |
python string (file1.txt) search from file2.txt : file1.txt contains usernames, i.e.
tony
peter
john
...
file2.txt contains user details, just one line for each user details, i.e.
alice 20160102 1101 abc
john 20120212 1110 zjc9
mary 20140405 0100 few3
peter 20140405 0001 io90
tango 19090114 0011 n4-8
tony 20150405 1001 ewdf
zoe 20000211 0111 jn09
...
I want to get a shortlist of user details from file2.txt by file1.txt user provided, i.e.
john 20120212 1110 zjc9
peter 20140405 0001 io90
tony 20150405 1001 ewdf
How to use python to do this?
Sorry, I'm the newbie for both coding and python.
Thanks a lot! | 0debug |
Pragmatically creating UIView Mask : <p>I have a UIView, which has a user selected number of circles (5) and a gradient color scheme (Top image) That part was easy</p>
<p>The circles are just additional subViews of the master UIView with black borders and the master UIView has a Red border</p>
<p>How can one create the cyan blue mask seen on the bottom image ?
With Code ?</p>
<p>Thanks in advance</p>
<p><a href="https://i.stack.imgur.com/9LjpE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9LjpE.png" alt="enter image description here"></a></p>
| 0debug |
static void ioport_write(void *opaque, target_phys_addr_t addr,
uint64_t val, unsigned size)
{
PCIQXLDevice *d = opaque;
uint32_t io_port = addr;
qxl_async_io async = QXL_SYNC;
uint32_t orig_io_port = io_port;
if (d->guest_bug && !io_port == QXL_IO_RESET) {
return;
if (d->revision <= QXL_REVISION_STABLE_V10 &&
io_port >= QXL_IO_FLUSH_SURFACES_ASYNC) {
qxl_set_guest_bug(d, "unsupported io %d for revision %d\n",
io_port, d->revision);
return;
switch (io_port) {
case QXL_IO_RESET:
case QXL_IO_SET_MODE:
case QXL_IO_MEMSLOT_ADD:
case QXL_IO_MEMSLOT_DEL:
case QXL_IO_CREATE_PRIMARY:
case QXL_IO_UPDATE_IRQ:
case QXL_IO_LOG:
case QXL_IO_MEMSLOT_ADD_ASYNC:
case QXL_IO_CREATE_PRIMARY_ASYNC:
default:
if (d->mode != QXL_MODE_VGA) {
trace_qxl_io_unexpected_vga_mode(d->id,
io_port, io_port_to_string(io_port));
if (io_port >= QXL_IO_UPDATE_AREA_ASYNC &&
io_port < QXL_IO_RANGE_SIZE) {
qxl_send_events(d, QXL_INTERRUPT_IO_CMD);
return;
orig_io_port = io_port;
switch (io_port) {
case QXL_IO_UPDATE_AREA_ASYNC:
io_port = QXL_IO_UPDATE_AREA;
goto async_common;
case QXL_IO_MEMSLOT_ADD_ASYNC:
io_port = QXL_IO_MEMSLOT_ADD;
goto async_common;
case QXL_IO_CREATE_PRIMARY_ASYNC:
io_port = QXL_IO_CREATE_PRIMARY;
goto async_common;
case QXL_IO_DESTROY_PRIMARY_ASYNC:
io_port = QXL_IO_DESTROY_PRIMARY;
goto async_common;
case QXL_IO_DESTROY_SURFACE_ASYNC:
io_port = QXL_IO_DESTROY_SURFACE_WAIT;
goto async_common;
case QXL_IO_DESTROY_ALL_SURFACES_ASYNC:
io_port = QXL_IO_DESTROY_ALL_SURFACES;
goto async_common;
case QXL_IO_FLUSH_SURFACES_ASYNC:
case QXL_IO_MONITORS_CONFIG_ASYNC:
async_common:
async = QXL_ASYNC;
qemu_mutex_lock(&d->async_lock);
if (d->current_async != QXL_UNDEFINED_IO) {
qxl_set_guest_bug(d, "%d async started before last (%d) complete",
io_port, d->current_async);
qemu_mutex_unlock(&d->async_lock);
return;
d->current_async = orig_io_port;
qemu_mutex_unlock(&d->async_lock);
default:
trace_qxl_io_write(d->id, qxl_mode_to_string(d->mode), addr, val, size,
async);
switch (io_port) {
case QXL_IO_UPDATE_AREA:
{
QXLCookie *cookie = NULL;
QXLRect update = d->ram->update_area;
if (d->ram->update_surface > d->ssd.num_surfaces) {
qxl_set_guest_bug(d, "QXL_IO_UPDATE_AREA: invalid surface id %d\n",
d->ram->update_surface);
return;
if (update.left >= update.right || update.top >= update.bottom) {
qxl_set_guest_bug(d,
"QXL_IO_UPDATE_AREA: invalid area (%ux%u)x(%ux%u)\n",
update.left, update.top, update.right, update.bottom);
return;
if (async == QXL_ASYNC) {
cookie = qxl_cookie_new(QXL_COOKIE_TYPE_IO,
QXL_IO_UPDATE_AREA_ASYNC);
cookie->u.area = update;
qxl_spice_update_area(d, d->ram->update_surface,
cookie ? &cookie->u.area : &update,
NULL, 0, 0, async, cookie);
case QXL_IO_NOTIFY_CMD:
qemu_spice_wakeup(&d->ssd);
case QXL_IO_NOTIFY_CURSOR:
qemu_spice_wakeup(&d->ssd);
case QXL_IO_UPDATE_IRQ:
qxl_update_irq(d);
case QXL_IO_NOTIFY_OOM:
if (!SPICE_RING_IS_EMPTY(&d->ram->release_ring)) {
d->oom_running = 1;
qxl_spice_oom(d);
d->oom_running = 0;
case QXL_IO_SET_MODE:
qxl_set_mode(d, val, 0);
case QXL_IO_LOG:
if (d->guestdebug) {
fprintf(stderr, "qxl/guest-%d: %" PRId64 ": %s", d->id,
qemu_get_clock_ns(vm_clock), d->ram->log_buf);
case QXL_IO_RESET:
qxl_hard_reset(d, 0);
case QXL_IO_MEMSLOT_ADD:
if (val >= NUM_MEMSLOTS) {
qxl_set_guest_bug(d, "QXL_IO_MEMSLOT_ADD: val out of range");
if (d->guest_slots[val].active) {
qxl_set_guest_bug(d,
"QXL_IO_MEMSLOT_ADD: memory slot already active");
d->guest_slots[val].slot = d->ram->mem_slot;
qxl_add_memslot(d, val, 0, async);
case QXL_IO_MEMSLOT_DEL:
if (val >= NUM_MEMSLOTS) {
qxl_set_guest_bug(d, "QXL_IO_MEMSLOT_DEL: val out of range");
qxl_del_memslot(d, val);
case QXL_IO_CREATE_PRIMARY:
if (val != 0) {
qxl_set_guest_bug(d, "QXL_IO_CREATE_PRIMARY (async=%d): val != 0",
async);
goto cancel_async;
d->guest_primary.surface = d->ram->create_surface;
qxl_create_guest_primary(d, 0, async);
case QXL_IO_DESTROY_PRIMARY:
if (val != 0) {
qxl_set_guest_bug(d, "QXL_IO_DESTROY_PRIMARY (async=%d): val != 0",
async);
goto cancel_async;
if (!qxl_destroy_primary(d, async)) {
trace_qxl_io_destroy_primary_ignored(d->id,
qxl_mode_to_string(d->mode));
goto cancel_async;
case QXL_IO_DESTROY_SURFACE_WAIT:
if (val >= d->ssd.num_surfaces) {
qxl_set_guest_bug(d, "QXL_IO_DESTROY_SURFACE (async=%d):"
"%" PRIu64 " >= NUM_SURFACES", async, val);
goto cancel_async;
qxl_spice_destroy_surface_wait(d, val, async);
case QXL_IO_FLUSH_RELEASE: {
QXLReleaseRing *ring = &d->ram->release_ring;
if (ring->prod - ring->cons + 1 == ring->num_items) {
fprintf(stderr,
"ERROR: no flush, full release ring [p%d,%dc]\n",
ring->prod, ring->cons);
qxl_push_free_res(d, 1 );
case QXL_IO_FLUSH_SURFACES_ASYNC:
qxl_spice_flush_surfaces_async(d);
case QXL_IO_DESTROY_ALL_SURFACES:
d->mode = QXL_MODE_UNDEFINED;
qxl_spice_destroy_surfaces(d, async);
case QXL_IO_MONITORS_CONFIG_ASYNC:
qxl_spice_monitors_config_async(d, 0);
default:
qxl_set_guest_bug(d, "%s: unexpected ioport=0x%x\n", __func__, io_port);
return;
cancel_async:
if (async) {
qxl_send_events(d, QXL_INTERRUPT_IO_CMD);
qemu_mutex_lock(&d->async_lock);
d->current_async = QXL_UNDEFINED_IO;
qemu_mutex_unlock(&d->async_lock);
| 1threat |
how to create tables with linked coulmns in sql server : i'm trying to create a database for a simple C# application using sql server.
i'm new to this
this is what I had planned
Clients: Client_ID, Client_Name, Client_Status
Employees: Emp_ID, Emp_Name, Emp_Role
Jobs: Job_ID, Job_Date, Client_ID, Employee_ID, Hours_Spent
how do i make the "Client_ID, Employee_ID" columns in table Jobs linked or connected the original ones in the tables Clients and Employees? do I do it from SQL server management or from the c# code?
| 0debug |
Creating a new column with True/False output : To give a situation say we have 2 columns in excel which holds following data. Column TF must be created as a new column.
1 Table
2 A B TF
3 ABC ABC TRUE
4 ABC BAC FALSE
5 #NA ABC #NA
The numbers on the side ranging 1-5 indicates the row number.
When the strings in column A and B match, return true else false. How do I create a new Column, with name "TF" to hold these values. If either A or B does not contain any value, TF should also not have any value.
I want to do this for rows starting from 3 all the way until the end.
Thanks in advance. Really appreciate any help!
| 0debug |
static ram_addr_t ram_block_add(RAMBlock *new_block, Error **errp)
{
RAMBlock *block;
RAMBlock *last_block = NULL;
ram_addr_t old_ram_size, new_ram_size;
old_ram_size = last_ram_offset() >> TARGET_PAGE_BITS;
qemu_mutex_lock_ramlist();
new_block->offset = find_ram_offset(new_block->max_length);
if (!new_block->host) {
if (xen_enabled()) {
xen_ram_alloc(new_block->offset, new_block->max_length,
new_block->mr);
} else {
new_block->host = phys_mem_alloc(new_block->max_length,
&new_block->mr->align);
if (!new_block->host) {
error_setg_errno(errp, errno,
"cannot set up guest memory '%s'",
memory_region_name(new_block->mr));
qemu_mutex_unlock_ramlist();
return -1;
memory_try_enable_merging(new_block->host, new_block->max_length);
QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
last_block = block;
if (block->max_length < new_block->max_length) {
break;
if (block) {
QLIST_INSERT_BEFORE_RCU(block, new_block, next);
} else if (last_block) {
QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
} else {
QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
ram_list.mru_block = NULL;
smp_wmb();
ram_list.version++;
qemu_mutex_unlock_ramlist();
new_ram_size = last_ram_offset() >> TARGET_PAGE_BITS;
int i;
for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
ram_list.dirty_memory[i] =
bitmap_zero_extend(ram_list.dirty_memory[i],
old_ram_size, new_ram_size);
cpu_physical_memory_set_dirty_range(new_block->offset,
new_block->used_length,
DIRTY_CLIENTS_ALL);
if (new_block->host) {
qemu_ram_setup_dump(new_block->host, new_block->max_length);
qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_DONTFORK);
if (kvm_enabled()) {
kvm_setup_guest_memory(new_block->host, new_block->max_length);
return new_block->offset;
| 1threat |
Is it a best practice in Java to declare variables before give them as parameters : <p>Assuming this code :</p>
<pre><code>public static Dataset<Row> getData(SparkSession sparkSession,
StructType schema, String delimiter, String pathToData) {
final Dataset<Row> dataset = sparkSession
.read()
.option("delimiter", "\\t")
.csv(pathToData);
StructType nSchema= newSchema(schema, schema.size(), dataset.columns().length);
...
}
</code></pre>
<p>Is it a best practice to declare variables and make them final before giving them to newSchema method, like this ?</p>
<pre><code>public static Dataset<Row> getData(SparkSession sparkSession,
StructType schema, String delimiter, String pathToData) {
final Dataset<Row> dataset = sparkSession
.read()
.option("delimiter", "\\t")
.csv(pathToData);
final int dataSize = dataset.columns().length;
final int schemaSize = schema.size();
StructType nSchema = newSchema(schema, schemaSize, dataSize);
...
}
</code></pre>
<p>Thank you</p>
| 0debug |
static void tcg_out_qemu_st(TCGContext* s, TCGReg data_reg, TCGReg addr_reg,
TCGMemOpIdx oi)
{
TCGMemOp opc = get_memop(oi);
#ifdef CONFIG_SOFTMMU
unsigned mem_index = get_mmuidx(oi);
tcg_insn_unit *label_ptr;
TCGReg base_reg;
base_reg = tcg_out_tlb_read(s, addr_reg, opc, mem_index, 0);
label_ptr = s->code_ptr + 1;
tcg_out_insn(s, RI, BRC, S390_CC_NE, 0);
tcg_out_qemu_st_direct(s, opc, data_reg, base_reg, TCG_REG_R2, 0);
add_qemu_ldst_label(s, 0, oi, data_reg, addr_reg, s->code_ptr, label_ptr);
#else
TCGReg index_reg;
tcg_target_long disp;
tcg_prepare_user_ldst(s, &addr_reg, &index_reg, &disp);
tcg_out_qemu_st_direct(s, opc, data_reg, addr_reg, index_reg, disp);
#endif
}
| 1threat |
HttpParams is deprecated. What should I do? : <p>I'm trying to make a Login and register on my android app. I'm having trouble with HttpParams. I am following a tutorial on Youtube by Tonikami. I'm just new with Android Studio. This is just the process I know. Your help with be very appreciated. :(</p>
<pre><code>public class ServerRequests {
ProgressDialog progressDialog;
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = "http://mywebsite.com/";
public ServerRequests(Context context) {
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("Processing...");
progressDialog.setMessage("Please wait...");
}
public void storeUserDataInBackground(User user, GetUserCallback userCallBack) {
progressDialog.show();
new StoreUserDataAsyncTask(user, userCallBack).execute();
}
public void fetchUserDataAsyncTask(User user, GetUserCallback userCallBack) {
progressDialog.show();
new fetchUserDataAsyncTask(user, userCallBack).execute();
}
/**
* parameter sent to task upon execution progress published during
* background computation result of the background computation
*/
public class StoreUserDataAsyncTask extends AsyncTask<Void, Void, Void> {
User user;
GetUserCallback userCallBack;
public StoreUserDataAsyncTask(User user, GetUserCallback userCallBack) {
this.user = user;
this.userCallBack = userCallBack;
}
@Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("name", user.name));
dataToSend.add(new BasicNameValuePair("username", user.username));
dataToSend.add(new BasicNameValuePair("password", user.password));
dataToSend.add(new BasicNameValuePair("age", user.age + ""));
HttpParams httpRequestParams = getHttpRequestParams();
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "Register.php");
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private HttpParams getHttpRequestParams() {
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams,
CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams,
CONNECTION_TIMEOUT);
return httpRequestParams;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progressDialog.dismiss();
userCallBack.done(null);
}
}
public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, User> {
User user;
GetUserCallback userCallBack;
public fetchUserDataAsyncTask(User user, GetUserCallback userCallBack) {
this.user = user;
this.userCallBack = userCallBack;
}
@Override
protected User doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("username", user.username));
dataToSend.add(new BasicNameValuePair("password", user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams,
CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams,
CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS
+ "FetchUserData.php");
User returnedUser = null;
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
HttpResponse httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
JSONObject jObject = new JSONObject(result);
if (jObject.length() != 0){
Log.v("happened", "2");
String name = jObject.getString("name");
int age = jObject.getInt("age");
returnedUser = new User(name, age, user.username,
user.password);
}
} catch (Exception e) {
e.printStackTrace();
}
return returnedUser;
}
@Override
protected void onPostExecute(User returnedUser) {
super.onPostExecute(returnedUser);
progressDialog.dismiss();
userCallBack.done(returnedUser);
}
}
</code></pre>
<p>}'</p>
| 0debug |
Get nested JSON values : <p>I send a request to an API and I get this JSON back:</p>
<pre><code>{{
"id": 1,
"name": "LoginTest",
"status": "ready",
"testvalues_count": 2,
"testvalues": [
{
"id": 1,
"name": "Username",
"value": "Test"
},
{
"id": 2,
"name": "Password",
"value": "password1"
}
]
}}
</code></pre>
<p>I can get the value of the <code>name</code> item easily:</p>
<pre><code>var api = new DataApi();
var json = api.GetTestData("LoginTest");
dynamic testData = JsonConvert.DeserializeObject<dynamic>(json);
var name = testData.name;
</code></pre>
<p>But I also need the values of the <code>Username</code> and <code>Password</code> items. How can I do that?</p>
| 0debug |
spring data jpa utf-8 encoding not working : <p>I use <code>spring-data-jpa</code> and <code>mysql</code> database. My tables character set is utf-8. Also I added <code>?useUnicode=yes&amp;characterEncoding=utf8</code> to mysql url in application.properties file. Problem when I pass characters like "ąčęėį" to controller to save it in mysql. In mysql I got ??? marks. But when I use mysql console example <code>update projects_data set data="ąęąčę" where id = 1;</code> every works well.</p>
<p>application.properties:</p>
<pre><code># "root" as username and password.
spring.datasource.url = jdbc:mysql://localhost:3306/gehive?useUnicode=yes&amp;characterEncoding=utf8
spring.datasource.username = gehive
spring.datasource.password = pass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
</code></pre>
<p>tables:</p>
<pre><code>+---------------+--------------------+
| TABLE_NAME | character_set_name |
+---------------+--------------------+
| customer | utf8 |
| projects | utf8 |
| projects_data | utf8 |
+---------------+--------------------+
</code></pre>
| 0debug |
Can I modify container's environment variables without restarting pod using kubernetes : <p>I have a running pod and I want to change one of it's container's environment variable and made it work immediately. Can I achieve that? If I can, how to do that?</p>
| 0debug |
How to use local proxy settings in docker-compose : <p>I am setting up a new server for our Redmine installation, since the old installation was done by hand, which makes it difficult to update everything properly. I decided to go with a Docker image but am having trouble starting the docker container due to an error message. The host is running behind a proxy server, which I think, is causing this problem, as everything else such as wget, curl, etc. is working fine.</p>
<p>Error message:</p>
<pre><code>Pulling redmine (redmine:)...
ERROR: Get https://registry-1.docker.io/v2/: dial tcp 34.206.236.31:443: connect: connection refused
</code></pre>
<p>I searched on Google about using Docker/Docker-Compose with a proxy server in the background and found a few websites where people had the same issue but none of these really helped me with my problem.</p>
<p>I checked with the Docker documentation and found a guide but this does not seem to work for me: <a href="https://docs.docker.com/network/proxy/" rel="noreferrer">https://docs.docker.com/network/proxy/</a></p>
<p>I also found an answered question here on StackOverflow: <a href="https://stackoverflow.com/questions/53477114/using-proxy-on-docker-compose-in-server">Using proxy on docker-compose in server</a> which might be the solution I am after but I am unsure where exactly I have to put the solution. I guess the person means the docker-compose.yml file but I could be wrong.</p>
<p>This is what my docker-compose.yml looks like:</p>
<pre><code>version: '3.1'
services:
redmine:
image: redmine
restart: always
ports:
- 80:3000
environment:
REDMINE_DB_MYSQL: db
REDMINE_DB_PASSWORD: SECRET_PASSWORD
db:
image: mysql:5.7
restart: always
environment:
MYSQL_ROOT_PASSWORD: SECRET_PASSWORD
MYSQL_DATABASE: redmine
</code></pre>
<p>I expect to run the following command without the above error message</p>
<pre><code>docker-compose -f docker-compose.yml up -d
</code></pre>
| 0debug |
How to Identify an annular region of a specific color in an white background image? : [What procedure should be followed to identify the **annular region**(pinkish orange color) having a white background. Also how to **amplify the intensity** values in the annular region to further work on them. ***Click on the link below***][1]
http://i.stack.imgur.com/2wJpd.jpg | 0debug |
Check if value of one array is found in another : <p>I don't know if this type of comparison is possible. I am trying to compare arrays like listed below. </p>
<pre><code>$array = ["User1-2", "User2-2", "User3-2", "User4-2"];
$array2 = ["User1-2:280", "User2-2:280", "User3-2:280", "User4-2:280"];
</code></pre>
<p>result for User1-2 would be 280, and it should be printed as result</p>
| 0debug |
Programmatically bind custom events for dynamic components in VueJS : <p>In my vuejs app I use dynamic component in the following way:</p>
<pre><code><mycomponent>
<component ref="compRef" :is="myComponent" v-bind="myComponentProps"></component>
<div class="my-buttons">
<my-button label="Reset" @click="reset()"/>
</div>
</mycomponent >
</code></pre>
<p><code>myComponent</code> is a prop on the parent component which hold the actual component to inject.
<code>myComponentProps</code> are also prop which holds the porps for the injected instance.</p>
<p>I would like to know how can I also dynamically bind listeners to the component - I have understand that <a href="https://github.com/vuejs/vue/issues/5578" rel="noreferrer">I cannot</a> send an object to v-on with multiple events.</p>
<p>I was thinking about adding it programatically however haven't found any info about how it can be done for Vue custom events (kind for <code>addEventListener</code> equivalent for custom events)</p>
<p>Any tip would be much appreciated! </p>
| 0debug |
def test_distinct(data):
if len(data) == len(set(data)):
return True
else:
return False; | 0debug |
Java and Golang http performance compare : <p>I recently started using golang, and I did a test to compare the performance of java and golang http calls; I was surprised to find that golang is much faster than java, and sometimes it takes almost no time to call another service from one service. I am curious that this is due to the nature of the language or is the java framework doing too much to make it slower?</p>
<p>JAVA environment:</p>
<p>JDK1.8</p>
<p>Springboot2.1.7.RELEASE</p>
<p>Golang environment:</p>
<p>go1.9.3</p>
<h1>JAVA service1(LISTEN 10006 PORT):</h1>
<pre><code> @GetMapping("/hello")
public String hello(String name) {
log.info("in");
String result = restTemplate.getForObject("http://localhost:10007/hello?name=" + name, String.class);
log.info("out");
return result;
}
</code></pre>
<h1>JAVA service2(LISTEN 10007 PORT):</h1>
<pre><code> @GetMapping("/hello")
public String hello(String name) {
log.info("in");
return "Hello " + name;
}
</code></pre>
<h1>Golang service1(LISTEN 10008 PORT):</h1>
<pre><code> func main() {
fmt.Println("start")
http.HandleFunc("/hello", DefaultHandler)
err := http.ListenAndServe(":10008", nil)
if err != nil {
fmt.Errorf("error: %s", err)
}
}
func DefaultHandler(w http.ResponseWriter, r *http.Request) {
name := r.FormValue("name")
fmt.Printf("%s, %s\r\n", time.Now(), "in")
resp, _ := http.Get("http://localhost:10009/hello?name=" + name)
body, _ := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
fmt.Printf("%s, %s\r\n", time.Now(), "out")
w.Write(body)
}
</code></pre>
<h1>Golang service2(LISTEN 10009 PORT):</h1>
<pre><code> func main() {
fmt.Println("start")
http.HandleFunc("/hello", DefaultHandler)
err := http.ListenAndServe(":10009", nil)
if err != nil {
fmt.Errorf("error: %s", err)
}
}
func DefaultHandler(w http.ResponseWriter, r *http.Request) {
fmt.Printf("%s, %s\r\n", time.Now(), "in")
name := r.FormValue("name")
w.Write([]byte("Hello " + name))
}
</code></pre>
<p>I used browser to send request like this:</p>
<p><a href="http://localhost:10006/hello?name=tom" rel="nofollow noreferrer">http://localhost:10006/hello?name=tom</a></p>
<p><a href="http://localhost:10008/hello?name=tom" rel="nofollow noreferrer">http://localhost:10008/hello?name=tom</a></p>
<p>The result is mostly like the following</p>
<p>JAVA service1:</p>
<p>2019-10-21 22:04:46.406 INFO 16936 --- [ XNIO-1 task-12] com.web.test6.controller.TestCtrl : in</p>
<p>2019-10-21 22:04:46.412 INFO 16936 --- [ XNIO-1 task-12] com.web.test6.controller.TestCtrl : out</p>
<p>JAVA service2:</p>
<p>2019-10-21 22:04:46.410 INFO 16200 --- [ XNIO-1 task-6] com.web.test7.controller.TestCtrl : in</p>
<p>Golang service1:</p>
<p>2019-10-21 22:06:36.1888823 +0800 CST m=+1438.272728801, in</p>
<p>2019-10-21 22:06:36.1888823 +0800 CST m=+1438.272728801, out</p>
<p>Golang service2:</p>
<p>2019-10-21 22:06:36.1888823 +0800 CST m=+1436.497480201, in</p>
| 0debug |
static int net_dump_init(VLANState *vlan, const char *device,
const char *name, const char *filename, int len)
{
struct pcap_file_hdr hdr;
DumpState *s;
s = qemu_malloc(sizeof(DumpState));
s->fd = open(filename, O_CREAT | O_WRONLY | O_BINARY, 0644);
if (s->fd < 0) {
qemu_error("-net dump: can't open %s\n", filename);
return -1;
}
s->pcap_caplen = len;
hdr.magic = PCAP_MAGIC;
hdr.version_major = 2;
hdr.version_minor = 4;
hdr.thiszone = 0;
hdr.sigfigs = 0;
hdr.snaplen = s->pcap_caplen;
hdr.linktype = 1;
if (write(s->fd, &hdr, sizeof(hdr)) < sizeof(hdr)) {
qemu_error("-net dump write error: %s\n", strerror(errno));
close(s->fd);
qemu_free(s);
return -1;
}
s->pcap_vc = qemu_new_vlan_client(NET_CLIENT_TYPE_DUMP,
vlan, NULL, device, name, NULL,
dump_receive, NULL, NULL,
net_dump_cleanup, s);
snprintf(s->pcap_vc->info_str, sizeof(s->pcap_vc->info_str),
"dump to %s (len=%d)", filename, len);
return 0;
}
| 1threat |
How to get data in UI using java method : <p>I already have java method written to pull data from database, how do I bring those data in user Interface. How to connect these method to User Interface?</p>
| 0debug |
How can I do it in c # : [How can I do it in c #][1]
[1]: https://i.stack.imgur.com/hjZQe.png
How to set output caching for an application in iis? Programmatically
| 0debug |
Validate cell in excel VBA : I would like to add a word limit validation to the cells within a column. For example, I do not want someone to be able to enter more than 150 words. Is this possible? If so, how is this done?
I have wrote a formula to count the words in the cell and tried to add data validation to the cell, however it does not work correctly. Therefore, I am hoping VBA can help me achieve this.
Please help!
| 0debug |
Why will my addClass not target only current element? : when I add class "Icon" using the if statement, it adds it to the correct h3 but also to any h3's ABOVE the correct one also. Even if the h3 above is 0. Icon will either be 0 or 1.
{ $('#accordion') .append($('<h3>') .html(Agency));
if (Icon == 1) {
$('h3') .addClass('Icon');
}
AccordionChild = $('<div>');
}
AccordionChild.append("<div>") .html(ToolsList);
$('#accordion').append(AccordionChild);
});
}
[enter image description here][1]
[1]: http://i.stack.imgur.com/3gy0r.png | 0debug |
static ssize_t mp_user_getxattr(FsContext *ctx, const char *path,
const char *name, void *value, size_t size)
{
char *buffer;
ssize_t ret;
if (strncmp(name, "user.virtfs.", 12) == 0) {
errno = ENOATTR;
return -1;
}
buffer = rpath(ctx, path);
ret = lgetxattr(buffer, name, value, size);
g_free(buffer);
return ret;
}
| 1threat |
Flutter: Unhandled exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences) : <p>My Flutter application uses the Flutter SharedPreferences plugin and send values to the iOS side with platform.invokeMethod. If I start the application, I have this error:</p>
<pre><code>[VERBOSE-2:dart_error.cc(16)] Unhandled exception:
MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
#0 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:278:7)
<asynchronous suspension>
#1 SharedPreferences.getInstance (package:shared_preferences/shared_preferences.dart:25:27)
<asynchronous suspension>
#2 main (file:///Users/Developer/workspace/flutter-app/q_flutter2/lib/main.dart:25:53)
<asynchronous suspension>
#3 _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:279:19)
#4 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:165:12)
</code></pre>
<p>If I comment the function to send the value to iOS side, the error is not displayed and the SharedPreferences is working.</p>
<p>Someone can help me?</p>
| 0debug |
static void pmac_ide_writel (void *opaque,
target_phys_addr_t addr, uint32_t val)
{
MACIOIDEState *d = opaque;
addr = (addr & 0xFFF) >> 4;
val = bswap32(val);
if (addr == 0) {
ide_data_writel(&d->bus, 0, val);
}
}
| 1threat |
static void ide_dma_restart_cb(void *opaque, int running, int reason)
{
BMDMAState *bm = opaque;
if (!running)
return;
if (bm->status & BM_STATUS_DMA_RETRY) {
bm->status &= ~BM_STATUS_DMA_RETRY;
ide_dma_restart(bm->ide_if);
} else if (bm->status & BM_STATUS_PIO_RETRY) {
bm->status &= ~BM_STATUS_PIO_RETRY;
ide_sector_write(bm->ide_if);
}
}
| 1threat |
void helper_mwait(CPUX86State *env, int next_eip_addend)
{
CPUState *cs;
X86CPU *cpu;
if ((uint32_t)env->regs[R_ECX] != 0) {
raise_exception(env, EXCP0D_GPF);
}
cpu_svm_check_intercept_param(env, SVM_EXIT_MWAIT, 0);
env->eip += next_eip_addend;
cpu = x86_env_get_cpu(env);
cs = CPU(cpu);
if (cs->cpu_index != 0 || CPU_NEXT(cs) != NULL) {
} else {
do_hlt(cpu);
}
}
| 1threat |
Java - returning a BigDecimal from a function? : <p>I was wondering if I can actually return a BigDecimal from a function as I have not seen anything online about this. Is it because it's not possible or is it really just bad practice to do so? Attempting the code below results in "error: cannot find symbol [in MainClass.java]"</p>
<pre><code>public BigDecimal foo(){
return new BigDecimal(10);
}
</code></pre>
| 0debug |
Django E.408, E.409 and E.410 errors on runserver : <p>I am installing a new Django project using virtualenv, all in the normal way. My version of Python is 3.7.3, and django is 2.2.3. </p>
<p>If I do python manage.py runserver, I get the following errors:</p>
<pre><code>?: (admin.E408)'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application.
?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application.
?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application.
</code></pre>
<p>Here is my settings.py, and you can see that those middleware are there. </p>
<pre><code>"""
Django settings for fcc_new project.
Generated by 'django-admin startproject' using Django 1.9.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = MY KEY goes here
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'fcc_new.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'fcc_new.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
</code></pre>
<p>I've tried reinstalling, checking versions, and changing 'MIDDLEWARE_CLASSES' to 'MIDDLEWARE'. Nothing is working. Can anyone identify the problem?</p>
| 0debug |
How to output the highest and lowest values selected after entering 10 numbers between 1 to 100 in C : I am trying to write a C program that can accept 10 numbers between 1 and 100. If values outside the range are entered an error message should be displayed.
I have managed to write the following code to check for the to check if the numbers are between 1 to 100
```
#include <stdio.h>
int main() {
int num1, num2, num3, num4, num5, num6, num7, num8, num9, num10;
printf("\nEnter the first number : ");
scanf("%d", &num1);
printf("\nEnter the second number : ");
scanf("%d", &num2);
printf("\nEnter the third number : ");
scanf("%d", &num3);
printf("\nEnter the fourth number : ");
scanf("%d", &num4);
printf("\nEnter the fifth number : ");
scanf("%d", &num5);
printf("\nEnter the sixth number : ");
scanf("%d", &num6);
printf("\nEnter the seventh number : ");
scanf("%d", &num7);
printf("\nEnter the eighth number : ");
scanf("%d", &num8);
printf("\nEnter the nineth number : ");
scanf("%d", &num9);
printf("\nEnter the tenth number : ");
scanf("%d", &num10);
if ((num1 <= 1 && num2 <= 1 && num3 <= 1 && num4 <= 1 && num5 <= 1 && num6 <= 1 && num7 <= 1 && num8 <= 1 && num9 <= 1 && num10 <= 1) &&
(num1 >= 100 && num2 >= 100 && num3 >= 100 && num4 >= 100 && num5 >= 100 && num6 >= 100 && num7 >= 100 && num8 >= 100 && num9 >= 100 && num10 >= 100)){
printf("good");
printf("Numbers are good");
}else{
printf("All numbers must be between 1 to 100");
}
return (0);
}
```
When i run the code i get this output "All numbers must be between 1 to 100" Even if the numbers i enter are between the range of 1-100. i expect the output to be "Numbers are good". Please help. | 0debug |
static av_cold int vdadec_init(AVCodecContext *avctx)
{
VDADecoderContext *ctx = avctx->priv_data;
struct vda_context *vda_ctx = &ctx->vda_ctx;
OSStatus status;
int ret;
ctx->h264_initialized = 0;
if (!ff_h264_vda_decoder.pix_fmts) {
if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber10_7)
ff_h264_vda_decoder.pix_fmts = vda_pixfmts_prior_10_7;
else
ff_h264_vda_decoder.pix_fmts = vda_pixfmts;
memset(vda_ctx, 0, sizeof(struct vda_context));
vda_ctx->width = avctx->width;
vda_ctx->height = avctx->height;
vda_ctx->format = 'avc1';
vda_ctx->use_sync_decoding = 1;
vda_ctx->use_ref_buffer = 1;
ctx->pix_fmt = avctx->get_format(avctx, avctx->codec->pix_fmts);
switch (ctx->pix_fmt) {
case AV_PIX_FMT_UYVY422:
vda_ctx->cv_pix_fmt_type = '2vuy';
break;
case AV_PIX_FMT_YUYV422:
vda_ctx->cv_pix_fmt_type = 'yuvs';
break;
case AV_PIX_FMT_NV12:
vda_ctx->cv_pix_fmt_type = '420v';
break;
case AV_PIX_FMT_YUV420P:
vda_ctx->cv_pix_fmt_type = 'y420';
break;
default:
av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format: %d\n", avctx->pix_fmt);
status = ff_vda_create_decoder(vda_ctx,
avctx->extradata, avctx->extradata_size);
if (status != kVDADecoderNoErr) {
av_log(avctx, AV_LOG_ERROR,
"Failed to init VDA decoder: %d.\n", status);
set_context(avctx);
ret = ff_h264_decoder.init(avctx);
restore_context(avctx);
if (ret < 0) {
av_log(avctx, AV_LOG_ERROR, "Failed to open H.264 decoder.\n");
ctx->h264_initialized = 1;
return 0;
failed:
vdadec_close(avctx);
return -1; | 1threat |
static int coroutine_fn mirror_dirty_init(MirrorBlockJob *s)
{
int64_t sector_num, end;
BlockDriverState *base = s->base;
BlockDriverState *bs = s->source;
BlockDriverState *target_bs = blk_bs(s->target);
int ret, n;
end = s->bdev_length / BDRV_SECTOR_SIZE;
if (base == NULL && !bdrv_has_zero_init(target_bs)) {
if (!bdrv_can_write_zeroes_with_unmap(target_bs)) {
bdrv_set_dirty_bitmap(s->dirty_bitmap, 0, end);
return 0;
}
s->initial_zeroing_ongoing = true;
for (sector_num = 0; sector_num < end; ) {
int nb_sectors = MIN(end - sector_num,
QEMU_ALIGN_DOWN(INT_MAX, s->granularity) >> BDRV_SECTOR_BITS);
mirror_throttle(s);
if (block_job_is_cancelled(&s->common)) {
s->initial_zeroing_ongoing = false;
return 0;
}
if (s->in_flight >= MAX_IN_FLIGHT) {
trace_mirror_yield(s, s->in_flight, s->buf_free_count, -1);
mirror_wait_for_io(s);
continue;
}
mirror_do_zero_or_discard(s, sector_num, nb_sectors, false);
sector_num += nb_sectors;
}
mirror_wait_for_all_io(s);
s->initial_zeroing_ongoing = false;
}
for (sector_num = 0; sector_num < end; ) {
int nb_sectors = MIN(INT_MAX >> BDRV_SECTOR_BITS,
end - sector_num);
mirror_throttle(s);
if (block_job_is_cancelled(&s->common)) {
return 0;
}
ret = bdrv_is_allocated_above(bs, base, sector_num, nb_sectors, &n);
if (ret < 0) {
return ret;
}
assert(n > 0);
if (ret == 1) {
bdrv_set_dirty_bitmap(s->dirty_bitmap, sector_num, n);
}
sector_num += n;
}
return 0;
}
| 1threat |
How to stop user from opening a website in another tab? : <p>Like it happens in Banking sites....i want to implement the same thing in my website. Please help me how to go about it.</p>
| 0debug |
static int h264_init_context(AVCodecContext *avctx, H264Context *h)
{
int i;
h->avctx = avctx;
h->picture_structure = PICT_FRAME;
h->slice_context_count = 1;
h->workaround_bugs = avctx->workaround_bugs;
h->flags = avctx->flags;
h->prev_poc_msb = 1 << 16;
h->x264_build = -1;
h->recovery_frame = -1;
h->frame_recovered = 0;
h->next_outputed_poc = INT_MIN;
for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
h->last_pocs[i] = INT_MIN;
ff_h264_reset_sei(h);
avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
if (!h->slice_ctx) {
h->nb_slice_ctx = 0;
return AVERROR(ENOMEM);
}
for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
h->DPB[i].f = av_frame_alloc();
if (!h->DPB[i].f)
return AVERROR(ENOMEM);
}
h->cur_pic.f = av_frame_alloc();
if (!h->cur_pic.f)
return AVERROR(ENOMEM);
for (i = 0; i < h->nb_slice_ctx; i++)
h->slice_ctx[i].h264 = h;
return 0;
}
| 1threat |
Resizing images with javascript on a JSF page in a ui:repeat : I need to resize images sitting in JSF's repeat loop.
This is the loop:
<ui:repeat value="#{searchResults.products}" var="product">
<img id="thumbnailId" src='#{product.thumbnailUrl}' class="img-responsive galleryproductimg" style="border: 0px solid blue; margin-top:10px;" />
</ui:repeat>
And my `javascript code`:
<h:outputScript target="head">
$(document).ready(function() {
console.log("ready to go");
var imgs = getElementsById("thumbnailId");
for (var i = 0; i < imgs.length; i++) {
var img = imgs[i];
img.onload = function () {
console.log("image is loaded");
}
resizeImage(img);
}
});
The methods called from this:
function getElementsById(elementID) {
var elementCollection = new Array();
var allElements = document.getElementsByTagName("*");
for(i = 0; i < allElements.length; i++) {
if(allElements[i].id == elementID)
elementCollection.push(allElements[i]);
}
return elementCollection;
}
And
function resizeImage(img) {
console.log("width, height, src " + img.width + ", " + img.height + ", " + img.src);
console.log("loaded? " + img.complete);
var width = img.width;
var height = img.height;
var constant = 100;
var ratio = width / height;
console.log("ratio " + ratio);
if(width > constant || height > constant) {
var newWidth = constant;
var newHeight = constant*ratio;
if(width > height) {
newWidth = constant;
newHeight = constant*ratio;
} else {
newWidth = constant*ratio;
newHeight = constant;
}
console.log("newWidth, newHeight " + newWidth + ", " + newHeight);
//img.width = newWidth;
//img.height = newHeight;
img.style.width = newWidth + "px;";
img.style.height = newHeight + + "px;";
console.log("img from url AFTER " + img.width + ", " + img.height);
}
console.log("==========================");
}
The code seems right, and works for one image. But not inside the repeat. The output I get is this:
ready to go
resizeImages called
width, height, src 84, 110, http://thumbs1.ebaystatic.com/m/mPlrV_wS_b1vK9avUQ22r9w/140.jpg
loaded? true
ratio 0.7636363636363637
newWidth, newHeight 76.36363636363637, 100
img from url AFTER 84, 110
==========================
width, height, src 86, 110, http://thumbs1.ebaystatic.com/m/mIeHLNVqUI1opFM0NmZvH_A/140.jpg
loaded? true
ratio 0.7818181818181819
newWidth, newHeight 78.18181818181819, 100
img from url AFTER 86, 110
==========================
2 image is loaded
So basically I'm not even getting the correct dimensions of the image at the start. For some reason the width is always 110. Any idea what's going on here? | 0debug |
Display issues on website after selecting language : <p><a href="https://www.hollandmarineparts.nl/" rel="nofollow noreferrer">Our website</a> has some display issues after selecting a language. Take <a href="https://www.hollandmarineparts.nl/de/" rel="nofollow noreferrer">This page</a> for example. When we view the page in German, the following becomes clear:</p>
<ul>
<li>The main slider is no longer able to slide</li>
<li>The language selector stops working</li>
<li>The middle section slider is half off the page and no longer able to slide.</li>
</ul>
<p>I suspect a javascript issue after the language selection is made. Yet all files are loaded correctly. We do not know where to start looking for the issue.</p>
<p>I do not expect an immediate solution, but I hope that someone can point us in the right direction.</p>
| 0debug |
static void video_image_display(VideoState *is)
{
Frame *vp;
Frame *sp = NULL;
SDL_Rect rect;
vp = frame_queue_peek_last(&is->pictq);
if (vp->bmp) {
if (is->subtitle_st) {
if (frame_queue_nb_remaining(&is->subpq) > 0) {
sp = frame_queue_peek(&is->subpq);
if (vp->pts >= sp->pts + ((float) sp->sub.start_display_time / 1000)) {
if (!sp->uploaded) {
uint8_t *pixels;
int pitch;
int i;
if (!sp->width || !sp->height) {
sp->width = vp->width;
sp->height = vp->height;
}
if (realloc_texture(&is->sub_texture, SDL_PIXELFORMAT_ARGB8888, sp->width, sp->height, SDL_BLENDMODE_BLEND, 1) < 0)
return;
for (i = 0; i < sp->sub.num_rects; i++) {
AVSubtitleRect *sub_rect = sp->sub.rects[i];
sub_rect->x = av_clip(sub_rect->x, 0, sp->width );
sub_rect->y = av_clip(sub_rect->y, 0, sp->height);
sub_rect->w = av_clip(sub_rect->w, 0, sp->width - sub_rect->x);
sub_rect->h = av_clip(sub_rect->h, 0, sp->height - sub_rect->y);
is->sub_convert_ctx = sws_getCachedContext(is->sub_convert_ctx,
sub_rect->w, sub_rect->h, AV_PIX_FMT_PAL8,
sub_rect->w, sub_rect->h, AV_PIX_FMT_BGRA,
0, NULL, NULL, NULL);
if (!is->sub_convert_ctx) {
av_log(NULL, AV_LOG_FATAL, "Cannot initialize the conversion context\n");
return;
}
if (!SDL_LockTexture(is->sub_texture, (SDL_Rect *)sub_rect, (void **)&pixels, &pitch)) {
sws_scale(is->sub_convert_ctx, (const uint8_t * const *)sub_rect->data, sub_rect->linesize,
0, sub_rect->h, &pixels, &pitch);
SDL_UnlockTexture(is->sub_texture);
}
}
sp->uploaded = 1;
}
} else
sp = NULL;
}
}
calculate_display_rect(&rect, is->xleft, is->ytop, is->width, is->height, vp->width, vp->height, vp->sar);
if (!vp->uploaded) {
if (upload_texture(vp->bmp, vp->frame, &is->img_convert_ctx) < 0)
return;
vp->uploaded = 1;
vp->flip_v = vp->frame->linesize[0] < 0;
}
SDL_RenderCopyEx(renderer, vp->bmp, NULL, &rect, 0, NULL, vp->flip_v ? SDL_FLIP_VERTICAL : 0);
if (sp) {
#if USE_ONEPASS_SUBTITLE_RENDER
SDL_RenderCopy(renderer, is->sub_texture, NULL, &rect);
#else
int i;
double xratio = (double)rect.w / (double)sp->width;
double yratio = (double)rect.h / (double)sp->height;
for (i = 0; i < sp->sub.num_rects; i++) {
SDL_Rect *sub_rect = (SDL_Rect*)sp->sub.rects[i];
SDL_Rect target = {.x = rect.x + sub_rect->x * xratio,
.y = rect.y + sub_rect->y * yratio,
.w = sub_rect->w * xratio,
.h = sub_rect->h * yratio};
SDL_RenderCopy(renderer, is->sub_texture, sub_rect, &target);
}
#endif
}
}
}
| 1threat |
void tcg_context_init(TCGContext *s)
{
int op, total_args, n;
TCGOpDef *def;
TCGArgConstraint *args_ct;
int *sorted_args;
memset(s, 0, sizeof(*s));
s->nb_globals = 0;
total_args = 0;
for(op = 0; op < NB_OPS; op++) {
def = &tcg_op_defs[op];
n = def->nb_iargs + def->nb_oargs;
total_args += n;
}
args_ct = g_malloc(sizeof(TCGArgConstraint) * total_args);
sorted_args = g_malloc(sizeof(int) * total_args);
for(op = 0; op < NB_OPS; op++) {
def = &tcg_op_defs[op];
def->args_ct = args_ct;
def->sorted_args = sorted_args;
n = def->nb_iargs + def->nb_oargs;
sorted_args += n;
args_ct += n;
}
#define GEN_HELPER 2
#include "helper.h"
tcg_target_init(s);
}
| 1threat |
Find no. of occurrence of each character in a string in C#.net ,C,Java etc..? :
**Find no. of occurrence of each character in a string in C#.net?**
*given string to count of each character to find below code I hope it is understand easy way logic *
protected void btnSave_Click(object sender, EventArgs e)
{
var Firstname = txtFname.Text;
var lastName = txtLastName.Text;
var FullName = Firstname + "" + lastName;
char[] charArray = FullName.ToLower().ToCharArray();
Dictionary<char, int> counter = new Dictionary<char, int>();
int tempVar = 0;
foreach (var item in charArray)
{
if (counter.TryGetValue(item, out tempVar))
{
counter[item] += 1;
}
else
{
counter.Add(item, 1);
}
}
//var numberofchars = "";
foreach (KeyValuePair<char, int> item in counter)
{
if (counter.Count > 0)
{
//Label1.Text=split(item.
}
Response.Write(item.Value + " " + item.Key + "<br />");
}
} | 0debug |
how can i filter json listview : //what i want is to show in the list is the String that equals(london) in:
//String location = respons.getString("location");
//if it equlas(manchestar)i dont want it to be in the list
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject respons =jsonArray.getJSONObject(i);
String id = respons.getString("id");
=String location = respons.getString("location");
String info = respons.getString("name");
String img = respons.getString("img");
listitmes.add(new Listitme(id, location, info, img));
listAllItme();
};
| 0debug |
Matplotlib move tick labels inside plot area : <p>Is it possible to put tick labels inside the plotting area? I have already tried:</p>
<pre><code>ax.tick_params(axis="y",pad=-.5, left="off",labelleft="on")
</code></pre>
<p>and </p>
<pre><code>ax.tick_params(axis="y",direction="in", left="off",labelleft="on")
</code></pre>
<p>The former just moves the axis inward, and the latter only moves the ticks not the tick labels.</p>
| 0debug |
GET list of objects located under a specific S3 folder : <p>I am trying to GET a list of objects located under a specific folder in an S3 bucket using a query-string which takes the foldername as the parameter and list all objects which match that specific folder using Node JS aws-sdk</p>
<p>For example: <a href="http://localhost:3000/listobjects?foldername=xxx" rel="noreferrer">http://localhost:3000/listobjects?foldername=xxx</a></p>
<p>Please suggest how to implement this functionality.</p>
| 0debug |
void usb_ohci_init_pxa(target_phys_addr_t base, int num_ports, int devfn,
qemu_irq irq)
{
OHCIState *ohci = (OHCIState *)qemu_mallocz(sizeof(OHCIState));
usb_ohci_init(ohci, num_ports, devfn, irq,
OHCI_TYPE_PXA, "OHCI USB");
ohci->mem_base = base;
cpu_register_physical_memory(ohci->mem_base, 0xfff, ohci->mem);
}
| 1threat |
can someone help to write this code more efficiently please? : As you can see in first picture I'm checking that a certain value contains in a document from firestore and returns a boolean value.
now I'm calling that function in a build and based on that return value I'm changing a chip color(Second picture). Now the problem is maybe because I'm calling it in a build function so its being called continuously and on that build and it costing me aton of reads in firestore or maybe the function is inefficient idk ..... so can anyone help to write the code or give a more efficient way for this please ??
| 0debug |
print_insn (bfd_vma pc, disassemble_info *info)
{
const struct dis386 *dp;
int i;
char *op_txt[MAX_OPERANDS];
int needcomma;
unsigned char uses_DATA_prefix, uses_LOCK_prefix;
unsigned char uses_REPNZ_prefix, uses_REPZ_prefix;
int sizeflag;
const char *p;
struct dis_private priv;
unsigned char op;
unsigned char threebyte;
if (info->mach == bfd_mach_x86_64_intel_syntax
|| info->mach == bfd_mach_x86_64)
address_mode = mode_64bit;
else
address_mode = mode_32bit;
if (intel_syntax == (char) -1)
intel_syntax = (info->mach == bfd_mach_i386_i386_intel_syntax
|| info->mach == bfd_mach_x86_64_intel_syntax);
if (info->mach == bfd_mach_i386_i386
|| info->mach == bfd_mach_x86_64
|| info->mach == bfd_mach_i386_i386_intel_syntax
|| info->mach == bfd_mach_x86_64_intel_syntax)
priv.orig_sizeflag = AFLAG | DFLAG;
else if (info->mach == bfd_mach_i386_i8086)
priv.orig_sizeflag = 0;
else
abort ();
for (p = info->disassembler_options; p != NULL; )
{
if (strncmp (p, "x86-64", 6) == 0)
{
address_mode = mode_64bit;
priv.orig_sizeflag = AFLAG | DFLAG;
}
else if (strncmp (p, "i386", 4) == 0)
{
address_mode = mode_32bit;
priv.orig_sizeflag = AFLAG | DFLAG;
}
else if (strncmp (p, "i8086", 5) == 0)
{
address_mode = mode_16bit;
priv.orig_sizeflag = 0;
}
else if (strncmp (p, "intel", 5) == 0)
{
intel_syntax = 1;
}
else if (strncmp (p, "att", 3) == 0)
{
intel_syntax = 0;
}
else if (strncmp (p, "addr", 4) == 0)
{
if (address_mode == mode_64bit)
{
if (p[4] == '3' && p[5] == '2')
priv.orig_sizeflag &= ~AFLAG;
else if (p[4] == '6' && p[5] == '4')
priv.orig_sizeflag |= AFLAG;
}
else
{
if (p[4] == '1' && p[5] == '6')
priv.orig_sizeflag &= ~AFLAG;
else if (p[4] == '3' && p[5] == '2')
priv.orig_sizeflag |= AFLAG;
}
}
else if (strncmp (p, "data", 4) == 0)
{
if (p[4] == '1' && p[5] == '6')
priv.orig_sizeflag &= ~DFLAG;
else if (p[4] == '3' && p[5] == '2')
priv.orig_sizeflag |= DFLAG;
}
else if (strncmp (p, "suffix", 6) == 0)
priv.orig_sizeflag |= SUFFIX_ALWAYS;
p = strchr (p, ',');
if (p != NULL)
p++;
}
if (intel_syntax)
{
names64 = intel_names64;
names32 = intel_names32;
names16 = intel_names16;
names8 = intel_names8;
names8rex = intel_names8rex;
names_seg = intel_names_seg;
index16 = intel_index16;
open_char = '[';
close_char = ']';
separator_char = '+';
scale_char = '*';
}
else
{
names64 = att_names64;
names32 = att_names32;
names16 = att_names16;
names8 = att_names8;
names8rex = att_names8rex;
names_seg = att_names_seg;
index16 = att_index16;
open_char = '(';
close_char = ')';
separator_char = ',';
scale_char = ',';
}
info->bytes_per_line = 7;
info->private_data = &priv;
priv.max_fetched = priv.the_buffer;
priv.insn_start = pc;
obuf[0] = 0;
for (i = 0; i < MAX_OPERANDS; ++i)
{
op_out[i][0] = 0;
op_index[i] = -1;
}
the_info = info;
start_pc = pc;
start_codep = priv.the_buffer;
codep = priv.the_buffer;
if (sigsetjmp(priv.bailout, 0) != 0)
{
const char *name;
if (codep > priv.the_buffer)
{
name = prefix_name (priv.the_buffer[0], priv.orig_sizeflag);
if (name != NULL)
(*info->fprintf_func) (info->stream, "%s", name);
else
{
(*info->fprintf_func) (info->stream, ".byte 0x%x",
(unsigned int) priv.the_buffer[0]);
}
return 1;
}
return -1;
}
obufp = obuf;
ckprefix ();
ckvexprefix ();
insn_codep = codep;
sizeflag = priv.orig_sizeflag;
fetch_data(info, codep + 1);
two_source_ops = (*codep == 0x62) || (*codep == 0xc8);
if (((prefixes & PREFIX_FWAIT)
&& ((*codep < 0xd8) || (*codep > 0xdf)))
|| (rex && rex_used))
{
const char *name;
name = prefix_name (priv.the_buffer[0], priv.orig_sizeflag);
if (name == NULL)
name = INTERNAL_DISASSEMBLER_ERROR;
(*info->fprintf_func) (info->stream, "%s", name);
return 1;
}
op = 0;
if (prefixes & PREFIX_VEX_0F)
{
used_prefixes |= PREFIX_VEX_0F | PREFIX_VEX_0F38 | PREFIX_VEX_0F3A;
if (prefixes & PREFIX_VEX_0F38)
threebyte = 0x38;
else if (prefixes & PREFIX_VEX_0F3A)
threebyte = 0x3a;
else
threebyte = *codep++;
goto vex_opcode;
}
if (*codep == 0x0f)
{
fetch_data(info, codep + 2);
threebyte = codep[1];
codep += 2;
vex_opcode:
dp = &dis386_twobyte[threebyte];
need_modrm = twobyte_has_modrm[threebyte];
uses_DATA_prefix = twobyte_uses_DATA_prefix[threebyte];
uses_REPNZ_prefix = twobyte_uses_REPNZ_prefix[threebyte];
uses_REPZ_prefix = twobyte_uses_REPZ_prefix[threebyte];
uses_LOCK_prefix = (threebyte & ~0x02) == 0x20;
if (dp->name == NULL && dp->op[0].bytemode == IS_3BYTE_OPCODE)
{
fetch_data(info, codep + 2);
op = *codep++;
switch (threebyte)
{
case 0x38:
uses_DATA_prefix = threebyte_0x38_uses_DATA_prefix[op];
uses_REPNZ_prefix = threebyte_0x38_uses_REPNZ_prefix[op];
uses_REPZ_prefix = threebyte_0x38_uses_REPZ_prefix[op];
break;
case 0x3a:
uses_DATA_prefix = threebyte_0x3a_uses_DATA_prefix[op];
uses_REPNZ_prefix = threebyte_0x3a_uses_REPNZ_prefix[op];
uses_REPZ_prefix = threebyte_0x3a_uses_REPZ_prefix[op];
break;
default:
break;
}
}
}
else
{
dp = &dis386[*codep];
need_modrm = onebyte_has_modrm[*codep];
uses_DATA_prefix = 0;
uses_REPNZ_prefix = 0;
uses_REPZ_prefix = *codep == 0x90;
uses_LOCK_prefix = 0;
codep++;
}
if (!uses_REPZ_prefix && (prefixes & PREFIX_REPZ))
{
oappend ("repz ");
used_prefixes |= PREFIX_REPZ;
}
if (!uses_REPNZ_prefix && (prefixes & PREFIX_REPNZ))
{
oappend ("repnz ");
used_prefixes |= PREFIX_REPNZ;
}
if (!uses_LOCK_prefix && (prefixes & PREFIX_LOCK))
{
oappend ("lock ");
used_prefixes |= PREFIX_LOCK;
}
if (prefixes & PREFIX_ADDR)
{
sizeflag ^= AFLAG;
if (dp->op[2].bytemode != loop_jcxz_mode || intel_syntax)
{
if ((sizeflag & AFLAG) || address_mode == mode_64bit)
oappend ("addr32 ");
else
oappend ("addr16 ");
used_prefixes |= PREFIX_ADDR;
}
}
if (!uses_DATA_prefix && (prefixes & PREFIX_DATA))
{
sizeflag ^= DFLAG;
if (dp->op[2].bytemode == cond_jump_mode
&& dp->op[0].bytemode == v_mode
&& !intel_syntax)
{
if (sizeflag & DFLAG)
oappend ("data32 ");
else
oappend ("data16 ");
used_prefixes |= PREFIX_DATA;
}
}
if (dp->name == NULL && dp->op[0].bytemode == IS_3BYTE_OPCODE)
{
dp = &three_byte_table[dp->op[1].bytemode][op];
modrm.mod = (*codep >> 6) & 3;
modrm.reg = (*codep >> 3) & 7;
modrm.rm = *codep & 7;
}
else if (need_modrm)
{
fetch_data(info, codep + 1);
modrm.mod = (*codep >> 6) & 3;
modrm.reg = (*codep >> 3) & 7;
modrm.rm = *codep & 7;
}
if (dp->name == NULL && dp->op[0].bytemode == FLOATCODE)
{
dofloat (sizeflag);
}
else
{
int index;
if (dp->name == NULL)
{
switch (dp->op[0].bytemode)
{
case USE_GROUPS:
dp = &grps[dp->op[1].bytemode][modrm.reg];
break;
case USE_PREFIX_USER_TABLE:
index = 0;
used_prefixes |= (prefixes & PREFIX_REPZ);
if (prefixes & PREFIX_REPZ)
index = 1;
else
{
used_prefixes |= (prefixes & PREFIX_REPNZ);
if (prefixes & PREFIX_REPNZ)
index = 3;
else
{
used_prefixes |= (prefixes & PREFIX_DATA);
if (prefixes & PREFIX_DATA)
index = 2;
}
}
dp = &prefix_user_table[dp->op[1].bytemode][index];
break;
case X86_64_SPECIAL:
index = address_mode == mode_64bit ? 1 : 0;
dp = &x86_64_table[dp->op[1].bytemode][index];
break;
default:
oappend (INTERNAL_DISASSEMBLER_ERROR);
break;
}
}
if (putop (dp->name, sizeflag) == 0)
{
for (i = 0; i < MAX_OPERANDS; ++i)
{
obufp = op_out[i];
op_ad = MAX_OPERANDS - 1 - i;
if (dp->op[i].rtn)
(*dp->op[i].rtn) (dp->op[i].bytemode, sizeflag);
}
}
}
if ((prefixes & ~used_prefixes) != 0)
{
const char *name;
name = prefix_name (priv.the_buffer[0], priv.orig_sizeflag);
if (name == NULL)
name = INTERNAL_DISASSEMBLER_ERROR;
(*info->fprintf_func) (info->stream, "%s", name);
return 1;
}
if (rex & ~rex_used)
{
const char *name;
name = prefix_name (rex | 0x40, priv.orig_sizeflag);
if (name == NULL)
name = INTERNAL_DISASSEMBLER_ERROR;
(*info->fprintf_func) (info->stream, "%s ", name);
}
obufp = obuf + strlen (obuf);
for (i = strlen (obuf); i < 6; i++)
oappend (" ");
oappend (" ");
(*info->fprintf_func) (info->stream, "%s", obuf);
if (intel_syntax || two_source_ops)
{
bfd_vma riprel;
for (i = 0; i < MAX_OPERANDS; ++i)
op_txt[i] = op_out[i];
for (i = 0; i < (MAX_OPERANDS >> 1); ++i)
{
op_ad = op_index[i];
op_index[i] = op_index[MAX_OPERANDS - 1 - i];
op_index[MAX_OPERANDS - 1 - i] = op_ad;
riprel = op_riprel[i];
op_riprel[i] = op_riprel [MAX_OPERANDS - 1 - i];
op_riprel[MAX_OPERANDS - 1 - i] = riprel;
}
}
else
{
for (i = 0; i < MAX_OPERANDS; ++i)
op_txt[MAX_OPERANDS - 1 - i] = op_out[i];
}
needcomma = 0;
for (i = 0; i < MAX_OPERANDS; ++i)
if (*op_txt[i])
{
if (needcomma)
(*info->fprintf_func) (info->stream, ",");
if (op_index[i] != -1 && !op_riprel[i])
(*info->print_address_func) ((bfd_vma) op_address[op_index[i]], info);
else
(*info->fprintf_func) (info->stream, "%s", op_txt[i]);
needcomma = 1;
}
for (i = 0; i < MAX_OPERANDS; i++)
if (op_index[i] != -1 && op_riprel[i])
{
(*info->fprintf_func) (info->stream, " # ");
(*info->print_address_func) ((bfd_vma) (start_pc + codep - start_codep
+ op_address[op_index[i]]), info);
break;
}
return codep - priv.the_buffer;
}
| 1threat |
static void xics_reset(DeviceState *d)
{
XICSState *icp = XICS(d);
int i;
for (i = 0; i < icp->nr_servers; i++) {
device_reset(DEVICE(&icp->ss[i]));
}
device_reset(DEVICE(icp->ics));
}
| 1threat |
Perl Dereferencing Syntax : <p>What is the syntax to dereference a reference in Perl?</p>
<p>           </p>
<p>           </p>
<p>           </p>
| 0debug |
Moving columns between two tables in mysql : I am working on PHP Codeigniter with MYSQL database, I have two tables Student(Original table) and Student1(temporary table) and both tables have different columns. I am uploading bulk of student list from a CSV file into that Student1(temporary table), later i have to move those student details into Student(Original table). How can i do this? please help me out.
Thanks | 0debug |
No constructor for type SwaggerGenerator can be instantiated using services from the service container and default values : <p>I'm trying to add Swagger to my project. The error received is as follows.</p>
<blockquote>
<p>No constructor for type 'Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator' can be instantiated using services from the service container and default values.</p>
</blockquote>
<p>Since I haven't changed anything in Swagger binaries themselves, just installed the packages <em>Swashbuckle.AspNetCore</em> and <em>Swashbuckle.AspNetCore.Swagger</em> (both in version 4.0.1) I'm assuming that it's about the configuration. Following the suggestion <a href="https://stackoverflow.com/a/48539782/1525840">here</a>, I've set up the config shown below.</p>
<pre><code>services.AddSwaggerGen(_ =>
{
_.SwaggerDoc("v1", new Info { Version = "v1", Title = "My API" });
});
app.UseSwagger();
app.UseSwaggerUI(_ => { _.SwaggerEndpoint("/swagger/v1/swagger.json", "API docs"); });
</code></pre>
<p>I'm not sure if I'm missing a package, if one of those I have is the wrong version or if the set config I'm providing isn't sufficient. </p>
| 0debug |
db.execute('SELECT * FROM employees WHERE id = ' + user_input) | 1threat |
How to find degree on a circle that is tangent to a point outside of that circle? : - I know the (x,y) of a point, P, outside of a circle.
- I know the (x,y) for the origin of a circle, O.
- I know the radius, r, of that circle.
How would I find what degree (i.e. 20 degrees, 270 degrees) is tangent to the point outside of the circle ?
[click here for an image][1]
[1]: https://i.stack.imgur.com/eVbc1.png
Many thanks in advance!
-joe | 0debug |
Fetching the results of a SQL query into a hash map in PERL : <p>I am a beginner to perl. So am just trying out some random perl codes.
I have an sql query which gives me a number of rows, with 2 values in each row.
I want to store this result into a hash say</p>
<pre><code>%result_hash
</code></pre>
<p>in such a way that the first value will be the key and second one will be its value.</p>
<p>I tried it with a while-loop which iterates over each row. Its working fine.
I wanted to know if there is any other simpler way of doing this..</p>
| 0debug |
AVCodecParserContext *av_parser_init(int codec_id)
{
AVCodecParserContext *s = NULL;
AVCodecParser *parser;
int ret;
if(codec_id == AV_CODEC_ID_NONE)
return NULL;
for(parser = av_first_parser; parser != NULL; parser = parser->next) {
if (parser->codec_ids[0] == codec_id ||
parser->codec_ids[1] == codec_id ||
parser->codec_ids[2] == codec_id ||
parser->codec_ids[3] == codec_id ||
parser->codec_ids[4] == codec_id)
goto found;
}
return NULL;
found:
s = av_mallocz(sizeof(AVCodecParserContext));
if (!s)
goto err_out;
s->parser = parser;
s->priv_data = av_mallocz(parser->priv_data_size);
if (!s->priv_data)
goto err_out;
s->fetch_timestamp=1;
s->pict_type = AV_PICTURE_TYPE_I;
if (parser->parser_init) {
if (ff_lock_avcodec(NULL) < 0)
goto err_out;
ret = parser->parser_init(s);
ff_unlock_avcodec();
if (ret != 0)
goto err_out;
}
s->key_frame = -1;
s->convergence_duration = 0;
s->dts_sync_point = INT_MIN;
s->dts_ref_dts_delta = INT_MIN;
s->pts_dts_delta = INT_MIN;
return s;
err_out:
if (s)
av_freep(&s->priv_data);
av_free(s);
return NULL;
}
| 1threat |
How to best get a byte array from a ClientResponse from Spring WebClient? : <p>I'm trying out the new <code>WebClient</code> from Spring 5 (5.0.0.RC2) in a codebase that uses reactive programming and I've had success mapping the JSON response from an endpoint to a DTO in my app, which works very nice:</p>
<pre><code>WebClient client = WebClient.create(baseURI);
Mono<DTO> dto = client.get()
.uri(uri)
.accept(MediaType.APPLICATION_JSON)
.exchange()
.flatMap(response -> response.bodyToMono(DTO.class));
</code></pre>
<p>However, now I'm trying to the response body from an endpoint which uses Protocol Buffers (binary data served as <code>application/octet-stream</code>), so I'd like to get the raw bytes from the response, which I'll then map to an object myself.</p>
<p>I got it to work like this using <code>Bytes</code> from Google Guava:</p>
<pre><code>Mono<byte[]> bytes = client.get()
.uri(uri)
.accept(MediaType.APPLICATION_OCTET_STREAM)
.exchange()
.flatMapMany(response -> response.body(BodyExtractors.toDataBuffers()))
.map(dataBuffer -> {
ByteBuffer byteBuffer = dataBuffer.asByteBuffer();
byte[] byteArray = new byte[byteBuffer.remaining()];
byteBuffer.get(byteArray, 0, bytes.length);
return byteArray;
})
.reduce(Bytes::concat)
</code></pre>
<p>This works, but is there an easier, more elegant way to get these bytes?</p>
| 0debug |
Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type : <p>I am trying to import components from react-materialize as - </p>
<pre><code>import {Navbar, NavItem} from 'react-materialize';
</code></pre>
<p>But when the webpack is compining my <code>.tsx</code> it throws an error for the above as -</p>
<pre><code>ERROR in ./src/common/navbar.tsx
(3,31): error TS7016: Could not find a declaration file for module 'react-materi
alize'. 'D:\Private\Works\Typescript\QuickReact\node_modules\react-materialize\l
ib\index.js' implicitly has an 'any' type.
</code></pre>
<p>Any resolution for this .I'm unsure how to resolve this import statement to work with <code>ts-loader</code> and webpack. </p>
<p>The <code>index.js</code> of react-materialize looks likes this . But how to resolve this for the module import in my own files ..</p>
<p><a href="https://github.com/react-materialize/react-materialize/blob/master/src/index.js" rel="noreferrer">https://github.com/react-materialize/react-materialize/blob/master/src/index.js</a></p>
| 0debug |
Why is dynamic array "constructor" much slower than SetLength and elements initialization? : <p>I was comparing performances between these two ways of initializing a dynamic array:</p>
<pre><code>Arr := TArray<integer>.Create(1, 2, 3, 4, 5);
</code></pre>
<p>and</p>
<pre><code>SetLength(Arr, 5);
Arr[0] := 1;
Arr[1] := 2;
Arr[2] := 3;
Arr[3] := 4;
Arr[4] := 5;
</code></pre>
<p>I've prepared a test and I've noticed that using the array "constructor" takes twice the time required by the other method.</p>
<p><strong>Test:</strong></p>
<pre><code>uses
DateUtils;
function CreateUsingSetLength() : TArray<integer>;
begin
SetLength(Result, 5);
Result[0] := 1;
Result[1] := 2;
Result[2] := 3;
Result[3] := 4;
Result[4] := 5;
end;
</code></pre>
<p>...</p>
<pre><code>const
C_COUNT = 10000000;
var
Start : TDateTime;
i : integer;
Arr : TArray<integer>;
MS1 : integer;
MS2 : integer;
begin
Start := Now;
i := 0;
while(i < C_COUNT) do
begin
Arr := TArray<integer>.Create(1, 2, 3, 4, 5);
Inc(i);
end;
MS1 := MillisecondsBetween(Now, Start);
Start := Now;
i := 0;
while(i < C_COUNT) do
begin
Arr := CreateUsingSetLength();
Inc(i);
end;
MS2 := MillisecondsBetween(Now, Start);
ShowMessage('Constructor = ' + IntToStr(MS1) + sLineBreak + 'Other method = ' + IntToStr(MS2));
</code></pre>
<p>Testing on my machine, the resulting values are always near the following:</p>
<blockquote>
<p>Constructor = 622 </p>
<p>Other method = 288</p>
</blockquote>
<p>Why is the array "constructor" so slow?</p>
| 0debug |
How do I store JWT and send them with every request using react : <p>So happy right know because I got my basic registration/authentication system going on.</p>
<p>so basically I got this :</p>
<pre><code>app.post('/login', function(req,res) {
Users.findOne({
email: req.body.email
}, function(err, user) {
if(err) throw err;
if(!user) {
res.send({success: false, message: 'Authentication Failed, User not found.'});
} else {
//Check passwords
checkingPassword(req.body.password, user.password, function(err, isMatch) {
if(isMatch && !err) {
//Create token
var token = jwt.sign(user,db.secret, {
expiresIn: 1008000
});
res.json({success: true, jwtToken: "JWT "+token});
} else {
res.json({success: false, message: 'Authentication failed, wrong password buddy'});
}
});
}
});
});
</code></pre>
<p>Then I secure my /admin routes and with POSTMAN whenever I send a get request with the jwt in the header everything works perfectly.</p>
<p>Now here is the tricky part, basically When i'm going to login if this a sucess then redirect me to the admin page, and everytime I try to access admin/* routes I want to send to the server my jwToken but the problem is, how do I achieve that ? I'm not using redux/flux, just using react/react-router.</p>
<p>I don't know how the mechanic works.</p>
<p>Thanks guys</p>
| 0debug |
Runtime error: Event loop is running : <p>I get the following error when I call the function <code>send_message</code>.</p>
<pre><code>Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.4/threading.py", line 920, in _bootstrap_inner
self.run()
File "/usr/lib/python3.4/threading.py", line 868, in run
self._target(*self._args, **self._kwargs)
File "/home/joffe/Documents/discord/irc/ircbot.py", line 44, in get_message
mydiscord.send_message(line[1])
File "/home/joffe/Documents/discord/irc/mydiscord.py", line 37, in send_message
client.loop.run_until_complete(client.send_message(SERVER,message))
File "/usr/lib/python3.4/asyncio/base_events.py", line 331, in run_until_complete
self.run_forever()
File "/usr/lib/python3.4/asyncio/base_events.py", line 296, in run_forever
raise RuntimeError('Event loop is running.')
RuntimeError: Event loop is running.
</code></pre>
<p>My function <code>send_message</code> takes a message and sends it to a discord channel.
The function is called from a function that is running in a thread. The client object is created in the main thread.</p>
<pre><code>def send_message(message):
print(str.encode("Message to discord: " + message))
client.loop.run_until_complete(client.send_message(SERVER,message))
</code></pre>
| 0debug |
how to run docker exec on a docker-compose.yml : <p>I am trying to create a mysql database schema during the docker-compose.yml file is getting executed </p>
<pre><code> version: "2"
services:
web:
build: docker
ports:
- "8080:8080"
environment:
- MYSQL_ROOT_PASSWORD=root
mysql:
image: mysql:latest
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=test
ports:
- "3306:3306"
links:
- web
onrun:
command: "docker exec -i test_mysql_1 mysql -uroot -proot test <dummy1.sql"
</code></pre>
<p>I tried onrun but this is not working .
i am building the first image but pulling the second image from the docker hub.
kindly help in how to execute the following command after the docker-compose up </p>
| 0debug |
addSubView SwiftUI View to UIKit UIView in Swift : <p>I have tried to addSubView a SwiftUI View to UIView. <code>self.view.addSubview(contentView)</code></p>
<blockquote>
<p>Error: Cannot convert value of type 'ContentView' to expected argument type
'UIView'</p>
</blockquote>
<p>Kindly help me to implement this UI.</p>
<pre><code>import UIKit
import SwiftUI
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = UIColor.lightGray
let contentView = ContentView()
view.addSubview(contentView) // Error: Cannot convert value of type 'ContentView' to expected argument type 'UIView'
}
}
struct ContentView: View {
var body: some View {
Text("Hello world")
}
}
</code></pre>
| 0debug |
get the coordinates and use them in android : I have successfully managed to get the current gps coordinates by calling requestLocationUpdates like this:
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
if( provider != null){
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
And my "onLocationChanged" is updating this position according to my criterias.
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "location is" + location);
double lat = (location.getLatitude());
double lng = (location.getLongitude());
String coordinates = (String.valueOf(lat) + "," + String.valueOf(lng));
longitudeField.setText(coordinates);
}
Now in my app I want to pass the latitude and longitude to firebase together with an image and some other information.
So I have another method that is taking the url from captured image and sending the image to firebase together with two strings that are the current date and time.
private void uploadFile() {
final String dateStamp = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
final String timeStamp = new SimpleDateFormat("HH:mm:ss").format(new Date());
if (mImageUri != null) {
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_LONG).show();
Upload upload = new Upload(
taskSnapshot.getDownloadUrl().toString(), timeStamp, dateStamp);
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(dateStamp).child(uploadId).setValue(upload);
}
})
**QUESTION:**
*How is the approach to getting the latitude and longitude in form of String so I can use it in my method for passing data to firebase?*
| 0debug |
passing an object to a function in a the same class to initialize the values, but not by reference : <p>I'm looking for some clarification and confirmation that this is indeed doing nothing.</p>
<p>Say I have an object</p>
<pre><code>public class Person
{
public string Name { get; set; }
}
</code></pre>
<p>and I am going to use this object and for some reason it has to be initialized, which should happen in the constructor but for this example its going to happen in a call to an initialize function</p>
<pre><code>public class myClass
{
private void doingSomething()
{
Person p = new Person();
Initialize(p);
}
private void Initialize(Person person)
{
person.Name = "";
}
}
</code></pre>
<p>This is just a waste correct. If I really wanted to change the values doesn't it have to be passed using ref, out, or returning a different Person?</p>
<p>If I'm wrong i'd appreciate an explanation. I found this while looking through some old code and feel confused because I can't believe it's there.</p>
| 0debug |
Why is my java lambda with a dummy assignment much faster than without it? : <p>I know that making judgements of Java microbenchmarks is extremely fraught, but I'm seeing something that seems odd, and I'd like to get some explanation for it.</p>
<p>Note that I'm not using the <a href="http://openjdk.java.net/projects/code-tools/jmh/" title="JMH">JMH</a> framework for this. I'm aware of it, but I didn't want to go to that length for this.</p>
<p>I'll provide the entire code sample, but in short, when I test the performance of these two methods</p>
<pre><code>private FooPrime[] testStreamToArray(ArrayList<Foo> fooList) {
return (FooPrime[]) fooList.stream().
map(it -> {
return new FooPrime().gamma(it.getAlpha() + it.getBeta());
}).
toArray(FooPrime[]::new);
}
private FooPrime[] testStreamToArray2(ArrayList<Foo> fooList) {
return (FooPrime[]) fooList.stream().
map(it -> {
int stuff = it.getAlpha().length();
return new FooPrime().gamma(it.getAlpha() + it.getBeta());
}).
toArray(FooPrime[]::new);
}
</code></pre>
<p>I find very surprising results. In the larger code sample, I'm measuring four different ways of doing this, and the first three are very close in performance. They all run about 50k ns per iteration. However, the second code sample consistently runs just under half of that total. That's right. It's not slower, it's quite a bit faster.</p>
<p>The last run shows numbers like this:</p>
<pre><code>manualcopy:54575 ns
toarray:53617 ns
streamtoarray:52990 ns
streamtoarray2:24217 ns
</code></pre>
<p>Each run has numbers similar to these.</p>
<p>I'll now provide the entire class and base class. Note that I do have a "warm-up" pass, where I execute the methods under test a few thousand times before starting the timings. Also note that although this runs "testStreamToArray2" last, I also tried moving that block to the first test, and the numbers come out about the same. The commented out lines are there to convince me that the methods are actually doing something (the timings are still about the same with those lines not commented out).</p>
<pre><code>package timings;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ListToArrayOfPrimesTiming {
public static void main(String[] args) {
ListToArrayOfPrimesTiming tests = new ListToArrayOfPrimesTiming(args);
tests.go();
}
public ListToArrayOfPrimesTiming(String[] args) { }
private void go() {
final ArrayList<Foo> fooList = new ArrayList<>();
for (int ctr = 0; ctr < 1000; ++ ctr) {
fooList.add(new Foo().alpha("a" + ctr).beta("b" + ctr));
}
for (int ctr = 0; ctr < 20000; ++ ctr) {
testManualCopy(fooList);
testToArray(fooList);
testStreamToArray(fooList);
testStreamToArray2(fooList);
}
int iters = 100000;
// Set<Integer> lengths = new HashSet<>();
// Set<FooPrime> distinctFooPrimes = new HashSet<>();
// lengths.clear();
// distinctFooPrimes.clear();
new TimingContainer(iters, "manualcopy", new TimingTest() {
@Override
public void run() {
FooPrime[] fooPrimeArray = testManualCopy(fooList);
// lengths.add(fooPrimeArray.length);
// distinctFooPrimes.add(fooPrimeArray[0]);
}
}).run();
// System.out.println("lengths[" + lengths + "]");
// lengths.clear();
// System.out.println("distinctFooPrimes[" + distinctFooPrimes + "]");
// distinctFooPrimes.clear();
new TimingContainer(iters, "toarray", new TimingTest() {
@Override
public void run() {
FooPrime[] fooPrimeArray = testManualCopy(fooList);
// lengths.add(fooPrimeArray.length);
// distinctFooPrimes.add(fooPrimeArray[0]);
}
}).run();
// System.out.println("lengths[" + lengths + "]");
// lengths.clear();
// System.out.println("distinctFooPrimes[" + distinctFooPrimes + "]");
// distinctFooPrimes.clear();
new TimingContainer(iters, "streamtoarray", new TimingTest() {
@Override
public void run() {
FooPrime[] fooPrimeArray = testStreamToArray(fooList);
// lengths.add(fooPrimeArray.length);
// distinctFooPrimes.add(fooPrimeArray[0]);
}
}).run();
// System.out.println("lengths[" + lengths + "]");
// lengths.clear();
// System.out.println("distinctFooPrimes[" + distinctFooPrimes + "]");
// distinctFooPrimes.clear();
new TimingContainer(iters, "streamtoarray2", new TimingTest() {
@Override
public void run() {
FooPrime[] fooPrimeArray = testStreamToArray2(fooList);
// lengths.add(fooPrimeArray.length);
// distinctFooPrimes.add(fooPrimeArray[0]);
}
}).run();
// System.out.println("lengths[" + lengths + "]");
// lengths.clear();
// System.out.println("distinctFooPrimes[" + distinctFooPrimes + "]");
// distinctFooPrimes.clear();
}
private FooPrime[] testManualCopy(ArrayList<Foo> fooList) {
FooPrime[] fooPrimeArray = new FooPrime[fooList.size()];
int index = -1;
for (Foo foo: fooList) {
++ index;
fooPrimeArray[index] = new FooPrime().gamma(foo.getAlpha() + foo.getBeta());
}
return fooPrimeArray;
}
private FooPrime[] testToArray(ArrayList<Foo> fooList) {
List<FooPrime> fooPrimeList = new ArrayList<>();
for (Foo foo: fooList) {
fooPrimeList.add(new FooPrime().gamma(foo.getAlpha() + foo.getBeta()));
}
return fooPrimeList.toArray(new FooPrime[fooList.size()]);
}
private FooPrime[] testStreamToArray(ArrayList<Foo> fooList) {
return (FooPrime[]) fooList.stream().
map(it -> {
return new FooPrime().gamma(it.getAlpha() + it.getBeta());
}).
toArray(FooPrime[]::new);
}
private FooPrime[] testStreamToArray2(ArrayList<Foo> fooList) {
return (FooPrime[]) fooList.stream().
map(it -> {
int stuff = it.getAlpha().length();
return new FooPrime().gamma(it.getAlpha() + it.getBeta());
}).
toArray(FooPrime[]::new);
}
public static FooPrime fooToFooPrime(Foo foo) {
return new FooPrime().gamma(foo.getAlpha() + foo.getBeta());
}
public static class Foo {
private String alpha;
private String beta;
public String getAlpha() { return alpha; }
public String getBeta() { return beta; }
public void setAlpha(String alpha) { this.alpha = alpha; }
public void setBeta(String beta) { this.beta = beta; }
public Foo alpha(String alpha) { this.alpha = alpha; return this; }
public Foo beta(String beta) { this.beta = beta; return this; }
}
public static class FooPrime {
private String gamma;
public String getGamma() { return gamma; }
public void setGamma(String gamma) { this.gamma = gamma; }
public FooPrime gamma(String gamma) { this.gamma = gamma; return this; }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((gamma == null) ? 0 : gamma.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FooPrime other = (FooPrime) obj;
if (gamma == null) {
if (other.gamma != null)
return false;
} else if (!gamma.equals(other.gamma))
return false;
return true;
}
@Override
public String toString() {
return "FooPrime [gamma=" + gamma + "]";
}
}
}
</code></pre>
<p>And the base class:</p>
<pre><code>package timings;
public class TimingContainer {
private int iterations;
private String label;
private TimingTest timingTest;
public TimingContainer(int iterations, String label, TimingTest timingTest) {
this.iterations = iterations;
this.label = label;
this.timingTest = timingTest;
}
public void run() {
long startTime = System.nanoTime();
for (int ctr = 0; ctr < iterations; ++ ctr) {
timingTest.randomize();
timingTest.run();
}
long endTime = System.nanoTime();
long totalns = (endTime - startTime);
System.out.println(label + ":" + (totalns / iterations) + " ns");
}
}
</code></pre>
| 0debug |
How to set jacoco code coverage levels to module in gradle : <p>I'm using gradle 4.3.1 with the jacoco plugin and I am able to ensure a certain level of code coverage in a a multi module project. This works great when I set the <strong>element</strong> to <strong>CLASS</strong> or <strong>PACAKAGE</strong>, but I'm stumped on how to get it work for the module. </p>
<p>Looking <a href="http://www.jacoco.org/jacoco/trunk/doc/api/org/jacoco/core/analysis/ICoverageNode.ElementType.html" rel="noreferrer">here</a> I think what I want is <strong>BUNDLE</strong> or <strong>GROUP</strong>, but then jacoco does not break when I go under the coverage amount.</p>
<p>Here is an example of what I have that does work for package level coverage enforcement :</p>
<pre><code>jacocoTestCoverageVerification {
violationRules {
rule {
// should be element = 'BUNDLE' or 'GROUP'?
element = 'PACKAGE'
limit {
minimum = 0.9
}
includes = ['com.mypackage.*']
}
}
}
</code></pre>
<p>When I change the element value to BUNDLE the build does not fail regardless of coverage. Again I'd like to be able to control the expectation at the module level.</p>
<p>Here is my gradle version information:</p>
<pre><code>------------------------------------------------------------
Gradle 4.3.1
------------------------------------------------------------
Build time: 2017-11-08 08:59:45 UTC
Revision: e4f4804807ef7c2829da51877861ff06e07e006d
Groovy: 2.4.12
Ant: Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM: 1.8.0_40 (Oracle Corporation 25.40-b25)
OS: Windows 8.1 6.3 amd64
</code></pre>
<p>I'm guessing I'm missing something pretty simple, since I don't think I'm the first to try to do this. Any help would be appreciated!</p>
| 0debug |
static void setup_rt_frame(int sig, struct target_sigaction *ka,
target_siginfo_t *info,
target_sigset_t *set, CPUS390XState *env)
{
int i;
rt_sigframe *frame;
abi_ulong frame_addr;
frame_addr = get_sigframe(ka, env, sizeof *frame);
qemu_log("%s: frame_addr 0x%llx\n", __FUNCTION__,
(unsigned long long)frame_addr);
if (!lock_user_struct(VERIFY_WRITE, frame, frame_addr, 0)) {
goto give_sigsegv;
}
qemu_log("%s: 1\n", __FUNCTION__);
if (copy_siginfo_to_user(&frame->info, info)) {
goto give_sigsegv;
}
__put_user(0, &frame->uc.tuc_flags);
__put_user((abi_ulong)0, (abi_ulong *)&frame->uc.tuc_link);
__put_user(target_sigaltstack_used.ss_sp, &frame->uc.tuc_stack.ss_sp);
__put_user(sas_ss_flags(get_sp_from_cpustate(env)),
&frame->uc.tuc_stack.ss_flags);
__put_user(target_sigaltstack_used.ss_size, &frame->uc.tuc_stack.ss_size);
save_sigregs(env, &frame->uc.tuc_mcontext);
for (i = 0; i < TARGET_NSIG_WORDS; i++) {
__put_user((abi_ulong)set->sig[i],
(abi_ulong *)&frame->uc.tuc_sigmask.sig[i]);
}
if (ka->sa_flags & TARGET_SA_RESTORER) {
env->regs[14] = (unsigned long) ka->sa_restorer | PSW_ADDR_AMODE;
} else {
env->regs[14] = (unsigned long) frame->retcode | PSW_ADDR_AMODE;
if (__put_user(S390_SYSCALL_OPCODE | TARGET_NR_rt_sigreturn,
(uint16_t *)(frame->retcode))) {
goto give_sigsegv;
}
}
if (__put_user(env->regs[15], (abi_ulong *) frame)) {
goto give_sigsegv;
}
env->regs[15] = frame_addr;
env->psw.addr = (target_ulong) ka->_sa_handler | PSW_ADDR_AMODE;
env->regs[2] = sig;
env->regs[3] = frame_addr + offsetof(typeof(*frame), info);
env->regs[4] = frame_addr + offsetof(typeof(*frame), uc);
return;
give_sigsegv:
qemu_log("%s: give_sigsegv\n", __FUNCTION__);
unlock_user_struct(frame, frame_addr, 1);
force_sig(TARGET_SIGSEGV);
}
| 1threat |
Replace a line in a config file with ansible : <p>I am new to ansible.</p>
<p>Is there a simple way to replace the line starting with <code>option domain-name-servers</code> in <code>/etc/dhcp/interface-br0.conf</code> with more IPs?</p>
<pre><code> option domain-name-servers 10.116.184.1,10.116.144.1;
</code></pre>
<p>I want to add <code>,10.116.136.1</code></p>
| 0debug |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.