problem stringlengths 26 131k | labels class label 2 classes |
|---|---|
ArrayList duplicates removal : <p>I have an Arraylist with pings, these are dates linked to a name, I want to delete all duplicates of the names and keep the closest date of the name.</p>
<p><strong>Code</strong></p>
<pre><code>private ArrayList <String> deleteDuplicates() {
ArrayList <Ping> tempPings = new ArrayList < Ping > ();
tempPings.addAll(jaws.pastMonth());
for (int i = 0; i < tempPings.size(); i++) {
Ping tempPing = tempPings.get(i);
for (int j = i + 1; j < tempPings.size() - 1; j++) {
Ping tempPing2 = tempPings.get(j);
if (tempPing.getName().equals(tempPing2.getName())) {
if (changePingToDate(tempPing2).before(changePingToDate(tempPing))) {
tempPings.remove(j);
}
}
}
}
return pingToNames(tempPings);
}
</code></pre>
<p>changePingToDate() is a method to convert the date string into a gregorian calendar.</p>
<p>When I use this code it deletes a high proportion of the duplicates but there are still some remaining each time through the loop. I have also tried it without comparing the dates and still the same problem. Can anyone help?</p>
<p>Thanks for the help!</p>
| 0debug |
No R interpreter defined: Many R related features like combination, code checking and help won't be available : <p>I am newbie to pycharm , I have installed this and everytime I got an error when I created a new project , K am not able to find the solution plz help me out .</p>
<p>[ No R interpreter defined. Many R related features like completion, code checking and help won't be available.You can set an interpreter under Preference->Languages->R ]</p>
<p>I tried to fix this as mentioned but I am not able to find where is "preference" .</p>
| 0debug |
Predict an estimate based on image and numerical value : <p>I am trying to predict a number based on an image and a numerical value. To put it in a practical matter, let's say I am trying to add to the standard house price predictor an image. So among the other features (price, sqm, no of rooms, etc.) there will be an image. So ultimately, the price to be predicted will be based on the image supplied. Has that been implemented before? Also how can I add an image along with numbers as a feature? Is there an already project, I can use?</p>
| 0debug |
static void sdram_unmap_bcr (ppc4xx_sdram_t *sdram)
{
int i;
for (i = 0; i < sdram->nbanks; i++) {
#ifdef DEBUG_SDRAM
printf("%s: Unmap RAM area " TARGET_FMT_plx " " TARGET_FMT_lx "\n",
__func__, sdram_base(sdram->bcr[i]), sdram_size(sdram->bcr[i]));
#endif
cpu_register_physical_memory(sdram_base(sdram->bcr[i]),
sdram_size(sdram->bcr[i]),
IO_MEM_UNASSIGNED);
}
}
| 1threat |
Boxing/Unboxing in C# : <p>I'm having trouble with a C# assignment dealing with boxing/unboxing. Here are the directions:</p>
<ul>
<li>Create an empty List of type object</li>
<li>Add the following values to the list: 7, 28, -1, true, "chair"</li>
<li>Loop through the list and print all values (Hint: Type Inference might
help here!)</li>
<li>Add all values that are Int type together and output the sum</li>
</ul>
<p>The trouble I am having is declaring a list that doesn't specify the data type so I can add multiple values of different data types to the list in the object (see Step 2). Any advice?</p>
| 0debug |
USBBus *usb_bus_new(DeviceState *host)
{
USBBus *bus;
bus = FROM_QBUS(USBBus, qbus_create(&usb_bus_info, host, NULL));
bus->busnr = next_usb_bus++;
TAILQ_INIT(&bus->free);
TAILQ_INIT(&bus->used);
TAILQ_INSERT_TAIL(&busses, bus, next);
return bus;
}
| 1threat |
Is c1.equals(c2) true or false? : <p>I have to guess the output for this code sequence:</p>
<pre><code>Circle c1 = new Circle(5);
Circle c2 = new Circle(5);
Circle c3 = new Circle(15);
Circle c4 = null;
System.out.println(c1==c1);
System.out.println(c1==c2);
System.out.println(c1==c3);
System.out.println(c1.equals(c1));
System.out.println(c1.equals(c2));
System.out.println(c1.equals(c3));
System.out.println(c1.equals(c4));
</code></pre>
<p>If I guess it by head I get:</p>
<blockquote>
<p>true false false false true true false false</p>
</blockquote>
<p>If I cheat and compile it I get:</p>
<blockquote>
<p>true false false false true false false false</p>
</blockquote>
<p>So my question is, is </p>
<blockquote>
<p>System.out.println(c1.equals(c2));</p>
</blockquote>
<p>true or false?</p>
| 0debug |
What is __ChadronAlwaysEqualString? : <p>I have a cloud based Ruby app with a public API. My server log files are showing attempts to access the API with the above odd parameter. Specifically, I have a GET request like :</p>
<pre><code>GET "/tenant/api/resource/__ChadronAlwaysEqualString
</code></pre>
<p>I Googled the string and there are a handful of results for it which suggest that it's somehow an Android thing. For example, someone else saw</p>
<pre><code>android.database.sqlite.SQLiteException: no such column: __ChadronAlwaysEqualString (code 1): , while compiling: SELECT * FROM `MyTable` WHERE `myColumn`=__ChadronAlwaysEqualString LIMIT 1
</code></pre>
<p>Can anyone shed any light on what this might be? </p>
| 0debug |
passing char pointer to the function in C. just thirst position is taken : I have a tiny problem. I want to pass a string (char pointer) to a function. In the function, I can just pass the first position of the char pointer.
Here is the code-snippet:
void put(struct DataItem* hashArray[SIZE], char* key){
struct DataItem* item = malloc(sizeof(struct DataItem));
item->key = *key;
item->value = 1;
So, when I call the debugger and check the value of "item->key". Then its just the first position of the char pointer.
For example I m passing "524234"
Then item->key is just "5"
| 0debug |
How to get iOS device apps count? : <p>I am working on to get the total apps count of the User device, Please let me know if somebody has an answer to this Topic. </p>
| 0debug |
static target_ulong h_client_architecture_support(PowerPCCPU *cpu,
sPAPRMachineState *spapr,
target_ulong opcode,
target_ulong *args)
{
target_ulong list = ppc64_phys_to_real(args[0]);
target_ulong ov_table;
bool explicit_match = false;
uint32_t max_compat = cpu->max_compat;
uint32_t best_compat = 0;
int i;
sPAPROptionVector *ov5_guest, *ov5_cas_old, *ov5_updates;
bool guest_radix;
for (i = 0; i < 512; ++i) {
uint32_t pvr, pvr_mask;
pvr_mask = ldl_be_phys(&address_space_memory, list);
pvr = ldl_be_phys(&address_space_memory, list + 4);
list += 8;
if (~pvr_mask & pvr) {
break;
}
if ((cpu->env.spr[SPR_PVR] & pvr_mask) == (pvr & pvr_mask)) {
explicit_match = true;
} else {
if (ppc_check_compat(cpu, pvr, best_compat, max_compat)) {
best_compat = pvr;
}
}
}
if ((best_compat == 0) && (!explicit_match || max_compat)) {
return H_HARDWARE;
}
trace_spapr_cas_pvr(cpu->compat_pvr, explicit_match, best_compat);
if (cpu->compat_pvr != best_compat) {
Error *local_err = NULL;
ppc_set_compat_all(best_compat, &local_err);
if (local_err) {
error_report_err(local_err);
return H_HARDWARE;
}
}
ov_table = list;
ov5_guest = spapr_ovec_parse_vector(ov_table, 5);
if (spapr_ovec_test(ov5_guest, OV5_MMU_BOTH)) {
error_report("guest requested hash and radix MMU, which is invalid.");
exit(EXIT_FAILURE);
}
guest_radix = spapr_ovec_test(ov5_guest, OV5_MMU_RADIX_300);
spapr_ovec_clear(ov5_guest, OV5_MMU_RADIX_300);
ov5_cas_old = spapr_ovec_clone(spapr->ov5_cas);
spapr_ovec_intersect(spapr->ov5_cas, spapr->ov5, ov5_guest);
spapr_ovec_cleanup(ov5_guest);
ov5_updates = spapr_ovec_new();
spapr->cas_reboot = spapr_ovec_diff(ov5_updates,
ov5_cas_old, spapr->ov5_cas);
if (guest_radix) {
if (kvm_enabled() && !kvmppc_has_cap_mmu_radix()) {
error_report("Guest requested unavailable MMU mode (radix).");
exit(EXIT_FAILURE);
}
spapr_ovec_set(spapr->ov5_cas, OV5_MMU_RADIX_300);
} else {
if (kvm_enabled() && kvmppc_has_cap_mmu_radix()
&& !kvmppc_has_cap_mmu_hash_v3()) {
error_report("Guest requested unavailable MMU mode (hash).");
exit(EXIT_FAILURE);
}
}
if (!spapr->cas_reboot) {
spapr->cas_reboot =
(spapr_h_cas_compose_response(spapr, args[1], args[2],
ov5_updates) != 0);
}
spapr_ovec_cleanup(ov5_updates);
if (spapr->cas_reboot) {
qemu_system_reset_request();
} else {
if ((spapr->patb_entry & PATBE1_GR) && !guest_radix) {
spapr_setup_hpt_and_vrma(spapr);
}
}
return H_SUCCESS;
}
| 1threat |
Get text from header besides some attrbute : Elements on the page map like this:
<!-- language: lang-html -->
<span [@class="some class"]>
<h1> Some text
<a> another text </a>
</h1>
</span>
How could I write xpath for getting text under "h1" besides "a" ? "a" is child for "h1" | 0debug |
How do I infinitely repeat a sequence in Kotlin? : <p>I want to infinitely repeat <code>T</code> elements in a <code>Sequence<T></code>. This can't be done using <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/as-sequence.html" rel="noreferrer">kotlin.collections.asSequence</a>. For example:</p>
<pre><code>val intArray = intArrayOf(1, 2, 3)
val finiteIntSequence = intArray.asSequence()
val many = 10
finiteIntSequence.take(many).forEach(::print)
// 123
</code></pre>
<p>This is not what I want. I expected some kind of <code>kotlin.collections.repeat</code> function to exist, but there isn't, so I implemented one myself (e.g. for this <code>IntArray</code>):</p>
<pre><code>var i = 0
val infiniteIntSequence = generateSequence { intArray[i++ % intArray.size] }
infiniteIntSequence.take(many).forEach(::print)
// 1231231231
</code></pre>
<p>This is quite imperative, so I feel there must be a more functional and less verbose way to do this. If it exists, what is/are Kotlin's standard way(s) to repeat collections / arrays a(n) (in)finite amount of times?</p>
| 0debug |
java.lang.Exception: No tests found matching Method using Intellij IDEA : <p>I am experiencing a strange behavior of Intellij IDEA 2016.3. Having a class with method <code>foo</code> and a JUnit test for the method when I get <code>java.lang.Exception: No tests found matching Method foo</code> when running the test. After I do <code>mvn test</code> it succeeds and then running the unit test right after executing mvn command it suddenly runs green. Seems like IDEA does not compile automatically. How can I fix this?</p>
<p>P.S. No settings were altered after upgrading to v. 2016.3</p>
| 0debug |
static QObject *visitor_get(TestOutputVisitorData *data)
{
visit_complete(data->ov, &data->obj);
g_assert(data->obj);
return data->obj;
}
| 1threat |
Split string to array - JavaScript - ES6 : Hove I split this string to array with Javascript ES6 Syntax?
let dataString = "<p>Lorem ipsum</p> <figure><img src="" alt=""></figure> <p>Lorem ipsum 2</p> <figure><img src="" alt=""></figure>"
I want do my array look like this:
let dataArray = ["<p>Lorem ipsum</p>", "<figure><img src="" alt=""></figure>", "<p>Lorem ipsum 2</p>", "<figure><img src="" alt=""></figure>"] | 0debug |
static uint64_t empty_slot_read(void *opaque, target_phys_addr_t addr,
unsigned size)
{
DPRINTF("read from " TARGET_FMT_plx "\n", addr);
return 0;
}
| 1threat |
static int kvm_irqchip_create(MachineState *machine, KVMState *s)
{
int ret;
if (!machine_kernel_irqchip_allowed(machine) ||
(!kvm_check_extension(s, KVM_CAP_IRQCHIP) &&
(kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0) < 0))) {
return 0;
}
ret = kvm_arch_irqchip_create(s);
if (ret < 0) {
return ret;
} else if (ret == 0) {
ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
if (ret < 0) {
fprintf(stderr, "Create kernel irqchip failed\n");
return ret;
}
}
kvm_kernel_irqchip = true;
kvm_async_interrupts_allowed = true;
kvm_halt_in_kernel_allowed = true;
kvm_init_irq_routing(s);
return 0;
}
| 1threat |
int qemu_read_config_file(const char *filename)
{
FILE *f = fopen(filename, "r");
int ret;
if (f == NULL) {
return -errno;
}
ret = qemu_config_parse(f, vm_config_groups, filename);
fclose(f);
if (ret == 0) {
return 0;
} else {
return -EINVAL;
}
}
| 1threat |
How to generate numeric Numbers? : when ever i call one method I need to generate random Numbers.like `test 1` next time `test 2`like that. If i use below code it is generating different numbers.
`NSInteger randomNumber = arc4random() % 16;`.
But I need one after another please help me. | 0debug |
static void tcx_screen_dump(void *opaque, const char *filename, bool cswitch,
Error **errp)
{
TCXState *s = opaque;
FILE *f;
uint8_t *d, *d1, v;
int ret, y, x;
f = fopen(filename, "wb");
if (!f) {
error_setg(errp, "failed to open file '%s': %s", filename,
strerror(errno));
return;
}
ret = fprintf(f, "P6\n%d %d\n%d\n", s->width, s->height, 255);
if (ret < 0) {
goto write_err;
}
d1 = s->vram;
for(y = 0; y < s->height; y++) {
d = d1;
for(x = 0; x < s->width; x++) {
v = *d;
ret = fputc(s->r[v], f);
if (ret == EOF) {
goto write_err;
}
ret = fputc(s->g[v], f);
if (ret == EOF) {
goto write_err;
}
ret = fputc(s->b[v], f);
if (ret == EOF) {
goto write_err;
}
d++;
}
d1 += MAXX;
}
out:
fclose(f);
return;
write_err:
error_setg(errp, "failed to write to file '%s': %s", filename,
strerror(errno));
unlink(filename);
goto out;
}
| 1threat |
void tb_phys_invalidate(TranslationBlock *tb, tb_page_addr_t page_addr)
{
CPUState *cpu;
PageDesc *p;
uint32_t h;
tb_page_addr_t phys_pc;
assert_tb_locked();
atomic_set(&tb->cflags, tb->cflags | CF_INVALID);
phys_pc = tb->page_addr[0] + (tb->pc & ~TARGET_PAGE_MASK);
h = tb_hash_func(phys_pc, tb->pc, tb->flags, tb->cflags & CF_HASH_MASK,
tb->trace_vcpu_dstate);
qht_remove(&tb_ctx.htable, tb, h);
if (tb->page_addr[0] != page_addr) {
p = page_find(tb->page_addr[0] >> TARGET_PAGE_BITS);
tb_page_remove(&p->first_tb, tb);
invalidate_page_bitmap(p);
}
if (tb->page_addr[1] != -1 && tb->page_addr[1] != page_addr) {
p = page_find(tb->page_addr[1] >> TARGET_PAGE_BITS);
tb_page_remove(&p->first_tb, tb);
invalidate_page_bitmap(p);
}
h = tb_jmp_cache_hash_func(tb->pc);
CPU_FOREACH(cpu) {
if (atomic_read(&cpu->tb_jmp_cache[h]) == tb) {
atomic_set(&cpu->tb_jmp_cache[h], NULL);
}
}
tb_remove_from_jmp_list(tb, 0);
tb_remove_from_jmp_list(tb, 1);
tb_jmp_unlink(tb);
tb_ctx.tb_phys_invalidate_count++;
}
| 1threat |
Trying to change the INSTALLDIR value to $APPDATA, but won't work. : <!-- What are you trying to accomplish? (Please include sample data.) -->
I'm trying to make an installer to extract some texture packs and stuff into the AppData folder, but keeps changing to program files. (Its for school, they have a gaming club, so I wanted shaders and stuff at it. )
<!-- Paste the part of the code that shows the problem. (Please indent 4 spaces.) -->
Heres the code in a pastebin link: https://pastebin.com/raw/cdwEjsE4
<!-- What do you expect the result to be? -->
<!-- What is the actual result you get? (Please include any errors.) -->
Any ideas on what i need to change?
| 0debug |
static void usbredir_alt_setting_status(void *priv, uint32_t id,
struct usb_redir_alt_setting_status_header *alt_setting_status)
{
USBRedirDevice *dev = priv;
AsyncURB *aurb;
int len = 0;
DPRINTF("alt status %d intf %d alt %d id: %u\n",
alt_setting_status->status,
alt_setting_status->interface,
alt_setting_status->alt, id);
aurb = async_find(dev, id);
if (!aurb) {
return;
}
if (aurb->packet) {
if (aurb->get) {
dev->dev.data_buf[0] = alt_setting_status->alt;
len = 1;
}
aurb->packet->len =
usbredir_handle_status(dev, alt_setting_status->status, len);
usb_generic_async_ctrl_complete(&dev->dev, aurb->packet);
}
async_free(dev, aurb);
}
| 1threat |
Android Studio, ImageButton not working when multi-threading. How to solve this? : came across a major problem while game developing in Android Studio. I've made a Class which creates a separate thread. The class it's purphose is to be an animation of a cloud moving:
`package com.example.j9.triqshot;`
`import android.content.Context;`
`import android.content.res.Resources;`
`import android.support.v7.widget.AppCompatImageView;`
`import android.util.AttributeSet;`
`import android.view.View;`
`public class Cloud extends AppCompatImageView {`
private int width;
private int height;
private int ScreenWidth;
private int ScreenHeight;
public long X;
public int Y;
public int speed = 1;
private long beginTime;
private long endTime;
private boolean MayMove = true;
private static int framerate = 12;
private Thread threadCloud;
public Cloud(Context context){
super(context);
}
public Cloud(Context context, AttributeSet attrs){
super(context, attrs);
}
public Cloud(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
}
public void setWidth(int width){
this.setMaxWidth(width);
this.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
this.width = this.getMeasuredWidth();
}
public void setHeight(int height){
this.setMaxWidth(height);
this.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
this.height = this.getMeasuredHeight();
}
public void Move(){
ScreenHeight = Resources.getSystem().getDisplayMetrics().heightPixels; //Define screen height
ScreenWidth = Resources.getSystem().getDisplayMetrics().widthPixels; //Define screen width
beginTime = System.currentTimeMillis();
threadCloud = new Thread(new Runnable(){
@Override
public void run() {
while(MayMove) {
endTime = System.currentTimeMillis();
long TimeDifference = endTime - beginTime;
if(TimeDifference >= (1000/framerate)) {
X += (speed * (TimeDifference/(1000/framerate)));
beginTime = endTime;
setXY(X, Y);
}
if(X > ScreenWidth){
X = 0 - width;
}
}
}});
threadCloud.start();
}
private void setXY(float X,float Y) {
this.setX(X);
this.setY(Y);
}
public void stopThread(){
threadCloud.interrupt();
}
`}//CLASS`
When I create one Cloud in the main activity the button will still work, but when I create more than one the button will most of the time not work.
Besides, if the button works and the intent to go to the next activity has been send, an error occours:
--------- beginning of crash
02-26 12:13:59.209 4370-4394/com.example.j9.triqshot E/AndroidRuntime: FATAL EXCEPTION: Thread-4
Process: com.example.j9.triqshot, PID: 4370
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6891) at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:1083) at android.view.ViewGroup.invalidateChild(ViewGroup.java:5205) at android.view.View.invalidateInternal(View.java:13656) at android.view.View.invalidate(View.java:13620) at android.view.View.invalidateViewProperty(View.java:13740) at android.view.View.setTranslationX(View.java:12848) at android.view.View.setX(View.java:12748) at com.example.j9.triqshot.Cloud.setXY(Cloud.java:87) at com.example.j9.triqshot.Cloud.access$400(Cloud.java:14) at com.example.j9.triqshot.Cloud$1.run(Cloud.java:75) at java.lang.Thread.run(Thread.java:761)
I've never came across an error like this, and I don't fully understand what it exactly means.
The Main activity:
`package com.example.j9.triqshot;`
`import android.content.Intent;`
`import android.content.res.Resources;`
`import android.os.CountDownTimer;`
`import android.support.v7.app.AppCompatActivity;`
`import android.os.Bundle;`
`import android.util.Log;`
`import android.view.View;`
`import android.widget.ImageButton;`
`import android.widget.ImageView;`
`public class MainActivity extends AppCompatActivity {`
ImageView BG; //Initialize background Image
ImageView GameName; //Initialize GameName Image
ImageView MenuBox; //Initialize MenuBox Image
ImageView MadeBy; //Initialize MadeBy Image
ImageButton playButton; //Initialize play button
ImageButton optionsButton; //Initialize options button
ImageButton shareButton; //Initialize share button
int width; //Initialize screen width
int height; //Initialize screen height
Cloud Cloud1;
Cloud Cloud2;
Cloud Cloud3;
boolean Moving = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
height = Resources.getSystem().getDisplayMetrics().heightPixels; //Define screen height
width = Resources.getSystem().getDisplayMetrics().widthPixels; //Define screen width
BG = (ImageView)findViewById(R.id.BG_MENU); //Assign Background
GameName = (ImageView)findViewById(R.id.GameName); //Assign GameName
MenuBox = (ImageView)findViewById(R.id.MenuBox); //Assign MenuBox
MadeBy = (ImageView)findViewById(R.id.MadeBy); //Assign MadeBy
playButton = (ImageButton)findViewById(R.id.playButton); //Assign playButton
optionsButton = (ImageButton)findViewById(R.id.optionsButton); //Assign OptionsButton
shareButton = (ImageButton)findViewById(R.id.shareButton); //Assign shareButton
Cloud1 = (Cloud)findViewById(R.id.Cloud1);
Cloud2 = (Cloud)findViewById(R.id.Cloud2);
Cloud3 = (Cloud)findViewById(R.id.Cloud3);
correctMenuSizes();
CorrectPositions();
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
playButtonClicked();
}
}); //Listen to playButton
optionsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
optionsButtonClicked();
}
}); //Listen to optionsButton
shareButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
shareButtonClicked();
}
});
Cloud1.Move();
Cloud2.Move();
Cloud3.Move();
}
//Set image sizes
private void correctMenuSizes(){
GameName.setMaxHeight(height/12);
MenuBox.setMaxHeight(height/2);
MadeBy.setMaxWidth(width/3);
playButton.setMaxWidth(width/8);
optionsButton.setMaxWidth(width/8);
shareButton.setMaxWidth(width/8);
Cloud1.setWidth(width/3);
Cloud2.setWidth(width/4);
Cloud3.setWidth(width/3);
//Measurements
Cloud1.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
Cloud2.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
Cloud3.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
}
private void CorrectPositions(){
//Cloud startPositions and speed
Cloud1.Y = (height / 10);
Cloud1.X = 0;
Cloud1.speed = 3;
Cloud2.Y = (height / 2);
Cloud2.X = (width / 2);
Cloud2.speed = 2;
Cloud3.Y = (height - (height / 3));
Cloud3.X = (width - (width / 3));
Cloud3.speed = 3;
}
//When clicked on playButton
public void playButtonClicked(){
playButton.setImageResource(R.drawable.play_pressed);
new CountDownTimer(500, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
playButtonTimer();
}
}.start();
}
//Reset the button with a delay of 0,5 seconds
//Go to LevelMenu
public void playButtonTimer(){
playButton.setImageResource(R.drawable.play_normal);
Cloud1.stopThread();
Cloud2.stopThread();
Cloud3.stopThread();
Intent intent = new Intent(this, LevelMenu.class);
startActivity(intent);
}
//When clicked on optionsButton
public void optionsButtonClicked(){
optionsButton.setImageResource(R.drawable.options_pressed);
new CountDownTimer(500, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
optionsButtonTimer();
}
}.start();
}
//Reset the button with a delay of 0,5 seconds
public void optionsButtonTimer(){
optionsButton.setImageResource(R.drawable.options_normal);
//Intent intent = new Intent(this, LevelMenu.class);
//startActivity(intent);
}
//When clicked on shareButton
public void shareButtonClicked(){
shareButton.setImageResource(R.drawable.share_pressed);
new CountDownTimer(500, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
shareButtonTimer();
}
}.start();
}
//Reset the button with a delay of 0,5 seconds
public void shareButtonTimer(){
shareButton.setImageResource(R.drawable.share_normal);
//Intent intent = new Intent(this, LevelMenu.class);
//startActivity(intent);
}
`}//CLASS`
I've already tried to search similar problems, but with still no results. | 0debug |
static void sdhci_data_transfer(void *opaque)
{
SDHCIState *s = (SDHCIState *)opaque;
if (s->trnmod & SDHC_TRNS_DMA) {
switch (SDHC_DMA_TYPE(s->hostctl)) {
case SDHC_CTRL_SDMA:
if ((s->trnmod & SDHC_TRNS_MULTI) &&
(!(s->trnmod & SDHC_TRNS_BLK_CNT_EN) || s->blkcnt == 0)) {
break;
}
if ((s->blkcnt == 1) || !(s->trnmod & SDHC_TRNS_MULTI)) {
sdhci_sdma_transfer_single_block(s);
} else {
sdhci_sdma_transfer_multi_blocks(s);
}
break;
case SDHC_CTRL_ADMA1_32:
if (!(s->capareg & SDHC_CAN_DO_ADMA1)) {
ERRPRINT("ADMA1 not supported\n");
break;
}
sdhci_do_adma(s);
break;
case SDHC_CTRL_ADMA2_32:
if (!(s->capareg & SDHC_CAN_DO_ADMA2)) {
ERRPRINT("ADMA2 not supported\n");
break;
}
sdhci_do_adma(s);
break;
case SDHC_CTRL_ADMA2_64:
if (!(s->capareg & SDHC_CAN_DO_ADMA2) ||
!(s->capareg & SDHC_64_BIT_BUS_SUPPORT)) {
ERRPRINT("64 bit ADMA not supported\n");
break;
}
sdhci_do_adma(s);
break;
default:
ERRPRINT("Unsupported DMA type\n");
break;
}
} else {
if ((s->trnmod & SDHC_TRNS_READ) && sdbus_data_ready(&s->sdbus)) {
s->prnsts |= SDHC_DOING_READ | SDHC_DATA_INHIBIT |
SDHC_DAT_LINE_ACTIVE;
sdhci_read_block_from_card(s);
} else {
s->prnsts |= SDHC_DOING_WRITE | SDHC_DAT_LINE_ACTIVE |
SDHC_SPACE_AVAILABLE | SDHC_DATA_INHIBIT;
sdhci_write_block_to_card(s);
}
}
}
| 1threat |
Only Enable the last Remove Element Button of a ListBox : <p>In my ListBox.ItemTemplate i have a TextBlock and a Remove button, the button must be enabled only if it's the last element o the listbox.</p>
| 0debug |
Sorting alphabetically in ruby on rails : <p>How do i make ActiveRecord to sort my movies title alphabetically when i click on a link in ruby on rails? Movies contains title with alphabets and others numbers. Thanks</p>
| 0debug |
static int vid_read_packet(AVFormatContext *s,
AVPacket *pkt)
{
BVID_DemuxContext *vid = s->priv_data;
AVIOContext *pb = s->pb;
unsigned char block_type;
int audio_length;
int ret_value;
if(vid->is_finished || pb->eof_reached)
return AVERROR(EIO);
block_type = avio_r8(pb);
switch(block_type){
case PALETTE_BLOCK:
avio_seek(pb, -1, SEEK_CUR);
ret_value = av_get_packet(pb, pkt, 3 * 256 + 1);
if(ret_value != 3 * 256 + 1){
av_free_packet(pkt);
return AVERROR(EIO);
}
pkt->stream_index = 0;
return ret_value;
case FIRST_AUDIO_BLOCK:
avio_rl16(pb);
s->streams[1]->codec->sample_rate = 1000000 / (256 - avio_r8(pb));
s->streams[1]->codec->bit_rate = s->streams[1]->codec->channels * s->streams[1]->codec->sample_rate * s->streams[1]->codec->bits_per_coded_sample;
case AUDIO_BLOCK:
audio_length = avio_rl16(pb);
ret_value = av_get_packet(pb, pkt, audio_length);
pkt->stream_index = 1;
return ret_value != audio_length ? AVERROR(EIO) : ret_value;
case VIDEO_P_FRAME:
case VIDEO_YOFF_P_FRAME:
case VIDEO_I_FRAME:
return read_frame(vid, pb, pkt, block_type, s,
s->streams[0]->codec->width * s->streams[0]->codec->height);
case EOF_BLOCK:
if(vid->nframes != 0)
av_log(s, AV_LOG_VERBOSE, "reached terminating character but not all frames read.\n");
vid->is_finished = 1;
return AVERROR(EIO);
default:
av_log(s, AV_LOG_ERROR, "unknown block (character = %c, decimal = %d, hex = %x)!!!\n",
block_type, block_type, block_type); return -1;
}
}
| 1threat |
def check_subset(test_tup1, test_tup2):
res = set(test_tup2).issubset(test_tup1)
return (res) | 0debug |
Code help to Play Multiple Sounds (objective c) to swift(x-code 7) : Hi programmers i am new to programming language! Trying to convert the below code (objective c ) to swift plz help me by doing so or help me with a new code to play MULTIPLE SOUNDS ***
-(IBAction)pushButton {
NSString *path = [[NSBundle mainBundle] pathForResouce:@"ring" ofType:@"mp3"];
if(theAudio) [theAudio release];
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
}
-(IBAction)pushButton1 {
NSString *path = [[NSBundle mainBundle] pathForResouce:@"amaze" ofType:@"mp3"];
if(theAudio) [theAudio release];
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
}
| 0debug |
Parsing JSON as String in Javascript : <p>I have a String whose value is a JSON object.</p>
<pre><code>var json = '{
"Name": {
"1": "Adam",
"2": "Tim",
"3": "Bob"
},
"Height": {
"1": "181",
"2": "157",
"3": "173"
}
}';
</code></pre>
<p>How to parse it to get values <strong>Adam</strong>, <strong>Tim</strong> and <strong>Bob</strong> and print it ?</p>
| 0debug |
ASP.NET Core 2.1 Identity: How to remove the Default UI razor pages? : <p>Expanding the answer in this question:
<a href="https://stackoverflow.com/questions/50682108/change-routing-in-asp-net-core-identity-ui/50682681">Change routing in ASP.NET Core Identity UI?</a></p>
<blockquote>
<p>Javier recommends one of the following options when wanting to
customise the URLs:</p>
<ul>
<li>Use the scaffolding element of the Default UI and make all necessary customisations yourself. </li>
<li>Use a redirection rule that points the old routes to the new routes.</li>
<li>Don't use the Default UI at all.</li>
</ul>
</blockquote>
<p>From a new ASP.NET Core 2.1 MVC project, with Authentication: Individual User Accounts set, how do you NOT use the Default UI? It seems to be installed by default with Identity Core. </p>
<p><a href="https://i.stack.imgur.com/OXqFk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OXqFk.png" alt="enter image description here"></a></p>
<p>After the project is created, what is the method to remove the Default UI razor pages, and still use Identity Core? </p>
<p>Can I just delete the <code>/Identity/</code> area, and create my own <code>AccountController</code> instead?</p>
| 0debug |
static int usb_qdev_init(DeviceState *qdev)
{
USBDevice *dev = USB_DEVICE(qdev);
int rc;
pstrcpy(dev->product_desc, sizeof(dev->product_desc),
usb_device_get_product_desc(dev));
dev->auto_attach = 1;
QLIST_INIT(&dev->strings);
usb_ep_init(dev);
rc = usb_claim_port(dev);
if (rc != 0) {
return rc;
}
rc = usb_device_init(dev);
if (rc != 0) {
usb_release_port(dev);
return rc;
}
if (dev->auto_attach) {
rc = usb_device_attach(dev);
if (rc != 0) {
usb_qdev_exit(qdev);
return rc;
}
}
return 0;
}
| 1threat |
Referencing a Managed Service Identity in ARM-template deploy : <p>When deploying a Microsoft.Web resource with the new MSI feature the principleId GUID for the created user is visible after deployment. Screenshot below shows the structure in the ARM-template.</p>
<p><a href="https://i.stack.imgur.com/nr4b8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nr4b8.png" alt="enter image description here"></a></p>
<p>What would be the best way to fetch this GUID later in the pipeline to be able to assign access rights in (for instance) Data Lake Store?</p>
<p>Is it possible to use any of the existing ARM template functions to do so?</p>
| 0debug |
int qemu_strtoul(const char *nptr, const char **endptr, int base,
unsigned long *result)
{
char *p;
int err = 0;
if (!nptr) {
if (endptr) {
*endptr = nptr;
}
err = -EINVAL;
} else {
errno = 0;
*result = strtoul(nptr, &p, base);
err = check_strtox_error(endptr, p, errno);
}
return err;
}
| 1threat |
@RestController @ResponseBody @RequestBody cant ready Model : We has "web service" rest with this
O problem consist in ready object with model, when ready attribute for attribute can ready,
- Project with spring 4.2.4-RELEASE
- User jackson 2.8.0
same stacktrace wrong, same call method create
<pre><code>
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unrecognized token 'event': was expecting ('true', 'false' or 'null')
at [Source: java.io.ByteArrayInputStream@4efc31a9; line: 1, column: 7]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'event': was expecting ('true', 'false' or 'null')
at [Source: java.io.ByteArrayInputStream@4efc31a9; line: 1, column: 7]
</code></pre>
how configure can read a model "Invoice"?
one stacktrace
| 0debug |
Miliseconds in C# - long or int? : <p>I'm working with Milisecond and I've used it like </p>
<pre><code>Timeout = (int)TimeSpan.FromMinutes(TimeoutVal).TotalMilliseconds
</code></pre>
<p>But I read on few places people are casting it to <code>long</code> instead of <code>int</code>? Why is that?</p>
| 0debug |
Initialization functionality unavailable for this session, in google Ads : <p>I'm getting this error of google Ads, suddently. I can't find anything here with this error. </p>
<p>Notice that ads are displaying correctly</p>
<pre><code>Google Mobile Ads SDK initialization functionality unavailable for this session. Ad requests can be made at any time.
</code></pre>
| 0debug |
I am using editText for password field in android. How to show the password visible for few seconds and then mask it with asterisk symbol?. : https://lh3.googleusercontent.com/-JqvpdKKQ2Eo/UOB9ixNzpLI/AAAAAAAAApQ/6nH9bvwc1ko/s512/p2.png
The output should look like this image. | 0debug |
using *args and **kwargs as a substitute for function's arguments : <p>I hava a question about *args and **kwargs. I know that they are used when you do not know how many arguments will be passed to function. But can it be a substitute for some arguments that are actually required when I do not know what those are? </p>
<p>If there is a function:</p>
<pre><code>def functionName(a, b):
...some code...
doSomethingUsing(a)
doSomethingUsing(b)
</code></pre>
<p>If I do not what arguments does the function take can I simply use functionName(*args, **kwargs) - or functionName(*args)? I noticed that some people tend to use it that way - but I am not sure if this is how * and ** work in python? </p>
| 0debug |
static void throttle_fix_bucket(LeakyBucket *bkt)
{
double min;
bkt->level = bkt->burst_level = 0;
min = bkt->avg / 10;
if (bkt->avg && !bkt->max) {
bkt->max = min;
}
}
| 1threat |
void qbus_free(BusState *bus)
{
DeviceState *dev;
while ((dev = QLIST_FIRST(&bus->children)) != NULL) {
qdev_free(dev);
}
if (bus->parent) {
QLIST_REMOVE(bus, sibling);
bus->parent->num_child_bus--;
}
if (bus->qdev_allocated) {
qemu_free(bus);
}
} | 1threat |
can't remove parameter using javascript : <p>i have a url like this</p>
<pre><code>test.html?dir=asc&end_date=2016-09-23&order=created_at&start_date=2016-08-14
</code></pre>
<p>i want to remove the parameter using the following javascript</p>
<pre><code>function removeParam(uri) {
uri = uri.replace(/([&\?]start_date=*$|start_date=*&|[?&]start_date=(?=#))/, '');
return uri.replace(/([&\?]end_date=*$|end_date=*&|[?&]end_date=(?=#))/, '');
}
</code></pre>
<p>but it didn't work, anyone know what's wrong with that?</p>
| 0debug |
Nodemcu temperature readings to raspberry pi wireless : I'm currently having issues sending data collected from a temperature sensor to my raspberry-pi. The PI says it hasn't received any data. I'm also not sure how GET and POST work. I'm fairly new to this stuff so any help would be much appreciated. Also can someone review my sendTemperatureTS method and my php code because as I said I'm new to this. Btw I created my php file in a php folder in /var/www in the raspberry pi. I used the command sudo nano collectdata.php in the php folder to write my code in.
Arduino Code for NodeMCU:
#include <ESP8266WiFi.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define myPeriodic 15 //in sec | Thingspeak pub is 15sec
#define ONE_WIRE_BUS 2 // DS18B20 on arduino pin2 corresponds to D4 on physical board
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
float prevTemp = 0;
const char* server = "172.168.2.143";
const char* MY_SSID = "AkhuogTkhbbEjhbuvouvr7i2";
const char* MY_PWD = "2pkpmbipsrbeirbp3niag%";
int sent = 0;
void setup() {
Serial.begin(115200);
connectWifi();
}
void loop() {
float temp;
//char buffer[10];
DS18B20.requestTemperatures();
temp = DS18B20.getTempCByIndex(0);
//String tempC = dtostrf(temp, 4, 1, buffer);//handled in sendTemp()
Serial.print(String(sent)+" Temperature: ");
Serial.println(temp);
//if (temp != prevTemp)
//{
//sendTemperatureTS(temp);
//prevTemp = temp;
//}
sendTemperatureTS(temp);
int count = myPeriodic;
while(count--)
delay(1000);
}
void connectWifi()
{
Serial.print("Connecting to "+*MY_SSID);
WiFi.begin(MY_SSID, MY_PWD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected");
Serial.println("");
}//end connect
void sendTemperatureTS(float temp)
{
WiFiClient client;
if (client.connect(server, 80)) {
Serial.println("WiFi Client connected ");
String postStr = "/php/";
postStr += "?temp=";
postStr += String(temp);
postStr += "\r\n\r\n";
client.print("POST 172.168.2.143/php/collectdata.php HTTP/1.1\n");
client.print("Host: 122.168.2.143\n");
client.print("Connection: close\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);
delay(1000);
}//end if
sent++;
client.stop();
}
PHP code:
<?php
$servername = “172.168.2.143”;
$username = “esp8266”;
$password = “Tutorial”;
$dbname = “esp8266”;
$temp = $_POST[‘temp’];
$conn = mysql_connect(“172.168.2.143”,”esp8266”,”Tutorial”);
if(!$conn)
{
die(‘Could not connect: ’ . mysql_error());
}
$datenow = date(‘Y-m-d’);
$sql = “INSERT INTO `JSDataTable`(`logdate`,`temperature`) VALUES (\”$datenow\”,\”$temp\”)”;
$result = mysql_query($sql);
if(!result)
{
die(‘Invalid query: ‘ . mysql_error());
}
echo “<h1>The data has been sent!</h1>”;
mysq
l_close($conn);
?>
| 0debug |
Property 'switchMap' does not exist on type 'Observable<User>' : <p>I have been getting the following error message when trying to apply the switchMap operator to my Observable:</p>
<blockquote>
<p>Property 'switchMap' does not exist on type 'Observable'.</p>
</blockquote>
<p>I'm currently using rxjs version 5.5.2, and in my component, I have it imported like so:</p>
<pre><code>import 'rxjs/operator/switchMap';
</code></pre>
<p>However, I still get a compilation error. I have looked at similar questions and have not found a proper solution to this, any suggestions on what could be the issue here?</p>
<pre><code>get appUser$() : Observable<AppUser> {
return this.user$
.switchMap(user => {
if (user) return this.userService.get(user.uid);
return Observable.of(null);
});
}
</code></pre>
<p>Image:
<a href="https://i.stack.imgur.com/nhYB8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nhYB8.png" alt="enter image description here"></a></p>
| 0debug |
static av_cold void x8_vlc_init(void){
int i;
int offset = 0;
int sizeidx = 0;
static const uint16_t sizes[8*4 + 8*2 + 2 + 4] = {
576, 548, 582, 618, 546, 616, 560, 642,
584, 582, 704, 664, 512, 544, 656, 640,
512, 648, 582, 566, 532, 614, 596, 648,
586, 552, 584, 590, 544, 578, 584, 624,
528, 528, 526, 528, 536, 528, 526, 544,
544, 512, 512, 528, 528, 544, 512, 544,
128, 128, 128, 128, 128, 128};
static VLC_TYPE table[28150][2];
#define init_ac_vlc(dst,src) \
dst.table = &table[offset]; \
dst.table_allocated = sizes[sizeidx]; \
offset += sizes[sizeidx++]; \
init_vlc(&dst, \
AC_VLC_BITS,77, \
&src[1],4,2, \
&src[0],4,2, \
INIT_VLC_USE_NEW_STATIC)
for(i=0;i<8;i++){
init_ac_vlc( j_ac_vlc[0][0][i], x8_ac0_highquant_table[i][0] );
init_ac_vlc( j_ac_vlc[0][1][i], x8_ac1_highquant_table[i][0] );
init_ac_vlc( j_ac_vlc[1][0][i], x8_ac0_lowquant_table [i][0] );
init_ac_vlc( j_ac_vlc[1][1][i], x8_ac1_lowquant_table [i][0] );
}
#undef init_ac_vlc
#define init_dc_vlc(dst,src) \
dst.table = &table[offset]; \
dst.table_allocated = sizes[sizeidx]; \
offset += sizes[sizeidx++]; \
init_vlc(&dst, \
DC_VLC_BITS,34, \
&src[1],4,2, \
&src[0],4,2, \
INIT_VLC_USE_NEW_STATIC);
for(i=0;i<8;i++){
init_dc_vlc( j_dc_vlc[0][i], x8_dc_highquant_table[i][0]);
init_dc_vlc( j_dc_vlc[1][i], x8_dc_lowquant_table [i][0]);
}
#undef init_dc_vlc
#define init_or_vlc(dst,src) \
dst.table = &table[offset]; \
dst.table_allocated = sizes[sizeidx]; \
offset += sizes[sizeidx++]; \
init_vlc(&dst, \
OR_VLC_BITS,12, \
&src[1],4,2, \
&src[0],4,2, \
INIT_VLC_USE_NEW_STATIC);
for(i=0;i<2;i++){
init_or_vlc( j_orient_vlc[0][i], x8_orient_highquant_table[i][0]);
}
for(i=0;i<4;i++){
init_or_vlc( j_orient_vlc[1][i], x8_orient_lowquant_table [i][0])
}
if (offset != sizeof(table)/sizeof(VLC_TYPE)/2)
av_log(NULL, AV_LOG_ERROR, "table size %i does not match needed %i\n", (int)(sizeof(table)/sizeof(VLC_TYPE)/2), offset);
}
| 1threat |
When I compress a tar gz file using paths, folders get included : <p>When I compress a tar gz file using paths, folders get included. However, I want to just compress the file only. This is what I tried:</p>
<pre><code>$ tar -czf ../coolfile.tar.gz newfol/coolfile
</code></pre>
<p>When I uncompress this tar.gz, I get the <code>coolfile</code> file in newfol folder. I would like compress <code>coolfile</code> only. </p>
<p>Uncompress tar gz command:</p>
<pre><code>$ tar -xvf coolfile.tar.gz`
</code></pre>
| 0debug |
static inline void RENAME(hScale)(int16_t *dst, int dstW, const uint8_t *src, int srcW, int xInc,
const int16_t *filter, const int16_t *filterPos, int filterSize)
{
#if COMPILE_TEMPLATE_MMX
assert(filterSize % 4 == 0 && filterSize>0);
if (filterSize==4) {
x86_reg counter= -2*dstW;
filter-= counter*2;
filterPos-= counter/2;
dst-= counter/2;
__asm__ volatile(
#if defined(PIC)
"push %%"REG_b" \n\t"
#endif
"pxor %%mm7, %%mm7 \n\t"
"push %%"REG_BP" \n\t"
"mov %%"REG_a", %%"REG_BP" \n\t"
ASMALIGN(4)
"1: \n\t"
"movzwl (%2, %%"REG_BP"), %%eax \n\t"
"movzwl 2(%2, %%"REG_BP"), %%ebx \n\t"
"movq (%1, %%"REG_BP", 4), %%mm1 \n\t"
"movq 8(%1, %%"REG_BP", 4), %%mm3 \n\t"
"movd (%3, %%"REG_a"), %%mm0 \n\t"
"movd (%3, %%"REG_b"), %%mm2 \n\t"
"punpcklbw %%mm7, %%mm0 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
"pmaddwd %%mm1, %%mm0 \n\t"
"pmaddwd %%mm2, %%mm3 \n\t"
"movq %%mm0, %%mm4 \n\t"
"punpckldq %%mm3, %%mm0 \n\t"
"punpckhdq %%mm3, %%mm4 \n\t"
"paddd %%mm4, %%mm0 \n\t"
"psrad $7, %%mm0 \n\t"
"packssdw %%mm0, %%mm0 \n\t"
"movd %%mm0, (%4, %%"REG_BP") \n\t"
"add $4, %%"REG_BP" \n\t"
" jnc 1b \n\t"
"pop %%"REG_BP" \n\t"
#if defined(PIC)
"pop %%"REG_b" \n\t"
#endif
: "+a" (counter)
: "c" (filter), "d" (filterPos), "S" (src), "D" (dst)
#if !defined(PIC)
: "%"REG_b
#endif
);
} else if (filterSize==8) {
x86_reg counter= -2*dstW;
filter-= counter*4;
filterPos-= counter/2;
dst-= counter/2;
__asm__ volatile(
#if defined(PIC)
"push %%"REG_b" \n\t"
#endif
"pxor %%mm7, %%mm7 \n\t"
"push %%"REG_BP" \n\t"
"mov %%"REG_a", %%"REG_BP" \n\t"
ASMALIGN(4)
"1: \n\t"
"movzwl (%2, %%"REG_BP"), %%eax \n\t"
"movzwl 2(%2, %%"REG_BP"), %%ebx \n\t"
"movq (%1, %%"REG_BP", 8), %%mm1 \n\t"
"movq 16(%1, %%"REG_BP", 8), %%mm3 \n\t"
"movd (%3, %%"REG_a"), %%mm0 \n\t"
"movd (%3, %%"REG_b"), %%mm2 \n\t"
"punpcklbw %%mm7, %%mm0 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
"pmaddwd %%mm1, %%mm0 \n\t"
"pmaddwd %%mm2, %%mm3 \n\t"
"movq 8(%1, %%"REG_BP", 8), %%mm1 \n\t"
"movq 24(%1, %%"REG_BP", 8), %%mm5 \n\t"
"movd 4(%3, %%"REG_a"), %%mm4 \n\t"
"movd 4(%3, %%"REG_b"), %%mm2 \n\t"
"punpcklbw %%mm7, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
"pmaddwd %%mm1, %%mm4 \n\t"
"pmaddwd %%mm2, %%mm5 \n\t"
"paddd %%mm4, %%mm0 \n\t"
"paddd %%mm5, %%mm3 \n\t"
"movq %%mm0, %%mm4 \n\t"
"punpckldq %%mm3, %%mm0 \n\t"
"punpckhdq %%mm3, %%mm4 \n\t"
"paddd %%mm4, %%mm0 \n\t"
"psrad $7, %%mm0 \n\t"
"packssdw %%mm0, %%mm0 \n\t"
"movd %%mm0, (%4, %%"REG_BP") \n\t"
"add $4, %%"REG_BP" \n\t"
" jnc 1b \n\t"
"pop %%"REG_BP" \n\t"
#if defined(PIC)
"pop %%"REG_b" \n\t"
#endif
: "+a" (counter)
: "c" (filter), "d" (filterPos), "S" (src), "D" (dst)
#if !defined(PIC)
: "%"REG_b
#endif
);
} else {
const uint8_t *offset = src+filterSize;
x86_reg counter= -2*dstW;
filterPos-= counter/2;
dst-= counter/2;
__asm__ volatile(
"pxor %%mm7, %%mm7 \n\t"
ASMALIGN(4)
"1: \n\t"
"mov %2, %%"REG_c" \n\t"
"movzwl (%%"REG_c", %0), %%eax \n\t"
"movzwl 2(%%"REG_c", %0), %%edx \n\t"
"mov %5, %%"REG_c" \n\t"
"pxor %%mm4, %%mm4 \n\t"
"pxor %%mm5, %%mm5 \n\t"
"2: \n\t"
"movq (%1), %%mm1 \n\t"
"movq (%1, %6), %%mm3 \n\t"
"movd (%%"REG_c", %%"REG_a"), %%mm0 \n\t"
"movd (%%"REG_c", %%"REG_d"), %%mm2 \n\t"
"punpcklbw %%mm7, %%mm0 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
"pmaddwd %%mm1, %%mm0 \n\t"
"pmaddwd %%mm2, %%mm3 \n\t"
"paddd %%mm3, %%mm5 \n\t"
"paddd %%mm0, %%mm4 \n\t"
"add $8, %1 \n\t"
"add $4, %%"REG_c" \n\t"
"cmp %4, %%"REG_c" \n\t"
" jb 2b \n\t"
"add %6, %1 \n\t"
"movq %%mm4, %%mm0 \n\t"
"punpckldq %%mm5, %%mm4 \n\t"
"punpckhdq %%mm5, %%mm0 \n\t"
"paddd %%mm0, %%mm4 \n\t"
"psrad $7, %%mm4 \n\t"
"packssdw %%mm4, %%mm4 \n\t"
"mov %3, %%"REG_a" \n\t"
"movd %%mm4, (%%"REG_a", %0) \n\t"
"add $4, %0 \n\t"
" jnc 1b \n\t"
: "+r" (counter), "+r" (filter)
: "m" (filterPos), "m" (dst), "m"(offset),
"m" (src), "r" ((x86_reg)filterSize*2)
: "%"REG_a, "%"REG_c, "%"REG_d
);
}
#else
#if COMPILE_TEMPLATE_ALTIVEC
hScale_altivec_real(dst, dstW, src, srcW, xInc, filter, filterPos, filterSize);
#else
int i;
for (i=0; i<dstW; i++) {
int j;
int srcPos= filterPos[i];
int val=0;
for (j=0; j<filterSize; j++) {
val += ((int)src[srcPos + j])*filter[filterSize*i + j];
}
dst[i] = FFMIN(val>>7, (1<<15)-1);
}
#endif
#endif
}
| 1threat |
Can anyone extract significant digit from 0.0007? : I want to extract significant digit of 7 from XX=0.0007
The code is as follows
XX=0.0007
enX1=XX//10**np.floor(np.log10(XX));
But XX becomes 6 not 7. Can anyone help me?
Thank you!!! | 0debug |
static int cloop_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVCloopState *s = bs->opaque;
uint32_t offsets_size, max_compressed_block_size = 1, i;
int ret;
bs->read_only = 1;
ret = bdrv_pread(bs->file, 128, &s->block_size, 4);
if (ret < 0) {
return ret;
s->block_size = be32_to_cpu(s->block_size);
ret = bdrv_pread(bs->file, 128 + 4, &s->n_blocks, 4);
if (ret < 0) {
return ret;
s->n_blocks = be32_to_cpu(s->n_blocks);
offsets_size = s->n_blocks * sizeof(uint64_t);
s->offsets = g_malloc(offsets_size);
ret = bdrv_pread(bs->file, 128 + 4 + 4, s->offsets, offsets_size);
if (ret < 0) {
goto fail;
for(i=0;i<s->n_blocks;i++) {
s->offsets[i] = be64_to_cpu(s->offsets[i]);
if (i > 0) {
uint32_t size = s->offsets[i] - s->offsets[i - 1];
if (size > max_compressed_block_size) {
max_compressed_block_size = size;
s->compressed_block = g_malloc(max_compressed_block_size + 1);
s->uncompressed_block = g_malloc(s->block_size);
if (inflateInit(&s->zstream) != Z_OK) {
ret = -EINVAL;
goto fail;
s->current_block = s->n_blocks;
s->sectors_per_block = s->block_size/512;
bs->total_sectors = s->n_blocks * s->sectors_per_block;
qemu_co_mutex_init(&s->lock);
return 0;
fail:
g_free(s->offsets);
g_free(s->compressed_block);
g_free(s->uncompressed_block);
return ret; | 1threat |
prevent bots / scrappers executing javascript to get output : <p>I see allot about Cpatcha's and Submission forms / methods to block bots and content scrappers / leechers but nothing about blocking those who take the entire JavaScript contents and execute it to obtain and view what it is outputting.</p>
<p>Is it possible to prevent bots executing JavaScript to obtain the output.</p>
<p>I have looked at if statements within JavaScipt checking screen resolutions, keyboards, mouse, touch screens basic human required functions etc but it is a hard area to find information on.</p>
<pre><code>if (bot){ //don't execute Javascript don't let the bot get the real output.
return;
}
</code></pre>
| 0debug |
Invert Angular 2 *ngFor : <pre><code><li *ngFor="#user of users ">
{{ user.name }} is {{ user.age }} years old.
</li>
</code></pre>
<p>Is it possible to invert the ngFor that the items are added bottom up? </p>
| 0debug |
No return in function in R : <pre><code>> B_linkages <- function (J,j) {sum((X-X_omit(J,j))/X[j+56*(J-1)])}
> B_linkages(1,1)
[1] 0.9723767
</code></pre>
<p>This one works just fine but</p>
<pre><code>> B_linkages_inter <- function (I,J) {
+ for (j in 1:56) {
+ for (i in 1:56) {
+ sum((X[i+56*(I-1)]-X_omit(J,j)[i+56*(I-1)])/X[j+56*(J-1)])
+ }
+ }
+ }
>
> B_linkages_inter(1,1)
> 1+2
[1] 3
</code></pre>
<p>B_linkages_inter(1,1) does not return any output compared to the previous function. </p>
<pre><code>> 1+2
[1] 3
</code></pre>
<p>is what I did to check if the R has stopped or not. Why isn't "B_linkages_inter(1,1)" showing any results?
X is an 2464*2464 matrix, X_omit(J,j) is a function which generates a matrix using the inverse of a 2464*2464 matrix.</p>
| 0debug |
Java Array Index Out Of Bounds Error For Array That Shouldn't Be Going Off Bounds : Hello helpful strangers on StackExchange. I have recently been working on a bit of a Java code and seems like I'm stuck.
Here is my code http://pastebin.com/XcFWjbUt
This line in particular: ma[count - 1] += 1;
Keeps going out of bounds whenever Trial tries t build it for some reason.I keep getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
I would really appreciate any help that you could spare because I can't seem to find any reason as to why that array would be going off bounds. My thanks. | 0debug |
Pip install of scikit-learn: No matching distribiution found. : <p>I am trying to install scikit-learn through pip on Mac OSX. I have updated all of numpy, scipy and pip itself but when I type:</p>
<blockquote>
<p>"pip install scikit-learn -U" </p>
</blockquote>
<p>I receive an error saying:</p>
<blockquote>
<p>"Could not find a version that satisfies the requirement scikit-learn (from versions: )
No matching distribution found for scikit-learn"</p>
</blockquote>
| 0debug |
NOOB! Replacing part of a string using a For loop : Hi i am a complete python and coding NOOB. recently started a college course. currently on For loops and have a question where i need to get a user to enter a sentence. using a FOR loop i then need to replace all spaces with %20 in order to prep the string to be used as a URL. cannot for the life of me figure it out. any help would be well received.
sentence = str(input("Please enter sentence:"))
space = (" ")
for space in sentence:
space.replace(sentence, space, "%20", 500)
print(sentence)
this is what i have entered so far but it is completely wrong and i really just cant fathom how to get around it. | 0debug |
ListView in BottomSheet : <p>I ran into a problem where I had a simple <code>ListView</code> in a <code>BottomSheet</code> and <code>ListView</code> had enough items to fill the screen and scroll even more.</p>
<p>When I scroll down, everything seems to work however when I tried to scroll back up, it was scrolling the <code>BottomSheet</code> itself and closing the view instead of just scrolling the <code>ListView</code>.</p>
<p>I was able to find a solution after a while and since I couldn't find it anywhere here, I figured I would post it here.</p>
| 0debug |
static int dnxhd_10bit_dct_quantize(MpegEncContext *ctx, DCTELEM *block,
int n, int qscale, int *overflow)
{
const uint8_t *scantable= ctx->intra_scantable.scantable;
const int *qmat = ctx->q_intra_matrix[qscale];
int last_non_zero = 0;
ctx->dsp.fdct(block);
block[0] = (block[0] + 2) >> 2;
for (int i = 1; i < 64; ++i) {
int j = scantable[i];
int sign = block[j] >> 31;
int level = (block[j] ^ sign) - sign;
level = level * qmat[j] >> DNX10BIT_QMAT_SHIFT;
block[j] = (level ^ sign) - sign;
if (level)
last_non_zero = i;
}
return last_non_zero;
}
| 1threat |
Python 3 type annotations and subclasses : <p>How do I refer to 'any object that subclasses a parent class' in Python type annotations?</p>
<p>Example: <code>FooBase</code> is an abstract base class, from which <code>Foo1</code>, <code>Foo2</code>, etc. are subclassed. I want the function to accept any descendant of <code>FooBase</code>. Will this do:</p>
<pre><code>def do_something(self, bar:FooBase):
pass
</code></pre>
<p>Or will this only accept an object of class <code>FooBase</code>, which of course is impossible given that <code>FooBase</code> is abstract? In that case, do I need to build a <code>Union</code> of all cases (please God I hope not!), or can I through some other way express this relationship abstractly?</p>
| 0debug |
TypeError 'x' is not a function : <p>TypeError: this.props.handleClick is not a function</p>
<pre><code>class Task extends React.Component{
render(){
return(
<div className="Task">
<span style = {{ textDecoration : this.props.todo.done ? 'line-through' : 'none'}}>{this.props.todo.value}</span>
<button onClick = {() => this.props.handleClick(this.props.index)}>{this.props.todo.done ? 'Undo' : 'Complete'}</button>
</div>
)
}
}
</code></pre>
| 0debug |
How to stop the loop when the same values appear in the list in Python? : [enter image description here][1]
[1]: https://i.stack.imgur.com/RmOKX.png
Above my task. I have to stop the loop when the same items appear in the list then sum them.
def squareA(a,b):
res = []
z = 0
while z!= 3:
res.insert(0,(a + z)**2)
res.insert(0,(b - z)**2)
z += 1
print(res)
res = list(dict.fromkeys(res))
print(res)
res = sum(res)
return res
a = 5
b = 6
print(squareA(a,b))
| 0debug |
alert('Hello ' + user_input); | 1threat |
how can change some [MSChart] series AxisLabel in c# : I want to change some series not all of them for my chart
I tried but I didn't solve this challenge
I wanna learn it for my progress
Thank You Masters | 0debug |
static int transcode(void)
{
int ret, i;
AVFormatContext *is, *os;
OutputStream *ost;
InputStream *ist;
uint8_t *no_packet;
int no_packet_count = 0;
int64_t timer_start;
if (!(no_packet = av_mallocz(nb_input_files)))
exit_program(1);
ret = transcode_init();
if (ret < 0)
goto fail;
av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
term_init();
timer_start = av_gettime();
for (; received_sigterm == 0;) {
int file_index, ist_index, past_recording_time = 1;
AVPacket pkt;
int64_t ipts_min;
ipts_min = INT64_MAX;
for (i = 0; i < nb_output_streams; i++) {
OutputFile *of;
ost = output_streams[i];
of = output_files[ost->file_index];
os = output_files[ost->file_index]->ctx;
if (ost->is_past_recording_time ||
(os->pb && avio_tell(os->pb) >= of->limit_filesize))
continue;
if (ost->frame_number > ost->max_frames) {
int j;
for (j = 0; j < of->ctx->nb_streams; j++)
output_streams[of->ost_index + j]->is_past_recording_time = 1;
continue;
}
past_recording_time = 0;
}
if (past_recording_time)
break;
file_index = -1;
for (i = 0; i < nb_input_streams; i++) {
int64_t ipts;
ist = input_streams[i];
ipts = ist->last_dts;
if (ist->discard || no_packet[ist->file_index])
continue;
if (!input_files[ist->file_index]->eof_reached) {
if (ipts < ipts_min) {
ipts_min = ipts;
file_index = ist->file_index;
}
}
}
if (file_index < 0) {
if (no_packet_count) {
no_packet_count = 0;
memset(no_packet, 0, nb_input_files);
usleep(10000);
continue;
}
break;
}
is = input_files[file_index]->ctx;
ret = av_read_frame(is, &pkt);
if (ret == AVERROR(EAGAIN)) {
no_packet[file_index] = 1;
no_packet_count++;
continue;
}
if (ret < 0) {
input_files[file_index]->eof_reached = 1;
for (i = 0; i < input_files[file_index]->nb_streams; i++) {
ist = input_streams[input_files[file_index]->ist_index + i];
if (ist->decoding_needed)
output_packet(ist, NULL);
}
if (opt_shortest)
break;
else
continue;
}
no_packet_count = 0;
memset(no_packet, 0, nb_input_files);
if (do_pkt_dump) {
av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
is->streams[pkt.stream_index]);
}
if (pkt.stream_index >= input_files[file_index]->nb_streams)
goto discard_packet;
ist_index = input_files[file_index]->ist_index + pkt.stream_index;
ist = input_streams[ist_index];
if (ist->discard)
goto discard_packet;
if (pkt.dts != AV_NOPTS_VALUE)
pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
if (pkt.pts != AV_NOPTS_VALUE)
pkt.pts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
if (pkt.pts != AV_NOPTS_VALUE)
pkt.pts *= ist->ts_scale;
if (pkt.dts != AV_NOPTS_VALUE)
pkt.dts *= ist->ts_scale;
if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE
&& (is->iformat->flags & AVFMT_TS_DISCONT)) {
int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
int64_t delta = pkt_dts - ist->next_dts;
if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {
input_files[ist->file_index]->ts_offset -= delta;
av_log(NULL, AV_LOG_DEBUG,
"timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
delta, input_files[ist->file_index]->ts_offset);
pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
if (pkt.pts != AV_NOPTS_VALUE)
pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
}
}
if (output_packet(ist, &pkt) < 0 || poll_filters() < 0) {
av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
ist->file_index, ist->st->index);
if (exit_on_error)
exit_program(1);
av_free_packet(&pkt);
continue;
}
discard_packet:
av_free_packet(&pkt);
print_report(0, timer_start);
}
for (i = 0; i < nb_input_streams; i++) {
ist = input_streams[i];
if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
output_packet(ist, NULL);
}
}
poll_filters();
flush_encoders();
term_exit();
for (i = 0; i < nb_output_files; i++) {
os = output_files[i]->ctx;
av_write_trailer(os);
}
print_report(1, timer_start);
for (i = 0; i < nb_output_streams; i++) {
ost = output_streams[i];
if (ost->encoding_needed) {
av_freep(&ost->st->codec->stats_in);
avcodec_close(ost->st->codec);
}
}
for (i = 0; i < nb_input_streams; i++) {
ist = input_streams[i];
if (ist->decoding_needed) {
avcodec_close(ist->st->codec);
}
}
ret = 0;
fail:
av_freep(&no_packet);
if (output_streams) {
for (i = 0; i < nb_output_streams; i++) {
ost = output_streams[i];
if (ost) {
if (ost->stream_copy)
av_freep(&ost->st->codec->extradata);
if (ost->logfile) {
fclose(ost->logfile);
ost->logfile = NULL;
}
av_fifo_free(ost->fifo);
av_freep(&ost->st->codec->subtitle_header);
av_free(ost->forced_kf_pts);
if (ost->avr)
avresample_free(&ost->avr);
av_dict_free(&ost->opts);
}
}
}
return ret;
}
| 1threat |
How does SQL SERVER broke down View code and pick the right tables to extract? : I encountered a problem regarding views in SQL SERVER 2017.
When query with a view, which has multiple underlying tables behind. Besides table involved in SELECT Clause, other tables also get logical read by SQL Server, want to know why.
So, here is scenario:
/*******************************************************/
CREATE VIEW v_test
AS
SELECT
a.col1,
a.col2,
b.col3,
b.col4,
c.col5,
c.col6,
d.col7,
d.col8,
e.col9,
e.col10,
f.col11,
f.col12,
g.col13,
g.col14
FROM a
LEFT JOIN b
LEFT JOIN c
LEFT JOIN d
LEFT JOIN e
LEFT JOIN f
LEFT JOIN g
/*********************************************************/
SELECT col1, col2
FROM V_test
--The col1 col2 should only be pulled out from tbl_a.=>means, logical reads should only read table a.
--However, the logical reads turns out to read more tables than tbl_a. In an senario I got, it reads tbl_a thru tbl_g.
WHY?
| 0debug |
Error on amazon SES: SendEmail operation: Illegal addres : <p>I'm trying to send email through <a href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/setting-up-email.html" rel="noreferrer">AWS SES</a>, but I'm receiving this error:</p>
<pre><code>botocore.exceptions.ClientError: An error occurred (InvalidParameterValue) when calling the SendEmail operation: Illegal address
</code></pre>
<p>I already verified the email I'm sending to and from.
This is my code:</p>
<pre><code>import boto3
client = boto3.client(
'ses',
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY
)
response = client.send_email(
Destination={
'ToAddresses': [
'xxx@xxx.com',
],
},
Message={
'Body': {
'Html': {
'Charset': 'UTF-8',
'Data': 'This message body contains HTML formatting. It can, for example, contain links like this one: <a class="ulink" href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide" target="_blank">Amazon SES Developer Guide</a>.',
},
'Text': {
'Charset': 'UTF-8',
'Data': 'This is the message body in text format.',
},
},
'Subject': {
'Charset': 'UTF-8',
'Data': 'Test email',
},
},
ReplyToAddresses=[
],
ReturnPath='',
ReturnPathArn='',
Source='xxx@xxx.com',
SourceArn='',
)
</code></pre>
<p>How can I fix this?</p>
| 0debug |
static int svag_read_header(AVFormatContext *s)
{
unsigned size, align;
AVStream *st;
avio_skip(s->pb, 4);
st = avformat_new_stream(s, NULL);
if (!st)
return AVERROR(ENOMEM);
size = avio_rl32(s->pb);
st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
st->codec->codec_id = AV_CODEC_ID_ADPCM_PSX;
st->codec->sample_rate = avio_rl32(s->pb);
if (st->codec->sample_rate <= 0)
return AVERROR_INVALIDDATA;
st->codec->channels = avio_rl32(s->pb);
if (st->codec->channels <= 0)
return AVERROR_INVALIDDATA;
st->duration = size / (16 * st->codec->channels) * 28;
align = avio_rl32(s->pb);
if (align <= 0 || align > INT_MAX / st->codec->channels)
return AVERROR_INVALIDDATA;
st->codec->block_align = align * st->codec->channels;
avio_skip(s->pb, 0x800 - avio_tell(s->pb));
avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
return 0;
}
| 1threat |
No 'Access-Control-Allow-Origin' header is present on the requested resource while accessing a local server by angular app : <p>I was trying to get results from a local server. The class which I am using in the service is as follows:</p>
<pre><code>@Injectable()
export class GridSearchService {
server = 'http://127.0.0.1:8100';
searchURL = this.server + '/yacy/grid/mcp/index/yacysearch.json?query=';
constructor(private http: Http,
private jsonp: Jsonp,
private store: Store<fromRoot.State>) {
}
getSearchResults(searchquery) {
return this.http
.get(this.searchURL+searchquery).map(res =>
res.json()
).catch(this.handleError);
}
</code></pre>
<p>but I was getting this error in console</p>
<pre><code>Failed to load http://127.0.0.1:8100/yacy/grid/mcp/index/yacysearch.json?query=india: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
</code></pre>
<p>Then I followed this answer <a href="https://stackoverflow.com/a/37228330/7407321">https://stackoverflow.com/a/37228330/7407321</a> and set headers accordingly. The new code looks like this:</p>
<pre><code>@Injectable()
export class GridSearchService {
server = 'http://127.0.0.1:8100';
searchURL = this.server + '/yacy/grid/mcp/index/yacysearch.json?query=';
constructor(private http: Http,
private jsonp: Jsonp,
private store: Store<fromRoot.State>) {
}
getSearchResults(searchquery) {
let params = new URLSearchParams();
params.set('query',searchquery);
let headers = new Headers({ "Access-Control-Allow-Origin":"*",
"Access-Control-Allow-Credentials":"true",
"Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT",
"Access-Control-Allow-Headers": "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"});
let options = new RequestOptions({ headers: headers, search: params });
return this.http
.get(this.searchURL,options).map(res =>
res.json()
).catch(this.handleError);
}
</code></pre>
<p>I get this error message now:</p>
<pre><code>Failed to load http://127.0.0.1:8100/yacy/grid/mcp/index/yacysearch.json?query=&query=india: Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.
</code></pre>
<p>Using a CORS plugin is working fine but can it be done without that.</p>
| 0debug |
static void tgen_ext8s(TCGContext *s, TCGType type, TCGReg dest, TCGReg src)
{
if (facilities & FACILITY_EXT_IMM) {
tcg_out_insn(s, RRE, LGBR, dest, src);
return;
}
if (type == TCG_TYPE_I32) {
if (dest == src) {
tcg_out_sh32(s, RS_SLL, dest, TCG_REG_NONE, 24);
} else {
tcg_out_sh64(s, RSY_SLLG, dest, src, TCG_REG_NONE, 24);
}
tcg_out_sh32(s, RS_SRA, dest, TCG_REG_NONE, 24);
} else {
tcg_out_sh64(s, RSY_SLLG, dest, src, TCG_REG_NONE, 56);
tcg_out_sh64(s, RSY_SRAG, dest, dest, TCG_REG_NONE, 56);
}
}
| 1threat |
def rgb_to_hsv(r, g, b):
r, g, b = r/255.0, g/255.0, b/255.0
mx = max(r, g, b)
mn = min(r, g, b)
df = mx-mn
if mx == mn:
h = 0
elif mx == r:
h = (60 * ((g-b)/df) + 360) % 360
elif mx == g:
h = (60 * ((b-r)/df) + 120) % 360
elif mx == b:
h = (60 * ((r-g)/df) + 240) % 360
if mx == 0:
s = 0
else:
s = (df/mx)*100
v = mx*100
return h, s, v | 0debug |
No javascript source from Github pages : <p>I cannot find the javascript source for a resume I'm trying to host on github pages. I'm not sure what is wrong...</p>
<p>Here is a link to the site
<a href="https://rowansdabomb.github.io/" rel="nofollow">https://rowansdabomb.github.io/</a></p>
<p>Thanks in advance for any help!</p>
| 0debug |
undefined reference to outputVLI? : I have to make 2 arrays and use functions to input, output, add, and compare them but I keep getting error message: "undefined reference to outputVLI(int*, int)". I am not sure what this means or how to fix it. Any help would be appreciated
#include <iostream>
using namespace std;
const int maxDigits = 100;
void inputVLI (int vli[], int size); // Inputs the very long integers
void outputVLI (int vli[], int size); // Outputs the very long integers
void addVLI (const int vli1[], const int vli2[], int vli3[], int size1, int size2, int& size3); // Adds the very long integers together
int compVLI (const int vli1, const int vli2, int size1, int size2); // Compares the very long integers
int main()
{
int vli1[maxDigits], vli2[maxDigits], vli3[maxDigits], size1, size2, size3;
inputVLI (vli1, maxDigits); // Calls the individual functions
outputVLI (vli1, maxDigits); // |
inputVLI (vli2, maxDigits); // |
outputVLI (vli2, maxDigits); // |
/*addVLI (vli1, vli2, vli3, size1, size2, size3); // |
compVLI (vli1, vli2, size1, size2);*/ // \/
return 0;
}
void inputVLI(int vli[], int size)
{
cout << "Enter a very long integer" << endl;
cin >> vli[maxDigits];
}
void output (int vli[], int size)
{
for (int i=maxDigits; i>=0; i--)
cout << vli[i];
}
void addVLI (const int vli1[], const int vli2[], int vli3[], int size1, int size2, int& size3)
{
/*
for (int i=0; i<maxDigits; i++)
{
vli3[i]=vli1[i] + vli2[i];
cout << "The sum of the vli's is:" << vli3[i] << endl;
}
*/
}
int compVLI (const int vli1, const int vli2, int size1, int size2)
{
/*
for (int i=0; vli1[maxDigits] && vli2[maxDigits]; i++)
{
if (vli1[maxDigits] != vli2[maxDigits])
{
return (-1); // -1 is not equal
}
return (1); // 1 is equal
}
*/
}
| 0debug |
how to get specific data from Json and display in Google map in rails : i connected to DB NOSQL online return json value
for example
`{"_id"=>"5b2e880c1de0c46b00001dda", "gps_lattitude"=>"30.63","gps_longitude"=>"31.09", "gps_speed_kph"=>"0.1", "gps_heading"=>"129.36", "gsm_csecond"=>58, "gsm_second"=>46, "gsm_minute"=>35, "gsm_hour"=>21, "gsm_month"=>6, "gsm_day"=>20, "gsm_year"=>2018, "HWID"=>"AC37439773C8", "pulse_rate"=>585, "recrdID"=>458}`
need display `gps_longitude` & `gps_lattitude` to google map
**when work with sql database can do it easy but not know how can do it use json** | 0debug |
How to redirect a .html file to a subfolder? : <p>I trying to create an online multilingual cv by using html. Just I don't find any solutions how can redirect "www.cv.com/cvfiles/index_en.html" url to "www.cv.com/en/cvfiles/" ? As well with French (index_fr.html) and German (index_de.html) too...</p>
<p>All files of the site of my cv can find in the following folder: .../public_html/cvfiles/</p>
| 0debug |
def remove_odd(l):
for i in l:
if i % 2 != 0:
l.remove(i)
return l | 0debug |
Postgres Docker image is not creating database with custom name : <p>The documentation of the <code>postgres</code> Docker image <a href="https://hub.docker.com/_/postgres/#postgres_db" rel="noreferrer">says</a> the following about the env var <code>POSTGRES_DB</code>:</p>
<blockquote>
<p>This optional environment variable can be used to define a different name for the default database that is created when the image is first started. If it is not specified, then the value of POSTGRES_USER will be used.</p>
</blockquote>
<p>I have found that this is not true at all. For example, with this config:</p>
<pre><code>version: '3.7'
services:
db:
image: postgres:11.3-alpine
restart: always
container_name: store
volumes:
- postgres_data:/var/lib/postgresql/data/
ports:
- 5432:5432
environment:
- POSTGRES_USER=custom
- POSTGRES_DB=customname
- POSTGRES_PASSWORD_FILE=/run/secrets/db_password
secrets:
- db_password
volumes:
postgres_data:
secrets:
db_password:
file: config/.secrets.db_password
</code></pre>
<p>The default database is called <code>postgres</code>, and not <code>customname</code> as I have specified:</p>
<pre><code>$ docker exec -it store psql -U custom customname
psql: FATAL: database customname does not exist
$ docker exec -it store psql -U custom postgres
psql (11.3)
Type help for help.
postgres=# ^D
</code></pre>
<p>Am I missing something obvious?</p>
| 0debug |
static int xen_add_to_physmap(XenIOState *state,
hwaddr start_addr,
ram_addr_t size,
MemoryRegion *mr,
hwaddr offset_within_region)
{
unsigned long i = 0;
int rc = 0;
XenPhysmap *physmap = NULL;
hwaddr pfn, start_gpfn;
hwaddr phys_offset = memory_region_get_ram_addr(mr);
char path[80], value[17];
const char *mr_name;
if (get_physmapping(state, start_addr, size)) {
return 0;
}
if (size <= 0) {
return -1;
}
if (mr == framebuffer && start_addr > 0xbffff) {
goto go_physmap;
}
return -1;
go_physmap:
DPRINTF("mapping vram to %"HWADDR_PRIx" - %"HWADDR_PRIx"\n",
start_addr, start_addr + size);
pfn = phys_offset >> TARGET_PAGE_BITS;
start_gpfn = start_addr >> TARGET_PAGE_BITS;
for (i = 0; i < size >> TARGET_PAGE_BITS; i++) {
unsigned long idx = pfn + i;
xen_pfn_t gpfn = start_gpfn + i;
rc = xc_domain_add_to_physmap(xen_xc, xen_domid, XENMAPSPACE_gmfn, idx, gpfn);
if (rc) {
DPRINTF("add_to_physmap MFN %"PRI_xen_pfn" to PFN %"
PRI_xen_pfn" failed: %d (errno: %d)\n", idx, gpfn, rc, errno);
return -rc;
}
}
mr_name = memory_region_name(mr);
physmap = g_malloc(sizeof (XenPhysmap));
physmap->start_addr = start_addr;
physmap->size = size;
physmap->name = mr_name;
physmap->phys_offset = phys_offset;
QLIST_INSERT_HEAD(&state->physmap, physmap, list);
xc_domain_pin_memory_cacheattr(xen_xc, xen_domid,
start_addr >> TARGET_PAGE_BITS,
(start_addr + size - 1) >> TARGET_PAGE_BITS,
XEN_DOMCTL_MEM_CACHEATTR_WB);
snprintf(path, sizeof(path),
"/local/domain/0/device-model/%d/physmap/%"PRIx64"/start_addr",
xen_domid, (uint64_t)phys_offset);
snprintf(value, sizeof(value), "%"PRIx64, (uint64_t)start_addr);
if (!xs_write(state->xenstore, 0, path, value, strlen(value))) {
return -1;
}
snprintf(path, sizeof(path),
"/local/domain/0/device-model/%d/physmap/%"PRIx64"/size",
xen_domid, (uint64_t)phys_offset);
snprintf(value, sizeof(value), "%"PRIx64, (uint64_t)size);
if (!xs_write(state->xenstore, 0, path, value, strlen(value))) {
return -1;
}
if (mr_name) {
snprintf(path, sizeof(path),
"/local/domain/0/device-model/%d/physmap/%"PRIx64"/name",
xen_domid, (uint64_t)phys_offset);
if (!xs_write(state->xenstore, 0, path, mr_name, strlen(mr_name))) {
return -1;
}
}
return 0;
}
| 1threat |
static int parse_frame_header(DCACoreDecoder *s)
{
DCACoreFrameHeader h = { 0 };
int err = avpriv_dca_parse_core_frame_header(&s->gb, &h);
if (err < 0) {
switch (err) {
case DCA_PARSE_ERROR_DEFICIT_SAMPLES:
av_log(s->avctx, AV_LOG_ERROR, "Deficit samples are not supported\n");
return h.normal_frame ? AVERROR_INVALIDDATA : AVERROR_PATCHWELCOME;
case DCA_PARSE_ERROR_PCM_BLOCKS:
av_log(s->avctx, AV_LOG_ERROR, "Unsupported number of PCM sample blocks (%d)\n", h.npcmblocks);
return (h.npcmblocks < 6 || h.normal_frame) ? AVERROR_INVALIDDATA : AVERROR_PATCHWELCOME;
case DCA_PARSE_ERROR_FRAME_SIZE:
av_log(s->avctx, AV_LOG_ERROR, "Invalid core frame size (%d bytes)\n", h.frame_size);
return AVERROR_INVALIDDATA;
case DCA_PARSE_ERROR_AMODE:
av_log(s->avctx, AV_LOG_ERROR, "Unsupported audio channel arrangement (%d)\n", h.audio_mode);
return AVERROR_PATCHWELCOME;
case DCA_PARSE_ERROR_SAMPLE_RATE:
av_log(s->avctx, AV_LOG_ERROR, "Invalid core audio sampling frequency\n");
return AVERROR_INVALIDDATA;
case DCA_PARSE_ERROR_RESERVED_BIT:
av_log(s->avctx, AV_LOG_ERROR, "Reserved bit set\n");
return AVERROR_INVALIDDATA;
case DCA_PARSE_ERROR_LFE_FLAG:
av_log(s->avctx, AV_LOG_ERROR, "Invalid low frequency effects flag\n");
return AVERROR_INVALIDDATA;
case DCA_PARSE_ERROR_PCM_RES:
av_log(s->avctx, AV_LOG_ERROR, "Invalid source PCM resolution\n");
return AVERROR_INVALIDDATA;
default:
av_log(s->avctx, AV_LOG_ERROR, "Unknown core frame header error\n");
return AVERROR_INVALIDDATA;
}
}
s->crc_present = h.crc_present;
s->npcmblocks = h.npcmblocks;
s->frame_size = h.frame_size;
s->audio_mode = h.audio_mode;
s->sample_rate = avpriv_dca_sample_rates[h.sr_code];
s->bit_rate = ff_dca_bit_rates[h.br_code];
s->drc_present = h.drc_present;
s->ts_present = h.ts_present;
s->aux_present = h.aux_present;
s->ext_audio_type = h.ext_audio_type;
s->ext_audio_present = h.ext_audio_present;
s->sync_ssf = h.sync_ssf;
s->lfe_present = h.lfe_present;
s->predictor_history = h.predictor_history;
s->filter_perfect = h.filter_perfect;
s->source_pcm_res = ff_dca_bits_per_sample[h.pcmr_code];
s->es_format = h.pcmr_code & 1;
s->sumdiff_front = h.sumdiff_front;
s->sumdiff_surround = h.sumdiff_surround;
return 0;
}
| 1threat |
Converting Decimal value to Binary in Java.(problem with used method in this code!) : Sir! here my problem is on method.
in this code used method was void type. ok then why there is return and
next it does recursion!
if anyone little describe it, then i think it will be easy for me :)
`
import java.util.Scanner;
class Code {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your Decimal value here : ");
int num = sc.nextInt();
printBinaryform(num);
System.out.println();
}
private static void printBinaryform(int number) {
int remainder;
if (number <= 1) {
System.out.print(number);
return; // KICK OUT OF THE RECURSION
}
remainder = number % 2;
printBinaryform(number >> 1);
System.out.print(remainder);
}
}
` | 0debug |
Is it possible to add two functions together in C++? : <p>I am looking for a way to return the addition of two functions within int main(). Is this possible or do I have to take the long route?</p>
| 0debug |
how do i insert expandable listview child item into sqlite? : <p>I am new in android. I want to insert expandable listview child click item into sqlite database Any help please give me suggestion.</p>
| 0debug |
Using Php and Mysql : <p>I recently joined this forum because I was impressed with the way problems are solved.. And i hope you guys will be of help..</p>
<p>K..I recently started working on php and mysql, and I have been able to create a database, login and sign up form.. I want to create a peer to peer donation website..where members donate to each other..but am faced with this problem currently</p>
<p>How to show user 1 details(name,email, phone number, PayPal details) from the database to user2, user3, user4.</p>
<p>I appreciate your help guys..</p>
| 0debug |
Batch - Commenting on YouTube : <p>I would like to create a simple program that can comment on youtube videos automatically. If This is possible then maybe i can find a Way To automatically comment on youtube
Thanks in advance</p>
| 0debug |
JButton ActionListener (Java 8 JDK 1.8.0_74) is not working : <p>I was in the middle of making a program to remove commented lines from any file, I had just finished the main GUI and added two action listeners to my JButtons and then it all broke. I feel like I made a really stupid mistake somewhere but I can't figure out where. Any ideas? (major region is commented out)</p>
<pre><code>import javax.swing.plaf.basic.BasicOptionPaneUI.ButtonActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JTextField;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.Box;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Dimension;
import java.awt.Component;
import java.awt.Container;
import java.awt.Toolkit;
import java.awt.Label;
import java.awt.Font;
public class ReplaceComments{
public static void main(String[]args){
createInitialWindow();
}
public static void createInitialWindow(){
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int w = (int)screenSize.getWidth();
int h = (int)screenSize.getHeight();
System.out.println("Width: " + w + "\nHeight: " + h + "\nCreating customized window...");
JLabel explanation1 = new JLabel("Welcome to Comment Replacer 1.0!");
explanation1.setFont(new Font("Verdana", Font.PLAIN, w/80));
explanation1.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel explanation2 = new JLabel("Simply paste in the file you want");
explanation2.setFont(new Font("Verdana", Font.PLAIN, w/80));
explanation2.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel explanation3 = new JLabel("to remove comments from, and the");
explanation3.setFont(new Font("Verdana", Font.PLAIN, w/80));
explanation3.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel explanation4 = new JLabel("folder it should output to.");
explanation4.setFont(new Font("Verdana", Font.PLAIN, w/80));
explanation4.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel Source = new JLabel("Source: ");
Source.setFont(new Font("Verdana", Font.PLAIN, w/80));
JTextField source = new JTextField(w/130);
source.setFont(new Font("Verdana", Font.PLAIN, w/80));
JLabel Output = new JLabel("Output: ");
Output.setFont(new Font("Verdana", Font.PLAIN, w/80));
JTextField output = new JTextField(w/130);
output.setFont(new Font("Verdana", Font.PLAIN, w/80));
/* \/ This Part \/ */
JButton replace = new JButton("Replace");
replace.setFont(new Font("Verdana", Font.PLAIN, w/80));
replace.setSize(new Dimension(w/8,h/8));
replace.addActionListener(new CustomActionListener(){ /*********************/
public void actionPerformed(ActionEvent e){ /* Added this action */
replaceButtonClicked(); /* listener and it */
} /* all broke :3 */
}); /*********************/
JButton cancel = new JButton("Cancel");
cancel.setFont(new Font("Verdana", Font.PLAIN, w/80));
cancel.setSize(new Dimension(w/8,h/8));
cancel.addActionListener(new CustomActionListener(){ /*********************/
public void actionPerformed(ActionEvent e){ /* Added this action */
cancelButtonClicked(); /* listener and it */
} /* all broke :3 */
}); /*********************/
/* /\ This Part /\ */
ButtonGroup screen1 = new ButtonGroup();
screen1.add(replace);
screen1.add(cancel);
Box info = Box.createVerticalBox();
info.add(Box.createVerticalStrut(w/100));
info.add(explanation1);
info.add(explanation2);
info.add(explanation3);
info.add(explanation4);
Box sourceBox = Box.createHorizontalBox();
sourceBox.add(Source);
sourceBox.add(source);
Box outputBox = Box.createHorizontalBox();
outputBox.add(Output);
outputBox.add(output);
Box textBoxes = Box.createVerticalBox();
info.add(Box.createVerticalStrut(w/21));
textBoxes.add(sourceBox);
textBoxes.add(outputBox);
Box buttons = Box.createHorizontalBox();
buttons.add(replace);
buttons.add(Box.createHorizontalStrut(w/50));
buttons.add(cancel);
buttons.add(Box.createVerticalStrut(w/30));
JPanel upperPanel = new JPanel();
upperPanel.add(info);
JPanel middlePanel = new JPanel();
middlePanel.add(textBoxes);
JPanel lowerPanel = new JPanel();
lowerPanel.add(buttons);
BorderLayout border = new BorderLayout();
JFrame frameWindow = new JFrame("Comment Replacer v1.0");
frameWindow.add(upperPanel,BorderLayout.NORTH);
frameWindow.add(middlePanel,BorderLayout.CENTER);
frameWindow.add(lowerPanel,BorderLayout.SOUTH);
frameWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameWindow.setSize(w/2,h/2);
frameWindow.setLocationRelativeTo(null);
frameWindow.setVisible(true);
System.out.println("Done!");
}
public void replaceButtonClicked(){
System.out.println("Replace button clicked!");
// Do something else
}
public void cancelButtonClicked(){
System.out.println(";-;");
System.exit(0);
}
}
</code></pre>
| 0debug |
How to send an ArrayList of objects to other activity? : <p>I want to know how to do it to make a listview in second activity</p>
<pre><code>Person person = new Person(nome, idade, numero);
this.list.add(person);
int number= this.list.size();
this.numero.setText(String.valueOf(number));
this.item.setText("");
}
break;
case R.id.btn_activity2:
Intent intent = new Intent(MainActivity.this, ListActivity.class);
intent.put(...here is the problem)
startActivity(intent);
break;
</code></pre>
| 0debug |
C# Regex replace all word that start with specific character : <p>I have an string and I wanna to replace all word that start with <code>$</code> and end with <code></code> (white space) with something else.</p>
<p>Whats the best practice for this?</p>
| 0debug |
JavaScript detect alert and stop it from showing : <p>I am using a 3rd party js that shows <code>alert</code>'s to the user, is there a way to catch the alert before it is displayed, and show something else instead? example:</p>
<pre><code>function doOtherPeopleCode(){
sdk.doStuff(); //catch all sdk alerts
}
</code></pre>
| 0debug |
How to delete a row of code in java : This is my code that im working with right now and even if it sounds like the most ez problem ever i still want to know how to solve it. My problem is that i want the command g.drawString(String.valueOf(FULLHEALTH), 50, 15); to be deleted when my player class goes under 100 hp and i dont know how to do that. also im new to this so no flame
package com.tutorial.main;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JTextArea;
public class HUD {
public static int HEALTH = 100;
public static int FULLHEALTH = 100;
private int greenValue = 255;
public void tick() {
HEALTH = Game.clamp(HEALTH, 0, 100);
greenValue = Game.clamp(greenValue, 0, 255);
greenValue = HEALTH*2;
if (HEALTH == 0)
System.exit(1);
}
public void render(Graphics g) {
g.setColor(Color.gray);
g.fillRect(15, 15, 200, 32);
g.setColor(new Color(75, greenValue, 0));
g.fillRect(15, 15, HEALTH * 2, 32);
g.setColor(Color.white);
g.drawRect(15, 15, 200, 32);
String string = "/";
Font stringFont = new Font( "HEALTH", Font.PLAIN, 18 );
g.setFont( stringFont );
g.drawString(String.valueOf(HEALTH), 15, 15);
g.drawString(String.valueOf(FULLHEALTH), 50, 15);
if(HEALTH < 100){
delete g.drawString(String.valueOf(FULLHEALTH), 50, 15);// how to make this command work plz help
g.drawString(String.valueOf(FULLHEALTH), 45, 15);
g.drawString("/", 40, 15);
}
}
}
| 0debug |
What's the point of <button type="button">? : <p>Is <code><button type="button></code> any different from a simple <code><button></code> with a blank or missing <code>type</code> attribute? MDN and the HTML5 spec say that <code>type=button</code> is for buttons whose purpose is to trigger custom JavaScript, but isn't that also what a <code><button></code> does by default?</p>
| 0debug |
Python 3: Activity 1 of task 1 prompt a user to input firstname, lastname and initials : Hi everyone I have been trying to figure out the best way to do this question I have to fix for my task 1. The teacher asks me to not hard code the answer or the name because I have to prompt user input. These are his errors he wrote out:
Activity 1: 2 errors
By the end of it I should be able to prompt him to enter a first name, a last name and initials without hard [enter image description here][1]coding
By the way this is my code I have attempted so far:
Activity 1 Part B is fine he said but its just part A and Activity 2
[attempted code I have done][2]
[1]: https://i.stack.imgur.com/vR6lG.png
[2]: https://i.stack.imgur.com/8SbUr.png | 0debug |
Python class and main function not running? : <pre><code>#Homework 10 Question 6 Zachariah Huckstep
#Employee Management System
#Employee Class
class Employee():
#Init method
def __init__(self,empName,empID,empDept,empTitle):
#Set self name, id number, department and job title
self.name=empName
self.idnum=empID
self.dept=empDept
self.title=empTitle
#set_name method
def set_name(self,empName):
#Set the name
self.__empName=empName
#set_idnum method
def set_idnum(self,empID):
#Set the id number
self.__empID=empID
#set_dept method
def set_dept(self,empDept):
#Set the department
self.__empDept=empDept
#set_title method
def set_title(self,empTitle):
#Set the title
self.__empTitle=empTitle
#get_name method
def get_name(self):
#Get the name
return self.__empName
#get_idnum method
def get_idnum(self):
#Get the id number
return self.__empID
#get_dept method
def get_dept(self):
#Get the department
return self.__empDept
#get_title method
def get_title(self):
#Get the title
return self.__empTitle
#__str__ method
def __str__(self):
#Return object state as a string
return "Name: "+self.__empName+\
"\nID Number: "+self.__empID+\
"\nDepartment: "+self.__empDept+\
"\nJob Title: "+self.__empTitle
#Start of program
import pickle
#Menu choices
lookup=1
add=2
change=3
delete=4
quit=5
#File name
fileName='staff.db'
#main function
def main():
#Load the existing employee database as a dictionary
#and assign it to staff
staff=load_staff()
#Set users option
opt=0
#Process menu options until quit
while opt != quit:
#Get the user's menu option
opt=get_menu_option()
#Decide what to do
if opt == lookup:
lookup(staff)
elif opt == add:
add(staff)
elif opt == change:
change(staff)
elif opt == delete:
delete(staff)
#Save staff dictionary to staff.db
save_staff(staff)
#Load staff function
def load_staff():
#Try opening staff.db
try:
#Open the staff.db file
file=open(fileName,'rb')
#Unpickle the dictionary
staff_dct=pickle.load(file)
#Close the staff.db file
file.close()
except IOError:
#Could not find file, so make an
#empty dictionary
staff_dct={}
#Return the staff database as a dictionary
return staff_dct
#Print menu options and get opt
def get_menu_option():
#Print menu
print()
print('Menu:')
print('1. Look up an employee')
print('2. Add a new employee')
print('3. Change an existing employee')
print('4. Delete an employee entry')
print('5. Quit the Employee Management System')
print()
#Get opt
opt=int(input('=>'))
#Validate opt
while opt < lookup or choice > quit:
#Get valid opt
opt=int(input('Enter valid choice: '))
#Return opt
return opt
#Lookup function
def lookup(staff):
#Ask for the employee ID
empID=input('Enter empoyee ID: ')
#Search employee database for employee ID
print(staff.get(empID,'Invalid ID Number.')
#Add function
def add(staff):
#Ask for employee info
print('Please enter the following new employee information:')
empName=input('Name: ')
empID=input('ID Number: ')
empDept=input('Department: ')
empTitle=input('Job Title: ')
#Create a current employee object named currEmp
currEmp=Employee(empName,empID,empDept,empTitle)
#If the ID number is invalid, add it as a key
#with the currEmp object as the value
if empID not in staff:
#Add currEmp into staff
staff[empID]=currEmp
print('New employee added.')
else:
#Print error
print('That employee ID already exists.')
#Change function
def change(staff):
#Ask for employee ID
empID=input('Enter Employee ID: ')
if empID in staff:
#Ask for new name
empName=input('Enter new name: ')
#Ask for new department
empDept=input('Enter new department: ')
#Ask for new job title
empTitle=input('Enter new job title: ')
#Create an employee object named currEmp
currEmp=Employee(empName,empID,empDept,empTitle)
#Update the employee information
staff[empID]=currEmp
else:
#Print error
print('Error: Invalid employee ID.')
#Delete function
def delete(staff):
#Ask for employee ID
empID=input('Enter employee ID: ')
#If the employee ID is found, delete it from staff
if empID in staff:
#Delete it
del staff[empID]
print('Employee deleted from database.')
else:
#Print error
print('Error: Invalid employee ID.')
#Save staff function
def save_staff(staff):
#Pickle the staff object and save it to staff.db
#Open file for writing
file=open(fileName,'wb')
#Pickle staff database and save it
pickle.dump(staff,file)
#Close the file
file.close()
#Call the main function
main()
</code></pre>
<p>This program is an Employee Management System, I wrote it all out last night, and now I can't run it. It is having trouble running at line 154 (the Add function)</p>
<p>Python is telling me this:
def add(staff):
^
SyntaxError: Invalid syntax</p>
<p>Please help.</p>
| 0debug |
static int mxf_parse_index(MXFContext *mxf, int track_id, AVStream *st)
{
int64_t accumulated_offset = 0;
int j, k, ret, nb_sorted_segments;
MXFIndexTableSegment **sorted_segments;
int n_delta = track_id - 1;
if (track_id < 1) {
av_log(mxf->fc, AV_LOG_ERROR, "TrackID not positive: %i\n", track_id);
return AVERROR_INVALIDDATA;
}
if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)))
return ret;
for (j = 0; j < nb_sorted_segments; j++) {
int duration, sample_duration = 1, last_sample_size = 0;
int64_t segment_size;
MXFIndexTableSegment *tableseg = sorted_segments[j];
if (j > 0 && tableseg->body_sid != sorted_segments[j-1]->body_sid)
accumulated_offset = 0;
if (n_delta >= tableseg->nb_delta_entries && st->index != 0)
continue;
duration = tableseg->index_duration > 0 ? tableseg->index_duration :
st->duration - st->nb_index_entries;
segment_size = tableseg->edit_unit_byte_count * duration;
if (tableseg->edit_unit_byte_count && tableseg->edit_unit_byte_count < 32
&& !tableseg->index_duration) {
sample_duration = 8192;
last_sample_size = (duration % sample_duration) * tableseg->edit_unit_byte_count;
tableseg->edit_unit_byte_count *= sample_duration;
duration /= sample_duration;
if (last_sample_size) duration++;
}
for (k = 0; k < duration; k++) {
int64_t pos;
int size, flags = 0;
if (k < tableseg->nb_index_entries) {
pos = tableseg->stream_offset_entries[k];
if (n_delta < tableseg->nb_delta_entries) {
if (n_delta < tableseg->nb_delta_entries - 1) {
size =
tableseg->slice_offset_entries[k][tableseg->slice[n_delta+1]-1] +
tableseg->element_delta[n_delta+1] -
tableseg->element_delta[n_delta];
if (tableseg->slice[n_delta] > 0)
size -= tableseg->slice_offset_entries[k][tableseg->slice[n_delta]-1];
} else if (k < duration - 1) {
size = tableseg->stream_offset_entries[k+1] -
tableseg->stream_offset_entries[k] -
tableseg->slice_offset_entries[k][tableseg->slice[tableseg->nb_delta_entries-1]-1] -
tableseg->element_delta[tableseg->nb_delta_entries-1];
} else
size = 0;
if (tableseg->slice[n_delta] > 0)
pos += tableseg->slice_offset_entries[k][tableseg->slice[n_delta]-1];
pos += tableseg->element_delta[n_delta];
} else
size = 0;
flags = !(tableseg->flag_entries[k] & 0x30) ? AVINDEX_KEYFRAME : 0;
} else {
pos = (int64_t)k * tableseg->edit_unit_byte_count + accumulated_offset;
if (n_delta < tableseg->nb_delta_entries - 1)
size = tableseg->element_delta[n_delta+1] - tableseg->element_delta[n_delta];
else {
if (last_sample_size && k == duration - 1)
size = last_sample_size;
else
size = tableseg->edit_unit_byte_count;
if (tableseg->nb_delta_entries)
size -= tableseg->element_delta[tableseg->nb_delta_entries-1];
}
if (n_delta < tableseg->nb_delta_entries)
pos += tableseg->element_delta[n_delta];
flags = AVINDEX_KEYFRAME;
}
if (mxf_absolute_bodysid_offset(mxf, tableseg->body_sid, pos, &pos) < 0) {
break;
}
av_dlog(mxf->fc, "Stream %d IndexEntry %d TrackID %d Offset %"PRIx64" Timestamp %"PRId64"\n",
st->index, st->nb_index_entries, track_id, pos, sample_duration * st->nb_index_entries);
if ((ret = av_add_index_entry(st, pos, sample_duration * st->nb_index_entries, size, 0, flags)) < 0)
return ret;
}
accumulated_offset += segment_size;
}
av_free(sorted_segments);
return 0;
}
| 1threat |
Can someone help me out with the download code in PHP with passing variables from links? : hey i crated a page indes.php with the following code :
<?php
include "db.php";
$select="SELECT *FROM alldocs ";
$query=mysqli_query($conn,$select);
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="text" name="name" placeholder="name"><br><br>
<input type="file" name="file" ><br><br>
<input type="submit" name="submit" value="submit"><br><br>
</form>
<div class="box-info">
<?php
while($row=mysqli_fetch_assoc($query)){
echo $row['name'].'<br>'.
'<a href="downloud.php?get=$path">downloud file</a> <br>';}
?>
</div>
than i crated the upload.php like this
<?php
if(isset($_POST['submit'])){
include "db.php";
$name =$_POST['name'];
$file =$_FILES['file'];
$fileName =$file['name'];
$fileTmp =$file['tmp_name'];
$path='downloud/$fileName';
if(move_uploaded_file($fileTmp , $path)){
$insert=" INSERT INTO alldocs(name,path) VALUES('$name','$path')";
$query=mysqli_query($conn,$insert);
header("Location:index.php");
}}
?>
Now i the index.pho in the link i tryed to hook up at the get=$path so that i can get in the next page wich will make it possible to dowloud the path from the db like this :
<?php
f(isset($_GET['get'])){
include "db.php";
$path=$_GET['get'];
$select="SELECT*FROM alldocs WHERE path='$path';" ;
$query=mysqli_query($conn,$select);
header('Conetent-type:application/octet-stream');
header('Conetent-disposition:attachment;filename="'.basename($path).'"' );
header('Conetent-lenght:.filesize($path)');
readfile($path);
}
?>
so please if someone could point me to the error that i make in this code : beacuse i get allways and error WARNING : readfile($path); as undefined !
thank you in advance | 0debug |
av_cold void ff_dcadsp_init(DCADSPContext *s)
{
s->lfe_fir[0] = dca_lfe_fir0_c;
s->lfe_fir[1] = dca_lfe_fir1_c;
s->qmf_32_subbands = dca_qmf_32_subbands;
s->int8x8_fmul_int32 = int8x8_fmul_int32_c;
if (ARCH_ARM) ff_dcadsp_init_arm(s);
if (ARCH_X86) ff_dcadsp_init_x86(s);
}
| 1threat |
void do_rfi (void)
{
env->nip = env->spr[SPR_SRR0] & ~0x00000003;
T0 = env->spr[SPR_SRR1] & ~0xFFFF0000UL;
do_store_msr(env, T0);
#if defined (DEBUG_OP)
dump_rfi();
#endif
env->interrupt_request |= CPU_INTERRUPT_EXITTB;
}
| 1threat |
JAVA: string problems : i'm realized a RSA cryptography program, but i have a problem with string.
Because if i code this letter for example: l , and use the key (n,e)=(221,31) to code, my coded message is: Î, and this is correct.
Problem is when i decode my message, because if i realize in Java this: String message="Î", and i take the numeric value with : int x=message.CharAt(0); in output i have x=206 and is correct.
But if i insert the string using class Scanner i have a problem, because if i realize: Scanner in=new Scanner(System.in); and i call: String message=in.next(); and i insert Î, when i take the numeric value with : int x=message.CharAt(0); in output i have x=65533, and is wrong.
I can not understand where I'm wrong. Thank's to all. I'm new and i hope to have posted my question correctly. | 0debug |
Concatenate 2 dictionaries and Add parent to it in python : I have multiple dictionaries which i need to concatenate and add a parent in the end. How do i achieve this
dict1 = { "project":"test1", "summary": "A Test","issuetype": {
"name": "Test"
}}
dict2 = { "project":"test2", "summary": "B Test","issuetype": {
"name": "Test"
}}
I need it in format
dictParent = {fields: {
{ "project":"test1", "summary": "A Test","issuetype": {
"name": "Test"
}}
{ "project":"test2", "summary": "B Test","issuetype": {
"name": "Test"
}}
}}
}
I used below code
dictParent = {}
dictParent["fields"] = dict1, dict2
it kind of works the problem is it comes as as array but i want fields to be parent object not array
{fields: **[**
{ "project":"test1", "summary": "A Test","issuetype": {
"name": "Test"
}}
{ "project":"test2", "summary": "B Test","issuetype": {
"name": "Test"
}}
}}
**]**
| 0debug |
static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
{
BDRVQcow2State *s = bs->opaque;
ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
*spec_info = (ImageInfoSpecific){
.kind = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
{
.qcow2 = g_new(ImageInfoSpecificQCow2, 1),
},
};
if (s->qcow_version == 2) {
*spec_info->qcow2 = (ImageInfoSpecificQCow2){
.compat = g_strdup("0.10"),
.refcount_bits = s->refcount_bits,
};
} else if (s->qcow_version == 3) {
*spec_info->qcow2 = (ImageInfoSpecificQCow2){
.compat = g_strdup("1.1"),
.lazy_refcounts = s->compatible_features &
QCOW2_COMPAT_LAZY_REFCOUNTS,
.has_lazy_refcounts = true,
.corrupt = s->incompatible_features &
QCOW2_INCOMPAT_CORRUPT,
.has_corrupt = true,
.refcount_bits = s->refcount_bits,
};
}
return spec_info;
}
| 1threat |
How to remove a contour inside contour in Python OpenCV? : <p>OpenCV in Python provides the following code:</p>
<pre><code>regions, hierarchy = cv2.findContours(binary_image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for region in regions:
x, y, w, h = cv2.boundingRect(region)
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 1)
</code></pre>
<p>This gives some contours within contour. How to remove them in Python?</p>
| 0debug |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.