problem stringlengths 26 131k | labels class label 2 classes |
|---|---|
Navigationbar coloring in ViewWillAppear happens too late in iOS 10 : <p>I am facing a weird bug, that happens only on iOS 10.</p>
<p>I have a application with several screens, and each screen colors the <code>navigationBar</code> in <code>viewWillAppear</code>. So when you go to the next screen, it will be properly colored.</p>
<p>However, when testing on iOS 10 I suddenly see the following behaviour when going back to a previous screen:
When the previous screen appears the <code>navigationBar</code> still has the color of the previous screen and then flashes to the proper color.
It almost looks like <code>viewWillAppear</code> somehow behaves as <code>viewDidAppear</code>.</p>
<p>Relevant code:</p>
<p>ViewController:</p>
<pre><code>- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[ViewControllerPainter paint:self withBackground:[UIColor whiteColor] andForeground:[UIColor blackColor] andIsLight:true];
}
</code></pre>
<p>Painter:</p>
<pre><code>+ (void)paint:(UIViewController *)controller withBackground:(UIColor *)backgroundColor andForeground:(UIColor *)foregroundColor andIsLight:(bool)isLight
{
controller.navigationController.navigationBar.opaque = true;
controller.navigationController.navigationBar.translucent = false;
controller.navigationController.navigationBar.tintColor = foregroundColor;
controller.navigationController.navigationBar.barTintColor = backgroundColor;
controller.navigationController.navigationBar.backgroundColor = backgroundColor;
controller.navigationController.navigationBar.barStyle = isLight ? UIBarStyleDefault : UIBarStyleBlack;
controller.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: foregroundColor};
}
</code></pre>
<p>Is this a bug? Is there something I can do about to fix this? It's very frustrating.</p>
| 0debug |
How do I crop an image in Flutter? : <p>Let's say I have a rectangular, portrait image:</p>
<p><a href="https://i.stack.imgur.com/lkd0a.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lkd0a.png" alt="enter image description here"></a></p>
<p>I'd like to crop it, such that it's rendered like this:</p>
<p><a href="https://i.stack.imgur.com/c9oQR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/c9oQR.png" alt="enter image description here"></a></p>
<p>How can I do this in Flutter?</p>
<p>(I don't need to resize the image.)</p>
<p>(Image from <a href="https://flic.kr/p/nwXTDb" rel="noreferrer">https://flic.kr/p/nwXTDb</a>)</p>
| 0debug |
static void uhci_async_cancel_device(UHCIState *s, USBDevice *dev)
{
UHCIQueue *queue;
UHCIAsync *curr, *n;
QTAILQ_FOREACH(queue, &s->queues, next) {
QTAILQ_FOREACH_SAFE(curr, &queue->asyncs, next, n) {
if (!usb_packet_is_inflight(&curr->packet) ||
curr->packet.ep->dev != dev) {
continue;
}
uhci_async_cancel(curr);
}
}
}
| 1threat |
static int configure_accelerator(void)
{
const char *p = NULL;
char buf[10];
int i, ret;
bool accel_initialised = false;
bool init_failed = false;
QemuOptsList *list = qemu_find_opts("machine");
if (!QTAILQ_EMPTY(&list->head)) {
p = qemu_opt_get(QTAILQ_FIRST(&list->head), "accel");
}
if (p == NULL) {
p = "tcg";
}
while (!accel_initialised && *p != '\0') {
if (*p == ':') {
p++;
}
p = get_opt_name(buf, sizeof (buf), p, ':');
for (i = 0; i < ARRAY_SIZE(accel_list); i++) {
if (strcmp(accel_list[i].opt_name, buf) == 0) {
if (!accel_list[i].available()) {
printf("%s not supported for this target\n",
accel_list[i].name);
continue;
}
*(accel_list[i].allowed) = true;
ret = accel_list[i].init();
if (ret < 0) {
init_failed = true;
fprintf(stderr, "failed to initialize %s: %s\n",
accel_list[i].name,
strerror(-ret));
*(accel_list[i].allowed) = false;
} else {
accel_initialised = true;
}
break;
}
}
if (i == ARRAY_SIZE(accel_list)) {
fprintf(stderr, "\"%s\" accelerator does not exist.\n", buf);
}
}
if (!accel_initialised) {
if (!init_failed) {
fprintf(stderr, "No accelerator found!\n");
}
exit(1);
}
if (init_failed) {
fprintf(stderr, "Back to %s accelerator.\n", accel_list[i].name);
}
return !accel_initialised;
}
| 1threat |
static void audio_pp_nb_voices (const char *typ, int nb)
{
switch (nb) {
case 0:
printf ("Does not support %s\n", typ);
break;
case 1:
printf ("One %s voice\n", typ);
break;
case INT_MAX:
printf ("Theoretically supports many %s voices\n", typ);
break;
default:
printf ("Theoretically supports upto %d %s voices\n", nb, typ);
break;
}
}
| 1threat |
Access props sent to components along with Redux state data : <p>Normally you can access props sent by parent to child on child component. But when redux is used on child components the props sent by parent is lost with use of 'connect' method which maps redux state with components props.</p>
<p>E.g.:</p>
<p>Declaring a component with properties:
<code><A_Component prop1='1' prop2='2' /></code></p>
<p>Accessing without redux on child component, works fine:
<code>this.props.prop1</code> or <code>this.props.prop2</code></p>
<p>Same statements will give <code>undefined</code> error if redux states are used.</p>
| 0debug |
db.execute('SELECT * FROM employees WHERE id = ' + user_input) | 1threat |
My PHP 7 code will not work : <p>To those who have already installed PHP 7, and it works fine when you give PHP 7 code, please check my PHP 7 code and tell me if it works with you, (this code came from a book.) if it does not work then tell me how I could fix it, then if it does work, then tell me what else I have to install or do.
This is the PHP 7 code:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title> Luke Reports | Home </title>
</head>
<body>
<?php
$url = 'http://rss.news.yahoo.com/rss/entertainment';
$xml =
simplexml_load_file( $url ) or die( 'Unalble to load data!');
include( 'includes/rss-footer.html');
foreach( $xml->channel->item as $item){
echo '<a href="'.item->link.'">'.$item->title.'</a>';
echo '<br><small>'.$item->pubDate.'</small><br>';
echo $item->description.'<hr>';}
include( 'includes/rss-footer.html');
?>
</body>
</html>
</code></pre>
<p>So I will highly appreciate it if you comment <em>or</em> Answer.</p>
<p>Thanks, Luke </p>
| 0debug |
How does Bitmoji work? : <p>does anyone have an idea, how bitmoji or other similar services work? I have an idea for an app, which should have custom Avatars. </p>
<p>There are multiple libraries for 3D-Games, which are based on Morphing. Easy. All the 2D-Characters however are seamingly made with sprites. But if you consider how many options bitmoji has, do you think, they basically have drawn all the possible sprites? Or am I to stupid to find the "yellow brick road"?</p>
<p>Thanks for any advice.</p>
| 0debug |
SwiftUI can't tap in Spacer of HStack : <p>I've got a List view and each row of the list contains an HStack with some text view('s) and an image, like so:</p>
<pre><code>HStack{
Text(group.name)
Spacer()
if (groupModel.required) { Text("Required").color(Color.gray) }
Image("ic_collapse").renderingMode(.template).rotationEffect(Angle(degrees: 90)).foregroundColor(Color.gray)
}.tapAction { self.groupSelected(self.group) }
</code></pre>
<p>This seems to work great, except when I tap in the empty section between my text and the image (where the <code>Spacer()</code> is) the tap action is not registered. The tap action will only occur when I tap on the text or on the image.</p>
<p>Has anyone else faced this issue / knows a workaround?</p>
| 0debug |
How to limited show item in recyclerView on Android : In my application I want show some data and this data I should get from server.<br> I want when **Won** is **true** just show this item. if **won** is **false** show other data. (for see won, please see below json)<br>
**My json :**
{
"statusCode": 200,
"statusMessage": "",
"data": [
{
"title": "Golden Globe",
"awards": [
{
"description": "Best Performance by an Actress in a Supporting Role in a Series, Limited Series or Motion Picture Made for Television",
"year": 2017,
"celebrity": {
"id": 10245,
"name": "Lena Headey",
"character": null,
"imageUrl": "http://example.com/cpanel/uploads/Celebrities/10245/thumb2-1WKXVM3I6M.jpg",
"userReview": ""
},
"won": false
},
{
"description": "Best Television Series - Drama",
"year": 2017,
"celebrity": {
"id": 0,
"name": "",
"character": null,
"imageUrl": "",
"userReview": ""
},
"won": false
},
{
"description": "Best Television Series - Drama",
"year": 2016,
"celebrity": {
"id": 0,
"name": "",
"character": null,
"imageUrl": "",
"userReview": ""
},
"won": false
},
{
"description": "Best Television Series - Drama",
"year": 2015,
"celebrity": {
"id": 0,
"name": "",
"character": null,
"imageUrl": "",
"userReview": ""
},
"won": false
},
{
"description": "Best Performance by an Actor in a Supporting Role in a Series, Miniseries or Motion Picture Made for Television",
"year": 2012,
"celebrity": {
"id": 10480,
"name": "Peter Dinklage",
"character": null,
"imageUrl": "http://example.com/cpanel/uploads/Celebrities/10480/thumb2-0QO7OA48JR.jpg",
"userReview": ""
},
"won": true
},
{
"description": "Best Television Series - Drama",
"year": 2012,
"celebrity": {
"id": 0,
"name": "",
"character": null,
"imageUrl": "",
"userReview": ""
},
"won": false
}
]
}
]
}
I write below codes, but show all of data. I want if **won** is **true** just show this item, else show other items (show won false items).<br>
**My Adapter codes:**
public class AwardModelAdater extends RecyclerView.Adapter<AwardModelAdater.ViewHolder> {
private Context context;
private List<Award> model;
private int modelImage;
public AwardModelAdater(Context context, List<Award> model) {
this.context = context;
this.model = model;
}
@Override
public AwardModelAdater.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_award, parent, false);
return new AwardModelAdater.ViewHolder(view);
}
@Override
public void onBindViewHolder(final AwardModelAdater.ViewHolder holder, final int position) {
if (model.get(position).getWon()) {
modelImage = R.drawable.golden_globe_gold;
} else {
modelImage = R.drawable.golden_globe_silver;
}
if (model.get(position).getWon()) {
Glide.with(context)
.load(modelImage)
.placeholder(R.drawable.default_image)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.row_awardImg);
} else {
Glide.with(context)
.load(modelImage)
.placeholder(R.drawable.default_image)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.row_awardImg);
}
}
@Override
public int getItemCount() {
return model.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView row_awardImg;
public ViewHolder(View itemView) {
super(itemView);
row_awardImg = (ImageView) itemView.findViewById(R.id.row_awardImg);
}
}
}
**My activity code:**
SendData = new SerialDetailSendData();
SendData.setSeriesID(serialID);
InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
Call<SeriesAwardResponse> call = api.getSeriesAward(SendData);
call.enqueue(new Callback<SeriesAwardResponse>() {
@Override
public void onResponse(Call<SeriesAwardResponse> call, Response<SeriesAwardResponse> response) {
if (response.body().getData() != null) {
awardModel.clear();
awardModel.addAll(response.body().getData().get(0).getAwards());
awardModelAdapter = new AwardModelAdater(context, awardModel);
//dialogList_loadingProgress.hide();
infoSerialFrag_AwardAcademyRecyclerView.setHasFixedSize(true);
infoSerialFrag_AwardAcademyRecyclerView.setAdapter(awardModelAdapter);
}
}
@Override
public void onFailure(Call<SeriesAwardResponse> call, Throwable t) {
//dialogList_loadingProgress.hide();
}
});
How can I it? please help me. | 0debug |
typeof(data.frame) shows "list" in R : <p>Can someone clarify why <strong>typeof (data.frame)</strong> shows <strong>list</strong> in R? In contrast, class gives expected type. E.g., demonstrate that using the built-in data.frame mtcars. </p>
<pre><code>> typeof(mtcars)
[1] "list"
> class(mtcars)
[1] "data.frame"
</code></pre>
<p>Any hints on how to use typeof versus class?</p>
| 0debug |
Decompile war file in eclipce : Hi i have WAR file with code java i need to decompile my war to project Eclipse
To do that i install Eclipse Jee 2018-12 and i have clic in `File->import` and i selected warFile, and i put my file war
but i have this when i go to src to see code java i have just pakage
[![enter image description here][1]][1]
When i clic in `open type hiererchy` i have this
[![enter image description here][2]][2]
How i can get code java please
[1]: https://i.stack.imgur.com/x7A4I.jpg
[2]: https://i.stack.imgur.com/vhZlS.jpg | 0debug |
static int rd_frame(CinepakEncContext *s, const AVFrame *frame, int isakeyframe, unsigned char *buf, int buf_size)
{
int num_strips, strip, i, y, nexty, size, temp_size, best_size;
AVPicture last_pict, pict, scratch_pict;
int64_t best_score = 0, score, score_temp;
#ifdef CINEPAK_REPORT_SERR
int64_t best_serr = 0, serr, serr_temp;
#endif
int best_nstrips;
if(s->pix_fmt == AV_PIX_FMT_RGB24) {
int x;
for(y = 0; y < s->h; y += 2) {
for(x = 0; x < s->w; x += 2) {
uint8_t *ir[2]; int32_t r, g, b, rr, gg, bb;
ir[0] = ((AVPicture*)frame)->data[0] + x*3 + y*((AVPicture*)frame)->linesize[0];
ir[1] = ir[0] + ((AVPicture*)frame)->linesize[0];
get_sub_picture(s, x, y, (AVPicture*)s->input_frame, &scratch_pict);
r = g = b = 0;
for(i=0; i<4; ++i) {
int i1, i2;
i1 = (i&1); i2 = (i>=2);
rr = ir[i2][i1*3+0];
gg = ir[i2][i1*3+1];
bb = ir[i2][i1*3+2];
r += rr; g += gg; b += bb;
rr = (2396625*rr + 4793251*gg + 1198732*bb) >> 23;
if( rr < 0) rr = 0;
else if (rr > 255) rr = 255;
scratch_pict.data[0][i1 + i2*scratch_pict.linesize[0]] = rr;
}
rr = (-299683*r - 599156*g + 898839*b) >> 23;
if( rr < -128) rr = -128;
else if (rr > 127) rr = 127;
scratch_pict.data[1][0] = rr + 128;
rr = (748893*r - 599156*g - 149737*b) >> 23;
if( rr < -128) rr = -128;
else if (rr > 127) rr = 127;
scratch_pict.data[2][0] = rr + 128;
}
}
}
for(num_strips = s->min_strips; num_strips <= s->max_strips && num_strips <= s->h / MB_SIZE; num_strips++) {
score = 0;
size = 0;
#ifdef CINEPAK_REPORT_SERR
serr = 0;
#endif
for(y = 0, strip = 1; y < s->h; strip++, y = nexty) {
int strip_height;
nexty = strip * s->h / num_strips;
if(nexty & 3)
nexty += 4 - (nexty & 3);
strip_height = nexty - y;
if(strip_height <= 0) {
av_log(s->avctx, AV_LOG_INFO, "skipping zero height strip %i of %i\n", strip, num_strips);
continue;
}
if(s->pix_fmt == AV_PIX_FMT_RGB24)
get_sub_picture(s, 0, y, (AVPicture*)s->input_frame, &pict);
else
get_sub_picture(s, 0, y, (AVPicture*)frame, &pict);
get_sub_picture(s, 0, y, (AVPicture*)s->last_frame, &last_pict);
get_sub_picture(s, 0, y, (AVPicture*)s->scratch_frame, &scratch_pict);
if((temp_size = rd_strip(s, y, strip_height, isakeyframe, &last_pict, &pict, &scratch_pict, s->frame_buf + size + CVID_HEADER_SIZE, &score_temp
#ifdef CINEPAK_REPORT_SERR
, &serr_temp
#endif
)) < 0)
return temp_size;
score += score_temp;
#ifdef CINEPAK_REPORT_SERR
serr += serr_temp;
#endif
size += temp_size;
}
if(best_score == 0 || score < best_score) {
best_score = score;
#ifdef CINEPAK_REPORT_SERR
best_serr = serr;
#endif
best_size = size + write_cvid_header(s, s->frame_buf, num_strips, size, isakeyframe);
#ifdef CINEPAK_REPORT_SERR
av_log(s->avctx, AV_LOG_INFO, "best number of strips so far: %2i, %12lli, %i B\n", num_strips, (long long int)serr, best_size);
#endif
FFSWAP(AVFrame *, s->best_frame, s->scratch_frame);
memcpy(buf, s->frame_buf, best_size);
best_nstrips = num_strips;
}
if(num_strips - best_nstrips > 4)
break;
}
if(!s->strip_number_delta_range) {
if(best_nstrips == s->max_strips) {
s->max_strips = best_nstrips + 1;
if(s->max_strips >= s->max_max_strips)
s->max_strips = s->max_max_strips;
} else {
s->max_strips = best_nstrips;
}
s->min_strips = s->max_strips - 1;
if(s->min_strips < s->min_min_strips)
s->min_strips = s->min_min_strips;
} else {
s->max_strips = best_nstrips + s->strip_number_delta_range;
if(s->max_strips >= s->max_max_strips)
s->max_strips = s->max_max_strips;
s->min_strips = best_nstrips - s->strip_number_delta_range;
if(s->min_strips < s->min_min_strips)
s->min_strips = s->min_min_strips;
}
return best_size;
}
| 1threat |
static int nbd_can_read(void *opaque)
{
NBDClient *client = opaque;
return client->recv_coroutine || client->nb_requests < MAX_NBD_REQUESTS;
}
| 1threat |
In the member initializer list, can I create a reference to a member variable not in the list? : <p>Consider:</p>
<pre><code>#include <string>
#include <iostream>
class Foo
{
public:
Foo( char const * msg ) : x( y )
{
y = msg;
}
std::string const & x;
private:
std::string y;
};
int main( int argc, char * argv[] )
{
if ( argc >= 2 )
{
Foo f( argv[1] );
std::cout << f.x << std::endl;
}
}
</code></pre>
<p>This compiles and prints the first parameter... but I have doubts whether it is actually "legal" / well-formed. I know that the initializer list should initialize variables in order of their declaration in the class, lest you reference variables that haven't been initialized yet. But what about member variables <em>not in the initializer list</em>? Can I safely create references to them as showcased?</p>
<p>(The example is, of course, meaningless. It's just to clarify what I am talking about.)</p>
| 0debug |
ValueError: unknown url type: h : <p>I wrote an application in python to download the file at a specified hour but I received <strong>ValueError: unknown url type: h</strong> Error
this is my code</p>
<pre><code>import time,os,urllib2
coun=input("Enter count of the movies:")
x=0
namelist=[]
addresslist=[]
os.chdir('D:\\')
while(coun > x):
name=raw_input("Enter the name of movie:")
namelist.append(name)
address=raw_input("enter the address of %s:"%(name))
addresslist.append(address)
x=x+1
ti= time.localtime().tm_hour
print('it\'s wating...')
while(ti!=11):
ti= time.localtime().tm_hour
timi=time.localtime().tm_min
tisec=time.localtime().tm_sec
if (ti==3 & timi==59 & tisec==59):
print('it\'s 3')
print('it\'s your time.let start downloating')
x=0
while(coun > x):
data=urllib2.urlopen(address[x])
file=open(namelist[x],'wb')
file.write(data)
file.close()
x=x+1
</code></pre>
<p>And when I run it and answer the questions that return to me this Error:</p>
<pre><code>Traceback (most recent call last):
File "tidopy.py", line 24, in <module>
data=urllib2.urlopen(address[x])
File "C:\Python27\lib\urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "C:\Python27\lib\urllib2.py", line 421, in open
protocol = req.get_type()
File "C:\Python27\lib\urllib2.py", line 283, in get_type
raise ValueError, "unknown url type: %s" % self.__original
ValueError: unknown url type: h
</code></pre>
<p><strong>How can I fix it?</strong>
please help</p>
| 0debug |
C# Exception Handling:Display Exception Message through Main Method : i have three methods(including main method) where exception handling is done for each. now i want to print the exception messages of other methods through main method.
**Note:** i want to use only one console.writeline() that to in main methods.
using System;
namespace Execp
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine(Arthimatic(10, 0));
Console.WriteLine("Hello World!");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine( " Message " + ex.Message);
Console.ReadKey();
}
}
private static int? Arthimatic(int num1, int num2)
{
try
{
int? value = Divide(num1, num2);
return value;
}
catch (Exception ex)
{
return null;
}
}
private static int? Divide(int num1, int num2)
{
try
{
int num3 = (num1 / num2);
return num3;
}
catch (Exception ex)
{
return null;
}
}
}
} | 0debug |
PCIBus *pci_apb_init(target_phys_addr_t special_base,
target_phys_addr_t mem_base,
qemu_irq *pic, PCIBus **bus2, PCIBus **bus3)
{
DeviceState *dev;
SysBusDevice *s;
APBState *d;
dev = qdev_create(NULL, "pbm");
qdev_init(dev);
s = sysbus_from_qdev(dev);
sysbus_mmio_map(s, 0, special_base + 0x2000ULL);
sysbus_mmio_map(s, 1, special_base + 0x2000000ULL);
sysbus_mmio_map(s, 2, special_base + 0x1000000ULL);
sysbus_mmio_map(s, 3, mem_base);
d = FROM_SYSBUS(APBState, s);
d->host_state.bus = pci_register_bus(&d->busdev.qdev, "pci",
pci_apb_set_irq, pci_pbm_map_irq, pic,
0, 32);
pci_create_simple(d->host_state.bus, 0, "pbm");
*bus2 = pci_bridge_init(d->host_state.bus, 8, PCI_VENDOR_ID_SUN,
PCI_DEVICE_ID_SUN_SIMBA, pci_apb_map_irq,
"Advanced PCI Bus secondary bridge 1");
*bus3 = pci_bridge_init(d->host_state.bus, 9, PCI_VENDOR_ID_SUN,
PCI_DEVICE_ID_SUN_SIMBA, pci_apb_map_irq,
"Advanced PCI Bus secondary bridge 2");
return d->host_state.bus;
}
| 1threat |
How to bundle video with application : <p>I have seen a lot of tutorials showing how to play a video from a URL but I want to be able to play a video that I put in my application before I build it. </p>
<p>Is it possible?</p>
<p>Also for those saying that my app will become too big, the video is only 267kb.</p>
| 0debug |
Changing color when specific div is visible : <p>Please tell me how can I make this in the most right way.</p>
<p>HTML:</p>
<pre><code><div id="fixed-red" class="fixed-red"></div>
<div id="fixed-green" class="fixed-green"></div>
<div id="fixed-blue" class="fixed-blue"></div>
<div id="red" class="red"></div>
<div id="green" class="green"></div>
<div id="blue" class="blue"></div>
</code></pre>
<p>CSS:</p>
<pre><code>html,body{
height:100%;
}
.fixed-red,.fixed-green,.fixed-blue{
width:30px;
height:30px;
position:fixed;
top:10px;
left:10px;
background:#333;
}
.fixed-green{
top:50px;
}
.fixed-blue{
top:90px;
}
.red-active{
background:#f00;
}
.green-active{
background:#0f0;
}
.blue-active{
background:#00f;
}
.red,.green,.blue{
width:100%;
height:100%;
}
.red{
background:#900;
}
.green{
background:#090;
}
.blue{
background:#009;
}
</code></pre>
<p>I want to add/remove <code>red/green/blue-active</code> class to the <code>fixed-red/green/blue</code> divs when the user is on/off the <code>red</code>, <code>green</code>, or <code>blue</code> divs(when they are visible), so the small divs would be respectively highlighted with the color of the big, display divs when the user is on them.</p>
<p>Thanks!</p>
| 0debug |
Why is there no mention of any research paper linked to the StereoBM implementation of OpenCV? : <p>I am looking for any link or source, explaining the internal implementation of OpenCV StereoBM.</p>
| 0debug |
paint_mouse_pointer(XImage *image, struct x11grab *s)
{
int x_off = s->x_off;
int y_off = s->y_off;
int width = s->width;
int height = s->height;
Display *dpy = s->dpy;
XFixesCursorImage *xcim;
int x, y;
int line, column;
int to_line, to_column;
int pixstride = image->bits_per_pixel >> 3;
uint8_t *pix = image->data;
Cursor c;
Window w;
XSetWindowAttributes attr;
if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)
return;
c = XCreateFontCursor(dpy, XC_left_ptr);
w = DefaultRootWindow(dpy);
attr.cursor = c;
XChangeWindowAttributes(dpy, w, CWCursor, &attr);
xcim = XFixesGetCursorImage(dpy);
x = xcim->x - xcim->xhot;
y = xcim->y - xcim->yhot;
to_line = FFMIN((y + xcim->height), (height + y_off));
to_column = FFMIN((x + xcim->width), (width + x_off));
for (line = FFMAX(y, y_off); line < to_line; line++) {
for (column = FFMAX(x, x_off); column < to_column; column++) {
int xcim_addr = (line - y) * xcim->width + column - x;
int image_addr = ((line - y_off) * width + column - x_off) * pixstride;
int r = (uint8_t)(xcim->pixels[xcim_addr] >> 0);
int g = (uint8_t)(xcim->pixels[xcim_addr] >> 8);
int b = (uint8_t)(xcim->pixels[xcim_addr] >> 16);
int a = (uint8_t)(xcim->pixels[xcim_addr] >> 24);
if (a == 255) {
pix[image_addr+0] = r;
pix[image_addr+1] = g;
pix[image_addr+2] = b;
} else if (a) {
pix[image_addr+0] = r + (pix[image_addr+0]*(255-a) + 255/2) / 255;
pix[image_addr+1] = g + (pix[image_addr+1]*(255-a) + 255/2) / 255;
pix[image_addr+2] = b + (pix[image_addr+2]*(255-a) + 255/2) / 255;
}
}
}
XFree(xcim);
xcim = NULL;
}
| 1threat |
I have a name string, but how do I make it where the person's inputted name is spit back out in a Console.WriteLine : <p>I have a string <code>public static string playerName;</code>and I want to make it where they can input a name for the playerName and then i can put that string in a Console.WriteLine and it says what they put. I am somewhat new to C# and was wondering how I could achieve this.</p>
| 0debug |
static int svq1_decode_frame(AVCodecContext *avctx, void *data,
int *data_size, AVPacket *avpkt)
{
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
MpegEncContext *s = avctx->priv_data;
uint8_t *current, *previous;
int result, i, x, y, width, height;
AVFrame *pict = data;
svq1_pmv *pmv;
init_get_bits(&s->gb, buf, buf_size * 8);
s->f_code = get_bits(&s->gb, 22);
if ((s->f_code & ~0x70) || !(s->f_code & 0x60))
return AVERROR_INVALIDDATA;
if (s->f_code != 0x20) {
uint32_t *src = (uint32_t *)(buf + 4);
if (buf_size < 36)
return AVERROR_INVALIDDATA;
for (i = 0; i < 4; i++)
src[i] = ((src[i] << 16) | (src[i] >> 16)) ^ src[7 - i];
}
result = svq1_decode_frame_header(&s->gb, s);
if (result) {
av_dlog(s->avctx, "Error in svq1_decode_frame_header %i\n", result);
return result;
}
avcodec_set_dimensions(avctx, s->width, s->height);
if (s->pict_type == AV_PICTURE_TYPE_B && s->last_picture_ptr == NULL)
return buf_size;
if ((avctx->skip_frame >= AVDISCARD_NONREF &&
s->pict_type == AV_PICTURE_TYPE_B) ||
(avctx->skip_frame >= AVDISCARD_NONKEY &&
s->pict_type != AV_PICTURE_TYPE_I) ||
avctx->skip_frame >= AVDISCARD_ALL)
return buf_size;
if ((result = ff_MPV_frame_start(s, avctx)) < 0)
return result;
pmv = av_malloc((FFALIGN(s->width, 16) / 8 + 3) * sizeof(*pmv));
if (!pmv)
return AVERROR(ENOMEM);
for (i = 0; i < 3; i++) {
int linesize;
if (i == 0) {
width = FFALIGN(s->width, 16);
height = FFALIGN(s->height, 16);
linesize = s->linesize;
} else {
if (s->flags & CODEC_FLAG_GRAY)
break;
width = FFALIGN(s->width / 4, 16);
height = FFALIGN(s->height / 4, 16);
linesize = s->uvlinesize;
}
current = s->current_picture.f.data[i];
if (s->pict_type == AV_PICTURE_TYPE_B)
previous = s->next_picture.f.data[i];
else
previous = s->last_picture.f.data[i];
if (s->pict_type == AV_PICTURE_TYPE_I) {
for (y = 0; y < height; y += 16) {
for (x = 0; x < width; x += 16) {
result = svq1_decode_block_intra(&s->gb, ¤t[x],
linesize);
if (result) {
av_log(s->avctx, AV_LOG_ERROR,
"Error in svq1_decode_block %i (keyframe)\n",
result);
goto err;
}
}
current += 16 * linesize;
}
} else {
memset(pmv, 0, ((width / 8) + 3) * sizeof(svq1_pmv));
for (y = 0; y < height; y += 16) {
for (x = 0; x < width; x += 16) {
result = svq1_decode_delta_block(s, &s->gb, ¤t[x],
previous, linesize,
pmv, x, y);
if (result) {
av_dlog(s->avctx,
"Error in svq1_decode_delta_block %i\n",
result);
goto err;
}
}
pmv[0].x =
pmv[0].y = 0;
current += 16 * linesize;
}
}
}
*pict = s->current_picture.f;
ff_MPV_frame_end(s);
*data_size = sizeof(AVFrame);
result = buf_size;
err:
av_free(pmv);
return result;
} | 1threat |
closing previous jframes while opening another : i have 2 jframes f1&f2 both having buttons b1&b2 respectively .The buttons b1&b2 switch frames ,ie if b1 is clicked it opens f2&if b2 is clicked it opens f1.
but i want my program to close previous jframe when attempting to open a new jframe,ie if b1 is clicked it should close/hide f1 and open f2 and vice versa
i have tried setVisible(false) but it dosent seem to work
please help me come up with a solution
my code:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class m extends JFrame implements ActionListener
{
static JFrame f1,f2;
static JButton b1,b2;
public m()
{
f1();
}
public void f1()
{
JFrame f1=new JFrame("frame 1");
JButton b1=new JButton("frame 2");
JLabel l1=new JLabel("FRAME 1");
f1.setSize(600,600);
b1.setBounds(300,300,100,100);
l1.setBounds(300,150,100,100);
b1.addActionListener(this);
f1.add(b1);
f1.add(l1);
f1.setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void f2()
{
JFrame f2=new JFrame("frame 2");
JButton b2=new JButton("frame 1");
JLabel l2=new JLabel("FRAME 2");
f2.setSize(600,600);
b2.setBounds(300,300,100,100);
l2.setBounds(300,150,100,100);
b2.addActionListener(this);
f2.add(b2);
f2.add(l2);
f2.setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public static void main(String args[])
{
new m();
}
public void actionPerformed(ActionEvent e)
{
String bt=String.valueOf(e.getActionCommand());
if(bt=="frame 2")
{
f1.setVisible(false);
f2();
}
else if(bt=="frame 1")
{
f2.setVisible(false);
f1();
}
}
} | 0debug |
static uint64_t pci_config_get_pref_base(PCIDevice *d,
uint32_t base, uint32_t upper)
{
uint64_t val;
val = ((uint64_t)pci_get_word(d->config + base) &
PCI_PREF_RANGE_MASK) << 16;
val |= (uint64_t)pci_get_long(d->config + upper) << 32;
return val;
}
| 1threat |
How to get substrings without using substring() method in Java? : <p>I'm just looking for a simple way to be able to extract substrings without using the substring method. </p>
| 0debug |
Repeated Errors Despite Correct Namespace [C++] : I added a class to ns3 and when using it I keep getting the error:
../scratch/seven.cc: In function ‘int main(int, char**)’:
../scratch/seven.cc:102:3: error: ‘RandomAppHelper’ was not declared in this scope
RandomAppHelper source = RandomAppHelper ("ns3::TcpSocketFactory", InetSocketAddress (Ipv4Address ("192.168.1.10"), 10));
^
../scratch/seven.cc:103:3: error: ‘source’ was not declared in this scope
source.SetAttribute ("Delay", StringValue ("Constant:2.5"));
^
The code for this is here: **https://www.nsnam.org/docs/release/3.3/doxygen/application.html**
I can't resolve the error. I used the correct namespace ns3 in the code. Since the error is of "not declared in scope", I am not sure how to rectify it.
Please help.
| 0debug |
cursor.execute('SELECT * FROM users WHERE username = ' + user_input) | 1threat |
function that has an ajax events return undefined when called : <p>I have a function called 'getAuthor' and inside there's an ajax events running (refer below)</p>
<pre><code>function getAuthor(id){
$.get('http://www.connectnigeria.com/articles/wp-json/wp/v2/users/74',function(e){
var author = e.name;
console.log(author);
return author;
});
}
</code></pre>
<p>try to run from the console, you'll see it returns "undefined" while console.log display the expected response from the ajax call.</p>
<p>Any, ideas help please?</p>
| 0debug |
My todo list is bugged : Can some one help me? i'm trying to code a **simple todolist with JS** i'm
begginer on this language, my tasks were adding ok, but when i created a button to complete the task it bugged everything.
Here's my code
<!DOCTYPE html>
<html>
<head>
<title>TODO</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>TODOLIST</h1>
<input id="task"><button id="add">Add</button>
<hr>
<h2>todo</h2>
<ul id="todos"></ul>
<h2>done</h2>
<ul id="done"></ul>
<script src="todo.js"></script>
</body>
</html>
JS:
function get_todos() {
var todos = new Array;
var todos_str = localStorage.getItem('todo');
if (todos_str !== null) {
todos = JSON.parse(todos_str);
}
return todos;
}
function get_dones(){
var dones = new Array;
var dones_str = localStorage.getItem('done');
if (dones_str !== null){
dones = JSON.parse(dones_str);
}
return dones;
}
function add() {
var task = document.getElementById('task').value;
var todos = get_todos();
todos.push(task);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
function remove() {
var id = this.getAttribute('id');
var todos = get_todos();
todos.splice(id, 1);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
function show() {
var todos = get_todos();
var dones = get_dones();
var html;
for(var i=0; i<todos.length; i++) {
html += '<li>' + todos[i] + '<button class="remove" id="' + i + '">Delete</button> <button class="done" id="' + i + '">Done</button></li>';
};
document.getElementById('todos').innerHTML = html;
var html;
for(var i=0; i<dones.length; i++) {
html += '<li>' + dones[i] + '<button class="remove" id="' + i + '">Delete</button> <button class="done" id="' + i + '">Done</button></li>';
};
document.getElementById('dones').innerHTML = html;
var buttons = document.getElementsByClassName('remove');
for (var i=0; i < buttons.length; i++) {
buttons[i].addEventListener('click', remove);
};
var buttons = document.getElementsByClassName('done');
for (var i=0; i < buttons.length; i++) {
buttons[i].addEventListener('click', done);
};
function done(){
var id = this.getAttribute('id');
var done = get_dones();
localStorage.setItem('done', JSON.stringify(dones));
show();
return false;
}
document.getElementById('add').addEventListener('click', add);
show(); | 0debug |
I don't really understand. What does "nearest larger" means (Ruby) : :
I am working on this question, but I still don't understand what exactly this question asks for?
I don't know why expected output for ([2,3,4,8], 2) is equal to 3
Maybe 3 is the nearest number to 2?? or some other number in the array?
I don't understand all the outputs below
Please help me! Thank you so much
This is the question and outputs below:
# Write a function, `nearest_larger(arr, i)` which takes an array and an
# index. The function should return another index, `j`: this should
# satisfy:
#
# (a) `arr[i] < arr[j]`, AND
# (b) there is no `j2` closer to `i` than `j` where `arr[i] < arr[j2]`.
#
# In case of ties (see example below), choose the earliest (left-most)
# of the two indices. If no number in `arr` is larger than `arr[i]`,
# return `nil`.
#
# Difficulty: 2/5
def nearest_larger(arr, idx)
end
puts("Tests for #nearest_larger")
puts("===============================================")
puts "nearest_larger([2,3,4,8], 2) == 3: " + (nearest_larger([2,3,4,8], 2) == 3).to_s
puts "nearest_larger([2,8,4,3], 2) == 1: " + (nearest_larger([2,8,4,3], 2) == 1).to_s
puts "nearest_larger([2,6,4,8], 2) == 1: " + (nearest_larger([2,6,4,8], 2) == 1).to_s
puts "nearest_larger([2,6,4,6], 2) == 1: " + (nearest_larger([2,6,4,6], 2) == 1).to_s
puts "nearest_larger([8,2,4,3], 2) == 0: " + (nearest_larger([8,2,4,3], 2) == 0).to_s
puts "nearest_larger([2,4,3,8], 1) == 3: " + (nearest_larger([2,4,3,8], 1) == 3).to_s
puts "nearest_larger([2, 6, 4, 8], 3) == nil: "+ (nearest_larger([2, 6, 4, 8], 3) == nil).to_s
puts "nearest_larger([2, 6, 9, 4, 8], 3) == 2: "+ (nearest_larger([2, 6, 9, 4, 8], 3) == 2).to_s
puts("===============================================")
| 0debug |
static void virtio_scsi_migration_state_changed(Notifier *notifier, void *data)
{
VirtIOSCSI *s = container_of(notifier, VirtIOSCSI,
migration_state_notifier);
MigrationState *mig = data;
if (migration_in_setup(mig)) {
if (!s->dataplane_started) {
return;
}
virtio_scsi_dataplane_stop(s);
s->dataplane_disabled = true;
} else if (migration_has_finished(mig) ||
migration_has_failed(mig)) {
if (s->dataplane_started) {
return;
}
bdrv_drain_all();
s->dataplane_disabled = false;
}
}
| 1threat |
How to Access styles from React? : <p>I am trying to access the width and height styles of a div in React but I have been running into one problem. This is what I got so far: </p>
<pre><code>componentDidMount() {
console.log(this.refs.container.style);
}
render() {
return (
<div ref={"container"} className={"container"}></div> //set reff
);
}
</code></pre>
<p>This works but the output that I get is a CSSStyleDeclaration object and in the all property I can all the CSS selectors for that object but they none of them are set. They are all set to an empty string. </p>
<p>This is the output of the CSSStyleDecleration is: <a href="http://pastebin.com/wXRPxz5p" rel="noreferrer">http://pastebin.com/wXRPxz5p</a></p>
<p>Any help on getting to see the actual styles (event inherrited ones) would be greatly appreciated!</p>
<p>Thanks!</p>
| 0debug |
Axios can't set data : <p>Here's my data:</p>
<pre><code>data: function(){
return {
contas: [{id: 3,
nome: "Conta de telefone",
pago: false,
valor: 55.99,
vencimento: "22/08/2016"}] //debug test value
};
},
</code></pre>
<p>And here's my get request:</p>
<pre><code>beforeMount() {
axios.get('http://127.0.0.1/api/bills')
.then(function (response) {
console.log("before: " + this.contas);
this.contas = response.data;
console.log("after: " + this.contas);
});
},
</code></pre>
<p>The problem is I can't access <code>this.contas</code> from within <code>axios.get()</code>. I've tried <code>Vue.set(this, 'contas', response.data);</code> and <code>window.listaPagarComponent.contas = response.data;</code> without success.</p>
<p>My console shows:</p>
<pre><code>before: undefined
after: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
</code></pre>
<p>But Vue Devtools shows only:</p>
<pre><code>contas: Array[1]
0: Object
id: 3
nome: "Conta de telefone"
pago: false
valor: 55.99
vencimento: "22/08/2016"
</code></pre>
<p>Here's my <a href="http://pastebin.com/3Seqkk6L" rel="noreferrer" title="pastebin">full code</a>.</p>
| 0debug |
Using @ViewBuilder to create Views which support multiple children : <p>Some Views in SwiftUI, like VStack and HStack support having multiple views as children, like this:</p>
<pre class="lang-swift prettyprint-override"><code>VStack {
Text("hello")
Text("world")
}
</code></pre>
<p>From what I gather, they use <a href="https://developer.apple.com/documentation/swiftui/viewbuilder" rel="noreferrer">ViewBuilder</a> to make this possible as explained <a href="https://stackoverflow.com/questions/56434549/what-enables-swiftuis-dsl/56435128#56435128">here</a>. </p>
<p>How can we use @ViewBuilder for creating our own Views which support multiple children? For example, let's say that I want to create a <code>Layout</code> View which accepts arbitrary children -- something like this:</p>
<pre class="lang-swift prettyprint-override"><code>struct Layout : View {
let content: Some View
var body : some View {
VStack {
Text("This is a layout")
content()
}
}
}
</code></pre>
<p>Any idea how to implement this pattern in SwiftUI? </p>
| 0debug |
Why using operator OR (logical operator) in if-else, why not using AND (logcial operator) in if-else : <p>I made the alphabet with the appearance of using stars to form the alphabet, but I was confused as to why to use the OR operation instead of the AND operation on if-else?</p>
<pre><code>int row,column;
for(row=1;row<=4;row++){
for(column=1;column<=7;column++){
if((column==1 || column==2 || column==3 || column==5 || column==6 || column==7) && (row==1))
printf(" ");
else if((column==1 || column==2 || column==4 || column==6 || column==7) && (row==2))
printf(" ");
else if((column==1 || column==7) && (row==3))
printf(" ");
else if((column==2 || column==3 || column==4 || column==5 || column==6) && (row==4))
printf(" ");
else
printf("*");
} printf("\n");
}
</code></pre>
<p>Why using operator || in if-else? why not using operator && in if-else for condition column...</p>
| 0debug |
static void sigp_initial_cpu_reset(CPUState *cs, run_on_cpu_data arg)
{
S390CPU *cpu = S390_CPU(cs);
S390CPUClass *scc = S390_CPU_GET_CLASS(cpu);
SigpInfo *si = arg.host_ptr;
cpu_synchronize_state(cs);
scc->initial_cpu_reset(cs);
cpu_synchronize_post_reset(cs);
si->cc = SIGP_CC_ORDER_CODE_ACCEPTED;
}
| 1threat |
def max_val(listval):
max_val = max(i for i in listval if isinstance(i, int))
return(max_val) | 0debug |
Notice: ob_end_flush(): failed to send buffer of zlib output compression (1) in : <p>I don't have any problem on localhost. but when i tested my codes on server, end of every page i see this notice.</p>
<p>my code:</p>
<pre><code><?php
ob_start();
include 'view.php';
$data = ob_get_contents();
ob_end_clean();
include 'master.php';
ob_end_flush(); // Problem is this line
</code></pre>
| 0debug |
static int qio_dns_resolver_lookup_sync_inet(QIODNSResolver *resolver,
SocketAddressLegacy *addr,
size_t *naddrs,
SocketAddressLegacy ***addrs,
Error **errp)
{
struct addrinfo ai, *res, *e;
InetSocketAddress *iaddr = addr->u.inet.data;
char port[33];
char uaddr[INET6_ADDRSTRLEN + 1];
char uport[33];
int rc;
Error *err = NULL;
size_t i;
*naddrs = 0;
*addrs = NULL;
memset(&ai, 0, sizeof(ai));
ai.ai_flags = AI_PASSIVE;
if (iaddr->has_numeric && iaddr->numeric) {
ai.ai_flags |= AI_NUMERICHOST | AI_NUMERICSERV;
}
ai.ai_family = inet_ai_family_from_address(iaddr, &err);
ai.ai_socktype = SOCK_STREAM;
if (err) {
error_propagate(errp, err);
return -1;
}
if (iaddr->host == NULL) {
error_setg(errp, "host not specified");
return -1;
}
if (iaddr->port != NULL) {
pstrcpy(port, sizeof(port), iaddr->port);
} else {
port[0] = '\0';
}
rc = getaddrinfo(strlen(iaddr->host) ? iaddr->host : NULL,
strlen(port) ? port : NULL, &ai, &res);
if (rc != 0) {
error_setg(errp, "address resolution failed for %s:%s: %s",
iaddr->host, port, gai_strerror(rc));
return -1;
}
for (e = res; e != NULL; e = e->ai_next) {
(*naddrs)++;
}
*addrs = g_new0(SocketAddressLegacy *, *naddrs);
for (i = 0, e = res; e != NULL; i++, e = e->ai_next) {
SocketAddressLegacy *newaddr = g_new0(SocketAddressLegacy, 1);
InetSocketAddress *newiaddr = g_new0(InetSocketAddress, 1);
newaddr->u.inet.data = newiaddr;
newaddr->type = SOCKET_ADDRESS_LEGACY_KIND_INET;
getnameinfo((struct sockaddr *)e->ai_addr, e->ai_addrlen,
uaddr, INET6_ADDRSTRLEN, uport, 32,
NI_NUMERICHOST | NI_NUMERICSERV);
*newiaddr = (InetSocketAddress){
.host = g_strdup(uaddr),
.port = g_strdup(uport),
.has_numeric = true,
.numeric = true,
.has_to = iaddr->has_to,
.to = iaddr->to,
.has_ipv4 = false,
.has_ipv6 = false,
};
(*addrs)[i] = newaddr;
}
freeaddrinfo(res);
return 0;
}
| 1threat |
static void spapr_reallocate_hpt(sPAPRMachineState *spapr, int shift,
Error **errp)
{
long rc;
g_free(spapr->htab);
spapr->htab = NULL;
spapr->htab_shift = 0;
close_htab_fd(spapr);
rc = kvmppc_reset_htab(shift);
if (rc < 0) {
error_setg_errno(errp, errno,
"Failed to allocate KVM HPT of order %d (try smaller maxmem?)",
shift);
} else if (rc > 0) {
if (rc != shift) {
error_setg(errp,
"Requested order %d HPT, but kernel allocated order %ld (try smaller maxmem?)",
shift, rc);
}
spapr->htab_shift = shift;
kvmppc_kern_htab = true;
} else {
size_t size = 1ULL << shift;
int i;
spapr->htab = qemu_memalign(size, size);
if (!spapr->htab) {
error_setg_errno(errp, errno,
"Could not allocate HPT of order %d", shift);
return;
}
memset(spapr->htab, 0, size);
spapr->htab_shift = shift;
kvmppc_kern_htab = false;
for (i = 0; i < size / HASH_PTE_SIZE_64; i++) {
DIRTY_HPTE(HPTE(spapr->htab, i));
}
}
}
| 1threat |
void qsb_free(QEMUSizedBuffer *qsb)
{
size_t i;
if (!qsb) {
return;
}
for (i = 0; i < qsb->n_iov; i++) {
g_free(qsb->iov[i].iov_base);
}
g_free(qsb->iov);
g_free(qsb);
}
| 1threat |
Testing a Promise using setTimeout with Jest : <p>I'm trying to understand Jest's asynchronous testing.</p>
<p>My module has a function which accepts a boolean and returns a Promise of a value. The executer function calls <code>setTimeout</code>, and in the timed out callback the promise resolves or rejects depending on the boolean initially supplied. The code looks like this: </p>
<pre><code>const withPromises = (passes) => new Promise((resolve, reject) => {
const act = () => {
console.log(`in the timout callback, passed ${passes}`)
if(passes) resolve('something')
else reject(new Error('nothing'))
}
console.log('in the promise definition')
setTimeout(act, 50)
})
export default { withPromises }
</code></pre>
<p>I'd like to test this using Jest. I guess that I need to use the mock timers Jest provides, so my test script looks a bit like this: </p>
<pre><code>import { withPromises } from './request_something'
jest.useFakeTimers()
describe('using a promise and mock timers', () => {
afterAll(() => {
jest.runAllTimers()
})
test('gets a value, if conditions favor', () => {
expect.assertions(1)
return withPromises(true)
.then(resolved => {
expect(resolved).toBe('something')
})
})
})
</code></pre>
<p>I get the following error/failed test, whether or not I call <code>jest.runAllTimers()</code></p>
<pre><code>Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
</code></pre>
<p>Can you explain where I'm going wrong and what I might do to get a passing test that the promise resolves as expected?</p>
| 0debug |
How to make a regex for numbers? : So i got this regex code `/[0-3][0-9][0-1][1-9]\d{2}[-\s]\d{4}?[^0-9]*|[0-3][0-9][0-1][1-9]\d{2}\d{4}/`
This regex code take this kind of numbers:
1002821187
100282 1187
100282-1187
But i found out i dont want the numbers: 1002821187
So is it possible to make 1 regex code that only finds:
100282 1187
100282-1187
Hope you all can help me.
and thx alot! | 0debug |
Synchronous alternative for setState : <p>I know setState is asynchronous and it may not mutate the state immediately after calling setState(), is there any alternative method for changing the state synchronously or immediately mutating the state ?</p>
| 0debug |
static av_cold int adpcm_decode_init(AVCodecContext * avctx)
{
ADPCMDecodeContext *c = avctx->priv_data;
unsigned int max_channels = 2;
switch(avctx->codec->id) {
case CODEC_ID_ADPCM_EA_R1:
case CODEC_ID_ADPCM_EA_R2:
case CODEC_ID_ADPCM_EA_R3:
case CODEC_ID_ADPCM_EA_XAS:
max_channels = 6;
break;
}
if(avctx->channels > max_channels){
return -1;
}
switch(avctx->codec->id) {
case CODEC_ID_ADPCM_CT:
c->status[0].step = c->status[1].step = 511;
break;
case CODEC_ID_ADPCM_IMA_WAV:
if (avctx->bits_per_coded_sample != 4) {
av_log(avctx, AV_LOG_ERROR, "Only 4-bit ADPCM IMA WAV files are supported\n");
return -1;
}
break;
case CODEC_ID_ADPCM_IMA_WS:
if (avctx->extradata && avctx->extradata_size == 2 * 4) {
c->status[0].predictor = AV_RL32(avctx->extradata);
c->status[1].predictor = AV_RL32(avctx->extradata + 4);
}
break;
default:
break;
}
avctx->sample_fmt = AV_SAMPLE_FMT_S16;
avcodec_get_frame_defaults(&c->frame);
avctx->coded_frame = &c->frame;
return 0;
}
| 1threat |
selecting every 3 consecutive elements starting from 1 by using nth selector : <p>i want to use the nth child selector to select my elements as shown in the example image below (the blue color elements are the ones that need to be selected, i have painted them blue in order to refer to ). I tried a lot of almost similar answers available but could not get the exact one. so, if anyone can please give me a solution, I would appreciate it.<a href="https://i.stack.imgur.com/Z167S.png" rel="nofollow noreferrer">nth child selectors</a></p>
| 0debug |
How can I communicate between running python code and nodejs : <p>I'd like to have some python code running and communicating with a nodejs express server. So far, I can get my nodejs server to call python functions via one of two mechanisms, either to spawn a python task or to have it talk to a zerorpc python server.</p>
<p>For the first, a la <a href="http://www.sohamkamani.com/blog/2015/08/21/python-nodejs-comm/" rel="noreferrer">http://www.sohamkamani.com/blog/2015/08/21/python-nodejs-comm/</a>, this works:</p>
<pre><code>var express = require( "express" );
var http = require( "http" );
var app = express();
var server = http.createServer( app ).listen( 3000 );
var io = require( "socket.io" )( server );
app.use( express.static( "./public" ) );
io.on( "connection", function( socket ) {
// Repeat interval is in milliseconds
setInterval( function() {
var spawn = require( 'child_process' ).spawn,
py = spawn( 'python', [ 'mytime.py' ] ),
message = '';
py.stdout.on( 'data', function( data ) {
message += data.toString();
});
py.stdout.on( 'end', function() {
socket.emit( "message", message );
});
}, 50 );
});
</code></pre>
<p>Where mytime.py is</p>
<pre><code>from datetime import datetime
import sys
def main():
now = datetime.now()
sys.stdout.write( now.strftime( "%-d %b %Y %H:%M:%S.%f" ) )
</code></pre>
<p>And with zerorpc <a href="http://www.zerorpc.io/" rel="noreferrer">http://www.zerorpc.io/</a>, if this python code is running:</p>
<pre><code>from datetime import datetime
import sys
import zerorpc
class MyTime( object ):
def gettime( self ):
now = datetime.now()
return now.strftime( "%-d %b %Y %H:%M:%S.%f" )
s = zerorpc.Server( MyTime() )
s.bind( "tcp://0.0.0.0:4242" )
s.run()
</code></pre>
<p>This nodejs code works:</p>
<pre><code>var express = require( "express" );
var http = require( "http" );
var app = express();
var server = http.createServer( app ).listen( 3000 );
var io = require( "socket.io" )( server );
var zerorpc = require( "zerorpc" );
var client = new zerorpc.Client();
client.connect( "tcp://127.0.0.1:4242" );
app.use( express.static( "./public" ) );
io.on( "connection", function( socket ) {
// Repeat interval is in milliseconds
setInterval( function() {
client.invoke( "gettime", function( error, res, more ) {
socket.emit( "message", res.toString( 'utf8' ) );
} );
}, 50 );
});
</code></pre>
<p>But what I'd like to be able to do is instead of just having python functions called, I'd like a separate python process running and sending messages to the nodejs server which listens for them and then handles them. I've experimented with middleware socketio-wildcard, but if I try to set up a python server with zerorpc on the same port as the nodejs express server, it gives a <em>zmq.error.ZMQError: Address already in use</em> error.</p>
<p>I know that I'm not thinking about this right--I know that I'm missing some logic around interprocess communication due to my naïveté here--so if there is a better way to do message sending from a python process with a nodejs server listening, I'm all ears.</p>
<p>Any ideas?</p>
<p>Many thanks in advance!</p>
| 0debug |
void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
{
size_t len;
len = strlen(str);
readline_set_completion_index(rs, len);
if (nb_args == 2) {
NetClientState *ncs[MAX_QUEUE_NUM];
int count, i;
count = qemu_find_net_clients_except(NULL, ncs,
NET_CLIENT_OPTIONS_KIND_NONE,
MAX_QUEUE_NUM);
for (i = 0; i < count; i++) {
const char *name = ncs[i]->name;
if (!strncmp(str, name, len)) {
readline_add_completion(rs, name);
}
}
} else if (nb_args == 3) {
add_completion_option(rs, str, "on");
add_completion_option(rs, str, "off");
}
}
| 1threat |
int init_put_byte(ByteIOContext *s,
unsigned char *buffer,
int buffer_size,
int write_flag,
void *opaque,
int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
void (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
int (*seek)(void *opaque, offset_t offset, int whence))
{
s->buffer = buffer;
s->buffer_size = buffer_size;
s->buf_ptr = buffer;
s->write_flag = write_flag;
if (!s->write_flag)
s->buf_end = buffer;
else
s->buf_end = buffer + buffer_size;
s->opaque = opaque;
s->write_packet = write_packet;
s->read_packet = read_packet;
s->seek = seek;
s->pos = 0;
s->must_flush = 0;
s->eof_reached = 0;
s->is_streamed = 0;
s->max_packet_size = 0;
s->checksum_ptr= NULL;
s->update_checksum= NULL;
return 0;
}
| 1threat |
Is it good to place a recycler view inside a recycler view : I am trying to make an app in which I have added a Horizontal recycler view. I want to make a vertical list of Horizontal Recycler views.
Here, I am trying to make a list of the books of the different category, like I have added list of books in comics category which can be horizontally scrolled.
I wanted to add more such categories. I am trying to do so by making a recycler view inside a recycler view. Is this a right approach? If not!
[Screenshot of my App][1]
[1]: https://i.stack.imgur.com/xd7SG.png
what would be the best approach to do so? | 0debug |
fgets() saving a skipping line char, not skipping inputs : <p>I know there is questions dealing with skipping inputs for <code>fgets()</code>; however i have not found any help with this problem online or asking friends around.</p>
<p>I use:</p>
<pre><code>fgets(tdataMplMsgStrng0_au8, 100, fpread);
</code></pre>
<p>to read a string from a text file and assign it to the string <code>tdataMplMsgStrng0_au8</code>. I have many <code>fgets()</code> before and after this and none are skipping data; however the others are all are converted to integers afterwards, like below:</p>
<pre><code>fgets(temp_s32, 100, fpread);
sint32 tCILXIOD_dataMplMsgDisp4To0_u32 = atoi(temp_s32);
</code></pre>
<p>The problem is when i print this string to a text file it skips an extra line (besides the \n) that none of the others in the same format do:</p>
<pre><code>fprintf(fp, "%s\n", tdataMplMsgStrng0_au8);
</code></pre>
<p>I printed each character in the string and noticed it has a "skipped line" as the character for the last char. I also see a char, 14 and onward, that i am not familiar with.</p>
<p>The code to print to command window:</p>
<pre><code> for (int i = 0; i < 100; i++)
{
printf("\n String[%d]: '%c'", i, tdataMplMsgStrng0_au8[i]);
}
</code></pre>
<p>The output on the command window (Note the text file contains "0jkhjkhkkljh" for the line that sets <code>tdataMplMsgStrng0_au8</code>):</p>
<pre><code>String[0]: '0'
String[1]: 'j'
String[2]: 'k'
String[3]: 'h'
String[4]: 'j'
String[5]: 'k'
String[6]: 'h'
String[7]: 'k'
String[8]: 'k'
String[9]: 'l'
String[10]: 'j'
String[11]: 'h'
String[12]: '
'
String[13]: ' '
String[14]: '|['
String[15]: '|['
String[16]: '|['
</code></pre>
<p>Any help understanding why the "skipping line" char in index 12 is there would be supper helpful. Also just for extra info, it would be nice to know why '|[' is there when i did not enter.</p>
| 0debug |
static void test_validate_alternate(TestInputVisitorData *data,
const void *unused)
{
UserDefAlternate *tmp = NULL;
Visitor *v;
v = validate_test_init(data, "42");
visit_type_UserDefAlternate(v, NULL, &tmp, &error_abort);
qapi_free_UserDefAlternate(tmp);
}
| 1threat |
How to locate a check box based on the following html - Selenium WebDriver and C# : <p>I'm trying to enable specific check boxes contained within a page. Please see the HTML code below</p>
<pre><code><div class="form-horizontal">
<div class="row">
<div class="col-sm-3">
<label for="Url_url_option1">Option 1</label>
</div>
<div class="col-sm-1">
<input type="checkbox" data-yesno-name="Url_option1" class="url-field-toggle">
<span class="glyphicon clickable glyphicon-remove" id="toggle_undefined"></span>
<input id="Url_option1" name="Url.url_option1" type="hidden" value="no">
&nbsp;
</div>
<div class="col-sm-3">
<label for="Url_option2">Option 2</label>
</div>
<div class="col-sm-1">
<input type="checkbox" data-yesno-name="Url_option2" class="url-field-toggle">
<span class="glyphicon clickable glyphicon-remove" id="toggle_undefined"></span>
<input id="Url_option2" name="Url.option2" type="hidden" value="no">
&nbsp;
</div>
<div class="col-sm-3">
<label for="Url_option3">Option 3</label>
</div>
<div class="col-sm-1">
<input type="checkbox" data-yesno-name="Url_option3" class="url-field-toggle">
<span class="glyphicon clickable glyphicon-remove" id="toggle_undefined"></span>
<input id="Url_option3" name="Url.option3" type="hidden" value="no">
&nbsp;
</div>
</div>
<div class="row">
<div class="col-sm-12">
&nbsp;
</div>
</div>
<div class="row">
<div class="col-sm-3">
<label for="Url_option4">Option 4</label>
</div>
<div class="col-sm-1">
<input type="checkbox" data-yesno-name="Url_option4" class="url-field-toggle">
<span class="glyphicon clickable glyphicon-remove" id="toggle_undefined"></span>
<input id="Url_option4" name="Url.option4" type="hidden" value="no">
&nbsp;
</div>
<div class="col-sm-3">
<label for="Url_option5">Option 5</label>
</div>
<div class="col-sm-1">
<input type="checkbox" data-yesno-name="Url_option5" class="url-field-toggle">
<span class="glyphicon clickable glyphicon-remove" id="toggle_undefined"></span>
<input id="Url_option5" name="Url.option5" type="hidden" value="no">
&nbsp;
</div>
<div class="col-sm-3">
<label for="Url_option6">Option 6</label>
</div>
<div class="col-sm-1">
<input type="checkbox" data-yesno-name="Url_option6" class="url-field-toggle">
<span class="glyphicon clickable glyphicon-remove" id="toggle_undefined"></span>
<input id="Url_option6" name="option6" type="hidden" value="no">
&nbsp;
</div>
</div>
</div>
</code></pre>
<p>All of the check box elements apepar to be unique so I can use standard by locators to find each checkbox but, when I try to click on any of them, I can an "Element not found" exception.<br>
Is the "Hidden" type preventing these buttons from being clicked on?</p>
<p>The only way I can sucessfully click on a check box is by finding and clicking on the following element:</p>
<pre><code><span class="glyphicon clickable glyphicon-remove" id="toggle_undefined"></span>
</code></pre>
<p>by using an xpath locator:</p>
<pre><code>//*[@id="toggle_undefined"]
</code></pre>
<p>This works ok. The click event gets fired sucessfully to the checkbox but this will obviously only fire the click to the first element (check box) on the page. </p>
<p>Let's assume I wanted to use this xpath locator to click on the second check box from the second row, how would I make the xpath unique for each element (check box) on the page?</p>
<p>From the HTML code above, this is the second check box from the second row:</p>
<pre><code> <div class="col-sm-3">
<label for="Url_option5">Option 5</label>
</div>
<div class="col-sm-1">
<input type="checkbox" data-yesno-name="Url_option5" class="url-field-toggle">
<span class="glyphicon clickable glyphicon-remove" id="toggle_undefined"></span>
<input id="Url_option5" name="Url.option5" type="hidden" value="no">
&nbsp;
</div>
</code></pre>
| 0debug |
void *qemu_realloc(void *ptr, size_t size)
{
if (!size && !allow_zero_malloc()) {
abort();
}
return oom_check(realloc(ptr, size ? size : 1));
}
| 1threat |
static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
{
pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
pthread_mutex_unlock(&c->current_job_lock);
}
| 1threat |
Submit an array string from codename one to PHP using connection request : <p>Am fetching data from mysqlite to a string array which i want to submit to PHP then update a mysql table.
Any easy way out, because doesn't seem to work?</p>
| 0debug |
Does Room support entity inheritance? : <p>I am trying to migrate our project to use Room, which, by the way, I think is an awesome step forward.</p>
<p>I have the following structure:</p>
<pre><code>public class Entity extends BaseObservable {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "_id", typeAffinity = ColumnInfo.INTEGER)
private long mId;
@ColumnInfo(name = "is_dirty")
@TypeConverters(BooleanTypeConverter.class)
private boolean mIsDirty;
// default constructor and accessors omitted for brevity
}
@Entity(tableName = "some_entities")
public class SomeEntity extends Entity {
@ColumnInfo(name = "type", typeAffinity = ColumnInfo.TEXT)
private String mType;
@ColumnInfo(name = "timestamp", typeAffinity = ColumnInfo.INTEGER)
private long mTimestamp;
// constructor, accessors
}
</code></pre>
<p>When I try to compile my project, it fails with no specific error.</p>
<p>If I try to compile it with a flat entity hierarchy, all is well.</p>
<p>So, my main question is:
Does Room support entity inheritance? Will it be able to get the column definitions from the parent <code>Entity</code> class? </p>
<p>I would also like to know if extending <code>BaseObservable</code> (which I need to get the Data Binding working) can cause problems with Room? <code>BaseObservable</code> has one private transient field, so maybe this is causing some issues with the code generation.</p>
<p>Are there any recommended patterns to deal with this, or will I just have to flatten my entity hierarchy?</p>
| 0debug |
static int kvm_irqchip_get_virq(KVMState *s)
{
uint32_t *word = s->used_gsi_bitmap;
int max_words = ALIGN(s->gsi_count, 32) / 32;
int i, bit;
bool retry = true;
again:
for (i = 0; i < max_words; i++) {
bit = ffs(~word[i]);
if (!bit) {
continue;
}
return bit - 1 + i * 32;
}
if (retry) {
retry = false;
kvm_flush_dynamic_msi_routes(s);
goto again;
}
return -ENOSPC;
}
| 1threat |
Mute a WebView in JavaFX, is it possible? : <p>Very simple. Is it possible to mute or control the volume of a JavaFX WebView? I googled for a while but I can't find any mention of this. I looked at the code for <code>WebView</code> and <code>WebEngine</code> and there doesn't seem to be anything about controlling the volume.</p>
<p>I still need other <code>MediaPlayer</code>s in the same app to work and produce sound, so, I can't mute the whole application.</p>
| 0debug |
AttributeError: 'NoneType' object has no attribute 'attname' (Django) : <p>I have a fairly complex model for which the first call to <code>MyModel.objects.create(**kwargs)</code> fails with</p>
<blockquote>
<p>AttributeError: 'NoneType' object has no attribute 'attname'</p>
</blockquote>
<p>The stack trace dives down like this (in Django 1.11)</p>
<pre><code>django/db/models/manager.py:85: in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
django/db/models/query.py:394: in create
obj.save(force_insert=True, using=self.db)
django/db/models/base.py:807: in save
force_update=force_update, update_fields=update_fields)
django/db/models/base.py:837: in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
django/db/models/base.py:889: in _save_table
pk_val = self._get_pk_val(meta)
django/db/models/base.py:644: in _get_pk_val
return getattr(self, meta.pk.attname)
django/db/models/query_utils.py:114: in __get__
val = self._check_parent_chain(instance, self.field_name)
django/db/models/query_utils.py:131: in __check_parent_chain
return getattr(instance, link_field.attname)
</code></pre>
<p>The model definition looks alright to me. I have checked all the parameters of the <code>create</code> call are just what I want them to be.</p>
<p>I'm not keen on stripping down the model to find the problem, because the model is so complex. (All my other models, many of them similar, appear to work fine.)</p>
<p>So what might cause this strange message?</p>
| 0debug |
void commit_start(BlockDriverState *bs, BlockDriverState *base,
BlockDriverState *top, int64_t speed,
BlockdevOnError on_error, BlockCompletionFunc *cb,
void *opaque, const char *backing_file_str, Error **errp)
{
CommitBlockJob *s;
BlockReopenQueue *reopen_queue = NULL;
int orig_overlay_flags;
int orig_base_flags;
BlockDriverState *overlay_bs;
Error *local_err = NULL;
assert(top != bs);
if (top == base) {
error_setg(errp, "Invalid files for merge: top and base are the same");
return;
}
overlay_bs = bdrv_find_overlay(bs, top);
if (overlay_bs == NULL) {
error_setg(errp, "Could not find overlay image for %s:", top->filename);
return;
}
s = block_job_create(&commit_job_driver, bs, speed, cb, opaque, errp);
if (!s) {
return;
}
orig_base_flags = bdrv_get_flags(base);
orig_overlay_flags = bdrv_get_flags(overlay_bs);
if (!(orig_overlay_flags & BDRV_O_RDWR)) {
reopen_queue = bdrv_reopen_queue(reopen_queue, overlay_bs, NULL,
orig_overlay_flags | BDRV_O_RDWR);
}
if (!(orig_base_flags & BDRV_O_RDWR)) {
reopen_queue = bdrv_reopen_queue(reopen_queue, base, NULL,
orig_base_flags | BDRV_O_RDWR);
}
if (reopen_queue) {
bdrv_reopen_multiple(reopen_queue, &local_err);
if (local_err != NULL) {
error_propagate(errp, local_err);
block_job_unref(&s->common);
return;
}
}
s->base = blk_new();
blk_insert_bs(s->base, base);
s->top = blk_new();
blk_insert_bs(s->top, top);
s->active = bs;
s->base_flags = orig_base_flags;
s->orig_overlay_flags = orig_overlay_flags;
s->backing_file_str = g_strdup(backing_file_str);
s->on_error = on_error;
s->common.co = qemu_coroutine_create(commit_run);
trace_commit_start(bs, base, top, s, s->common.co, opaque);
qemu_coroutine_enter(s->common.co, s);
}
| 1threat |
Slicing string in a dataframe : I have the following dataframe imported from a csv file:
Speed event_id event_params gps_lng
0 0 Down "type":"Down","maximumangle":0,"duration":0 -81.98
1 0 Left "type":"Left","maximumangle":-38.57,"duration"... -81.98
2 0 Right "type":"Right","maximumangle":52.975,"duration... -81.98
3 0 Down "type":"Down","maximumangle":0,"duration":0 -81.98
4 0 Down "type":"Down","maximumangle":0,"duration":0 -81.98
I need to split the event_params column into separate columns with headers- Type, Maximum Angle and Duration, and I need to get rid of curly braces. In short I need the following output.
ts employee_id gps_lat gps_lng event_id Type maximumangle duration speed status serial_number Duration
0 9/22/2016 13:53 1 34.97 -81.98 Down Down 0 0 0 1100110 211
1 9/22/2016 13:53 1 34.97 -81.98 Left Left -38.57 203 0 1102110 212 0 days 00:00:03.000000000
2 9/22/2016 13:53 1 34.97 -81.98 Right Right 52.975 17 0 1102130 250 0 days 00:00:23.000000000
3 9/22/2016 13:53 1 34.97 -81.98 Down Down 0 0 0 1102130 249 0 days 00:00:00.000000000
4 9/22/2016 13:54 1 34.97 -81.98 Down Down 0 0 0 1102140 280 0 days 00:00:42.000000000
I am trying to approach the problem by spliting it first about : delimiter, then splitting the last column by } and then deleting the columns with contents maximum angle and duration.
I have been trying to use the re.split function in the following way but it returns error--expected string or bytes-like object
import re
parts = re.split('\df3|(?<!\d)[:.](?!\d)', df3)
parts
Kindly suggest.
| 0debug |
Python All my keys are using the same values : <p>I have a problem with my code! I am in the process of making a program that will create a file that will store words alongside thee definitions using dictionaries. So far, I have gotten it to work the way I intended, but when I see the results, each key that returns all have the same value. Why/</p>
<pre><code>words = {}
word = raw_input("What word is it? ")
definition = raw_input("What's the meaning of the word ")
words[word] = definition
addition = raw_input('Have another word you need to remember? Y/N ')
while addition == "Y":
word = raw_input("What word is it? ")
definition = raw_input("What's the meaning of the word ")
words[word] = definition
addition = raw_input('Have another word you need to rememeber? Y/N ')
# How to get my key to display the correct information.
for key, value in words.items():
print(key + ": " + definition)
f = open("Dcitionary.txt", "w")
for key, value in words.items():
f.write(key + ": " + definition)
f.close
</code></pre>
| 0debug |
socket.io connection event not firing in firefox : <p>Im having something like the below code.</p>
<pre><code><script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost:8080');
socket.on('connect', function(){
socket.on('some-event', function(data) {});
});
socket.on('disconnect', function(){});
</script>
</code></pre>
<p>Inside the connect callback I have some code that responds to messages. This works perfectly fine on chrome. On first page load it works fine on firefox. If you reload the page then the connect event does not get called.</p>
<p>Im using 1.4.8 version of server and js client</p>
| 0debug |
int update_dimensions(VP8Context *s, int width, int height, int is_vp7)
{
AVCodecContext *avctx = s->avctx;
int i, ret;
if (width != s->avctx->width ||
height != s->avctx->height) {
vp8_decode_flush_impl(s->avctx, 1);
ret = ff_set_dimensions(s->avctx, width, height);
if (ret < 0)
return ret;
}
s->mb_width = (s->avctx->coded_width + 15) / 16;
s->mb_height = (s->avctx->coded_height + 15) / 16;
s->mb_layout = is_vp7 || avctx->active_thread_type == FF_THREAD_SLICE &&
FFMIN(s->num_coeff_partitions, avctx->thread_count) > 1;
if (!s->mb_layout) {
s->macroblocks_base = av_mallocz((s->mb_width + s->mb_height * 2 + 1) *
sizeof(*s->macroblocks));
s->intra4x4_pred_mode_top = av_mallocz(s->mb_width * 4);
} else
s->macroblocks_base = av_mallocz((s->mb_width + 2) * (s->mb_height + 2) *
sizeof(*s->macroblocks));
s->top_nnz = av_mallocz(s->mb_width * sizeof(*s->top_nnz));
s->top_border = av_mallocz((s->mb_width + 1) * sizeof(*s->top_border));
s->thread_data = av_mallocz(MAX_THREADS * sizeof(VP8ThreadData));
for (i = 0; i < MAX_THREADS; i++) {
s->thread_data[i].filter_strength =
av_mallocz(s->mb_width * sizeof(*s->thread_data[0].filter_strength));
#if HAVE_THREADS
pthread_mutex_init(&s->thread_data[i].lock, NULL);
pthread_cond_init(&s->thread_data[i].cond, NULL);
#endif
}
if (!s->macroblocks_base || !s->top_nnz || !s->top_border ||
(!s->intra4x4_pred_mode_top && !s->mb_layout))
return AVERROR(ENOMEM);
s->macroblocks = s->macroblocks_base + 1;
return 0;
}
| 1threat |
Destructuring array get second value? : <p>How to get array using destructing? </p>
<pre><code>const num = [1,2,3,4,5];
const [ first ] = num; //1
</code></pre>
<p><code>console.log(first)</code> I'm able to get 1, but when I try to do <code>const [ null, second ] = num</code> it has expected token error. How to get 2nd item of num array?</p>
| 0debug |
static void mb_cpu_initfn(Object *obj)
{
CPUState *cs = CPU(obj);
MicroBlazeCPU *cpu = MICROBLAZE_CPU(obj);
CPUMBState *env = &cpu->env;
static bool tcg_initialized;
cs->env_ptr = env;
cpu_exec_init(cs, &error_abort);
set_float_rounding_mode(float_round_nearest_even, &env->fp_status);
#ifndef CONFIG_USER_ONLY
qdev_init_gpio_in(DEVICE(cpu), microblaze_cpu_set_irq, 2);
#endif
if (tcg_enabled() && !tcg_initialized) {
tcg_initialized = true;
mb_tcg_init();
}
}
| 1threat |
void tlb_fill(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
uintptr_t retaddr)
{
bool ret;
uint32_t fsr = 0;
ARMMMUFaultInfo fi = {};
ret = arm_tlb_fill(cs, addr, is_write, mmu_idx, &fsr, &fi);
if (unlikely(ret)) {
ARMCPU *cpu = ARM_CPU(cs);
CPUARMState *env = &cpu->env;
uint32_t syn, exc;
unsigned int target_el;
bool same_el;
if (retaddr) {
cpu_restore_state(cs, retaddr);
}
target_el = exception_target_el(env);
if (fi.stage2) {
target_el = 2;
env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
}
same_el = arm_current_el(env) == target_el;
syn = fsr & ~(1 << 9);
if (is_write == 2) {
syn = syn_insn_abort(same_el, 0, fi.s1ptw, syn);
exc = EXCP_PREFETCH_ABORT;
} else {
syn = syn_data_abort(same_el, 0, 0, fi.s1ptw, is_write == 1, syn);
if (is_write == 1 && arm_feature(env, ARM_FEATURE_V6)) {
fsr |= (1 << 11);
}
exc = EXCP_DATA_ABORT;
}
env->exception.vaddress = addr;
env->exception.fsr = fsr;
raise_exception(env, exc, syn, target_el);
}
}
| 1threat |
How to write the below snippet in python? : <pre><code>if(stuckSomewhere()||lost() == true)
{
stuckSomewhere().stop();
lost().stop();
debugAvailableOptions();
}
</code></pre>
<p>I'm pretty much newbie for python. I was exploring python but I'm unable to come to a solution for this snippet. </p>
| 0debug |
static int ram_save_complete(QEMUFile *f, void *opaque)
{
rcu_read_lock();
migration_bitmap_sync();
ram_control_before_iterate(f, RAM_CONTROL_FINISH);
while (true) {
int pages;
pages = ram_find_and_save_block(f, true, &bytes_transferred);
if (pages == 0) {
break;
}
}
flush_compressed_data(f);
ram_control_after_iterate(f, RAM_CONTROL_FINISH);
migration_end();
rcu_read_unlock();
qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
return 0;
}
| 1threat |
static int raw_write(BlockDriverState *bs, int64_t sector_num,
const uint8_t *buf, int nb_sectors)
{
if (check_write_unsafe(bs, sector_num, buf, nb_sectors)) {
int ret;
ret = raw_write_scrubbed_bootsect(bs, buf);
if (ret < 0) {
return ret;
}
ret = bdrv_write(bs->file, 1, buf + 512, nb_sectors - 1);
if (ret < 0) {
return ret;
}
return ret + 512;
}
return bdrv_write(bs->file, sector_num, buf, nb_sectors);
}
| 1threat |
void helper_sysret(CPUX86State *env, int dflag)
{
int cpl, selector;
if (!(env->efer & MSR_EFER_SCE)) {
raise_exception_err(env, EXCP06_ILLOP, 0);
}
cpl = env->hflags & HF_CPL_MASK;
if (!(env->cr[0] & CR0_PE_MASK) || cpl != 0) {
raise_exception_err(env, EXCP0D_GPF, 0);
}
selector = (env->star >> 48) & 0xffff;
if (env->hflags & HF_LMA_MASK) {
cpu_load_eflags(env, (uint32_t)(env->regs[11]), TF_MASK | AC_MASK
| ID_MASK | IF_MASK | IOPL_MASK | VM_MASK | RF_MASK |
NT_MASK);
if (dflag == 2) {
cpu_x86_load_seg_cache(env, R_CS, (selector + 16) | 3,
0, 0xffffffff,
DESC_G_MASK | DESC_P_MASK |
DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK |
DESC_L_MASK);
env->eip = env->regs[R_ECX];
} else {
cpu_x86_load_seg_cache(env, R_CS, selector | 3,
0, 0xffffffff,
DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);
env->eip = (uint32_t)env->regs[R_ECX];
}
cpu_x86_load_seg_cache(env, R_SS, selector + 8,
0, 0xffffffff,
DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
DESC_W_MASK | DESC_A_MASK);
cpu_x86_set_cpl(env, 3);
} else {
env->eflags |= IF_MASK;
cpu_x86_load_seg_cache(env, R_CS, selector | 3,
0, 0xffffffff,
DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);
env->eip = (uint32_t)env->regs[R_ECX];
cpu_x86_load_seg_cache(env, R_SS, selector + 8,
0, 0xffffffff,
DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
DESC_W_MASK | DESC_A_MASK);
cpu_x86_set_cpl(env, 3);
}
}
| 1threat |
could someone explain how this code can be reversed? (recursion) : got code from Pierre Fourgeaud (internet) but i cant understand how it can be reversed?
void reverse( string& word )
{
if ( word.size() <= 1 ) return;
// Get the string without the first and the last char
string temp = word.substr( 1, word.size() - 2 );
// Reverse it
reverse( temp );
// Recompose the string
word = word.substr( word.size() - 1 ) + temp + word[0];
}
thanks. | 0debug |
Find an easy web server framework for mobile game : <p>I need a web server to provide api interface like login/ranking for a mobile game, which web framework should I use, I primary program C++ before.</p>
| 0debug |
Where a thread object is created in stack or in heap memory? : <p>Actually I was asked this question recently in an interview , I answered stack , am I right as I thought that threads would be executing methods, but could you please explain as why threads get created in stack or if not then why is it created in heap.</p>
<p>Thanks in advance</p>
| 0debug |
How to remove character outside a string from a tab delimited text : <p>I have a file lets say "Mrinq_Parts_Available.txt" which looks like this.</p>
<pre><code>Source Date Category SubCategory Present Description Value Units Vendor Part No Package Box Name Location Quantity Ordered Used MOQ=1 MOQ=100 MOQ=1000 Comments Link
Digikey 29-May-15 RF Amplifier No 0.5 W RFMD RFPA3807 SOIC8 10 0 3.4 5V http://www.digikey.com/product-detail/en/RFPA3807TR13/689-1073-1-ND/2567207
</code></pre>
<p>I have a python code which does split of those lines.</p>
<pre><code>def removeEmptyLines(inputFile):
with open(inputFile, 'rb') as f:
d = f.readlines()
k = []
for i in d:
k.append(i.split())
print (k)
if __name__=="__main__":
parts_database_file = "Mrinq_Parts_Available.txt"
removeEmptyLines(parts_database_file)
</code></pre>
<p>But the output is shown like this:</p>
<pre><code>[b'Source', b'Date', b'Category', b'SubCategory', b'Present', b'Description', b'Value', b'Units', b'Vendor', b'Part', b'No', b'Package', b'Box', b'Name', b'Location', b'Quantity', b'Ordered', b'Used', b'MOQ=1', b'MOQ=100', b'MOQ=1000', b'Comments', b'Link']
[b'Digikey', b'29-May-15', b'RF', b'Amplifier', b'No', b'0.5', b'W', b'RFMD', b'RFPA3807', b'SOIC8', b'10', b'0', b'3.4', b'5V', b'http://www.digikey.com/product-detail/en/RFPA3807TR13/689-1073-1-ND/2567207']
</code></pre>
<p>How do I remove the 'b' preceding each parsed data?</p>
| 0debug |
Use print instead of return, why? : Why this doesn't work?
from random import randint
def jump():
return randint(1, 6)
jump()
Why do I have to use `print` instead of `return`? | 0debug |
Intent getting null in onReceive in MyAlarm class even though I sat putEctra while sending intent : MainActivity:
package com.jimmytrivedi.alarmdemo;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = MainActivity.class.getSimpleName();
@BindView(R.id.timePicker)
TimePicker timePicker;
@BindView(R.id.buttonAlarm)
Button buttonAlarm;
@BindView(R.id.cancelAlarm)
Button cancelAlarm;
private AlarmManager alarmManager;
private PendingIntent pendingIntent;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
cancelAlarm.setEnabled(false);
selClickListener();
}
private void selClickListener() {
buttonAlarm.setOnClickListener(this);
cancelAlarm.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.buttonAlarm:
Calendar calendar = Calendar.getInstance();
if (Build.VERSION.SDK_INT >= 23) {
calendar.set(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getHour(), timePicker.getMinute(), 0);
} else {
calendar.set(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
}
setAlarm(calendar.getTimeInMillis());
showLog("getTimeInMillis: "+calendar.getTimeInMillis() );
cancelAlarm.setEnabled(true);
break;
case R.id.cancelAlarm:
cancelAlarm();
break;
}
}
private void setAlarm(long time) {
//creating a new intent specifying the broadcast receiver
Intent intent = new Intent(this, MyAlarm.class);
intent.putExtra("REMINDER_ID", "1");
//creating a pending intent using the intent
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
//setting the repeating alarm that will be fired every day
alarmManager.setRepeating(AlarmManager.RTC, time, AlarmManager.INTERVAL_DAY, pendingIntent);
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}
private void cancelAlarm() {
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.cancel(pendingIntent);
Toast.makeText(this, "Canceled", Toast.LENGTH_SHORT).show();
}
private void showLog(String msg) {
Log.d(TAG, msg);
}
}
----------------------
setAlarm:
private void setAlarm(long time) {
//creating a new intent specifying the broadcast receiver
Intent intent = new Intent(this, MyAlarm.class);
intent.putExtra("REMINDER_ID", "1");
//creating a pending intent using the intent
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
//setting the repeating alarm that will be fired every day
alarmManager.setRepeating(AlarmManager.RTC, time, AlarmManager.INTERVAL_DAY, pendingIntent);
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}
MyAlarm class:
package com.jimmytrivedi.alarmdemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.provider.Settings;
import android.util.Log;
public class MyAlarm extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String id = intent.getStringExtra("REMINDER_ID");
Log.d("Test", "ID: "+ id) ;
MediaPlayer mediaPlayer = MediaPlayer.create(context, Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
Log.d("Test", "Alarm just fired") ;
}
}
Don't know why intent is getting null? BTW, onReceived called and works other things. Reminder is also coming. And I printed logs also, This: (Log.d("Test", "Alarm just fired") ;) is also printing.
Why?
Any help?
Looks like mostly code, so added some random article:
It looks like your post is mostly code; please add some more details
An article (with the linguistic glossing abbreviation art) is a word that is used with a noun (as a standalone word or a prefix or suffix) to specify grammatical definiteness of the noun, and in some languages extending to volume or numerical scope.
The articles in English grammar are the and a/an, and in certain contexts some. "An" and "a" are modern forms of the Old English "an", which in Anglian dialects was the number "one" (compare "on" in Saxon dialects) and survived into Modern Scots as the number "owan". Both "on" (respelled "one" by the Norman language) and "an" survived into Modern English, with "one" used as the number and "an" ("a", before nouns that begin with a consonant sound) as an indefinite article.
In many languages, articles are a special part of speech which cannot be easily combined[clarification needed] with other parts of speech. In English grammar, articles are frequently considered part of a broader category called determiners, which contains articles, demonstratives (such as "this" and "that"), possessive determiners (such as "my" and "his"), and quantifiers (such as "all" and "few").[1] Articles and other determiners are also sometimes counted as a type of adjective, since they describe the words that they precede.[2]
In languages that employ articles, every common noun, with some exceptions, is expressed with a certain definiteness, definite or indefinite, as an attribute (similar to the way many languages express every noun with a certain grammatical number—singular or plural—or a grammatical gender). Articles are among the most common words in many languages; in English, for example, the most frequent word is the.[3]
Articles are usually categorized as either definite or indefinite.[4] A few languages with well-developed systems of articles may distinguish additional subtypes. Within each type, languages may have various forms of each article, due to conforming to grammatical attributes such as gender, number, or case. Articles may also be modified as influenced by adjacent sounds or words as in elision (e.g., French "le" becoming "l'" before a vowel), epenthesis (e.g., English "a" becoming "an" before a vowel), or contraction (e.g. Irish "i + na" becoming "sna").
| 0debug |
static int mpeg1_decode_sequence(AVCodecContext *avctx,
const uint8_t *buf, int buf_size)
{
Mpeg1Context *s1 = avctx->priv_data;
MpegEncContext *s = &s1->mpeg_enc_ctx;
int width, height;
int i, v, j;
init_get_bits(&s->gb, buf, buf_size * 8);
width = get_bits(&s->gb, 12);
height = get_bits(&s->gb, 12);
if (width == 0 || height == 0) {
av_log(avctx, AV_LOG_WARNING,
"Invalid horizontal or vertical size value.\n");
if (avctx->err_recognition & (AV_EF_BITSTREAM | AV_EF_COMPLIANT))
return AVERROR_INVALIDDATA;
}
s->aspect_ratio_info = get_bits(&s->gb, 4);
if (s->aspect_ratio_info == 0) {
av_log(avctx, AV_LOG_ERROR, "aspect ratio has forbidden 0 value\n");
if (avctx->err_recognition & (AV_EF_BITSTREAM | AV_EF_COMPLIANT))
return AVERROR_INVALIDDATA;
}
s->frame_rate_index = get_bits(&s->gb, 4);
if (s->frame_rate_index == 0 || s->frame_rate_index > 13) {
av_log(avctx, AV_LOG_WARNING,
"frame_rate_index %d is invalid\n", s->frame_rate_index);
s->frame_rate_index = 1;
}
s->bit_rate = get_bits(&s->gb, 18) * 400;
if (get_bits1(&s->gb) == 0) {
av_log(avctx, AV_LOG_ERROR, "Marker in sequence header missing\n");
return AVERROR_INVALIDDATA;
}
s->width = width;
s->height = height;
s->avctx->rc_buffer_size = get_bits(&s->gb, 10) * 1024 * 16;
skip_bits(&s->gb, 1);
if (get_bits1(&s->gb)) {
load_matrix(s, s->chroma_intra_matrix, s->intra_matrix, 1);
} else {
for (i = 0; i < 64; i++) {
j = s->idsp.idct_permutation[i];
v = ff_mpeg1_default_intra_matrix[i];
s->intra_matrix[j] = v;
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(&s->gb)) {
load_matrix(s, s->chroma_inter_matrix, s->inter_matrix, 0);
} else {
for (i = 0; i < 64; i++) {
int j = s->idsp.idct_permutation[i];
v = ff_mpeg1_default_non_intra_matrix[i];
s->inter_matrix[j] = v;
s->chroma_inter_matrix[j] = v;
}
}
if (show_bits(&s->gb, 23) != 0) {
av_log(s->avctx, AV_LOG_ERROR, "sequence header damaged\n");
return AVERROR_INVALIDDATA;
}
s->progressive_sequence = 1;
s->progressive_frame = 1;
s->picture_structure = PICT_FRAME;
s->first_field = 0;
s->frame_pred_frame_dct = 1;
s->chroma_format = 1;
s->codec_id =
s->avctx->codec_id = AV_CODEC_ID_MPEG1VIDEO;
s->out_format = FMT_MPEG1;
s->swap_uv = 0;
if (s->flags & CODEC_FLAG_LOW_DELAY)
s->low_delay = 1;
if (s->avctx->debug & FF_DEBUG_PICT_INFO)
av_log(s->avctx, AV_LOG_DEBUG, "vbv buffer: %d, bitrate:%d, aspect_ratio_info: %d \n",
s->avctx->rc_buffer_size, s->bit_rate, s->aspect_ratio_info);
return 0;
}
| 1threat |
static void socket_start_incoming_migration(SocketAddressLegacy *saddr,
Error **errp)
{
QIOChannelSocket *listen_ioc = qio_channel_socket_new();
qio_channel_set_name(QIO_CHANNEL(listen_ioc),
"migration-socket-listener");
if (qio_channel_socket_listen_sync(listen_ioc, saddr, errp) < 0) {
object_unref(OBJECT(listen_ioc));
qapi_free_SocketAddressLegacy(saddr);
return;
}
qio_channel_add_watch(QIO_CHANNEL(listen_ioc),
G_IO_IN,
socket_accept_incoming_migration,
listen_ioc,
(GDestroyNotify)object_unref);
qapi_free_SocketAddressLegacy(saddr);
}
| 1threat |
Why 'scanner is never closed ' don't disappear? : [Source Code][1]
Why in the 13 Line, Despite I wrote 'scanner.close() in Line 46', Warning about scanner is not disappear?
[1]: https://i.stack.imgur.com/uJIet.jpg | 0debug |
How to itierate over objects in an array? : I have an array object as mentioned below;
var myArray=[{dateformat:"apr1", score:1},{dateformat:"apr2",score:2},{dateformat:"apr3",score:3}];
I would like to extract the values of dateformat into seperate array fex.
var dateArray=["apr1","apr2","apr3"];
var score=[1,2,3];
I am using for loop to extract the index but not able to get the values....
Your help will be appreciated | 0debug |
int ff_new_chapter(AVFormatContext *s, int id, int64_t start, int64_t end, const char *title)
{
AVChapter *chapter = NULL;
int i;
for(i=0; i<s->num_chapters; i++)
if(s->chapters[i]->id == id)
chapter = s->chapters[i];
if(!chapter){
chapter= av_mallocz(sizeof(AVChapter));
if(!chapter)
return AVERROR(ENOMEM);
dynarray_add(&s->chapters, &s->num_chapters, chapter);
}
if(chapter->title)
av_free(chapter->title);
if (title)
chapter->title = av_strdup(title);
chapter->id = id;
chapter->start = start;
chapter->end = end;
return 0;
}
| 1threat |
Unable to inject ActivatedRouteSnapshot : <p>Injecting ActivatedRouteSnapshot into a component is not working (and neither is injecting ActivatedRoute). Here the stack trace:</p>
<pre><code>"Error: Can't resolve all parameters for ActivatedRouteSnapshot: (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?).
at SyntaxError.ZoneAwareError (http://localhost:4200/polyfills.bundle.js:7042:33)
at SyntaxError.BaseError [as constructor] (http://localhost:4200/vendor.bundle.js:73735:16)
at new SyntaxError (http://localhost:4200/vendor.bundle.js:6140:16)
at CompileMetadataResolver._getDependenciesMetadata (http://localhost:4200/vendor.bundle.js:19345:31)
at CompileMetadataResolver._getTypeMetadata (http://localhost:4200/vendor.bundle.js:19220:26)
at CompileMetadataResolver._getInjectableMetadata (http://localhost:4200/vendor.bundle.js:19208:21)
at CompileMetadataResolver.getProviderMetadata (http://localhost:4200/vendor.bundle.js:19450:40)
at http://localhost:4200/vendor.bundle.js:19408:49
at Array.forEach (native)
at CompileMetadataResolver._getProvidersMetadata (http://localhost:4200/vendor.bundle.js:19375:19)
at CompileMetadataResolver.getNonNormalizedDirectiveMetadata (http://localhost:4200/vendor.bundle.js:18848:30)
at CompileMetadataResolver._loadDirectiveMetadata (http://localhost:4200/vendor.bundle.js:18736:23)
at http://localhost:4200/vendor.bundle.js:18937:54
at Array.forEach (native)
at CompileMetadataResolver.loadNgModuleDirectiveAndPipeMetadata (http://localhost:4200/vendor.bundle.js:18936:41)"
</code></pre>
<hr>
<p>In the component, ActivatedRouteSnapshot is injected as follows:</p>
<pre><code>constructor([...], private router: Router,
private route: ActivatedRouteSnapshot) {
[...]
}
</code></pre>
<hr>
<p>ActivatedRouteSnapshot is provided in <code>app.component.ts</code>:</p>
<pre><code>@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [[...], ActivatedRouteSnapshot]
})
</code></pre>
<hr>
<p>I'm trying to access the query params similarly to how it is done here: <a href="https://stackoverflow.com/a/38997116/3433306">https://stackoverflow.com/a/38997116/3433306</a></p>
<p>According to the docs it should be as simple as adding it to the constructor parameters: <a href="https://angular.io/docs/ts/latest/api/router/index/ActivatedRouteSnapshot-interface.html" rel="noreferrer">https://angular.io/docs/ts/latest/api/router/index/ActivatedRouteSnapshot-interface.html</a></p>
<p>What am I missing to successfully inject ActivatedRouteSnapshot?</p>
| 0debug |
Google maps, update directions on click : <p>I need to show 3 different routes to the same point on google maps (or any maps as an alternative), on my website, so I have map shown on the top, and three clickable boxes under it, and when a user click on specific box the map would show direction according to it. Example image attached, from viamichelin site. To be more clear, I have same end point for all 3 cases, but different start points.
What would be the best approach here, I couldn't find anything regards this in gmaps documentation? Thanks!
<a href="https://i.stack.imgur.com/Aq3aZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Aq3aZ.jpg" alt="enter image description here"></a></p>
| 0debug |
int ff_mjpeg_decode_sos(MJpegDecodeContext *s, const uint8_t *mb_bitmask,
int mb_bitmask_size, const AVFrame *reference)
{
int len, nb_components, i, h, v, predictor, point_transform;
int index, id, ret;
const int block_size = s->lossless ? 1 : 8;
int ilv, prev_shift;
if (!s->got_picture) {
av_log(s->avctx, AV_LOG_WARNING,
"Can not process SOS before SOF, skipping\n");
return -1;
av_assert0(s->picture_ptr->data[0]);
len = get_bits(&s->gb, 16);
nb_components = get_bits(&s->gb, 8);
if (nb_components == 0 || nb_components > MAX_COMPONENTS) {
avpriv_report_missing_feature(s->avctx,
"decode_sos: nb_components (%d)",
nb_components);
return AVERROR_PATCHWELCOME;
if (len != 6 + 2 * nb_components) {
av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
for (i = 0; i < nb_components; i++) {
id = get_bits(&s->gb, 8) - 1;
av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
for (index = 0; index < s->nb_components; index++)
if (id == s->component_id[index])
break;
if (index == s->nb_components) {
av_log(s->avctx, AV_LOG_ERROR,
"decode_sos: index(%d) out of components\n", index);
if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
&& nb_components == 3 && s->nb_components == 3 && i)
index = 3 - i;
s->quant_sindex[i] = s->quant_index[index];
s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
s->h_scount[i] = s->h_count[index];
s->v_scount[i] = s->v_count[index];
if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
index = (i+2)%3;
if(nb_components == 1 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
index = (index+2)%3;
s->comp_index[i] = index;
s->dc_index[i] = get_bits(&s->gb, 4);
s->ac_index[i] = get_bits(&s->gb, 4);
if (s->dc_index[i] < 0 || s->ac_index[i] < 0 ||
s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
goto out_of_range;
if (!s->vlcs[0][s->dc_index[i]].table || !(s->progressive ? s->vlcs[2][s->ac_index[0]].table : s->vlcs[1][s->ac_index[i]].table))
goto out_of_range;
predictor = get_bits(&s->gb, 8);
ilv = get_bits(&s->gb, 8);
if(s->avctx->codec_tag != AV_RL32("CJPG")){
prev_shift = get_bits(&s->gb, 4);
point_transform = get_bits(&s->gb, 4);
}else
prev_shift = point_transform = 0;
if (nb_components > 1) {
s->mb_width = (s->width + s->h_max * block_size - 1) / (s->h_max * block_size);
s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
} else if (!s->ls) {
h = s->h_max / s->h_scount[0];
v = s->v_max / s->v_scount[0];
s->mb_width = (s->width + h * block_size - 1) / (h * block_size);
s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
s->nb_blocks[0] = 1;
s->h_scount[0] = 1;
s->v_scount[0] = 1;
if (s->avctx->debug & FF_DEBUG_PICT_INFO)
av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d skip:%d %s comp:%d\n",
s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
predictor, point_transform, ilv, s->bits, s->mjpb_skiptosod,
s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), nb_components);
for (i = s->mjpb_skiptosod; i > 0; i--)
skip_bits(&s->gb, 8);
next_field:
for (i = 0; i < nb_components; i++)
s->last_dc[i] = (4 << s->bits);
if (s->lossless) {
av_assert0(s->picture_ptr == s->picture);
if (CONFIG_JPEGLS_DECODER && s->ls) {
if ((ret = ff_jpegls_decode_picture(s, predictor,
point_transform, ilv)) < 0)
return ret;
} else {
if (s->rgb) {
if ((ret = ljpeg_decode_rgb_scan(s, nb_components, predictor, point_transform)) < 0)
return ret;
} else {
if ((ret = ljpeg_decode_yuv_scan(s, predictor,
point_transform,
nb_components)) < 0)
return ret;
} else {
if (s->progressive && predictor) {
av_assert0(s->picture_ptr == s->picture);
if ((ret = mjpeg_decode_scan_progressive_ac(s, predictor,
ilv, prev_shift,
point_transform)) < 0)
return ret;
} else {
if ((ret = mjpeg_decode_scan(s, nb_components,
prev_shift, point_transform,
mb_bitmask, mb_bitmask_size, reference)) < 0)
return ret;
if (s->interlaced &&
get_bits_left(&s->gb) > 32 &&
show_bits(&s->gb, 8) == 0xFF) {
GetBitContext bak = s->gb;
align_get_bits(&bak);
if (show_bits(&bak, 16) == 0xFFD1) {
av_log(s->avctx, AV_LOG_DEBUG, "AVRn interlaced picture marker found\n");
s->gb = bak;
skip_bits(&s->gb, 16);
s->bottom_field ^= 1;
goto next_field;
emms_c();
return 0;
out_of_range:
av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n"); | 1threat |
C# framework 2.0 Return two value from method : <p>i create a dll with C# framework 2.0 and want use that in another applications...
but i have a problem
i cannot return two value from method
for example: </p>
<pre><code> public string Two_String_Returner()
{
int aa = 50;
string bb = "Hello";
return aa.ToString();
return bb;
}
</code></pre>
<p>1-i must return two value, once is int and another is string
2- this return should be Apart from each other</p>
<p>i how can do this?</p>
| 0debug |
open form on html button click in asp.net using C# : <p>will any body help me in opening a form on button click?? Thanks in advance.</p>
<p><strong>aspx.cs Code:</strong></p>
<pre><code> public string wogrid()
{
string htmlStr = "";
con.COpen();
string qry = "SELECT id,casetype,Case when status_c=1 then 'Active' else 'Inactive' End as status_c FROM t_claimtype";
SqlDataReader rd = gd.DataReader(qry);
while (rd.Read())
{
int ID = Convert.ToInt16(rd["id"].ToString());
string caseType = rd["casetype"].ToString();
string status = rd["status_c"].ToString();
htmlStr += "<tr><td>" + ID + "</td>" + "<td>" + caseType + "</td>" + "<td>" + status + "</td>" + "<td>" + "<input type='submit' id='" + (rd)["ID"].ToString() + "' name='edit' value='EDIT' **onclick='windows.open(viewClaims.aspx)'** runat='server' />" + "</td></tr>";
}
con.cClose();
return htmlStr;
}
private void AddPlanToCart()
{
Response.Redirect("viewClaims.aspx");
}
</code></pre>
| 0debug |
Appcelerator Studio apps does not run after El Capitan Update. Invalid Request on compile : <p>As the title says, After I have updated my OS to El Capitan all my apps on Appcelerator Studio does not build successfully anymore. Even newly created sample apps does not build. I only get a very generic error message from the console.</p>
<p>My app is targeted for iOS and Android and it does not work for both. I get the same error message as below.</p>
<pre><code>[INFO] : ----- OPTIMIZING -----
[INFO] : - android/alloy.js
[INFO] : - android/alloy/sync/localStorage.js
[INFO] : - android/alloy/sync/properties.js
[INFO] : - android/alloy/sync/sql.js
[INFO] :
[INFO] : Alloy compiled in 1.48612s
[INFO] : Alloy compiler completed successfully
[ERROR] : invalid request
</code></pre>
<p>How to resolve this? I already tried to project clean multiple times.</p>
| 0debug |
static void up_heap(uint32_t val, uint32_t *heap, uint32_t *weights)
{
uint32_t initial_val = heap[val];
while (weights[initial_val] < weights[heap[val >> 1]]) {
heap[val] = heap[val >> 1];
val >>= 1;
}
heap[val] = initial_val;
}
| 1threat |
How to check the docker-compose file version? : <p>I would like to make sure that I'm using version 3 of the compose file format. However, on <a href="https://docs.docker.com/compose/compose-file/" rel="noreferrer">https://docs.docker.com/compose/compose-file/</a> I was not able to find out how to do this.</p>
<p>My Docker version is <code>17.04.0-ce, build 4845c56</code>, and my Docker-Compose version is <code>docker-compose version 1.9.0, build 2585387</code>. I'm not sure since when version 3 of the compose file format was introduced, however. How can I find this out?</p>
| 0debug |
static void qxl_log_cmd_draw(PCIQXLDevice *qxl, QXLDrawable *draw, int group_id)
{
fprintf(stderr, ": surface_id %d type %s effect %s",
draw->surface_id,
qxl_name(qxl_draw_type, draw->type),
qxl_name(qxl_draw_effect, draw->effect));
switch (draw->type) {
case QXL_DRAW_COPY:
qxl_log_cmd_draw_copy(qxl, &draw->u.copy, group_id);
break;
}
}
| 1threat |
Add members into Array in runtime : How can I add other member (during declaration of class) into array/dictionary? Any workarounds?
public class X{
private string[] texts = new string[]{}; // or lets say it's dictionary
.....
.....
.....
.....
..... //hundreds of lines here
.....
.....
.....
.....
texts[1] = "hello"; // <--- I want to add it here, not in top. but fires error
public X(){
}
}
| 0debug |
static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
{
const char *filename = opts->device;
CharDriverState *chr;
WinCharState *s;
chr = g_malloc0(sizeof(CharDriverState));
s = g_malloc0(sizeof(WinCharState));
chr->opaque = s;
chr->chr_write = win_chr_write;
chr->chr_close = win_chr_close;
if (win_chr_pipe_init(chr, filename) < 0) {
g_free(s);
g_free(chr);
return NULL;
}
return chr;
}
| 1threat |
document.write('<script src="evil.js"></script>'); | 1threat |
static uint32_t get_cmd(ESPState *s, uint8_t *buf, uint8_t buflen)
{
uint32_t dmalen;
int target;
target = s->wregs[ESP_WBUSID] & BUSID_DID;
if (s->dma) {
dmalen = s->rregs[ESP_TCLO];
dmalen |= s->rregs[ESP_TCMID] << 8;
dmalen |= s->rregs[ESP_TCHI] << 16;
if (dmalen > buflen) {
s->dma_memory_read(s->dma_opaque, buf, dmalen);
} else {
dmalen = s->ti_size;
memcpy(buf, s->ti_buf, dmalen);
buf[0] = buf[2] >> 5;
trace_esp_get_cmd(dmalen, target);
s->ti_size = 0;
s->ti_rptr = 0;
s->ti_wptr = 0;
if (s->current_req) {
scsi_req_cancel(s->current_req);
s->async_len = 0;
s->current_dev = scsi_device_find(&s->bus, 0, target, 0);
if (!s->current_dev) {
s->rregs[ESP_RSTAT] = 0;
s->rregs[ESP_RINTR] = INTR_DC;
s->rregs[ESP_RSEQ] = SEQ_0;
esp_raise_irq(s);
return dmalen;
| 1threat |
Reading from txt file to ArrayList : Why it does not like parseInt? How to fix it? Can someone pls help me out
import java.lang.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.List;
import java.lang.*;
public class Table {
static class Data
{
private String name = "";
private int num = 0;
public Data(String name, int num)
{
this.name = name;
this.num = num;
}
public String getName()
{
return name;
}
public int getNum()
{
return num;
}
public String toString()
{
return name + " " + num;
}
}
public static void main(String[] args) throws IOException
{
List<Data> table = new ArrayList<Data>();
try
{
String filename= ""C:\\input.txt";
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line = reader.readLine();
while(line != null)
{
String[] tokens = line.split("[ ]+");
String tempname = tokens[0];
int tempnum = Integer.parseInt(tokens[1]);
Data temp = new Data(tempname,tempnum);
table.add(temp);
line = reader.readLine();
}
reader.close();
}
catch(FileNotFoundException n)
{
System.out.println("file not found");
}
catch(IOException a)
{
a.printStackTrace();
}
for(Data n:table)
{
System.out.println(n);
}
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method parseInt(String) is undefined for the type Integer
at Table.main(Table.java:58)
| 0debug |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.