problem
stringlengths
26
131k
labels
class label
2 classes
def move_num(test_str): res = '' dig = '' for ele in test_str: if ele.isdigit(): dig += ele else: res += ele res += dig return (res)
0debug
Angular - On Paste Event Get Content : <p>I have an angular component that allows a user to enter data into a <code>textarea</code>. There are two events tied to this <code>keydown</code> and <code>paste</code>. Both of these events trigger the same method which will try and determine the data entered.</p> <p>The issue I am having is when the data is pasted <code>paste</code>, I am getting the value of the <code>formControl</code> but its the value BEFORE the data is pasted and doesn't include what I actually just entered into the field.</p> <p><strong>HTML</strong></p> <pre><code>&lt;textarea formControlName="multiSearch" class="form-control" placeholder="Enter one or more values. One per line." rows="6" (keydown)="keyDownFunction($event)" (paste)="onPaste()"&gt; &lt;/textarea&gt; </code></pre> <p><strong>Component</strong></p> <pre><code> /** * If we hit enter in our text area, determine the data type */ keyDownFunction(event) { // Enter Key? if (event.keyCode == 13) { this.determineDataType(); } } /** * If we paste data in our text area, determine the data type */ onPaste() { this.determineDataType(); } /** * Using regex, determine the datatype of the data and confirm with the user. */ determineDataType() { console.log(this.searchForm.value.multiSearch) } </code></pre> <p><strong>Question</strong> How can I get access to the data that is pasted into the form as soon as the <code>paste</code> event is fired and not what the value was before pasting?</p>
0debug
How to set object elements correctly in java? : <p>I have a constructor:</p> <pre><code> private String name; private int price; public Fruit (String name, int price){ this.name = name; this.price = price; System.out.println("NAME/PRICE SET"); if (getCheapestFruit() == null){ setCheapestFruit(name, price); System.out.println("CHEAPEST NAME/PRICE INITIALIZED"); } else { if(getCheapestFruit().price&gt; price){ setCheapestFruit(name, price); System.out.println("CHEAPEST NAME/PRICE SET"); } } } </code></pre> <p>And I want to set the cheapestFruit.</p> <pre><code>public Fruit cheapestFruit = null; public Fruit getCheapestFruit(){ return this.cheapestFruit; } public void setCheapestFruit(String name, int price){ this.cheapestFruit.price = price; this.cheapestFruit.name = name; } </code></pre> <p>And this die at <code>this.cheapestFruit.price = price;</code> with null pointer exception. How can I set it correctly?</p>
0debug
sort integer array in java class fairly basic from 2 to 18 : <p>i need to sort an array of the type intgere in a basic way (nothing too complex) for a school computer science project. It would be nice if sb could give me not only a one sentence answer waht to consider but also some code i can work with.</p> <p>thanks a lot.</p>
0debug
static int parse_filter(const char *spec, struct USBAutoFilter *f) { enum { BUS, DEV, VID, PID, DONE }; const char *p = spec; int i; f->bus_num = -1; f->addr = -1; f->vendor_id = -1; f->product_id = -1; for (i = BUS; i < DONE; i++) { p = strpbrk(p, ":."); if (!p) break; p++; if (*p == '*') continue; switch(i) { case BUS: f->bus_num = strtol(p, NULL, 10); break; case DEV: f->addr = strtol(p, NULL, 10); break; case VID: f->vendor_id = strtol(p, NULL, 16); break; case PID: f->product_id = strtol(p, NULL, 16); break; } } if (i < DEV) { fprintf(stderr, "husb: invalid auto filter spec %s\n", spec); return -1; } return 0; }
1threat
Is this explanation of ternary operator valid? : <p><strong>Question:</strong></p> <ul> <li>I want to know if this explanation of the ternary operator is valid.</li> </ul> <blockquote> <p>var = (condition) ? set value if condition one : set value of condition two;</p> </blockquote> <p>If the condition is something than the value of the variable will be something. If it's not the value will be different. Basically assign a variable with a value based on a condition. Is this explanation valid? I need to know this if I'm understanding this correctly.</p> <p><strong>Code:</strong></p> <pre><code>#include &lt;iostream&gt; bool maxEntries() { int entries = 11; bool users = (entries &gt; 10) ? true : false; return users; } int main(int argc, const char* argv[]) { if(maxEntries()) { std::cout &lt;&lt; "Entries are greater than 10." &lt;&lt; std::endl; } else { std::cout &lt;&lt; "Entries are less than 10." &lt;&lt; std::endl; } return 0; } . </code></pre>
0debug
Property 'allSettled' does not exist on type 'PromiseConstructor'.ts(2339) : <p>I try to use <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled" rel="noreferrer">Promise.allSettled</a> API with TypeScript. Code here:</p> <p><code>server.test.ts</code>:</p> <pre class="lang-js prettyprint-override"><code>it('should partial success if QPS &gt; 50', async () =&gt; { const requests: any[] = []; for (let i = 0; i &lt; 51; i++) { requests.push(rp('http://localhost:3000/place')); } await Promise.allSettled(requests); // ... }); </code></pre> <p>But TSC throws an error: </p> <blockquote> <p>Property 'allSettled' does not exist on type 'PromiseConstructor'.ts(2339)</p> </blockquote> <p>I already added these values to <code>lib</code> option of <code>tsconfig.json</code>:</p> <p><code>tsconfig.json</code>:</p> <pre><code>{ "compilerOptions": { /* Basic Options */ "target": "ES2015" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */, "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */, "lib": [ "ES2015", "ES2016", "ES2017", "ES2018", "ES2019", "ES2020", "ESNext" ] // ... } </code></pre> <p>TypeScript version: <code>"typescript": "^3.7.3"</code></p> <p>So, how can I solve this? I know I can use an alternative module, but I am curious about working with TypeScript natively.</p>
0debug
int ff_lpc_calc_coefs(LPCContext *s, const int32_t *samples, int blocksize, int min_order, int max_order, int precision, int32_t coefs[][MAX_LPC_ORDER], int *shift, enum FFLPCType lpc_type, int lpc_passes, int omethod, int max_shift, int zero_shift) { double autoc[MAX_LPC_ORDER+1]; double ref[MAX_LPC_ORDER]; double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER]; int i, j, pass = 0; int opt_order; av_assert2(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER && lpc_type > FF_LPC_TYPE_FIXED); if (blocksize != s->blocksize || max_order != s->max_order || lpc_type != s->lpc_type) { ff_lpc_end(s); ff_lpc_init(s, blocksize, max_order, lpc_type); } if(lpc_passes <= 0) lpc_passes = 2; if (lpc_type == FF_LPC_TYPE_LEVINSON || (lpc_type == FF_LPC_TYPE_CHOLESKY && lpc_passes > 1)) { s->lpc_apply_welch_window(samples, blocksize, s->windowed_samples); s->lpc_compute_autocorr(s->windowed_samples, blocksize, max_order, autoc); compute_lpc_coefs(autoc, max_order, &lpc[0][0], MAX_LPC_ORDER, 0, 1); for(i=0; i<max_order; i++) ref[i] = fabs(lpc[i][i]); pass++; } if (lpc_type == FF_LPC_TYPE_CHOLESKY) { LLSModel m[2]; LOCAL_ALIGNED(32, double, var, [FFALIGN(MAX_LPC_ORDER+1,4)]); double av_uninit(weight); memset(var, 0, FFALIGN(MAX_LPC_ORDER+1,4)*sizeof(*var)); for(j=0; j<max_order; j++) m[0].coeff[max_order-1][j] = -lpc[max_order-1][j]; for(; pass<lpc_passes; pass++){ avpriv_init_lls(&m[pass&1], max_order); weight=0; for(i=max_order; i<blocksize; i++){ for(j=0; j<=max_order; j++) var[j]= samples[i-j]; if(pass){ double eval, inv, rinv; eval= m[(pass-1)&1].evaluate_lls(&m[(pass-1)&1], var+1, max_order-1); eval= (512>>pass) + fabs(eval - var[0]); inv = 1/eval; rinv = sqrt(inv); for(j=0; j<=max_order; j++) var[j] *= rinv; weight += inv; }else weight++; m[pass&1].update_lls(&m[pass&1], var); } avpriv_solve_lls(&m[pass&1], 0.001, 0); } for(i=0; i<max_order; i++){ for(j=0; j<max_order; j++) lpc[i][j]=-m[(pass-1)&1].coeff[i][j]; ref[i]= sqrt(m[(pass-1)&1].variance[i] / weight) * (blocksize - max_order) / 4000; } for(i=max_order-1; i>0; i--) ref[i] = ref[i-1] - ref[i]; } opt_order = max_order; if(omethod == ORDER_METHOD_EST) { opt_order = estimate_best_order(ref, min_order, max_order); i = opt_order-1; quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i], max_shift, zero_shift); } else { for(i=min_order-1; i<max_order; i++) { quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i], max_shift, zero_shift); } } return opt_order; }
1threat
static int put_v(ByteIOContext *bc, uint64_t val) { int i; if (bytes_left(bc) < 1) return -1; val &= 0x7FFFFFFFFFFFFFFFULL; i= get_length(val); for (i-=7; i>0; i-=7){ put_byte(bc, 0x80 | (val>>i)); } put_byte(bc, val&0x7f); return 0; }
1threat
Spark RDD to DataFrame python : <p>I am trying to convert the Spark RDD to a DataFrame. I have seen the documentation and example where the scheme is passed to <code>sqlContext.CreateDataFrame(rdd,schema)</code> function. </p> <p>But I have 38 columns or fields and this will increase further. If I manually give the schema specifying each field information, that it going to be so tedious job.</p> <p>Is there any other way to specify the schema without knowing the information of the columns prior.</p>
0debug
int css_do_tsch_get_irb(SubchDev *sch, IRB *target_irb, int *irb_len) { SCSW *s = &sch->curr_status.scsw; PMCW *p = &sch->curr_status.pmcw; uint16_t stctl; IRB irb; if (!(p->flags & (PMCW_FLAGS_MASK_DNV | PMCW_FLAGS_MASK_ENA))) { return 3; } stctl = s->ctrl & SCSW_CTRL_MASK_STCTL; memset(&irb, 0, sizeof(IRB)); memcpy(&irb.scsw, s, sizeof(SCSW)); if (stctl & SCSW_STCTL_STATUS_PEND) { if (s->cstat & (SCSW_CSTAT_DATA_CHECK | SCSW_CSTAT_CHN_CTRL_CHK | SCSW_CSTAT_INTF_CTRL_CHK)) { irb.scsw.flags |= SCSW_FLAGS_MASK_ESWF; irb.esw[0] = 0x04804000; } else { irb.esw[0] = 0x00800000; } if ((s->dstat & SCSW_DSTAT_UNIT_CHECK) && (p->chars & PMCW_CHARS_MASK_CSENSE)) { int i; irb.scsw.flags |= SCSW_FLAGS_MASK_ESWF | SCSW_FLAGS_MASK_ECTL; memcpy(irb.ecw, sch->sense_data, sizeof(sch->sense_data)); for (i = 0; i < ARRAY_SIZE(irb.ecw); i++) { irb.ecw[i] = be32_to_cpu(irb.ecw[i]); } irb.esw[1] = 0x01000000 | (sizeof(sch->sense_data) << 8); } } copy_irb_to_guest(target_irb, &irb, p, irb_len); return ((stctl & SCSW_STCTL_STATUS_PEND) == 0); }
1threat
Android Material Design support for ecipse : Is it possible to work on material design in eclipse IDE. when i run the app i'm getting issue to change the app theme to appcomact instead of android:Theme.Material
0debug
Java Array split() displaying all values but giving arrayindexoutofbound exception error : <p>I am writing code to take input from a file which has records in a given format and then splitting them to display pincodes which i need to compare later and write the records. To do the comparision i am first taking all the pincode fields in the records and storing them in a array.I am able to display pincodes but there is an exception. My method code is below.</p> <pre><code>String[] getPincodesArray(String filename) { String[] st=new String[30]; int index=0; try { FileReader fr=new FileReader(filename); BufferedReader br=new BufferedReader(fr); String line=br.readLine(); while(line!=null) { String s[]=line.split(","); String s1[]=s[1].split(";"); st[index]=s1[1]; index++; line=br.readLine(); } } catch(Exception e) { e.printStackTrace(); } return st; </code></pre> <p>}</p> <p>when i am executing this function is main(),I am getting an exception but am able to display all pincodes.The output is </p> <pre><code>java.lang.ArrayIndexOutOfBoundsException: 1 at info.pack.Methods.getPincodesArray(Methods.java:270) at info.pack.studentidpincode.main(studentidpincode.java:18) </code></pre> <p>560054 560076 560098 560054 560097 560087 560054 null null null..</p> <p>I am able to see all pincodes, then why is the exception coming? </p>
0debug
static int count_contiguous_clusters_unallocated(int nb_clusters, uint64_t *l2_table, QCow2ClusterType wanted_type) { int i; assert(wanted_type == QCOW2_CLUSTER_ZERO || wanted_type == QCOW2_CLUSTER_UNALLOCATED); for (i = 0; i < nb_clusters; i++) { uint64_t entry = be64_to_cpu(l2_table[i]); QCow2ClusterType type = qcow2_get_cluster_type(entry); if (type != wanted_type || entry & L2E_OFFSET_MASK) { break; } } return i; }
1threat
static void migrate_fd_put_ready(void *opaque) { MigrationState *s = opaque; int ret; if (s->state != MIG_STATE_ACTIVE) { DPRINTF("put_ready returning because of non-active state\n"); return; } DPRINTF("iterate\n"); ret = qemu_savevm_state_iterate(s->mon, s->file); if (ret < 0) { migrate_fd_error(s); } else if (ret == 1) { int old_vm_running = runstate_is_running(); DPRINTF("done iterating\n"); vm_stop_force_state(RUN_STATE_FINISH_MIGRATE); if (qemu_savevm_state_complete(s->mon, s->file) < 0) { migrate_fd_error(s); } else { migrate_fd_completed(s); } if (s->state != MIG_STATE_COMPLETED) { if (old_vm_running) { vm_start(); } } } }
1threat
haskell couldnt match expeted type : On this code there's no way to do it polymorphic: data NumericExpr e = Var e | Const e | Times [e] | Div e e deriving (Show,Read) readCommand:: a -> b readCommand entrada = Var 3 it gives me a big error which I can't copy: couldn't match expected type b with actual type NumericExpr e0 b is a rigid type variable bound by the type signature for readcommand :: a -> b
0debug
static void do_rematrixing(AC3DecodeContext *ctx) { ac3_audio_block *ab = &ctx->audio_block; uint8_t bnd1 = 13, bnd2 = 25, bnd3 = 37, bnd4 = 61; uint8_t bndend; bndend = FFMIN(ab->endmant[0], ab->endmant[1]); if (ab->rematflg & 1) _do_rematrixing(ctx, bnd1, bnd2); if (ab->rematflg & 2) _do_rematrixing(ctx, bnd2, bnd3); if (ab->rematflg & 4) { if (ab->cplbegf > 0 && ab->cplbegf <= 2 && (ab->flags & AC3_AB_CPLINU)) _do_rematrixing(ctx, bnd3, bndend); else { _do_rematrixing(ctx, bnd3, bnd4); if (ab->rematflg & 8) _do_rematrixing(ctx, bnd4, bndend); } } }
1threat
What is a complex type in entity framework and when to use it? : <p>I have tried to read the msdn <a href="https://msdn.microsoft.com/en-us/library/cc716799(v=vs.100).aspx" rel="noreferrer">article</a> on complex types. But it does not explain when to use it. Also there is not a comprehensive explanation on the web on complex types and when to use them. </p>
0debug
Creating hierarchy of methods in python class : I have class with hundreds of methods I want create hierarchy of them that will let easy find method. For example class MyClass: def SpectrumFrequencyStart()... def SpectrumFrequencyStop()... def SpectrumFrequencyCenter()... def SignalAmplitudedBm()... I want that call will: ` MyClassObject.Spectrum.Frequency.Start() MyClassObject.Spectrum.Frequency.Stop() MyClassObject.Signal.Amplitude.dBm() ` Thanks, Nadav
0debug
C# getting text in form after a button is clicked : <p>Hello I am very new to programming and I have been experimenting with c# and was creating a form where the user would input a file path which would be assigned to a string after a button was clicked. I am not sure how to go about this and was wondering if anyone could help. </p>
0debug
def count_Digit(n): count = 0 while n != 0: n //= 10 count += 1 return count
0debug
void pcmcia_socket_unregister(PCMCIASocket *socket) { struct pcmcia_socket_entry_s *entry, **ptr; ptr = &pcmcia_sockets; for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr) if (entry->socket == socket) { *ptr = entry->next; g_free(entry); } }
1threat
for loop though a string produces TypeError: 'int' object is not subscriptable : # 1. Print every character in the string "Camus". string_1 = "Camus" x = 0 for string_1 in range(5): output_1 = (string_1[x]) print(output_1) x =+ 1
0debug
C# How to add a property setter in derived class? : <p>I have a requirement where I have a number of classes all derived from a single base class. The base class contains lists of child classes also derived from the same base class.</p> <p>All classes need to be able to obtain specific values which may be obtained from the class itself -OR- it's parent depending on what the derived class is.</p> <p>I looked at using Methods rather than properties however I also want to make the values available to a .NET reporting component which directly accesses exposed public properties in the reporting engine so this excludes the use of methods.</p> <p>My question is what would be the 'best practices' method of implementing a setter in DerivedClass without having a publicly available setter in BaseClass</p> <pre><code>public class BaseClass { private BaseClass _Parent; public virtual decimal Result { get { return ((_Parent != null) ? _Parent.Result : -1); } } } public class DerivedClass : BaseClass { private decimal _Result; public override decimal Result { get { return _Result; } // I can't use a setter here because there is no set method in the base class so this throws a build error //set { _Result = value; } } } </code></pre> <p>I can't add a protected setter (as follows) in BaseClass as I cannot change access modifiers in DerivedClass.</p> <pre><code>public class BaseClass { private BaseClass _Parent; public virtual decimal Result { get { return ((_Parent != null) ? _Parent.Result : -1); } protected set { } } } public class DerivedClass : BaseClass { private decimal _Result; public override decimal Result { get { return _Result; } // This setter throws a build error because of a change of access modifiers. //set { _Result = value; } } } </code></pre> <p>I don't want to add a member variable in BaseClass with a setter as I do not want the ability to set the property from the BaseClass or other classes that derive from base.</p> <pre><code>public class BaseClass { private BaseClass _Parent; protected Decimal _Result; // This could result in a lot of unnecessary members in BaseClass. public virtual decimal Result { get { return _Result; } // Empty setter ahead :) This does nothing. // I could also throw an exception here but then issues would not be found until runtime // and could cause confusion in the future with new developers etc. set { } } } public class DerivedClass : BaseClass { public override decimal Result { get { return base.Result; } set { base._Result = value; } } } </code></pre> <p>Other suggestions ?</p>
0debug
How to adjust the size of a view at the top of UITableView programatically? : <p>I have a UITableVIew in my app with views holding content at the top and bottom. These obviously scroll out of frame when the user scrolls which is the desired behaviour. </p> <p>Depending on user inputs I'd like to hide half of the topView but I can't edit the height of that view directly for some reason. I don't know why. I can drag it in Interface Builder but can't edit it programatically. The debugger tells me it's a read only value. </p> <p>I can get half way there by editing the height of the inner view (statusView) but it then leaves a gap between the end of the topView and the table cells. </p> <p>Any suggestions?</p> <p><a href="https://i.stack.imgur.com/OVtbB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OVtbB.png" alt="enter image description here"></a></p>
0debug
Call F# function from C# passing function as a parameter : <p>I have the following F# function</p> <pre><code>let Fetch logger id = logger "string1" "string2" // search a database with the id and return a result </code></pre> <p>In my C# class I want to call the <em>Fetch</em> F# function mocking out the <em>logger</em> function. So I have the following C# function as the mocker.</p> <pre><code>void Print(string x, string y) { // do nothing } </code></pre> <p>I'm trying to call the F# function from a C# class with the following.</p> <pre><code>var _logger = FuncConvert.ToFSharpFunc&lt;string, string&gt;(Print); var _result = Fetch(logger, 3); </code></pre> <p>The problem with FuncConvert.ToFSharpFunc is that takes only one type argument. When I change the <em>Fetch</em> F# logger function to the following it works fine when I use ToFSharpFunc(Print) where the C# Print function also takes in one string.</p> <pre><code>let Fetch logger id = logger "string1" // search a database with the id and return a result </code></pre> <p>Anyone got ideas?</p>
0debug
void ff_thread_flush(AVCodecContext *avctx) { FrameThreadContext *fctx = avctx->thread_opaque; if (!avctx->thread_opaque) return; park_frame_worker_threads(fctx, avctx->thread_count); if (fctx->prev_thread) update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0); fctx->next_decoding = fctx->next_finished = 0; fctx->delaying = 1; fctx->prev_thread = NULL; }
1threat
JSDoc typedef in a separate file : <p>Can I define all custom types in a separate file (e.g. <code>types.jsdoc</code>), so that they can be reused throughout the application? What's the right way to do it?</p> <pre><code>/** * 2d coordinates. * @typedef {Object} Coordinates * @property {Number} x - Coordinate x. * @property {Number} y - Coordinate y. */ </code></pre>
0debug
WKWebView loadFileURL works only once : <p>I need to load a local file in a WKWebView. I'm using the new ios9 method </p> <p><code>- (nullable WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL</code></p> <p>It works perfectly for the first load (navigation delegation is properly called), but if I try to load a new and different file, it does nothing.</p> <p>The URL for the currentItem in the wkwebview instance is modified. But if I force a reload the delegate method didFinishNavigation is called with the previous set URL. I also tried to navigate forward but the file that was supposed to be loaded is the current one, it's not on the backForwardList. </p> <p>The code I'm using to start the WKWebView and load the file:</p> <pre><code>self.wk_webview = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; self.wk_webview.scrollView.delegate = self; self.wk_webview.navigationDelegate = self; [self.view addSubview:self.wk_webview]; NSURL *url = [NSURL fileURLWithPath:local_path]; [self.wk_webview loadFileURL:url allowingReadAccessToURL:[url URLByDeletingLastPathComponent]]; </code></pre> <p>Am I missing something? I couldn't find anything related to this. </p> <p>Any help is appreciated, thanks.</p>
0debug
static void ppc_cpu_unrealizefn(DeviceState *dev, Error **errp) { PowerPCCPU *cpu = POWERPC_CPU(dev); CPUPPCState *env = &cpu->env; int i; for (i = 0; i < PPC_CPU_OPCODES_LEN; i++) { if (env->opcodes[i] != &invalid_handler) { g_free(env->opcodes[i]); } } }
1threat
Extract rows having the 11th column values lies between 1st and 2nd of a second file : Hello I have two files file1 : 11th column chromosome position another.... tag name.....score ..... sum chr1 816 ..... 2456.50 chr1 991 ..... 50345 chr2 816 ..... 2456.50 chr2 880 ..... 78939 chr2 18768 ..... 678909 ... chr5 9736286 .... 78905 file2 chromosome start end ..... ..... ..... chr1 2450 2460 chr2 50340 50350 chr2 678900 678920 chr5 9736280 9736290 I'm interested in printing rows from file 1 using a python code if the values of 11th column falls within the range start and end (2nd and 3rd columns )declared in the seconds file. As the position is only unique within a certain chromosome (chr) first it has to be tested if the chr's are identical... hence my desired output is chromosome position another.... tag name.....score ..... sum chr1 816 ..... 2456.50 chr2 18768 ..... 678909 chr5 9736286 .... 78905 I have tried awk codes.. it works perfectly fine but they are very very slow ! The files I'm testing ( from which I need to print the rows are around 4 GB ). I would highly appreciate if I can have some python code Thanks !
0debug
Whats the right way to separate model and logic : <p>Hi I'm setting up a new project and was struggeling with Java Annotations. Are they related to Logic / API or Model</p> <h2>In Detail:</h2> <p>I have a started a multi maven module for example:</p> <ul> <li>project-parent</li> <li>project-model</li> <li>project-persist</li> <li>project-logic1</li> </ul> <p>I separated model from every other module simple POJOs with JPA. To use them with different frontends or REST etc. Now I wanna use annotations from <strong>project-logic1</strong> in the model.</p> <p>Now i'm confused with the seperation.</p> <ul> <li>Should I make an own API module (<strong>project-API</strong>) for this and similar annotation / interfaces</li> <li>Should I simply add the annotation in the <strong>project-model</strong></li> <li>Should I add the dependency of <strong>project-logic1</strong> into the <strong>project-model</strong> POM</li> </ul> <p>I think the first one is correctly but I'm not sure.</p>
0debug
can you assign initial value to global static variable in C? : <p>I have a global variable "count". All I want to do is increment it each time the loop runs. Is there a potential problem with initializing static count as 0? How is this works in C?</p> <pre><code>static unsigned short count = 0; while(1) { count++; // do something } </code></pre>
0debug
AWS Java S3 Uploading error: "profile file cannot be null" : <p>I get an exception when trying to upload a file to Amazon S3 from my Java Spring application. The method is pretty simple:</p> <pre><code>private void productionFileSaver(String keyName, File f) throws InterruptedException { String bucketName = "{my-bucket-name}"; TransferManager tm = new TransferManager(new ProfileCredentialsProvider()); // TransferManager processes all transfers asynchronously, // so this call will return immediately. Upload upload = tm.upload( bucketName, keyName, new File("/mypath/myfile.png")); try { // Or you can block and wait for the upload to finish upload.waitForCompletion(); System.out.println("Upload complete."); } catch (AmazonClientException amazonClientException) { System.out.println("Unable to upload file, upload was aborted."); amazonClientException.printStackTrace(); } } </code></pre> <p>It is basically the same that amazon provides <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/HLuploadFileJava.html" rel="noreferrer">here</a>, and the same exception with the exactly same message ("profile file cannot be null") appears when trying <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpJava.html" rel="noreferrer">this other</a> version. The problem is not related to the file not existing or being null (I have already checked in a thousand ways that the File argument recieved by <code>TransferManager.upload</code> method exists before calling it).</p> <p>I cannot find any info about my exception message "<strong>profile file cannot be null</strong>". The first lines of the error log are the following:</p> <pre><code>com.amazonaws.AmazonClientException: Unable to complete transfer: profile file cannot be null at com.amazonaws.services.s3.transfer.internal.AbstractTransfer.unwrapExecutionException(AbstractTransfer.java:281) at com.amazonaws.services.s3.transfer.internal.AbstractTransfer.rethrowExecutionException(AbstractTransfer.java:265) at com.amazonaws.services.s3.transfer.internal.AbstractTransfer.waitForCompletion(AbstractTransfer.java:103) at com.fullteaching.backend.file.FileController.productionFileSaver(FileController.java:371) at com.fullteaching.backend.file.FileController.handlePictureUpload(FileController.java:247) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) </code></pre> <p>My S3 policy allows getting and puttings objects for all kind of users.</p> <p>Any idea about what's happening?</p>
0debug
int css_do_xsch(SubchDev *sch) { SCSW *s = &sch->curr_status.scsw; PMCW *p = &sch->curr_status.pmcw; int ret; if (~(p->flags) & (PMCW_FLAGS_MASK_DNV | PMCW_FLAGS_MASK_ENA)) { ret = -ENODEV; goto out; } if (!(s->ctrl & SCSW_CTRL_MASK_FCTL) || ((s->ctrl & SCSW_CTRL_MASK_FCTL) != SCSW_FCTL_START_FUNC) || (!(s->ctrl & (SCSW_ACTL_RESUME_PEND | SCSW_ACTL_START_PEND | SCSW_ACTL_SUSP))) || (s->ctrl & SCSW_ACTL_SUBCH_ACTIVE)) { ret = -EINPROGRESS; goto out; } if (s->ctrl & SCSW_CTRL_MASK_STCTL) { ret = -EBUSY; goto out; } s->ctrl &= ~(SCSW_FCTL_START_FUNC | SCSW_ACTL_RESUME_PEND | SCSW_ACTL_START_PEND | SCSW_ACTL_SUSP); sch->channel_prog = 0x0; sch->last_cmd_valid = false; s->dstat = 0; s->cstat = 0; ret = 0; out: return ret; }
1threat
How i can create the modal and nodejs query for following json? : { "_id" : ObjectId("5a0e77f4b7368f14c088f542"), "folderName" : "team 4", "tag" : "search", "ismainFolder" : true, "innerFolder" : [ { parentfolderId" : null, "ismainFolder" : false, "foldername" : "Onkar 11" "subinnerFolder" : [ { "parentfolderId" : null, "ismainFolder" : false, "foldername" : "Onkar 11" "thirdSubFolder" : [ { "parentfolderId" : null, "ismainFolder" : false, "foldername" : "Onkar 11" }, { "parentfolderId" : null, "ismainFolder" : false, "foldername" : "Onkar 11" } ] }, ] }, ] } I need to write the mongo schema and modal for nested innerfolder and subinner folder its will continue till nth order please can you please guide for this ?
0debug
Having an issue with simple account checking program? Program returns compiling error that states "no match for 'operator||' unsure of how to fix?" : <p>I'm new to programming and so I bought a book to help me learn C++, in the book it asks me to do a practice assignment where I must create a program that allows me to take input of multiple usernames and passwords, match them, and also allow someone who incorrectly enters information to try entering it again. I've wrote the following program in order to do so. If anyone can also shed any light on how to make the program allow for retry of username/password entry without ending the program that would also be greatly appreciated. Thank you!</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; int main() { string username1="Varun"; string username2="Agne"; string username3="Geetha"; string username4="Mohan"; //Usernames for accounts string pass1="PassworD"; string pass2="PASSWORD"; //Passwords for accounts string pass3="password"; string pass4="Password"; string Uattempt; //User input for username string Pattempt; //User input for password cout &lt;&lt; "Please enter your username.\n"; cin &gt;&gt; Uattempt; cout &lt;&lt; "Please enter your password \n"; //Asks for username and password entry by user cin &gt;&gt; Pattempt; if(Uattempt!=username1 || username2 || username3 || username4) { cout &lt;&lt; "Access Denied. Incorrect username or password. Please retry.\n"; //If username does not match possible entries, program will ask to retry } if(Pattempt !=(pass1||pass2)&amp;&amp;(pass3||pass4) { cout &lt;&lt; "Access Denied. Incorrect username or password. Please retry.\n"; //If password does not match possible entries, program will ask to retry } if (Uattempt&amp;&amp;Pattempt==username1&amp;&amp;pass1||username2&amp;&amp;pass2||username3&amp;&amp;pass3||username4&amp;&amp;pass4) { cout &lt;&lt; "Access Granted. Welcome " + &lt;&lt;Uattempt&lt;&lt; + ".\n"; } else { return 0; } } </code></pre>
0debug
static void vc1_draw_sprites(VC1Context *v, SpriteData* sd) { int i, plane, row, sprite; int sr_cache[2][2] = { { -1, -1 }, { -1, -1 } }; uint8_t* src_h[2][2]; int xoff[2], xadv[2], yoff[2], yadv[2], alpha; int ysub[2]; MpegEncContext *s = &v->s; for (i = 0; i < 2; i++) { xoff[i] = av_clip(sd->coefs[i][2], 0, v->sprite_width-1 << 16); xadv[i] = sd->coefs[i][0]; if (xadv[i] != 1<<16 || (v->sprite_width << 16) - (v->output_width << 16) - xoff[i]) xadv[i] = av_clip(xadv[i], 0, ((v->sprite_width<<16) - xoff[i] - 1) / v->output_width); yoff[i] = av_clip(sd->coefs[i][5], 0, v->sprite_height-1 << 16); yadv[i] = av_clip(sd->coefs[i][4], 0, ((v->sprite_height << 16) - yoff[i]) / v->output_height); } alpha = av_clip(sd->coefs[1][6], 0, (1<<16) - 1); for (plane = 0; plane < (s->flags&CODEC_FLAG_GRAY ? 1 : 3); plane++) { int width = v->output_width>>!!plane; for (row = 0; row < v->output_height>>!!plane; row++) { uint8_t *dst = v->sprite_output_frame.data[plane] + v->sprite_output_frame.linesize[plane] * row; for (sprite = 0; sprite <= v->two_sprites; sprite++) { uint8_t *iplane = s->current_picture.f.data[plane]; int iline = s->current_picture.f.linesize[plane]; int ycoord = yoff[sprite] + yadv[sprite] * row; int yline = ycoord >> 16; ysub[sprite] = ycoord & 0xFFFF; if (sprite) { iplane = s->last_picture.f.data[plane]; iline = s->last_picture.f.linesize[plane]; } if (!(xoff[sprite] & 0xFFFF) && xadv[sprite] == 1 << 16) { src_h[sprite][0] = iplane + (xoff[sprite] >> 16) + yline * iline; if (ysub[sprite]) src_h[sprite][1] = iplane + (xoff[sprite] >> 16) + (yline + 1) * iline; } else { if (sr_cache[sprite][0] != yline) { if (sr_cache[sprite][1] == yline) { FFSWAP(uint8_t*, v->sr_rows[sprite][0], v->sr_rows[sprite][1]); FFSWAP(int, sr_cache[sprite][0], sr_cache[sprite][1]); } else { v->vc1dsp.sprite_h(v->sr_rows[sprite][0], iplane + yline * iline, xoff[sprite], xadv[sprite], width); sr_cache[sprite][0] = yline; } } if (ysub[sprite] && sr_cache[sprite][1] != yline + 1) { v->vc1dsp.sprite_h(v->sr_rows[sprite][1], iplane + (yline + 1) * iline, xoff[sprite], xadv[sprite], width); sr_cache[sprite][1] = yline + 1; } src_h[sprite][0] = v->sr_rows[sprite][0]; src_h[sprite][1] = v->sr_rows[sprite][1]; } } if (!v->two_sprites) { if (ysub[0]) { v->vc1dsp.sprite_v_single(dst, src_h[0][0], src_h[0][1], ysub[0], width); } else { memcpy(dst, src_h[0][0], width); } } else { if (ysub[0] && ysub[1]) { v->vc1dsp.sprite_v_double_twoscale(dst, src_h[0][0], src_h[0][1], ysub[0], src_h[1][0], src_h[1][1], ysub[1], alpha, width); } else if (ysub[0]) { v->vc1dsp.sprite_v_double_onescale(dst, src_h[0][0], src_h[0][1], ysub[0], src_h[1][0], alpha, width); } else if (ysub[1]) { v->vc1dsp.sprite_v_double_onescale(dst, src_h[1][0], src_h[1][1], ysub[1], src_h[0][0], (1<<16)-1-alpha, width); } else { v->vc1dsp.sprite_v_double_noscale(dst, src_h[0][0], src_h[1][0], alpha, width); } } } if (!plane) { for (i = 0; i < 2; i++) { xoff[i] >>= 1; yoff[i] >>= 1; } } } }
1threat
Sql Injection Method Clarification : <p>From this sql Query,</p> <pre><code> select Id, Name from Student1 where Id = 1; </code></pre> <p>The Table records will appear only one data </p> <pre><code> 1 Ramu S </code></pre> <p>But, This query when execute, </p> <pre><code> SELECT Id, Name FROM Student1 WHERE Id = '' OR 1=1 </code></pre> <p>it shows all the records of the table. So, how the query functions?</p>
0debug
How to format my date to Default format : <p>I am using java 8 I have an sql server type of date like this</p> <pre><code>2016-01-20T00:00:00.000 </code></pre> <p>The default date format is : </p> <blockquote> <p>new Date() ==> Wed Aug 30 11:03:30 CEST 2017</p> </blockquote> <p>I would like to format my date to the default one.</p> <p>thanks</p>
0debug
static int adx_decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt) { const uint8_t *buf0 = avpkt->data; int buf_size = avpkt->size; ADXContext *c = avctx->priv_data; int16_t *samples = data; const uint8_t *buf = buf0; int rest = buf_size; if (!c->header_parsed) { int hdrsize = adx_decode_header(avctx, buf, rest); if (!hdrsize) return -1; c->header_parsed = 1; buf += hdrsize; rest -= hdrsize; } if (rest / 18 > *data_size / 64) rest = (*data_size / 64) * 18; if (c->in_temp) { int copysize = 18 * avctx->channels - c->in_temp; memcpy(c->dec_temp + c->in_temp, buf, copysize); rest -= copysize; buf += copysize; if (avctx->channels == 1) { adx_decode(samples, c->dec_temp, c->prev); samples += 32; } else { adx_decode_stereo(samples, c->dec_temp, c->prev); samples += 32*2; } } if (avctx->channels == 1) { while (rest >= 18) { adx_decode(samples, buf, c->prev); rest -= 18; buf += 18; samples += 32; } } else { while (rest >= 18 * 2) { adx_decode_stereo(samples, buf, c->prev); rest -= 18 * 2; buf += 18 * 2; samples += 32 * 2; } } c->in_temp = rest; if (rest) { memcpy(c->dec_temp, buf, rest); buf += rest; } *data_size = (uint8_t*)samples - (uint8_t*)data; return buf - buf0; }
1threat
static int planarCopyWrapper(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY, int srcSliceH, uint8_t* dst[], int dstStride[]) { int plane, i, j; for (plane=0; plane<4; plane++) { int length= (plane==0 || plane==3) ? c->srcW : -((-c->srcW )>>c->chrDstHSubSample); int y= (plane==0 || plane==3) ? srcSliceY: -((-srcSliceY)>>c->chrDstVSubSample); int height= (plane==0 || plane==3) ? srcSliceH: -((-srcSliceH)>>c->chrDstVSubSample); const uint8_t *srcPtr= src[plane]; uint8_t *dstPtr= dst[plane] + dstStride[plane]*y; if (!dst[plane]) continue; if (plane == 1 && !dst[2]) continue; if (!src[plane] || (plane == 1 && !src[2])) { if(is16BPS(c->dstFormat)) length*=2; fillPlane(dst[plane], dstStride[plane], length, height, y, (plane==3) ? 255 : 128); } else { if(is9_OR_10BPS(c->srcFormat)) { const int src_depth = av_pix_fmt_descriptors[c->srcFormat].comp[plane].depth_minus1+1; const int dst_depth = av_pix_fmt_descriptors[c->dstFormat].comp[plane].depth_minus1+1; const uint16_t *srcPtr2 = (const uint16_t*)srcPtr; if (is16BPS(c->dstFormat)) { uint16_t *dstPtr2 = (uint16_t*)dstPtr; #define COPY9_OR_10TO16(rfunc, wfunc) \ for (i = 0; i < height; i++) { \ for (j = 0; j < length; j++) { \ int srcpx = rfunc(&srcPtr2[j]); \ wfunc(&dstPtr2[j], (srcpx<<(16-src_depth)) | (srcpx>>(2*src_depth-16))); \ } \ dstPtr2 += dstStride[plane]/2; \ srcPtr2 += srcStride[plane]/2; \ } if (isBE(c->dstFormat)) { if (isBE(c->srcFormat)) { COPY9_OR_10TO16(AV_RB16, AV_WB16); } else { COPY9_OR_10TO16(AV_RL16, AV_WB16); } } else { if (isBE(c->srcFormat)) { COPY9_OR_10TO16(AV_RB16, AV_WL16); } else { COPY9_OR_10TO16(AV_RL16, AV_WL16); } } } else if (is9_OR_10BPS(c->dstFormat)) { uint16_t *dstPtr2 = (uint16_t*)dstPtr; #define COPY9_OR_10TO9_OR_10(loop) \ for (i = 0; i < height; i++) { \ for (j = 0; j < length; j++) { \ loop; \ } \ dstPtr2 += dstStride[plane]/2; \ srcPtr2 += srcStride[plane]/2; \ } #define COPY9_OR_10TO9_OR_10_2(rfunc, wfunc) \ if (dst_depth > src_depth) { \ COPY9_OR_10TO9_OR_10(int srcpx = rfunc(&srcPtr2[j]); \ wfunc(&dstPtr2[j], (srcpx << 1) | (srcpx >> 9))); \ } else if (dst_depth < src_depth) { \ DITHER_COPY(dstPtr2, dstStride[plane]/2, wfunc, \ srcPtr2, srcStride[plane]/2, rfunc, \ dither_8x8_1, 1); \ } else { \ COPY9_OR_10TO9_OR_10(wfunc(&dstPtr2[j], rfunc(&srcPtr2[j]))); \ } if (isBE(c->dstFormat)) { if (isBE(c->srcFormat)) { COPY9_OR_10TO9_OR_10_2(AV_RB16, AV_WB16); } else { COPY9_OR_10TO9_OR_10_2(AV_RL16, AV_WB16); } } else { if (isBE(c->srcFormat)) { COPY9_OR_10TO9_OR_10_2(AV_RB16, AV_WL16); } else { COPY9_OR_10TO9_OR_10_2(AV_RL16, AV_WL16); } } } else { #define W8(a, b) { *(a) = (b); } #define COPY9_OR_10TO8(rfunc) \ if (src_depth == 9) { \ DITHER_COPY(dstPtr, dstStride[plane], W8, \ srcPtr2, srcStride[plane]/2, rfunc, \ dither_8x8_1, 1); \ } else { \ DITHER_COPY(dstPtr, dstStride[plane], W8, \ srcPtr2, srcStride[plane]/2, rfunc, \ dither_8x8_3, 2); \ } if (isBE(c->srcFormat)) { COPY9_OR_10TO8(AV_RB16); } else { COPY9_OR_10TO8(AV_RL16); } } } else if(is9_OR_10BPS(c->dstFormat)) { const int dst_depth = av_pix_fmt_descriptors[c->dstFormat].comp[plane].depth_minus1+1; uint16_t *dstPtr2 = (uint16_t*)dstPtr; if (is16BPS(c->srcFormat)) { const uint16_t *srcPtr2 = (const uint16_t*)srcPtr; #define COPY16TO9_OR_10(rfunc, wfunc) \ if (dst_depth == 9) { \ DITHER_COPY(dstPtr2, dstStride[plane]/2, wfunc, \ srcPtr2, srcStride[plane]/2, rfunc, \ dither_8x8_128, 7); \ } else { \ DITHER_COPY(dstPtr2, dstStride[plane]/2, wfunc, \ srcPtr2, srcStride[plane]/2, rfunc, \ dither_8x8_64, 6); \ } if (isBE(c->dstFormat)) { if (isBE(c->srcFormat)) { COPY16TO9_OR_10(AV_RB16, AV_WB16); } else { COPY16TO9_OR_10(AV_RL16, AV_WB16); } } else { if (isBE(c->srcFormat)) { COPY16TO9_OR_10(AV_RB16, AV_WL16); } else { COPY16TO9_OR_10(AV_RL16, AV_WL16); } } } else { #define COPY8TO9_OR_10(wfunc) \ for (i = 0; i < height; i++) { \ for (j = 0; j < length; j++) { \ const int srcpx = srcPtr[j]; \ wfunc(&dstPtr2[j], (srcpx<<(dst_depth-8)) | (srcpx >> (16-dst_depth))); \ } \ dstPtr2 += dstStride[plane]/2; \ srcPtr += srcStride[plane]; \ } if (isBE(c->dstFormat)) { COPY8TO9_OR_10(AV_WB16); } else { COPY8TO9_OR_10(AV_WL16); } } } else if(is16BPS(c->srcFormat) && !is16BPS(c->dstFormat)) { const uint16_t *srcPtr2 = (const uint16_t*)srcPtr; #define COPY16TO8(rfunc) \ DITHER_COPY(dstPtr, dstStride[plane], W8, \ srcPtr2, srcStride[plane]/2, rfunc, \ dither_8x8_256, 8); if (isBE(c->srcFormat)) { COPY16TO8(AV_RB16); } else { COPY16TO8(AV_RL16); } } else if(!is16BPS(c->srcFormat) && is16BPS(c->dstFormat)) { for (i=0; i<height; i++) { for (j=0; j<length; j++) { dstPtr[ j<<1 ] = srcPtr[j]; dstPtr[(j<<1)+1] = srcPtr[j]; } srcPtr+= srcStride[plane]; dstPtr+= dstStride[plane]; } } else if(is16BPS(c->srcFormat) && is16BPS(c->dstFormat) && isBE(c->srcFormat) != isBE(c->dstFormat)) { for (i=0; i<height; i++) { for (j=0; j<length; j++) ((uint16_t*)dstPtr)[j] = av_bswap16(((const uint16_t*)srcPtr)[j]); srcPtr+= srcStride[plane]; dstPtr+= dstStride[plane]; } } else if (dstStride[plane] == srcStride[plane] && srcStride[plane] > 0 && srcStride[plane] == length) { memcpy(dst[plane] + dstStride[plane]*y, src[plane], height*dstStride[plane]); } else { if(is16BPS(c->srcFormat) && is16BPS(c->dstFormat)) length*=2; for (i=0; i<height; i++) { memcpy(dstPtr, srcPtr, length); srcPtr+= srcStride[plane]; dstPtr+= dstStride[plane]; } } } } return srcSliceH; }
1threat
static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom) { AVStream *st = c->fc->streams[c->fc->nb_streams-1]; MOVStreamContext *sc = st->priv_data; unsigned int i, entries; get_byte(pb); get_be24(pb); entries = get_be32(pb); dprintf(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries); if(entries >= UINT_MAX / sizeof(*sc->stsc_data)) return -1; sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data)); if (!sc->stsc_data) return AVERROR(ENOMEM); sc->stsc_count = entries; for(i=0; i<entries; i++) { sc->stsc_data[i].first = get_be32(pb); sc->stsc_data[i].count = get_be32(pb); sc->stsc_data[i].id = get_be32(pb); } return 0; }
1threat
End of Public Updates for Oracle JDK 8, what is the meaning of that? : <p>According to <a href="https://www.oracle.com/technetwork/java/javase/overview/index.html" rel="nofollow noreferrer">this link</a>, Can we say that starting in January 2019, Java is no longer open source?</p>
0debug
static int vnc_update_client_sync(VncState *vs, int has_dirty) { int ret = vnc_update_client(vs, has_dirty); vnc_jobs_join(vs); return ret; }
1threat
Android Custom Dialog Size : <p>I have a custom dialog, which xml code is below, but when dialog opens the view is very small, how to customize the size of it</p> <pre><code>&lt;LinearLayout android:orientation="vertical" android:background="#ffffff" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;Spinner android:id="@+id/name_list" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;/Spinner&gt; &lt;Button android:id="@+id/name_search" android:text="Search" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:background="#ffffff" android:textStyle="bold" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt; </code></pre>
0debug
Output problem - with itertools.groupby in pyton : I got this homework question, after taking a course on udemy I still cannot figure out how to get the right output like the Solution. furthermore: and how can i make it more efficace how can i do it without use explicit loops, but use list/dictionary comprehensions instead. this is what i do: def group_permutation_values(permutations_list): dic = {} f = lambda x: x[1] for key, group in itertools.groupby(sorted(permutations_list, key=f), f): dic[key] = list(group) return dic pass results = [((1, 2, 3), -4), ((1, 3, 2), -4), ((2, 1, 3), -2), ((2, 3, 1), -2), ((3, 1, 2), 0), ((3, 2, 1), 0)] print(group_permutation_values(results)) this is what i got : {-4: [((1, 2, 3), -4), ((1, 3, 2), -4)], -2: [((2, 1, 3), -2), ((2, 3, 1), -2)], 0: [((3, 1, 2), 0), ((3, 2, 1), 0)]} and the expect output: {-4: [(1, 2, 3), (1, 3, 2)], -2: [(2, 1, 3), (2, 3, 1)], 0: [(3, 1, 2), (3, 2, 1)]}
0debug
static void pred4x4_vertical_vp8_c(uint8_t *src, const uint8_t *topright, int stride){ const int lt= src[-1-1*stride]; LOAD_TOP_EDGE LOAD_TOP_RIGHT_EDGE uint32_t v = PACK_4U8((lt + 2*t0 + t1 + 2) >> 2, (t0 + 2*t1 + t2 + 2) >> 2, (t1 + 2*t2 + t3 + 2) >> 2, (t2 + 2*t3 + t4 + 2) >> 2); AV_WN32A(src+0*stride, v); AV_WN32A(src+1*stride, v); AV_WN32A(src+2*stride, v); AV_WN32A(src+3*stride, v); }
1threat
static void setup_rt_frame(int sig, struct target_sigaction *ka, target_siginfo_t *info, target_sigset_t *set, CPUState *env) { fprintf(stderr, "setup_rt_frame: not implemented\n"); }
1threat
find primers and palindromes in python : A palindromic prime is a prime number that is also palindromic. For example, 131 is a prime and also a palindromic prime, as are 313 and 757. I need to write a function that displays the first n palindromic prime numbers. Display 10 numbers per line and align the numbers properly, as follows: 2 3 5 7 11 101 131 151 181 191 313 353 373 383 727 757 787 797 919 929 my code is: def paliPrime(n): a=0 b=n a+=1 for i in range(a,b): paliPrime=True if str(i) == str(i)[::-1]: if i>2: for a in range(2,i): if i%a==0: paliPrime=False break if paliPrime: print i the code works but not in the way i wanted: >>> >>> paliPrime(10) 3 5 7 >>> And what I want is a function that displays the first n palindromic prime numbers. It should display 10 numbers per line and align the numbers properly.
0debug
React redux application folder structure : <p>I understand the concept of a react/redux app.</p> <p>My question is, is there a preferred way to layout the folder structure and files.</p> <p>After doing much research of repos online it appears that everyone does it slightly differently depending on their code flavor.</p> <p>Angular on the other hand appears that there is a set structure.</p> <p>Is this what makes react more powerful as you can tweak and adjust as your needs change?</p> <p>Has the community agreed on any set patterns?</p>
0debug
Does Rust have Collection traits? : <p>I'd like to write a library that's a thin wrapper around some of the functionality in <a href="https://doc.rust-lang.org/std/collections/btree_map/struct.BTreeMap.html">BTreeMap</a>. I'd prefer not to tightly couple it to that particular data structure though. Strictly speaking, I only need a subset of its functionality, something along the lines of the <a href="https://docs.oracle.com/javase/7/docs/api/java/util/NavigableMap.html">NavigableMap</a> interface in Java. I was hoping to find an analogous trait I could use. I seem to recall that at some point there were traits like <code>Map</code> and <code>MutableMap</code> in the standard library, but they seem to be absent now.</p> <p>Is there a crate that defines these? Or will they eventually be re-added to std?</p>
0debug
Why to put img inside div? : <p>Hey guys I am beginner at html and css and confused with why to put img inside div, I mean, are there any benefits. Secondly, if I put img inside div then will it suffice to define height of the img without specifying width of the img.</p>
0debug
Translate c# to VB.NET : I am trying to use code from [here][1] but my project is VB.NET I tried few online converters but without much success. C# version works great but not VB.NET one. What might be the problem ? [1]: https://stackoverflow.com/questions/32961051/convert-nested-json-to-csv My VB.NET version Dim arr As JArray = Nothing Dim obj As JObject = Nothing Try arr = JArray.Parse(json) Catch End Try If arr Is Nothing Then obj = JObject.Parse(arr.ToString()) Else json = "{ Response: [" & json & "]}" obj = JObject.Parse(json) End If Dim values = obj.DescendantsAndSelf().OfType(Of JProperty)().Where(Function(p) TypeOf p.Value Is JValue).GroupBy(Function(p) p.Name).ToList() Dim columns = values.[Select](Function(g) g.Key).ToArray() Dim parentsWithChildren = values.SelectMany(Function(g) g).SelectMany(Function(v) v.AncestorsAndSelf().OfType(Of JObject)().Skip(1)).ToHashSet() Dim rows = obj.DescendantsAndSelf().OfType(Of JObject)().Where(Function(o) o.PropertyValues().OfType(Of JValue)().Any()).Where(Function(o) o = obj OrElse Not parentsWithChildren.Contains(o)).[Select](Function(o) columns.[Select](Function(c) o.AncestorsAndSelf().OfType(Of JObject)().[Select](Function(parent) parent(c)).Where(Function(v) TypeOf v Is JValue).[Select](Function(v) CStr(v)).FirstOrDefault()).Reverse().SkipWhile(Function(s) s Is Nothing).Reverse()) Dim csvRows = {columns}.Concat(rows).[Select](Function(r) String.Join(",", r)) Dim csv = String.Join(vbLf, csvRows)
0debug
How to print CHEQUE without background in wpf C# : <p>i would like to print the cheque so i am taking one background image to put the textblocks on correct place so that the text should be on correct place my requirement is i have to put the cheque in the printer and i have to show the values on cheque so my intention is after printing it should not show the image on cheque <a href="http://i.stack.imgur.com/6sZKo.jpg" rel="nofollow">cheque</a></p> <pre><code>private void Button_Click_1(object sender, RoutedEventArgs e) { PrintDialog dialog = new PrintDialog(); if (dialog.ShowDialog() == true) { dialog.PrintVisual(stackPrinting, "stackPrinting"); } } </code></pre>
0debug
Check if a date is greater than specified date vb.net : I want to check if a date is greater than a specified date using vb.net. The same thing i got working in the following : http://stackoverflow.com/questions/38344471/check-if-a-date-is-greater-than-specified-date/38344660?noredirect=1#comment64104240_38344660 but the above is using javascript. I did it using javascript as : var Jun16 = new Date('JUN-2016') var SelectedDate=new Date("<% =session("month")%>" + "-" + "<% =session("yrs")%>") if(SelectedDate.getTime() > Jun16.getTime()) { grossinc=parseInt("<% =rset1("othermontize_benefit") %>") + parseInt("<% =rset1("basic") %>") + parseInt("<% =rset1("house") %>") + parseInt("<% =rset1("utility") %>") } else { grossinc=parseInt("<% =rset1("gross") %>") + parseInt("<% =rset1("bonus") %>") + parseInt("<% =rset1("arrears") %>") + parseInt("<% =rset1("ot") %>") } How can I get the same in Vb script. Thanks.
0debug
static int twolame_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr) { TWOLAMEContext *s = avctx->priv_data; int ret; if ((ret = ff_alloc_packet(avpkt, MPA_MAX_CODED_FRAME_SIZE)) < 0) return ret; if (frame) { switch (avctx->sample_fmt) { case AV_SAMPLE_FMT_FLT: ret = twolame_encode_buffer_float32_interleaved(s->glopts, (const float *)frame->data[0], frame->nb_samples, avpkt->data, avpkt->size); break; case AV_SAMPLE_FMT_FLTP: ret = twolame_encode_buffer_float32(s->glopts, (const float *)frame->data[0], (const float *)frame->data[1], frame->nb_samples, avpkt->data, avpkt->size); break; case AV_SAMPLE_FMT_S16: ret = twolame_encode_buffer_interleaved(s->glopts, (const short int *)frame->data[0], frame->nb_samples, avpkt->data, avpkt->size); break; case AV_SAMPLE_FMT_S16P: ret = twolame_encode_buffer(s->glopts, (const short int *)frame->data[0], (const short int *)frame->data[1], frame->nb_samples, avpkt->data, avpkt->size); break; default: av_log(avctx, AV_LOG_ERROR, "Unsupported sample format %d.\n", avctx->sample_fmt); return AVERROR_BUG; } } else { ret = twolame_encode_flush(s->glopts, avpkt->data, avpkt->size); } if (!ret) return 0; if (ret < 0) return AVERROR_UNKNOWN; avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples); if (frame) { if (frame->pts != AV_NOPTS_VALUE) avpkt->pts = frame->pts - ff_samples_to_time_base(avctx, avctx->initial_padding); } else { avpkt->pts = s->next_pts; } if (avpkt->pts != AV_NOPTS_VALUE) s->next_pts = avpkt->pts + avpkt->duration; av_shrink_packet(avpkt, ret); *got_packet_ptr = 1; return 0; }
1threat
A particolar :hoover effect : I'm currently working on this [website][1], in the project section there are 3 columns, i already set the scale to change when hoovering over one of it, but my client requested that the middle column need to be already scaled when the page is opened for the first time, and after hoovering on the one on the left or on the right, the middle column get back to the original scale, the same as the other. Is possible? the correct way should be: 0= Original scale 1= Bigger scale First view of the page->[ 0| 1 |0 ] --hoovering in another column-->[ 1| 0 |0 ] --not hoovering in a column->[ 0| 0 |0 ] I don't know if i was clear enough, sorry for my english but is not my mother tongue. Thanks for helping. [1]: https://big-d.mt/
0debug
Jupyter notebook permission error : <p>I'm having some issues with opening Jupyter. I just installed Anaconda, but got the same error as before when I try to write "Jupyter notebook" in terminal.</p> <pre><code>Johans-MBP:~ JDMac$ Jupyter notebook Traceback (most recent call last): File "/Users/JDMac/anaconda3/lib/python3.5/site-packages/traitlets/traitlets.py", line 501, in get value = obj._trait_values[self.name] KeyError: 'runtime_dir' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/JDMac/anaconda3/bin/jupyter-notebook", line 6, in &lt;module&gt; sys.exit(notebook.notebookapp.main()) File "/Users/JDMac/anaconda3/lib/python3.5/site-packages/jupyter_core/application.py", line 267, in launch_instance return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs) File "/Users/JDMac/anaconda3/lib/python3.5/site-packages/traitlets/config/application.py", line 588, in launch_instance app.initialize(argv) File "&lt;decorator-gen-7&gt;", line 2, in initialize File "/Users/JDMac/anaconda3/lib/python3.5/site-packages/traitlets/config/application.py", line 74, in catch_config_error return method(app, *args, **kwargs) File "/Users/JDMac/anaconda3/lib/python3.5/site-packages/notebook/notebookapp.py", line 1021, in initialize self.init_configurables() File "/Users/JDMac/anaconda3/lib/python3.5/site-packages/notebook/notebookapp.py", line 815, in init_configurables connection_dir=self.runtime_dir, File "/Users/JDMac/anaconda3/lib/python3.5/site-packages/traitlets/traitlets.py", line 529, in __get__ return self.get(obj, cls) File "/Users/JDMac/anaconda3/lib/python3.5/site-packages/traitlets/traitlets.py", line 508, in get value = self._validate(obj, dynamic_default()) File "/Users/JDMac/anaconda3/lib/python3.5/site-packages/jupyter_core/application.py", line 99, in _runtime_dir_default ensure_dir_exists(rd, mode=0o700) File "/Users/JDMac/anaconda3/lib/python3.5/site-packages/ipython_genutils/path.py", line 167, in ensure_dir_exists os.makedirs(path, mode=mode) File "/Users/JDMac/anaconda3/lib/python3.5/os.py", line 241, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/Users/JDMac/Library/Jupyter/runtime' </code></pre> <p>As I'm close to clueless with all of this, I need some assistance over here :)</p>
0debug
No overload for method 'ToString' takes 1 arguments : <p>I have a Web API runs a stored procedure and returns the records from the table.The record includes the int field called CounterSeq</p> <pre><code>[HttpGet] public IHttpActionResult Get(string Account) { // other code for connecting to the SQL seerver and calling the stored procedure reader = command.ExecuteReader(); List&lt;QueryResult&gt;qresults = new List&lt;QueryResult&gt;(); while (reader.Read()) { QueryResult qr = new QueryResult(); qr.AccountID = reader["AccountID"].ToString(); qr.CounterSeq = reader["CounterSeq"].ToString("000"); qresults.Add(qr); } DbConnection.Close(); return Ok(qresults); </code></pre> <p>To have the CounterSeq to have the response as "001","010","100". It thows the error like <code>No overload for method 'ToString' takes 1 arguments</code> in <code>reader["CounterSeq"].ToString("000");</code></p>
0debug
void ptimer_set_limit(ptimer_state *s, uint64_t limit, int reload) { if (!use_icount && limit * s->period < 10000 && s->period) { limit = 10000 / s->period; } s->limit = limit; if (reload) s->delta = limit; if (s->enabled && reload) { s->next_event = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL); ptimer_reload(s); } }
1threat
void checkasm_check_vf_interlace(void) { check_lowpass_line(8); report("lowpass_line_8"); check_lowpass_line(16); report("lowpass_line_16"); }
1threat
SQL server - Using self join/Inner join get the data by adding all the above rows data : I need urgent help with reference to SQL server, the query details is as mentioned below: Need to get the calculative column whose result will be addition of all the above rows. And I can't use correlated queries, Lag and Lead as it is not supported. I tried using Selfjoin/inner join/left outer join, the only problem I am facing is due to group by clause of other columns the result is not coming as expected.. For example, Data is like [Data is like this image][1] Expected Output [Expected output is like this image][2] But the output I am getting due to group by clause applied on Column4 [Output getting is like][3] Please let me know some alternative of GROUP by clause or other alternative. Your quick help will be much appreciated. Thanks, [1]: https://i.stack.imgur.com/auM2D.png [2]: https://i.stack.imgur.com/CFEzw.png [3]: https://i.stack.imgur.com/ADTxi.png
0debug
Git bash Error: Could not fork child process: There are no available terminals (-1) : <p>I have had up to 8 git bash terminals running at the same time before. </p> <p>Currently I have only 2 up.</p> <p>I have not seen this error before and I am not understanding what is causing it.</p> <p>Any help would be appreciated!</p> <p>Picture attached:</p> <p><a href="https://i.stack.imgur.com/Tps5X.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Tps5X.png" alt="enter image description here"></a></p>
0debug
Should I make two versions of one program, each with different language, or add an option to change language? : <p>I have a program that I'm currently writing in English. In future, I would like to make the program multilingual, therefore I'm wondering what's the best option to do so. I thought about this two option for now:</p> <ol> <li>Enable users to change language in settings;</li> <li>Select the appropriate language while downloading;</li> </ol> <p>With each option comes a problem:</p> <ol> <li>A ton of code dedicated to displaying one message in different languages;</li> <li>I will have to make many versions just to change the language of the displayed text;</li> </ol> <p>Now my question is, which one of these options is more memory efficient and user friendly? Maybe neither of them are? Do you have any other option that is better than given two? </p>
0debug
static void trigger_ascii_console_data(void *opaque, int n, int level) { sclp_service_interrupt(0); }
1threat
Get the operation attempted in case of NPE : <p>Consider the below code:</p> <pre><code>String s = null; s.toLowerCase(); </code></pre> <p>It throws a NPE:</p> <blockquote> <p>Exception in thread "main" java.lang.NullPointerException<br> at pracJava1.Prac.main(Prac.java:7)</p> </blockquote> <p>The question is: Why can't the JVM also put a helper message saying: </p> <blockquote> <p>Exception in thread "main" java.lang.NullPointerException. Attempted <code>toLowerCase() on null</code></p> </blockquote> <p>This is useful in cases like <code>obj.setName(s.toLowerCase())</code>, where the line number is not sufficient to guess if <code>obj</code> was null or <code>s</code>.</p> <hr> <p>On the feasibility of it, lets look at the byte code generated:</p> <pre><code> stack=1, locals=2, args_size=1 0: aconst_null 1: astore_1 2: aload_1 3: invokevirtual #2 // Method java/lang/String.toLowerCase:()Ljava/lang/String; </code></pre> <p>So may be it does know, the method name it attempted the operation on. JVM experts, what's your opinion?</p>
0debug
I have read that using anchor tags for onepage scrolling or in tabs are not good for seo can you help me to create a bootstrap tab without "href="#" : I have read that using anchor tags for onepage scrolling or in tabs are not good for seo can you help me to create a bootstrap tab without "href="#" and i found that donw in this website "http://www.asmhijas.com/"
0debug
How to substitute several regex in Python? : <p>I would like to loop on every lines from a .txt file and then use <code>re.sub</code> method from Python in order to change some contents if there is a specific pattern matcing in this line.</p> <p>But how can I do that for two different pattern in the same file ?</p> <p>For example, here's my code :</p> <pre><code>file = open(path, 'r') output = open(temporary_path, 'w') for line in file: out = re.sub("patternToChange", "patternToWrite", line) #Here I would like to also do the same trick with "patternToChange2 and patternToWrite2 also in the same file output .write(out) </code></pre> <p>Do you have any ideas ?</p>
0debug
static int adx_decode_init(AVCodecContext * avctx) { ADXContext *c = avctx->priv_data; c->prev[0].s1 = 0; c->prev[0].s2 = 0; c->prev[1].s1 = 0; c->prev[1].s2 = 0; c->header_parsed = 0; c->in_temp = 0; return 0; }
1threat
How can I run selenium chrome driver in a docker container? : <h1>tl;dr</h1> <p>How can I install all the components to run Selenium in a docker container?</p> <hr> <h1>Question</h1> <p>I'm starting with this image:</p> <pre><code>FROM microsoft/aspnetcore-build:2 AS builder WORKDIR /source COPY . . RUN dotnet restore RUN dotnet build ENTRYPOINT ["dotnet", "run"] </code></pre> <p>How can I make it so that I can start and use an headless Chrome Driver with this:</p> <pre><code>ChromeOptions options = new ChromeOptions(); options.AddArgument("--headless"); options.AddArgument("--disable-gpu"); var driverPath = Path.GetFullPath(Path.Combine(environment.ContentRootPath, "bin/Debug/netcoreapp2.0")); return new ChromeDriver(driverPath, options, TimeSpan.FromSeconds(60)); </code></pre> <p>within a docker container?</p> <hr> <h1>What have I tried</h1> <h3>Installing the Chrome driver</h3> <p>The <code>chromedriver</code> is distributed via the <code>Selenium.WebDriver.ChromeDriver</code> NuGet package. </p> <h3>Installing Chrome</h3> <p>On my Mac OS X with Google Chrome installed the current setup works just fine.</p> <p>I've tried to add these lines:</p> <pre><code>RUN apt-get update &amp;&amp; apt-get -y install libglib2.0-dev libxi6 libnss3-dev RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - RUN sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" &gt;&gt; /etc/apt/sources.list.d/google.list' RUN apt-get update &amp;&amp; apt-get -y install google-chrome-stable </code></pre> <p>The above installs this version of Chrome:</p> <pre><code>google-chrome-stable: Installed: 64.0.3282.119-1 Candidate: 64.0.3282.119-1 Version table: *** 64.0.3282.119-1 500 500 http://dl.google.com/linux/chrome/deb stable/main amd64 Packages 100 /var/lib/dpkg/status </code></pre> <p>which is compatible with the version of the Chrome Driver.</p> <p>which come from trying to solve each error that came out by trying to run Selenium with the docker container.</p> <p>If I run this setup I get:</p> <blockquote> <p>Starting ChromeDriver 2.35.528139 (47ead77cb35ad2a9a83248b292151462a66cd881) on port 57889 Only local connections are allowed. An error occurred while sending the request. Couldn't connect to</p> </blockquote> <p>when running the container.</p> <h3>Debugging in the container</h3> <p>If I enter the container manually and try to run the chrome driver manually I get:</p> <blockquote> <p>Starting ChromeDriver 2.35.528139 (47ead77cb35ad2a9a83248b292151462a66cd881) on port 9515 Only local connections are allowed.</p> </blockquote> <p>and running <code>curl -i http://localhost:9515/status</code> I get:</p> <pre><code>HTTP/1.1 200 OK Content-Length:136 Content-Type:application/json; charset=utf-8 Connection:close {"sessionId":"","status":0,"value":{"build":{"version":"alpha"},"os":{"arch":"x86_64","name":"Linux","version":"4.9.60-linuxkit-aufs"}}} </code></pre> <p>so it seems that the driver works just fine.</p> <p>If I run chrome headless instead via <code>google-chrome-stable --headless --disable-cpu --no-sandbox</code> I get:</p> <pre><code>[0125/210641.877388:WARNING:discardable_shared_memory_manager.cc(178)] Less than 64MB of free space in temporary directory for shared memory files: 63 [0125/210641.902689:ERROR:instance.cc(49)] Unable to locate service manifest for metrics [0125/210641.902756:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics [0125/210642.031088:ERROR:instance.cc(49)] Unable to locate service manifest for metrics [0125/210642.031119:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics [0125/210642.032934:ERROR:gpu_process_transport_factory.cc(1009)] Lost UI shared context. </code></pre> <p>The first warning can be solved via setting a docker volume in <code>/dev/shm:/dev/shm</code> or by setting <code>-shm-size</code> to something large (higher than 64MB).</p> <p>The rest of the errors, if google, lead to me many bug reports from Google Chrome repositories.</p>
0debug
Getting domain part from path : <p>If I use <code>__DIV__</code> I get path something like this:</p> <pre><code>/home/domaincom/public_html/account/assets </code></pre> <p>I need to get the <strong>domaincom</strong> part only, how do I do that?</p> <p>Thanks</p>
0debug
Is it allowed to place ...<T> as class name java? : <p>I have this code for a class that represent a element in a list</p> <pre><code>public class Element&lt;T&gt;{ Element&lt;T&gt; next; Element&lt;T&gt; previous; T info; } </code></pre> <p>I have some ideas but I actually don't figure out the full meaning of the above declaration. And have some hard times to search for an explanation of this technique.</p>
0debug
static void x86_cpu_unrealizefn(DeviceState *dev, Error **errp) { X86CPU *cpu = X86_CPU(dev); #ifndef CONFIG_USER_ONLY cpu_remove_sync(CPU(dev)); qemu_unregister_reset(x86_cpu_machine_reset_cb, dev); #endif if (cpu->apic_state) { object_unparent(OBJECT(cpu->apic_state)); cpu->apic_state = NULL; } xcc->parent_unrealize(dev, &local_err); if (local_err != NULL) { error_propagate(errp, local_err); return; } }
1threat
Why should forEach be preferred over regular iterators? : <p>I was reading <a href="https://github.com/airbnb/javascript" rel="noreferrer">airbnb javascript guide</a>. There is a particular statement, that says:</p> <blockquote> <p>Don’t use iterators. Prefer JavaScript’s higher-order functions instead of loops like for-in or for-of.</p> </blockquote> <p>The reason they give for the above statement is:</p> <blockquote> <p>This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.</p> </blockquote> <p>I could not differentiate between the two coding practices given:</p> <pre><code> const numbers = [1, 2, 3, 4, 5]; // bad let sum = 0; for (let num of numbers) { sum += num; } sum === 15; // good let sum = 0; numbers.forEach((num) =&gt; { sum += num; }); sum === 15; </code></pre> <p>Could anyone explain, why should <code>forEach</code> be preferred over regular <code>for</code> loop? How does it really make a difference? Are there any side effects of using the regular <code>iterators</code>?</p>
0debug
Stripe not working with error 'Uncaught (in promise) Error: We could not retrieve data from the specified Element.' : <p>I am trying to use Stripe.js following <a href="https://stripe.com/docs/stripe-js/elements/quickstart" rel="noreferrer">https://stripe.com/docs/stripe-js/elements/quickstart</a></p> <p>I made html, css, javascript just same as sample of that url.</p> <p>But when I click 'Submit Payment' Button, it always shows console error and not working.</p> <pre><code>(index):1 Uncaught (in promise) Error: We could not retrieve data from the specified Element. Please make sure the Element you are attempting to use is still mounted. at new t ((index):1) at e._handleMessage ((index):1) at e._handleMessage ((index):1) at (index):1 </code></pre> <p>Please let me know why this happens.</p>
0debug
bool guest_validate_base(unsigned long guest_base) { return 1; }
1threat
static void vnc_dpy_resize(DisplayState *ds) { int size_changed; VncState *vs = ds->opaque; vs->old_data = qemu_realloc(vs->old_data, ds_get_linesize(ds) * ds_get_height(ds)); if (vs->old_data == NULL) { fprintf(stderr, "vnc: memory allocation failed\n"); exit(1); } if (ds_get_bytes_per_pixel(ds) != vs->depth) console_color_init(ds); vnc_colordepth(ds); size_changed = ds_get_width(ds) != vs->width || ds_get_height(ds) != vs->height; if (size_changed) { vs->width = ds_get_width(ds); vs->height = ds_get_height(ds); if (vs->csock != -1 && vs->has_resize) { vnc_write_u8(vs, 0); vnc_write_u8(vs, 0); vnc_write_u16(vs, 1); vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds), -223); vnc_flush(vs); } } memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row)); memset(vs->old_data, 42, ds_get_linesize(vs->ds) * ds_get_height(vs->ds)); }
1threat
When I run this code it is giving output as 10 10 10 12 24 10. Can anyone please help me in understanding the output? I am new to python programming : class A: x = 10 class B(A): pass class C(A): pass print (A.x) print (B.x) print (C.x) A.x += 2 B.x *= 2 C.x -= 2 print (A.x) print (B.x) print (C.x)
0debug
static void vmxnet3_process_tx_queue(VMXNET3State *s, int qidx) { struct Vmxnet3_TxDesc txd; uint32_t txd_idx; uint32_t data_len; hwaddr data_pa; for (;;) { if (!vmxnet3_pop_next_tx_descr(s, qidx, &txd, &txd_idx)) { break; } vmxnet3_dump_tx_descr(&txd); if (!s->skip_current_tx_pkt) { data_len = (txd.len > 0) ? txd.len : VMXNET3_MAX_TX_BUF_SIZE; data_pa = le64_to_cpu(txd.addr); if (!net_tx_pkt_add_raw_fragment(s->tx_pkt, data_pa, data_len)) { s->skip_current_tx_pkt = true; } } if (s->tx_sop) { vmxnet3_tx_retrieve_metadata(s, &txd); s->tx_sop = false; } if (txd.eop) { if (!s->skip_current_tx_pkt && net_tx_pkt_parse(s->tx_pkt)) { if (s->needs_vlan) { net_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci); } vmxnet3_send_packet(s, qidx); } else { vmxnet3_on_tx_done_update_stats(s, qidx, VMXNET3_PKT_STATUS_ERROR); } vmxnet3_complete_packet(s, qidx, txd_idx); s->tx_sop = true; s->skip_current_tx_pkt = false; net_tx_pkt_reset(s->tx_pkt); } } }
1threat
void object_property_add_link(Object *obj, const char *name, const char *type, Object **child, void (*check)(Object *, const char *, Object *, Error **), ObjectPropertyLinkFlags flags, Error **errp) { Error *local_err = NULL; LinkProperty *prop = g_malloc(sizeof(*prop)); gchar *full_type; prop->child = child; prop->check = check; prop->flags = flags; full_type = g_strdup_printf("link<%s>", type); object_property_add(obj, name, full_type, object_get_link_property, check ? object_set_link_property : NULL, object_release_link_property, prop, &local_err); if (local_err) { error_propagate(errp, local_err); g_free(prop); } g_free(full_type); }
1threat
How to add a drawer and a search icon on my app bar in flutter : <p>I'm new to flutter and exploring it. I already have an app bar but I can't seem to figure out how to properly display a drawer icon and a search icon on it. I want it to look like the gmail app bar like the image below. I am working on a company helpdesk mobile app. Thanks.</p> <p><a href="https://i.stack.imgur.com/QQ3Cw.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/QQ3Cw.jpg" alt="gmail app bar"></a></p>
0debug
Warning! ***HDF5 library version mismatched error*** python pandas windows : <p>I'm using pandas/python to save a DataFrame in a HDFStore format. When I apply the <em>my_data_frame.to_hdf(arguments...)</em> command I have an error message:<strong>Warning! ***HDF5 library version mismatched error</strong> *** and my program is stopped.</p> <p>I'm working on Windows 7 (64bits), using Python 3.5.2 :: Anaconda 4.1.1 (64-bit).</p> <p>I've been reading about this error message and as it says it's a problem between the version of HDF5 installed on my computer and the one used by Anacondas. According <a href="https://github.com/h5py/h5py/issues/853" rel="noreferrer">this</a> post, a simple <strong><em>"conda install -c anaconda hdf5=1.8.18"</em></strong> could resolve my problem but I'm still having the same message error.</p> <p>Thanks for your help guys.</p> <p>Here I put a complete log of the error:</p> <pre> Warning! ***HDF5 library version mismatched error*** The HDF5 header files used to compile this application do not match the version used by the HDF5 library to which this application is linked. Data corruption or segmentation faults may occur if the application continues. This can happen when an application was compiled by one version of HDF5 but linked with a different version of static or shared HDF5 library. You should recompile the application or check your shared library related settings such as 'LD_LIBRARY_PATH'. You can, at your own risk, disable this warning by setting the environment variable 'HDF5_DISABLE_VERSION_CHECK' to a value of '1'. Setting it to 2 or higher will suppress the warning messages totally. Headers are 1.8.15, library is 1.8.18 SUMMARY OF THE HDF5 CONFIGURATION ================================= General Information: ------------------- HDF5 Version: 1.8.18 Configured on: 2017-05-31 Configured by: NMake Makefiles Configure mode: CMAKE 3.8.0 Host system: Windows-6.3.9600 Uname information: Windows Byte sex: little-endian Libraries: Installation point: C:/bld/hdf5_1496269860661/_b_env/Library Compiling Options: ------------------ Compilation Mode: RELEASE C Compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe CFLAGS: /DWIN32 /D_WINDOWS /W3 H5_CFLAGS: AM_CFLAGS: CPPFLAGS: H5_CPPFLAGS: AM_CPPFLAGS: Shared C Library: YES Static C Library: YES Statically Linked Executables: OFF LDFLAGS: /machine:x64 AM_LDFLAGS: Extra libraries: C:/bld/hdf5_1496269860661/_b_env/Library/lib/z. lib Archiver: Ranlib: Debugged Packages: API Tracing: OFF Languages: ---------- Fortran: OFF Fortran Compiler: Fortran 2003 Compiler: Fortran Flags: H5 Fortran Flags: AM Fortran Flags: Shared Fortran Library: YES Static Fortran Library: YES C++: ON C++ Compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe C++ Flags: /DWIN32 /D_WINDOWS /W3 /GR /EHsc H5 C++ Flags: AM C++ Flags: Shared C++ Library: YES Static C++ Library: YES Features: --------- Parallel HDF5: OFF High Level library: ON Threadsafety: ON Default API Mapping: v18 With Deprecated Public Symbols: ON I/O filters (external): DEFLATE MPE: Direct VFD: dmalloc: Clear file buffers before write: ON Using memory checker: OFF Function Stack Tracing: OFF Strict File Format Checks: OFF Optimization Instrumentation: </pre>
0debug
{} + "" vs "" + {} - Consistency in Addition : <p>I stumbled across this the other day on reddit. The poster noted that </p> <pre><code>{} + "" </code></pre> <p>is equal to <code>0</code>, while the similar</p> <pre><code>"" + {} </code></pre> <p>is equal to an empty <code>[object Object]</code>.</p> <p>Normal math rules tell me this is odd, but why is it this way?</p>
0debug
Import interface in Angular 2 : <p>In a Meteor app that uses Angular 2, I want to create a custom data type, something like this:</p> <pre><code>interface MyCustomType { index: number; value: string; } </code></pre> <p>I then want to use this custom type in multiple files. I've tried creating a separate file named "mycustom.type.ts", with the following content:</p> <pre><code>export interface MyCustomType { index: number; value: string; } </code></pre> <p>I then attempt to import this type so that it can be used in another file:</p> <pre><code>import MyCustomType from "./mycustom.type" </code></pre> <p>However, Atom reports the following error:</p> <pre><code>TS Error File '/.../mycustom.type.ts' is not a module ... </code></pre> <p>How should I be declaring and importing types, so that they can be used in multiple places?</p>
0debug
Pass through authentication with ASP Core MVC, Web API and IdentityServer4? : <p>I have been working on migrating a monolithic ASP Core MVC application to use an service architecture design. The MVC front-end website uses an <code>HttpClient</code> to load necessary data from the ASP Core Web API. A small portion of the front-end MVC app also requires authentication which is in place using IdentityServer4 (integrated with the back-end API). This all works great, until I put an <code>Authorize</code> attribute on a controller or method on the Web API. I know I need to somehow pass the user authorization from the front-end to the back-end in order for this to work, but I'm not sure how. I have tried getting the access_token: <code>User.FindFirst("access_token")</code> but it returns null. I then tried this method and I am able to get the token:</p> <pre><code>var client = new HttpClient("url.com"); var token = HttpContext.Authentication.GetTokenAsync("access_token")?.Result; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); </code></pre> <p>This method gets the token but still doesn't authentication with the back-end API. I'm pretty new to this OpenId/IdentityServer concepts and any help would be appreciated!</p> <p>Here is the relevant code from the MVC Client Startup class:</p> <pre><code> private void ConfigureAuthentication(IApplicationBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookies", AutomaticAuthenticate = true, ExpireTimeSpan = TimeSpan.FromMinutes(60) }); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { AuthenticationScheme = "oidc", SignInScheme = "Cookies", Authority = "https://localhost:44348/", RequireHttpsMetadata = false, ClientId = "clientid", ClientSecret = "secret", ResponseType = "code id_token", Scope = { "openid", "profile" }, GetClaimsFromUserInfoEndpoint = true, AutomaticChallenge = true, // Required to 302 redirect to login SaveTokens = true, TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { NameClaimType = "Name", RoleClaimType = "Role", SaveSigninToken = true }, }); } </code></pre> <p>and the StartUp class of the API:</p> <pre><code> // Add authentication services.AddIdentity&lt;ExtranetUser, IdentityRole&gt;(options =&gt; { // Password settings options.Password.RequireDigit = true; options.Password.RequiredLength = 8; options.Password.RequireNonAlphanumeric = true; options.Password.RequireUppercase = true; options.Password.RequireLowercase = true; // Lockout settings options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30); options.Lockout.MaxFailedAccessAttempts = 10; // User settings options.User.RequireUniqueEmail = true; }) .AddDefaultTokenProviders(); services.AddScoped&lt;IUserStore&lt;ExtranetUser&gt;, ExtranetUserStore&gt;(); services.AddScoped&lt;IRoleStore&lt;IdentityRole&gt;, ExtranetRoleStore&gt;(); services.AddSingleton&lt;IAuthorizationHandler, AllRolesRequirement.Handler&gt;(); services.AddSingleton&lt;IAuthorizationHandler, OneRoleRequirement.Handler&gt;(); services.AddSingleton&lt;IAuthorizationHandler, EditQuestionAuthorizationHandler&gt;(); services.AddSingleton&lt;IAuthorizationHandler, EditExamAuthorizationHandler&gt;(); services.AddAuthorization(options =&gt; { /* ... etc .... */ }); var serviceProvider = services.BuildServiceProvider(); var serviceSettings = serviceProvider.GetService&lt;IOptions&lt;ServiceSettings&gt;&gt;().Value; services.AddIdentityServer() // Configures OAuth/IdentityServer framework .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources()) .AddInMemoryClients(IdentityServerConfig.GetClients(serviceSettings)) .AddAspNetIdentity&lt;ExtranetUser&gt;() .AddTemporarySigningCredential(); // ToDo: Add permanent SigningCredential for IdentityServer </code></pre>
0debug
Regex number between : <p>how to make regex for number from -100 to 100? Thanks in advance</p>
0debug
Is there a <wbr> equivalent tag to affect whole sentences instead of just a single word? : `<wbr>` breaks a word in case of word-wrap due to a small screen. But is there a tag that could be used in order to break and "word-wrap" the text of a sentence on a specific point in case of a small screen? The CSS question tag is probable irrelevant, but I thought that maybe someone could have implemented a solution using CSS.
0debug
need to group sequence of letters while keeping the order in pandas or/and python : noobie here. in a hurry to figure this out. So new, I can not even figure to do a simple posting. Columns get out of whack. So here is a pic. pic always works [my humble question][1] someone answered a similar question. but using oracle sql. I only have pandas and python available. https://stackoverflow.com/questions/16987174/group-rows-keeping-the-order-of-values [done with sql][1] [1]: https://i.stack.imgur.com/7XIHo.png
0debug
How we can dynamically show names on labels by entering into the text field on the click of the button using Javascript? : Can anyone give me the code for this ? Firstly i want to enter names using input field and then show those names dynamically on the click of button.
0debug
How to build library(opeface) in project using jhbuild without cmake file in library(openface) : **I want to build OpenFace library in my project but some of issue i am facing bellow:** **What I have done:** * I have clone openface library from github and put into jhbuild. * Now, I have create **openface.moduleset** file for build library in project but openface dosn't having **CmakeList.txt** file so unable to understand what i have to write in .moduleset file to build openface library. * I have build openface library using **sudo apt-get** and follow all command they provide in website and build without jhbuild but using jhbuild i am stuck how can i do it :( . **Problem:** * In openface library there is no cmake file. * I have made .moduleset file but but how to build openface if library not supported cmake so how can i do it using sudo apt with jhbuild. * What i have to write in .modileset file to build library in project using jhbuild.Please help !!
0debug
int qcrypto_pbkdf2_count_iters(QCryptoHashAlgorithm hash, const uint8_t *key, size_t nkey, const uint8_t *salt, size_t nsalt, Error **errp) { uint8_t out[32]; long long int iterations = (1 << 15); unsigned long long delta_ms, start_ms, end_ms; while (1) { if (qcrypto_pbkdf2_get_thread_cpu(&start_ms, errp) < 0) { return -1; } if (qcrypto_pbkdf2(hash, key, nkey, salt, nsalt, iterations, out, sizeof(out), errp) < 0) { return -1; } if (qcrypto_pbkdf2_get_thread_cpu(&end_ms, errp) < 0) { return -1; } delta_ms = end_ms - start_ms; if (delta_ms > 500) { break; } else if (delta_ms < 100) { iterations = iterations * 10; } else { iterations = (iterations * 1000 / delta_ms); } } iterations = iterations * 1000 / delta_ms; if (iterations > INT32_MAX) { error_setg(errp, "Iterations %lld too large for a 32-bit int", iterations); return -1; } return iterations; }
1threat
Searching multiple word in a given column using regular expression in MS SQL server : I want to perform multiple word on particular column. The given search string may be in different order. For example , I want to search the book name "Harry Potter Dream world "from books table using like operator and regular expression. I know, using multiple like operator, we can perform operation using below query "SELECT * FROM TABLE_1 WHERE bookname like 'Harry Potter' or like 'Heaven world'"; In this case, i want to perform this in a single query. Also i tried with FREETEXT options. That wont be useful when i use self-join. Kindly provide me any other alternatives to solve this. Also can you provide , how to use regular expression to search multiple word in MS SQL. I tried with multiple options. It won't work for me. Thanks in advance
0debug
Check if the word is a palindrome in COBOL : Create a program that will ask the user to enter a word. Check if the word is a palindrome. WHEN I TYPE LOL IT SAYS IT IS NOT A PALINDROME. PLS HELP ME DISPLAY "Enter a word to check if it is a Palindrome: " ACCEPT WS-STR1 MOVE FUNCTION REVERSE(WS-STR1)TO WS-STR2 DISPLAY WS-STR1 DISPLAY WS-STR2 IF WS-STR1(1:1) = WS-STR2(15:1) AND WS-STR1(2:1) = WS-STR2(14:1) AND WS-STR1(3:1) = WS-STR2(13:1) AND WS-STR1(4:1) = WS-STR2(12:1) AND WS-STR1(5:1) = WS-STR2(11:1) AND WS-STR1(6:1) = WS-STR2(10:1) AND WS-STR1(7:1) = WS-STR2(9:1) DISPLAY "A PALINDROME! " ELSE DISPLAY "NOT A PALINDROME " END-IF.
0debug
How to deseriliaze into different object where contain complex object property with different property name : <p>I have an object as below:</p> <pre><code>Organization: { Id : 1, Name : name, OrgType : { typeId : 1, name: tname }, employees : [{id:1, name:sm },{id:2, name:sm1 },{id:3, name:sm3 }] </code></pre> <p>so, here its complex object containing- Organization, OrgType and Employee list.</p> <p>Problem, is I receive this collection from one service response and my application has different structure of object.</p> <p>How can i deserialize above object to below structure:</p> <pre><code>Organization : Id changed to OrgId Name as Name, OrgType object changed to Type object Employees List object changed to EmpList object In Type object - typeId changed to OtId, name changed to Name. Employee object - id changed Id, name changed to EmployeeName </code></pre> <p>here, how to deserialize into above object where different property and also containing complex object. </p>
0debug
Spring Boot: Oauth2: Access is denied (user is anonymous); redirecting to authentication entry point : <p>I am trying to use spring boot oauth2 to accomplish stateless authentication and authorisation. However, I am struggling to it working.</p> <p>Here is my code:</p> <pre><code>@EnableAutoConfiguration @ComponentScan //@EnableEurekaClient //@EnableZuulProxy @Configuration public class AuthServiceApp { public static void main(String[] args) { SpringApplication.run(AuthServiceApp.class, args); } } </code></pre> <p><strong>Authorisation Config:</strong></p> <pre><code>@Configuration @EnableAuthorizationServer public class Oauth2ServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired @Qualifier("authenticationManagerBean") private AuthenticationManager auth; @Autowired private DataSource dataSource; @Autowired private CustomUserDetailsService userDetailService; @Autowired private ClientDetailsService clientDetailsService; @Bean public JdbcTokenStore tokenStore() { return new JdbcTokenStore(dataSource); } @Bean protected AuthorizationCodeServices authorizationCodeServices() { return new JdbcAuthorizationCodeServices(dataSource); } @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()"); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { // @OFF endpoints .authorizationCodeServices(authorizationCodeServices()) .authenticationManager(auth) .userDetailsService(userDetailService) .tokenStore(tokenStore()); // @ON } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { // @OFF clients.jdbc(dataSource) .withClient("client") .secret("secret") .authorizedGrantTypes("password","refresh_token", "client_credentials") .authorities("USER") .scopes("read", "write") .autoApprove(true) .accessTokenValiditySeconds(60) .refreshTokenValiditySeconds(300); // @ON } } </code></pre> <p><strong>Resource Server Config:</strong></p> <pre><code>@Configuration @EnableResourceServer @EnableGlobalMethodSecurity(prePostEnabled = true) class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Autowired private CustomAuthenticationEntryPoint customAuthenticationEntryPoint; @Autowired private CustomLogoutSuccessHandler customLogoutSuccessHandler; @Override public void configure(HttpSecurity http) throws Exception { // @OFF http .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .exceptionHandling() .authenticationEntryPoint(customAuthenticationEntryPoint) .and() .logout() .logoutUrl("/oauth/logout") .logoutSuccessHandler(customLogoutSuccessHandler) .and() .csrf() // .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize")) .disable() .headers() .frameOptions().disable() .and() .authorizeRequests() .antMatchers("/identity/**").authenticated(); // @ON } } @Configuration public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private CustomUserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity http) throws Exception { // @OFF http .csrf() .disable() .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin().permitAll(); // @ON } } </code></pre> <p><strong>Controller:</strong></p> <pre><code>@RestController @RequestMapping("/") public class AuthController { @PreAuthorize("#oauth2.hasScope('read')") @GetMapping("/user") public Principal getUser(Principal user) { return user; } } </code></pre> <p>I can get the access token using POSTMAN. I am using the same access token in the header to get the user details as <code>http://localhost:8082/identity/user</code> before it gets expired. However, I get login page html response with following log on console:</p> <pre><code>2017-05-24 22:55:16.070 DEBUG 16899 --- [nio-8082-exec-9] o.s.s.w.a.AnonymousAuthenticationFilter : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 301C6EDD36372CF9C553FCFCD4AA47E3; Granted Authorities: ROLE_ANONYMOUS' 2017-05-24 22:55:16.070 DEBUG 16899 --- [nio-8082-exec-9] o.s.security.web.FilterChainProxy : /user at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter' 2017-05-24 22:55:16.070 DEBUG 16899 --- [nio-8082-exec-9] o.s.security.web.FilterChainProxy : /user at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter' 2017-05-24 22:55:16.070 DEBUG 16899 --- [nio-8082-exec-9] o.s.security.web.FilterChainProxy : /user at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor' 2017-05-24 22:55:16.070 DEBUG 16899 --- [nio-8082-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user'; against '/login' 2017-05-24 22:55:16.070 DEBUG 16899 --- [nio-8082-exec-9] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /user; Attributes: [authenticated] 2017-05-24 22:55:16.071 DEBUG 16899 --- [nio-8082-exec-9] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 301C6EDD36372CF9C553FCFCD4AA47E3; Granted Authorities: ROLE_ANONYMOUS 2017-05-24 22:55:16.071 DEBUG 16899 --- [nio-8082-exec-9] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@55b4f25d, returned: -1 2017-05-24 22:55:16.071 DEBUG 16899 --- [nio-8082-exec-9] o.s.s.w.a.ExceptionTranslationFilter : Access is denied (user is anonymous); redirecting to authentication entry point org.springframework.security.access.AccessDeniedException: Access is denied at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE] </code></pre> <p>But it seems like I have been authenticated when making first call to get the access token to <code>oauth/token</code>:</p> <pre><code>2017-05-24 22:54:35.966 DEBUG 16899 --- [nio-8082-exec-6] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /oauth/token; Attributes: [fullyAuthenticated] 2017-05-24 22:54:35.966 DEBUG 16899 --- [nio-8082-exec-6] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@50c8f5e8: Principal: org.springframework.security.core.userdetails.User@af12f3cb: Username: client; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@21a2c: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 2F070B741A55BD1E47933621D9127780; Granted Authorities: USER 2017-05-24 22:54:35.966 DEBUG 16899 --- [nio-8082-exec-6] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@61f8721f, returned: 1 2017-05-24 22:54:35.966 DEBUG 16899 --- [nio-8082-exec-6] o.s.s.w.a.i.FilterSecurityInterceptor : Authorization successful 2017-05-24 22:54:35.966 DEBUG 16899 --- [nio-8082-exec-6] o.s.s.w.a.i.FilterSecurityInterceptor : RunAsManager did not change Authentication object 2017-05-24 22:54:35.966 DEBUG 16899 --- [nio-8082-exec-6] o.s.security.web.FilterChainProxy : /oauth/token reached end of additional filter chain; proceeding with original chain 2017-05-24 22:54:35.967 DEBUG 16899 --- [nio-8082-exec-6] .s.o.p.e.FrameworkEndpointHandlerMapping : Looking up handler method for path /oauth/token 2017-05-24 22:54:35.968 DEBUG 16899 --- [nio-8082-exec-6] .s.o.p.e.FrameworkEndpointHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity&lt;org.springframework.security.oauth2.common.OAuth2AccessToken&gt; org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(java.security.Principal,java.util.Map&lt;java.lang.String, java.lang.String&gt;) throws org.springframework.web.HttpRequestMethodNotSupportedException] 2017-05-24 22:54:35.975 DEBUG 16899 --- [nio-8082-exec-6] .o.p.p.ResourceOwnerPasswordTokenGranter : Getting access token for: client 2017-05-24 22:54:35.975 DEBUG 16899 --- [nio-8082-exec-6] o.s.s.authentication.ProviderManager : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider Hibernate: select user0_.id as id1_1_, user0_.enabled as enabled2_1_, user0_.name as name3_1_, user0_.password as password4_1_, user0_.username as username5_1_ from user user0_ where user0_.username=? Hibernate: select roles0_.user_id as user_id1_2_0_, roles0_.role_id as role_id2_2_0_, role1_.id as id1_0_1_, role1_.role as role2_0_1_ from user_role roles0_ inner join role role1_ on roles0_.role_id=role1_.id where roles0_.user_id=? 2017-05-24 22:54:36.125 INFO 16899 --- [nio-8082-exec-6] o.s.s.o.p.token.store.JdbcTokenStore : Failed to find access token for token 180c2528-b712-4088-9cce-71e9cc7ccb94 2017-05-24 22:54:36.232 DEBUG 16899 --- [nio-8082-exec-6] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally 2017-05-24 22:54:36.232 DEBUG 16899 --- [nio-8082-exec-6] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed </code></pre> <p>May be I am configuring something wrong. What am I missing here?</p>
0debug
How to set up filter chain in spring boot? : <p>I have come across spring-boot and intend to add a filter chain for incoming request.</p> <p>Here is the Application:</p> <pre><code>package example.hello; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; @SpringBootApplication public class Application { public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(Application.class, args); } } </code></pre> <p>Here is the Controller:</p> <pre><code>package example.hello; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.concurrent.atomic.AtomicLong; @RestController public class GreetingController { private static final String template = "Hello, %s!"; private final AtomicLong counter = new AtomicLong(); @RequestMapping("/greeting") public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) { return new Greeting(counter.incrementAndGet(), String.format(template, name)); } } </code></pre> <p>Here is the Filter Config:</p> <pre><code>package example.hello; import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class WebConfig { @Bean public FilterRegistrationBean greetingFilterRegistrationBean() { FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setName("greeting"); GreetingFilter greetingFilter = new GreetingFilter(); registrationBean.setFilter(greetingFilter); registrationBean.setOrder(1); return registrationBean; } @Bean public FilterRegistrationBean helloFilterRegistrationBean() { FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setName("hello"); HelloFilter helloFilter = new HelloFilter(); registrationBean.setFilter(helloFilter); registrationBean.setOrder(2); return registrationBean; } } </code></pre> <p>Here is the HelloFilter and Greeting Filter:</p> <pre><code>package example.hello; import javax.servlet.*; import java.io.IOException; public class HelloFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("HelloFilter!"); } @Override public void destroy() { } } package example.hello; import javax.servlet.*; import java.io.IOException; public class GreetingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("Greetings from filter!"); } @Override public void destroy() { } } </code></pre> <p>When I start the application and run <code>curl localhost:8080/greeting</code>, Only "Greetings from filter" is received and the <code>HelloFilter</code> is not invoked.</p> <p>Besides there is no response from <code>Greeting Controller</code>. It seems that the <code>GreetingFilter</code> blocks the procedure.</p> <p>So how to set the filter chain in Spring boot. Are there any bugs in the code above?</p>
0debug
Getting UIButton postition - swift : I have a tableview, and a collectionview in a cell of this tableview. And a button in a cell of this collectionview. I need the position of this button( where it is in the screen ) when it is pressed. I couldn't get the correct values. Any help will be appreciated. Thanks in advance.
0debug
To get the length of a java script object : If I have a JavaScript object, say data : Array[1] 0 : Object section : Array[6] tool : Array[6] wellcon : Array[6] welltra Array[6] from this how i get the section length. i try like data.section.length but this is wrong. what is the wrong in my syntax?
0debug
Can't install Azure Functions and Web Jobs extension : <p>I have been trying to install the Azure Functions and Web Jobs extension, however installation fails. Looking through the error log it appears that the piece that isn't working is this:</p> <pre><code>Install Error : System.InvalidOperationException: Installation of Azure Functions and Web Jobs Tools failed. To install this extension please install at least one of the following components: Microsoft Azure WebJobs Tools </code></pre> <p>I think that the problem is that it is looking for itself with the wrong name (Microsoft Azure WebJobs Tools instead of Microsoft Azure Web Jobs Tools). Is there any way to fix this?</p>
0debug