problem
stringlengths
26
131k
labels
class label
2 classes
program error exceptions shouldn't be caught by application program : <p>I'm learning java and I don't understand Why should the program error exception never be caught by the application program?</p>
0debug
how to merge between two arrays by index : i have two arrays .. first array like this : $questions = [ "type" => "form", "controls" => [] ]; and second array is filled by foreach loop like this : $count = 0; foreach($x as $y){ $controls [ "id" => $y.$count, "id2" => $y.$count+1, ] $count++; } i want to merge all values from the second array to `controls` index from first array any help please
0debug
static int ide_drive_initfn(IDEDevice *dev) { return ide_dev_initfn(dev, bdrv_get_type_hint(dev->conf.bs) == BDRV_TYPE_CDROM ? IDE_CD : IDE_HD); }
1threat
This app is not allowed to query for scheme tel : <p>I just opened an old project onbjectif-c created in 2010, the application works correctly except an interface is not working.The error is -canOpenURL: failed for URL: "tel: 0" - error: "This app is not allowed to query for scheme tel".</p> <p>according to my research I find that the error is related to ios 9 but I do not find how to resolve it thank you</p>
0debug
When will Uber Pool be added to the Uber Developers API? : <p>As the question says, when will the Uber Developers API support Uber Pool?</p> <p>Thanks!</p>
0debug
How does this code works in c++? : <p>I participated in Codeforces Round #396 (Div. 2) yesterday. The (A) problem seemed pretty advanced in my opinion when I read it. I tried solving it all the competition time yesterday and some time today. I came up with a 200 lines long(half-working) solution. And then I gave up.</p> <p>I looked what other people wrote there and I saw max 20 lines long code that seems magic to me.</p> <p>The problem asks you to output the length of the longest uncommon subsequence of letters from two strings. You can read the full problem here: <a href="http://codeforces.com/contest/766/problem/A" rel="nofollow noreferrer">http://codeforces.com/contest/766/problem/A</a></p> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; string a,b; int main(){ cin&gt;&gt;a&gt;&gt;b; printf("%d",a==b?-1:max(a.size(),b.size())); return 0; } </code></pre> <p>This is all the code used to solve the problem, and I really want to know how that one line of code</p> <pre><code>printf("%d",a==b?-1:max(a.size(),b.size())); </code></pre> <p>can solve this "advanced" task?</p>
0debug
void helper_do_semihosting(CPUMIPSState *env) { target_ulong *gpr = env->active_tc.gpr; const UHIOp op = gpr[25]; char *p, *p2; switch (op) { case UHI_exit: qemu_log("UHI(%d): exit(%d)\n", op, (int)gpr[4]); exit(gpr[4]); case UHI_open: GET_TARGET_STRING(p, gpr[4]); if (!strcmp("/dev/stdin", p)) { gpr[2] = 0; } else if (!strcmp("/dev/stdout", p)) { gpr[2] = 1; } else if (!strcmp("/dev/stderr", p)) { gpr[2] = 2; } else { gpr[2] = open(p, get_open_flags(gpr[5]), gpr[6]); gpr[3] = errno_mips(errno); } FREE_TARGET_STRING(p, gpr[4]); break; case UHI_close: if (gpr[4] < 3) { gpr[2] = 0; goto uhi_done; } gpr[2] = close(gpr[4]); gpr[3] = errno_mips(errno); break; case UHI_read: gpr[2] = read_from_file(env, gpr[4], gpr[5], gpr[6], 0); gpr[3] = errno_mips(errno); break; case UHI_write: gpr[2] = write_to_file(env, gpr[4], gpr[5], gpr[6], 0); gpr[3] = errno_mips(errno); break; case UHI_lseek: gpr[2] = lseek(gpr[4], gpr[5], gpr[6]); gpr[3] = errno_mips(errno); break; case UHI_unlink: GET_TARGET_STRING(p, gpr[4]); gpr[2] = remove(p); gpr[3] = errno_mips(errno); FREE_TARGET_STRING(p, gpr[4]); break; case UHI_fstat: { struct stat sbuf; memset(&sbuf, 0, sizeof(sbuf)); gpr[2] = fstat(gpr[4], &sbuf); gpr[3] = errno_mips(errno); if (gpr[2]) { goto uhi_done; } gpr[2] = copy_stat_to_target(env, &sbuf, gpr[5]); gpr[3] = errno_mips(errno); } break; case UHI_argc: gpr[2] = semihosting_get_argc(); break; case UHI_argnlen: if (gpr[4] >= semihosting_get_argc()) { gpr[2] = -1; goto uhi_done; } gpr[2] = strlen(semihosting_get_arg(gpr[4])); break; case UHI_argn: if (gpr[4] >= semihosting_get_argc()) { gpr[2] = -1; goto uhi_done; } gpr[2] = copy_argn_to_target(env, gpr[4], gpr[5]); break; case UHI_plog: GET_TARGET_STRING(p, gpr[4]); p2 = strstr(p, "%d"); if (p2) { int char_num = p2 - p; char *buf = g_malloc(char_num + 1); strncpy(buf, p, char_num); buf[char_num] = '\0'; gpr[2] = printf("%s%d%s", buf, (int)gpr[5], p2 + 2); g_free(buf); } else { gpr[2] = printf("%s", p); } FREE_TARGET_STRING(p, gpr[4]); break; case UHI_assert: GET_TARGET_STRING(p, gpr[4]); GET_TARGET_STRING(p2, gpr[5]); printf("assertion '"); printf("\"%s\"", p); printf("': file \"%s\", line %d\n", p2, (int)gpr[6]); FREE_TARGET_STRING(p2, gpr[5]); FREE_TARGET_STRING(p, gpr[4]); abort(); break; case UHI_pread: gpr[2] = read_from_file(env, gpr[4], gpr[5], gpr[6], gpr[7]); gpr[3] = errno_mips(errno); break; case UHI_pwrite: gpr[2] = write_to_file(env, gpr[4], gpr[5], gpr[6], gpr[7]); gpr[3] = errno_mips(errno); break; #ifndef _WIN32 case UHI_link: GET_TARGET_STRING(p, gpr[4]); GET_TARGET_STRING(p2, gpr[5]); gpr[2] = link(p, p2); gpr[3] = errno_mips(errno); FREE_TARGET_STRING(p2, gpr[5]); FREE_TARGET_STRING(p, gpr[4]); break; #endif default: fprintf(stderr, "Unknown UHI operation %d\n", op); abort(); } uhi_done: return; }
1threat
selecting the table and some columns in another table : <p>I've two tables, and I want ist table and selected columns in another table in one query</p>
0debug
Open AndroidStudio project from command line on OSX : <p>I would like to open an AndroidStudio project from the command line on my Mac. Something like:</p> <pre><code>~ $ AndroidStudio --path ~/my_android_project </code></pre> <p>Is this possible in some way?</p>
0debug
C# Post Increment : <p>While I am testing post increment operator in a simple console application, I realized that I did not understand full concept. It seems weird to me:</p> <pre><code>int i = 0; bool b = i++ == i; Console.WriteLine(b); </code></pre> <p>The output has been false. I have expected that it would be true. AFAIK, at line 2, because of the post increment, compiler does comparison and assigned b to true, after i incremented by one. But obviously I am wrong. After that I modify the code like that:</p> <pre><code>int i = 0; bool b = i == i++; Console.WriteLine(b); </code></pre> <p>This time output has been true. What did change from first sample?</p>
0debug
static inline void gen_evmergelo(DisasContext *ctx) { if (unlikely(!ctx->spe_enabled)) { gen_exception(ctx, POWERPC_EXCP_APU); return; } #if defined(TARGET_PPC64) TCGv t0 = tcg_temp_new(); TCGv t1 = tcg_temp_new(); tcg_gen_ext32u_tl(t0, cpu_gpr[rB(ctx->opcode)]); tcg_gen_shli_tl(t1, cpu_gpr[rA(ctx->opcode)], 32); tcg_gen_or_tl(cpu_gpr[rD(ctx->opcode)], t0, t1); tcg_temp_free(t0); tcg_temp_free(t1); #else tcg_gen_mov_i32(cpu_gprh[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)]); tcg_gen_mov_i32(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rB(ctx->opcode)]); #endif }
1threat
C++ Array Index : <p>I'm trying to make a black jack like card program in c++, but one of the restrictions is that the array of the cards has to contain both the suit and value of the card, i.e 2H, 3H, 2C, 3C, and so on. How would I do this?</p>
0debug
static void simple_list(void) { int i; struct { const char *encoded; LiteralQObject decoded; } test_cases[] = { { .encoded = "[43,42]", .decoded = QLIT_QLIST(((LiteralQObject[]){ QLIT_QINT(43), QLIT_QINT(42), { } })), }, { .encoded = "[43]", .decoded = QLIT_QLIST(((LiteralQObject[]){ QLIT_QINT(43), { } })), }, { .encoded = "[]", .decoded = QLIT_QLIST(((LiteralQObject[]){ { } })), }, { .encoded = "[{}]", .decoded = QLIT_QLIST(((LiteralQObject[]){ QLIT_QDICT(((LiteralQDictEntry[]){ {}, })), {}, })), }, { } }; for (i = 0; test_cases[i].encoded; i++) { QObject *obj; QString *str; obj = qobject_from_json(test_cases[i].encoded); g_assert(obj != NULL); g_assert(qobject_type(obj) == QTYPE_QLIST); g_assert(compare_litqobj_to_qobj(&test_cases[i].decoded, obj) == 1); str = qobject_to_json(obj); qobject_decref(obj); obj = qobject_from_json(qstring_get_str(str)); g_assert(obj != NULL); g_assert(qobject_type(obj) == QTYPE_QLIST); g_assert(compare_litqobj_to_qobj(&test_cases[i].decoded, obj) == 1); qobject_decref(obj); QDECREF(str); } }
1threat
Automate Click On Hyperlink Having Event listener : How to automate click on the hyper link `<a>Reply</a>` using Javascript on below case. <span class="PostFull__reply"><a>Reply</a><!-- react-text: 276 --> <!-- /react-text --><!-- react-text: 277 --> <!-- /react-text --></span> [Onclick Events][1] [1]: https://i.stack.imgur.com/DMjYy.png
0debug
How do i create a online forum? : <p>Is there any way that i can create my own forum using php and mysql knowledge?The forum should be able to </p> <ol> <li>show points for answered questions</li> <li>be able to support question and answering</li> <li>also be able to create a small news feed I wanna learn this process from scratch </li> </ol>
0debug
C Programming Problems( Rate charge) : A call is charged 30 cents per minute. The cost for line rental is RM60.00. The tax for the overall bill (including the line rental) is 15%. Calculate the amount, that need to be paid by the user given the number of minutes that the user uses his/her mobile phone. How can I transform this formula into C code? rate = (minute*0.30)+15/100 *60
0debug
Gitlab docker executor - cache image after before_script : <p>In <code>gitlab-ci</code> there's an option in the <a href="http://doc.gitlab.com/ce/ci/yaml/README.html" rel="noreferrer"><code>.gitlab-ci.yml</code></a> file to execute commands before any of the actual script runs, called <code>before_script</code>. <code>.gitlab-ci.yml</code> examples illustrate installing ancillary programs here. However, what I've noticed is that these changes are not cached in Docker when using a docker executor. I had naively assumed that after running these commands, docker would cache the image, so for the next run or test, docker would just load the cached image produced after <code>before_script</code>. This would drastically speed up builds.</p> <p>As an example, my <code>.gitlab-ci.yml</code> looks a little like:</p> <pre><code>image: ubuntu before_script: - apt-get update -qq &amp;&amp; apt-get install -yqq make ... build: script: - cd project &amp;&amp; make </code></pre> <p>A possible solution is to go to the runner machine and create a docker image that can build my software without any other installation and then reference it in the <code>image</code> section of the yaml file. The downside of this is that whenever I want to add a dependency, I need to log in to the runner machine and update the image before builds will succeed. It would be much nicer if I just had to add the dependency to to the end of <code>apt-get install</code> and have docker / gitlab-ci handle the appropriate caching.</p> <p>There is also a <code>cache</code> command in <code>.gitlab-ci.yml</code>, which I tried setting to <code>untracked: true</code>, which I thought would cache everything that wasn't a byproduct of my project, but it didn't seem to have any effect.</p> <p>Is there any way to get the behavior I desire?</p>
0debug
Cite various python packages in paper : <p>We have a working tool built off of various packages in python. I am not sure how to cite these packages for a paper I am working on. How do I properly cite python packages? One of them have a way they ask us to cite them via a book. Most say nothing on citations that I can find. Is there a standard?</p>
0debug
Token null Sign-in Google Account : <p>I am following the example of google to get the token but without success. Always fails to acquire the token. This is latest way Google displays on your page developers I believe the error is not in my code</p> <pre><code> private String CLIENTE_ID = "...apps.googleusercontent.com"; GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(CLIENTE_ID) .requestEmail() .build(); // Build GoogleAPIClient with the Google Sign-In API and the above options. mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); imgBGoogle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, 9002); } }); @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == 9002) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); handleSignInResult(result, data); } if (requestCode == 9002) { // [START get_id_token] GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); Log.d(TAG, "onActivityResult:GET_TOKEN:success:" + result.getStatus().isSuccess()); if (result.isSuccess()) { GoogleSignInAccount acct = result.getSignInAccount(); String idToken = acct.getIdToken(); // Show signed-in UI. Log.d(TAG, "idToken:" + idToken); Log.d(TAG, "\n "); // TODO(user): send token to server and validate server-side } else { // Show signed-out UI. Log.d(TAG, "idToken: fail"); } // [END get_id_token] } } private void handleSignInResult(GoogleSignInResult result, Intent data) { getToken1(data); getToken2(result); String BOOKS_API_SCOPE = "https://www.googleapis.com/auth/books"; String GPLUS_SCOPE = "https://www.googleapis.com/auth/plus.login"; String mScopes = "oauth2:" + BOOKS_API_SCOPE + " " + GPLUS_SCOPE; } void getToken1(Intent data){ GoogleSignInResult a = Auth.GoogleSignInApi.getSignInResultFromIntent(data); if (a.isSuccess()) { Log.d(TAG, "TOKEN 1: " + a.getSignInAccount().getIdToken()); Log.d(TAG, "DISPLAY NAME 1: " +a.getSignInAccount().getDisplayName()); Log.d(TAG, "ID 1: " + a.getSignInAccount().getId()+"\n "); }else{ Log.d(TAG, "ID 1: falhou"+"\n "); } } void getToken2(GoogleSignInResult result){ if (result.isSuccess()) { GoogleSignInAccount acct = result.getSignInAccount(); Log.d(TAG, "TOKEN 2: " + acct.getIdToken()); Log.d(TAG, "DISPLAY NAME 2: " + acct.getDisplayName()); Log.d(TAG, "ID 2: " + acct.getId()+"\n "); }else{ Log.d(TAG, "ID 2: falhou"+"\n "); } } </code></pre> <p><strong>how can I get the token? can anyone help me?</strong></p> <p><a href="https://i.stack.imgur.com/Uj0LO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Uj0LO.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/6keg0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6keg0.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/csq4D.png" rel="noreferrer"><img src="https://i.stack.imgur.com/csq4D.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/p2zSX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/p2zSX.png" alt="enter image description here"></a></p>
0debug
static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *in) { HQDN3DContext *hqdn3d = inlink->dst->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFilterBufferRef *out; int direct, c; if (in->perms & AV_PERM_WRITE) { direct = 1; out = in; } else { out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h); if (!out) { avfilter_unref_bufferp(&in); return AVERROR(ENOMEM); } avfilter_copy_buffer_ref_props(out, in); out->video->w = outlink->w; out->video->h = outlink->h; } for (c = 0; c < 3; c++) { denoise(hqdn3d, in->data[c], out->data[c], hqdn3d->line, &hqdn3d->frame_prev[c], in->video->w >> (!!c * hqdn3d->hsub), in->video->h >> (!!c * hqdn3d->vsub), in->linesize[c], out->linesize[c], hqdn3d->coefs[c?2:0], hqdn3d->coefs[c?3:1]); } if (!direct) avfilter_unref_bufferp(&in); return ff_filter_frame(outlink, out); }
1threat
Angular 5: remove route history : <p>In my app I have a category page that has links to a various product list pages. If it turns out that when you get to a product list page there is only one product then it automatically navigates to that product detail page. What I want is to remove the product list page route in the history so that when the user is on the product detail page and hits the back button they will go to the category page and not the product list page because that will just redirect them back to the detail page.</p>
0debug
Still getting CORS error in chrome after adding headers in node express server : I'm trying to do a simple GET request to an XML file, and I'm stuck on this CORS error. I've tried multiple solutions including adding the headers manually in my server.js file, and using the cors npm package. With both of those, If i hit the endpoint in postman, i can see the headers attached to the request, as well as the response. However in google chrome the headers are not being attached to the request. here's the code in my index.html file <body> <h1>test</h1> <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script> <!-- <script src="./server.js"></script> --> <script> var xhr = new XMLHttpRequest(); xhr.open('GET',xmlRemoteUrl, true); xhr.withCredentials = true; xhr.send(null); </script> </body> note that i've hidden the url, but the variable xmlRemoteUrl contains the link to the xml page i'm trying to get information from. here's the code in my server.js file var express = require("express"); var bodyParser = require("body-parser"); var path = require("path"); //var cors = require('cors') // Sets up the Express App var app = express(); var PORT = 3000; //app.use(cors()) // Sets up the Express app to handle data parsing app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // Routes app.get("/test", function(req, res) { res.set({ 'Access-Control-Allow-Origin': ['*'], 'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE', 'Access-Control-Allow-Headers': 'Content-Type' }); res.sendFile(path.join(__dirname, "./index.html")); console.log('hit me') console.log(res); }); app.get("/", function(req, res) { res.send('fuckkkkkkkkkkkkk') }); // Starts the server to begin listening app.listen(PORT, function() { console.log("App listening on PORT " + PORT); });
0debug
def sum_even_odd(list1): first_even = next((el for el in list1 if el%2==0),-1) first_odd = next((el for el in list1 if el%2!=0),-1) return (first_even+first_odd)
0debug
MS SQL Need help returning information where value from Table A falls between a date range in table B : Table A Transaction details TTime (datetime), TableAValues, TableAValues, <etc>... Table B Related table ID, DateTimeStart (datetime), DateTimeEnd (datetime), TableBValues, TableBValues, <etc>... I need a way to return a row of information which includes All TableAValues as well as all TableBValues where TTime Table A falls between DateTimeStart and DateTimeEnd of table B.
0debug
How do I count by frequency of a letter in index in Pyhton : lets say youre giving 5 inputs like so: hello hullo zeros It is then stored into a list like so ['hello','hullo','zeros'] I would like it to return a dictionary that counts the frequency of the letter in their index. It should return something like this {h:2,z:1} {e:2,u:1} {l:2,r:1} {l:2,o:1} {o:2,s:1}
0debug
MainActivity.kt doesn't see button's id. WTF? : [one][1] [two][2] [1]: https://i.stack.imgur.com/F8SdN.png [2]: https://i.stack.imgur.com/2uf7O.png I haven't idea what the error might be. Reloading, rebuild didn't help
0debug
How to check if a dict value contains a word/string? : <p>I have a simple condition where i need to check if a dict value contains say <code>[Complted]</code> in a particular key. </p> <p><strong>example</strong> :</p> <pre><code>'Events': [ { 'Code': 'instance-reboot'|'system-reboot'|'system-maintenance'|'instance-retirement'|'instance-stop', 'Description': 'string', 'NotBefore': datetime(2015, 1, 1), 'NotAfter': datetime(2015, 1, 1) }, ], </code></pre> <p>I need to check if the <code>Description</code> key contains <code>[Complted]</code> in it at starting. i.e </p> <blockquote> <p>'Descripton': '[Completed] The instance is running on degraded hardware'</p> </blockquote> <p>How can i do so ? I am looking for something like </p> <pre><code>if inst ['Events'][0]['Code'] == "instance-stop": if inst ['Events'][0]['Description'] consists '[Completed]": print "Nothing to do here" </code></pre>
0debug
static int decode_unit(SCPRContext *s, PixelModel *pixel, unsigned step, unsigned *rval) { GetByteContext *gb = &s->gb; RangeCoder *rc = &s->rc; unsigned totfr = pixel->total_freq; unsigned value, x = 0, cumfr = 0, cnt_x = 0; int i, j, ret, c, cnt_c; if ((ret = s->get_freq(rc, totfr, &value)) < 0) return ret; while (x < 16) { cnt_x = pixel->lookup[x]; if (value >= cumfr + cnt_x) cumfr += cnt_x; else break; x++; c = x * 16; cnt_c = 0; while (c < 256) { cnt_c = pixel->freq[c]; if (value >= cumfr + cnt_c) cumfr += cnt_c; else break; c++; if ((ret = s->decode(gb, rc, cumfr, cnt_c, totfr)) < 0) return ret; pixel->freq[c] = cnt_c + step; pixel->lookup[x] = cnt_x + step; totfr += step; if (totfr > BOT) { totfr = 0; for (i = 0; i < 256; i++) { unsigned nc = (pixel->freq[i] >> 1) + 1; pixel->freq[i] = nc; totfr += nc; for (i = 0; i < 16; i++) { unsigned sum = 0; unsigned i16_17 = i << 4; for (j = 0; j < 16; j++) sum += pixel->freq[i16_17 + j]; pixel->lookup[i] = sum; pixel->total_freq = totfr; *rval = c & s->cbits; return 0;
1threat
Error 503 doing GET operation on survey : <p>I am using the API to GET and FETCH data from my 150 or so Google surveys. For some surveys I find the FETCH works OK but the GET is rejected with error 503. For instance:</p> <p><code>HttpError 503 when requesting https://www.googleapis.com/consumersurveys/v2/surveys/6mndemyqw5b5k?alt=json returned "Survey is configured in a way not supported by the API, i.e. contains unsupported question types or options Request Id: 5750b15c00ff025d5da8b9f4b00001737e3430322d747269616c320001707573682d30362d30322d7231330001010a</code></p> <p>The surveys are nearly all one single response questions and were created with the web interface. The common factor I notice is that the failing surveys I have looked at all contain an answer with a non-Latin character, e.g. <code>Siân Berry (Green)</code>.</p> <p>Whatever the reason, this is quite a problem because the GET operation is the only one that returns a full list of answers in the originally specified order. Also, the question text itself is only otherwise available by scraping the Overview sheet of the exported XLS file. I say scraping because so far as I can tell the spreadsheet format is neither documented nor stable - for instance the response data used to be in worksheet "1" but more recently seem to be in worksheet "Complete responses".</p>
0debug
db.execute('SELECT * FROM employees WHERE id = ' + user_input)
1threat
How are private variables accessed in operator overloading? : <p>How can private variables be accessed in operator overloading (obj.real,obj.imag,res.real,res.imag) in this code. Can someone explain</p> <pre><code>#include&lt;iostream&gt; using namespace std; class Complex { private: int real, imag; public: Complex(int r = 0, int i =0) {real = r; imag = i;} // This is automatically called when '+' is used with // between two Complex objects Complex operator + (Complex const &amp;obj) { Complex res; res.real = real + obj.real; res.imag = imag + obj.imag; return res; } void print() { cout &lt;&lt; real &lt;&lt; " + i" &lt;&lt; imag &lt;&lt; endl; } }; int main() { Complex c1(10, 5), c2(2, 4); Complex c3 = c1 + c2; // An example call to "operator+" c3.print(); } </code></pre>
0debug
void virtio_scsi_handle_ctrl_req(VirtIOSCSI *s, VirtIOSCSIReq *req) { VirtIODevice *vdev = (VirtIODevice *)s; uint32_t type; int r = 0; if (iov_to_buf(req->elem.out_sg, req->elem.out_num, 0, &type, sizeof(type)) < sizeof(type)) { virtio_scsi_bad_req(); return; } virtio_tswap32s(vdev, &type); if (type == VIRTIO_SCSI_T_TMF) { if (virtio_scsi_parse_req(req, sizeof(VirtIOSCSICtrlTMFReq), sizeof(VirtIOSCSICtrlTMFResp)) < 0) { virtio_scsi_bad_req(); } else { r = virtio_scsi_do_tmf(s, req); } } else if (type == VIRTIO_SCSI_T_AN_QUERY || type == VIRTIO_SCSI_T_AN_SUBSCRIBE) { if (virtio_scsi_parse_req(req, sizeof(VirtIOSCSICtrlANReq), sizeof(VirtIOSCSICtrlANResp)) < 0) { virtio_scsi_bad_req(); } else { req->resp.an.event_actual = 0; req->resp.an.response = VIRTIO_SCSI_S_OK; } } if (r == 0) { virtio_scsi_complete_req(req); } else { assert(r == -EINPROGRESS); } }
1threat
static int find_snapshot_by_id(BlockDriverState *bs, const char *id_str) { BDRVQcowState *s = bs->opaque; int i; for(i = 0; i < s->nb_snapshots; i++) { if (!strcmp(s->snapshots[i].id_str, id_str)) return i; } return -1; }
1threat
static int local_setuid(FsContext *ctx, uid_t uid) { struct passwd *pw; gid_t groups[33]; int ngroups; static uid_t cur_uid = -1; if (cur_uid == uid) { return 0; } if (setreuid(0, 0)) { return -1; } pw = getpwuid(uid); if (pw == NULL) { return -1; } ngroups = 33; if (getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups) == -1) { return -1; } if (setgroups(ngroups, groups)) { return -1; } if (setregid(-1, pw->pw_gid)) { return -1; } if (setreuid(-1, uid)) { return -1; } cur_uid = uid; return 0; }
1threat
How does numpy.reshape() with order = 'F' work? : <p>I thought I understood the reshape function in Numpy until I was messing around with it and came across this example:</p> <pre><code>a = np.arange(16).reshape((4,4)) </code></pre> <p>which returns:</p> <pre><code>array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) </code></pre> <p>This makes sense to me, but then when I do:</p> <pre><code>a.reshape((2,8), order = 'F') </code></pre> <p>it returns:</p> <pre><code>array([[0, 8, 1, 9, 2, 10, 3, 11], [4, 12, 5, 13, 6, 14, 7, 15]]) </code></pre> <p>I would expect it to return:</p> <pre><code>array([[0, 4, 8, 12, 1, 5, 9, 13], [2, 6, 10, 14, 3, 7, 11, 15]]) </code></pre> <p>Can someone please explain what is happening here? </p>
0debug
Coverting C script to PHP : <p>I want to study the following script in PHP, it's actually in C, how can I convert the exactly same code to PHP?</p> <pre><code>int solution(int A[], int N) { int equi(int arr[], int n) { if (n==0) return -1; long long sum = 0; int i; for(i=0;i&lt;n;i++) sum+=(long long) arr[i]; long long sum_left = 0; for(i=0;i&lt;n;i++) { long long sum_right = sum - sum_left - (long long) arr[i]; if (sum_left == sum_right) return i; sum_left += (long long) arr[i]; } return -1; } </code></pre> <p>}</p>
0debug
void ff_snow_horizontal_compose97i_sse2(DWTELEM *b, int width){ const int w2= (width+1)>>1; DWTELEM temp_buf[(width>>1) + 4]; DWTELEM * const temp = temp_buf + 4 - (((int)temp_buf & 0xF) >> 2); const int w_l= (width>>1); const int w_r= w2 - 1; int i; { DWTELEM * const ref = b + w2 - 1; DWTELEM b_0 = b[0]; i = 0; asm volatile( "pcmpeqd %%xmm7, %%xmm7 \n\t" "pslld $31, %%xmm7 \n\t" "psrld $29, %%xmm7 \n\t" ::); for(; i<w_l-7; i+=8){ asm volatile( "movdqu (%1), %%xmm1 \n\t" "movdqu 16(%1), %%xmm5 \n\t" "movdqu 4(%1), %%xmm2 \n\t" "movdqu 20(%1), %%xmm6 \n\t" "paddd %%xmm1, %%xmm2 \n\t" "paddd %%xmm5, %%xmm6 \n\t" "movdqa %%xmm2, %%xmm0 \n\t" "movdqa %%xmm6, %%xmm4 \n\t" "paddd %%xmm2, %%xmm2 \n\t" "paddd %%xmm6, %%xmm6 \n\t" "paddd %%xmm0, %%xmm2 \n\t" "paddd %%xmm4, %%xmm6 \n\t" "paddd %%xmm7, %%xmm2 \n\t" "paddd %%xmm7, %%xmm6 \n\t" "psrad $3, %%xmm2 \n\t" "psrad $3, %%xmm6 \n\t" "movdqa (%0), %%xmm0 \n\t" "movdqa 16(%0), %%xmm4 \n\t" "psubd %%xmm2, %%xmm0 \n\t" "psubd %%xmm6, %%xmm4 \n\t" "movdqa %%xmm0, (%0) \n\t" "movdqa %%xmm4, 16(%0) \n\t" :: "r"(&b[i]), "r"(&ref[i]) : "memory" ); } snow_horizontal_compose_lift_lead_out(i, b, b, ref, width, w_l, 0, W_DM, W_DO, W_DS); b[0] = b_0 - ((W_DM * 2 * ref[1]+W_DO)>>W_DS); } { DWTELEM * const dst = b+w2; i = 0; for(; (((long)&dst[i]) & 0xF) && i<w_r; i++){ dst[i] = dst[i] - (b[i] + b[i + 1]); } for(; i<w_r-7; i+=8){ asm volatile( "movdqu (%1), %%xmm1 \n\t" "movdqu 16(%1), %%xmm5 \n\t" "movdqu 4(%1), %%xmm2 \n\t" "movdqu 20(%1), %%xmm6 \n\t" "paddd %%xmm1, %%xmm2 \n\t" "paddd %%xmm5, %%xmm6 \n\t" "movdqa (%0), %%xmm0 \n\t" "movdqa 16(%0), %%xmm4 \n\t" "psubd %%xmm2, %%xmm0 \n\t" "psubd %%xmm6, %%xmm4 \n\t" "movdqa %%xmm0, (%0) \n\t" "movdqa %%xmm4, 16(%0) \n\t" :: "r"(&dst[i]), "r"(&b[i]) : "memory" ); } snow_horizontal_compose_lift_lead_out(i, dst, dst, b, width, w_r, 1, W_CM, W_CO, W_CS); } { DWTELEM * const ref = b+w2 - 1; DWTELEM b_0 = b[0]; i = 0; asm volatile( "pslld $1, %%xmm7 \n\t" ::); for(; i<w_l-7; i+=8){ asm volatile( "movdqu (%1), %%xmm1 \n\t" "movdqu 16(%1), %%xmm5 \n\t" "movdqu 4(%1), %%xmm0 \n\t" "movdqu 20(%1), %%xmm4 \n\t" "paddd %%xmm1, %%xmm0 \n\t" "paddd %%xmm5, %%xmm4 \n\t" "paddd %%xmm7, %%xmm0 \n\t" "paddd %%xmm7, %%xmm4 \n\t" "movdqa (%0), %%xmm1 \n\t" "movdqa 16(%0), %%xmm5 \n\t" "psrad $2, %%xmm0 \n\t" "psrad $2, %%xmm4 \n\t" "paddd %%xmm1, %%xmm0 \n\t" "paddd %%xmm5, %%xmm4 \n\t" "psrad $2, %%xmm0 \n\t" "psrad $2, %%xmm4 \n\t" "paddd %%xmm1, %%xmm0 \n\t" "paddd %%xmm5, %%xmm4 \n\t" "movdqa %%xmm0, (%0) \n\t" "movdqa %%xmm4, 16(%0) \n\t" :: "r"(&b[i]), "r"(&ref[i]) : "memory" ); } snow_horizontal_compose_liftS_lead_out(i, b, b, ref, width, w_l); b[0] = b_0 + ((2 * ref[1] + W_BO-1 + 4 * b_0) >> W_BS); } { DWTELEM * const src = b+w2; i = 0; for(; (((long)&temp[i]) & 0xF) && i<w_r; i++){ temp[i] = src[i] - ((-W_AM*(b[i] + b[i+1]))>>W_AS); } for(; i<w_r-7; i+=8){ asm volatile( "movdqu 4(%1), %%xmm2 \n\t" "movdqu 20(%1), %%xmm6 \n\t" "paddd (%1), %%xmm2 \n\t" "paddd 16(%1), %%xmm6 \n\t" "movdqu (%0), %%xmm0 \n\t" "movdqu 16(%0), %%xmm4 \n\t" "paddd %%xmm2, %%xmm0 \n\t" "paddd %%xmm6, %%xmm4 \n\t" "psrad $1, %%xmm2 \n\t" "psrad $1, %%xmm6 \n\t" "paddd %%xmm0, %%xmm2 \n\t" "paddd %%xmm4, %%xmm6 \n\t" "movdqa %%xmm2, (%2) \n\t" "movdqa %%xmm6, 16(%2) \n\t" :: "r"(&src[i]), "r"(&b[i]), "r"(&temp[i]) : "memory" ); } snow_horizontal_compose_lift_lead_out(i, temp, src, b, width, w_r, 1, -W_AM, W_AO+1, W_AS); } { snow_interleave_line_header(&i, width, b, temp); for (; (i & 0x1E) != 0x1E; i-=2){ b[i+1] = temp[i>>1]; b[i] = b[i>>1]; } for (i-=30; i>=0; i-=32){ asm volatile( "movdqa (%1), %%xmm0 \n\t" "movdqa 16(%1), %%xmm2 \n\t" "movdqa 32(%1), %%xmm4 \n\t" "movdqa 48(%1), %%xmm6 \n\t" "movdqa (%1), %%xmm1 \n\t" "movdqa 16(%1), %%xmm3 \n\t" "movdqa 32(%1), %%xmm5 \n\t" "movdqa 48(%1), %%xmm7 \n\t" "punpckldq (%2), %%xmm0 \n\t" "punpckldq 16(%2), %%xmm2 \n\t" "punpckldq 32(%2), %%xmm4 \n\t" "punpckldq 48(%2), %%xmm6 \n\t" "movdqa %%xmm0, (%0) \n\t" "movdqa %%xmm2, 32(%0) \n\t" "movdqa %%xmm4, 64(%0) \n\t" "movdqa %%xmm6, 96(%0) \n\t" "punpckhdq (%2), %%xmm1 \n\t" "punpckhdq 16(%2), %%xmm3 \n\t" "punpckhdq 32(%2), %%xmm5 \n\t" "punpckhdq 48(%2), %%xmm7 \n\t" "movdqa %%xmm1, 16(%0) \n\t" "movdqa %%xmm3, 48(%0) \n\t" "movdqa %%xmm5, 80(%0) \n\t" "movdqa %%xmm7, 112(%0) \n\t" :: "r"(&(b)[i]), "r"(&(b)[i>>1]), "r"(&(temp)[i>>1]) : "memory" ); } } }
1threat
void tcg_cpu_address_space_init(CPUState *cpu, AddressSpace *as) { assert(cpu->as == as); if (cpu->cpu_ases) { return; } cpu->cpu_ases = g_new0(CPUAddressSpace, 1); cpu->cpu_ases[0].cpu = cpu; cpu->cpu_ases[0].as = as; cpu->cpu_ases[0].tcg_as_listener.commit = tcg_commit; memory_listener_register(&cpu->cpu_ases[0].tcg_as_listener, as); }
1threat
static av_cold int vaapi_encode_mjpeg_init(AVCodecContext *avctx) { return ff_vaapi_encode_init(avctx, &vaapi_encode_type_mjpeg); }
1threat
Random forest for important predictor variables : <p>In my data set I've 19 predictor variables which include both categorical and continuous variables. I want to fit a random forest model using only <strong>important predictor variables</strong> (not all the predictor variables) and also I've to repeat the process 100 times.How can I do this by using R? Any suggestions please?</p>
0debug
static int qemu_rdma_reg_whole_ram_blocks(RDMAContext *rdma) { int i; RDMALocalBlocks *local = &rdma->local_ram_blocks; for (i = 0; i < local->nb_blocks; i++) { local->block[i].mr = ibv_reg_mr(rdma->pd, local->block[i].local_host_addr, local->block[i].length, IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE ); if (!local->block[i].mr) { perror("Failed to register local dest ram block!\n"); break; } rdma->total_registrations++; } if (i >= local->nb_blocks) { return 0; } for (i--; i >= 0; i--) { ibv_dereg_mr(local->block[i].mr); rdma->total_registrations--; } return -1; }
1threat
Move constant object without compiler warning : <p>I tested the following code using Visual Studio 2017 version 15.3.1. </p> <p><code>v.push_back(std::move(str1))</code> works as expected. It moves the contents of <code>str1</code> into the vector.</p> <p><code>str2</code> is a constant string. Since a constant string cannot be modified after it is created, I was expecting that the <code>v.push_back(std::move(str2))</code> statement would result in a compiler warning. However, to my surprise there was no compiler warning. After stepped into it, I found that the overload of <code>push_back(const T&amp;)</code> was actually called. The <code>std::move</code> in <code>std::move(str2)</code> seems has no effect.</p> <p>My question: Should a compiler warning be given for trying to move a constant object?</p> <pre><code>// Compiled with Visual Studio 2017 version 15.3.1 std::vector&lt;std::string&gt; v; std::string str1 = "string 1"; v.push_back(std::move(str1)); // Call push_back(T&amp;&amp;). The contents of str1 is moved into the vector. // This is less expensive, but str1 is now valid but unspecified. const std::string str2 = "string 2"; v.push_back(std::move(str2)); // Call push_back(const T&amp;). A copy of str2 is added into the vector. // str2 itself is unchanged. </code></pre>
0debug
ImageView/ImageButton overlay on camera preview not dislayed : A very standard overlay [tutorial][1] in this link was followed for developing the camera preview with overlay. However, when I change the `<Button/>` to `<ImageView/>` or `<ImageButton/>` the image doesn't get displayed. All I am getting is camera preview while using `<ImageView/>` and on using `<ImageButton/>` the images are not shown however little white lines at places where there should be images are displayed. The images are present in `mipmap-xxhdpi`. These buttons will be used to start another activity or take picture on click by user. I've looked into many questions on StackOverFlow but solutions don't work for me. Answer [here][2] doesn't work for me. **Other Relevant Details** The minSdkVersion is 16 and compileSdkVersion is 25. When I run the app in emulator on API-21 or above all I am getting is a black screen. ***Q1:*** How to overlay `<ImageView/>` or `<ImageButton/>` on camera preview? ***Q2:*** Would getting black screen have something to do with Camera API (old) being deprecated and I have to build separate classes to take into account different API? Like the code below if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { //do something } else { //do something else } [2]: https://stackoverflow.com/questions/13527943/overlay-a-static-drawable-image-over-camera-preview [1]: http://www.edumobile.org/android/overlay-on-camera-preview/
0debug
static int nut_write_packet(AVFormatContext *s, AVPacket *pkt){ NUTContext *nut = s->priv_data; StreamContext *nus= &nut->stream[pkt->stream_index]; AVIOContext *bc = s->pb, *dyn_bc; FrameCode *fc; int64_t coded_pts; int best_length, frame_code, flags, needed_flags, i, header_idx, best_header_idx; int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY); int store_sp=0; int ret; if(pkt->pts < 0) return -1; if(1LL<<(20+3*nut->header_count) <= avio_tell(bc)) write_headers(s, bc); if(key_frame && !(nus->last_flags & FLAG_KEY)) store_sp= 1; if(pkt->size + 30 + avio_tell(bc) >= nut->last_syncpoint_pos + nut->max_distance) store_sp= 1; if(store_sp){ Syncpoint *sp, dummy= {.pos= INT64_MAX}; ff_nut_reset_ts(nut, *nus->time_base, pkt->dts); for(i=0; i<s->nb_streams; i++){ AVStream *st= s->streams[i]; int64_t dts_tb = av_rescale_rnd(pkt->dts, nus->time_base->num * (int64_t)nut->stream[i].time_base->den, nus->time_base->den * (int64_t)nut->stream[i].time_base->num, AV_ROUND_DOWN); int index= av_index_search_timestamp(st, dts_tb, AVSEEK_FLAG_BACKWARD); if(index>=0) dummy.pos= FFMIN(dummy.pos, st->index_entries[index].pos); } if(dummy.pos == INT64_MAX) dummy.pos= 0; sp= av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp, NULL); nut->last_syncpoint_pos= avio_tell(bc); ret = avio_open_dyn_buf(&dyn_bc); if(ret < 0) return ret; put_tt(nut, nus->time_base, dyn_bc, pkt->dts); ff_put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos)>>4 : 0); put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE); ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0, pkt->dts); } av_assert0(nus->last_pts != AV_NOPTS_VALUE); coded_pts = pkt->pts & ((1<<nus->msb_pts_shift)-1); if(ff_lsb2full(nus, coded_pts) != pkt->pts) coded_pts= pkt->pts + (1<<nus->msb_pts_shift); best_header_idx= find_best_header_idx(nut, pkt); best_length=INT_MAX; frame_code= -1; for(i=0; i<256; i++){ int length= 0; FrameCode *fc= &nut->frame_code[i]; int flags= fc->flags; if(flags & FLAG_INVALID) continue; needed_flags= get_needed_flags(nut, nus, fc, pkt); if(flags & FLAG_CODED){ length++; flags = needed_flags; } if((flags & needed_flags) != needed_flags) continue; if((flags ^ needed_flags) & FLAG_KEY) continue; if(flags & FLAG_STREAM_ID) length+= ff_get_v_length(pkt->stream_index); if(pkt->size % fc->size_mul != fc->size_lsb) continue; if(flags & FLAG_SIZE_MSB) length += ff_get_v_length(pkt->size / fc->size_mul); if(flags & FLAG_CHECKSUM) length+=4; if(flags & FLAG_CODED_PTS) length += ff_get_v_length(coded_pts); if( (flags & FLAG_CODED) && nut->header_len[best_header_idx] > nut->header_len[fc->header_idx]+1){ flags |= FLAG_HEADER_IDX; } if(flags & FLAG_HEADER_IDX){ length += 1 - nut->header_len[best_header_idx]; }else{ length -= nut->header_len[fc->header_idx]; } length*=4; length+= !(flags & FLAG_CODED_PTS); length+= !(flags & FLAG_CHECKSUM); if(length < best_length){ best_length= length; frame_code=i; } } av_assert0(frame_code != -1); fc= &nut->frame_code[frame_code]; flags= fc->flags; needed_flags= get_needed_flags(nut, nus, fc, pkt); header_idx= fc->header_idx; ffio_init_checksum(bc, ff_crc04C11DB7_update, 0); avio_w8(bc, frame_code); if(flags & FLAG_CODED){ ff_put_v(bc, (flags^needed_flags) & ~(FLAG_CODED)); flags = needed_flags; } if(flags & FLAG_STREAM_ID) ff_put_v(bc, pkt->stream_index); if(flags & FLAG_CODED_PTS) ff_put_v(bc, coded_pts); if(flags & FLAG_SIZE_MSB) ff_put_v(bc, pkt->size / fc->size_mul); if(flags & FLAG_HEADER_IDX) ff_put_v(bc, header_idx= best_header_idx); if(flags & FLAG_CHECKSUM) avio_wl32(bc, ffio_get_checksum(bc)); else ffio_get_checksum(bc); avio_write(bc, pkt->data + nut->header_len[header_idx], pkt->size - nut->header_len[header_idx]); nus->last_flags= flags; nus->last_pts= pkt->pts; if(flags & FLAG_KEY) av_add_index_entry( s->streams[pkt->stream_index], nut->last_syncpoint_pos, pkt->pts, 0, 0, AVINDEX_KEYFRAME); return 0; }
1threat
How i launch particular URL at same time daily in Chrome : I want to launch a particular URL in chrome every day at the same time. How to achieve this using command line.
0debug
How to find all id's to an array from array of objects - Javascript : <p>How to find all id's to an array from array of objects. Here through normal for loop I can able to get but using ECMA new features by findAll etc..how to get?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let items = [ {id: 28, name: "Action", isSelected: true}, {id: 10770, name: "TV Movie", isSelected: false}, {id: 53, name: "Thriller", isSelected: true}, {id: 10752, name: "War", isSelected: false}, {id: 37, name: "Western", isSelected: true} ]</code></pre> </div> </div> </p> <p>Here I want to find all id's based on isSelected is true.</p>
0debug
compar hashmap<string,arraylist<string>> and arraylist<string> java : I have a hashmap that contains a list of words map<string,arraylist<string>> And a list that also contains words I want to compare this list with the hashmap Which gives us another hashmap that contains binary values 1 if word exist 0 if not. [The problem is it adds the first list to the 2nd .... ][1] [1]: https://i.stack.imgur.com/FoFNT.png
0debug
In Ansible, how to combine variables from separate files into one array? : <p>In Ansible, in a role, I have vars files like this:</p> <pre><code>vars/ app1.yml app2.yml </code></pre> <p>Each file contains vars specific to an app/website like this:</p> <pre><code>name: app1 git_repo: https://github.com/philgyford/app1.git # ... </code></pre> <p>Ideally, without the task knowing in advance which apps have variable files, I'd like to end up with an array called <code>apps</code> like this:</p> <pre><code>apps: - name: app1 git_repo: https://github.com/philgyford/app1.git # ... - name: app2 git_repo: https://github.com/philgyford/app2.git # ... </code></pre> <p>ie, that combines the variables from the files into one.</p> <p>I know I can load all the variable files like this:</p> <pre><code>- name: Load var files with_fileglob: - ../vars/*.yml include_vars: '{{ item }}' </code></pre> <p>But given each file has identical variable names, it will overwrite each previous set of variables. I can't see a way to load the variables and put them into an <code>apps</code> array.</p> <p>I'm open to rearranging things slightly if it's the only way to make something like this possible.</p>
0debug
AWS Cognito - User stuck in CONFIRMED and email_verified = false : <p>How do I go about email verifying a user who is CONFIRMED yet email_verified is false?</p> <p>The scenario is roughly an agent signs up user on their behalf, and I confirm the user through the admin call adminConfirmSignUp. At that point, the user cannot change their password because of the email_verified flag being false.</p> <p>I can't call resendConfirmationCode because the user is already confirmed.</p> <p>I can't call forgotPassword because the email_verified flag is false.</p> <p>The best I can think of is deleting the user account and calling signUp (prompting them to re-enter their password or a new password), hence recreating their account.</p>
0debug
How to work with DTO in Spring Data REST projects? : <p>Spring Data REST automates exposing only domain object. But most often we have to deal with Data Transfer Objects. So how to do this in SDR way?</p>
0debug
Replace all letters in a string with an underscore and space : <p>As the title says, I am attempting to replace every letter in a string with an underscore followed by a space. For example: "hello" would be replaced with "_ _ _ _ _". I can replace letters with just a space or just an underscore, but I am having trouble with replacing both. Any help is appreciated!</p>
0debug
How to print every third element od Array? : I have a problem. I need to take 2 inputs from user (size of array) and then second input (elements of that same array). After that i need to print every third element of array. I done it! But with this i can print elements from last element in array and i want to print from first. Example size of array is 9. Elements: 1,2,3,4,5,6,7,8,9. I need to print 3,6,9 but i am printing 9,6,3 :D Help, Here is my code so far. class Demo { public static void main(String[] args) { int x; int[] y; Scanner tastatura = new Scanner(System.in); System.out.println("Enter size of array:"); x = tastatura.nextInt(); y = new int[x]; System.out.println("Enter the elements of array:"); for (int i = 0; i < x; i++) { y[i] = tastatura.nextInt(); } System.out.println("\n Every third element of array is : "); for (int i = y.length - 1; i >= 0; i = i - 3) { System.out.println(y[i]); } tastatura.close(); }
0debug
Access AWS from bash by IP address : <p>Do anyone possibly know how to access AWS having only server IP (239.255.255.255 for example) and .pem file from bash console in Ubuntu?</p>
0debug
Unable to access application container from iPad running on iOS 10 beta : <p>I am not able to download app container using xcode for my application on iOS 10 beta 4. I am using later xcode (beta 4). When I connect my device and go to <code>Device</code> in xcode, I am able to see my app listed but when I click on download container I get below error:</p> <p><a href="https://i.stack.imgur.com/3u8Dt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3u8Dt.png" alt="enter image description here"></a></p> <p>Is there anything to do with my app setting or device setting. How can I get my app data for iOS10 beta 4.</p>
0debug
Disable Marketplace from Eclipse : <p>I'm running Eclipse Neon on a virtual machine without Internet connection.</p> <p>I frequently get the annoying prompt "Search Marketplace for compatible editor has encountered a problem", how can I disable the lookup for editors or just entirely the Marketplace?</p>
0debug
What's wrong with this code? : This is the end of my script. I'm getting the error : print "[%s]\t %s " % (item.sharing['access'], item.title) ^ SyntaxError: invalid syntax `#List titles and sharing status for items in users'home folder for item in currentUser.items: print "[%s]\t %s " % (item.sharing['access'], item.title)` If you tell me how to correct this mistake as well as provide resources to avoid mistakes such as this one that would be greatly appreciated.
0debug
static int decode_band_types(AACContext *ac, enum BandType band_type[120], int band_type_run_end[120], GetBitContext *gb, IndividualChannelStream *ics) { int g, idx = 0; const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5; for (g = 0; g < ics->num_window_groups; g++) { int k = 0; while (k < ics->max_sfb) { uint8_t sect_end = k; int sect_len_incr; int sect_band_type = get_bits(gb, 4); if (sect_band_type == 12) { av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n"); return -1; } while ((sect_len_incr = get_bits(gb, bits)) == (1 << bits) - 1) sect_end += sect_len_incr; sect_end += sect_len_incr; if (get_bits_left(gb) < 0) { av_log(ac->avctx, AV_LOG_ERROR, overread_err); return -1; } if (sect_end > ics->max_sfb) { av_log(ac->avctx, AV_LOG_ERROR, "Number of bands (%d) exceeds limit (%d).\n", sect_end, ics->max_sfb); return -1; } for (; k < sect_end; k++) { band_type [idx] = sect_band_type; band_type_run_end[idx++] = sect_end; } } } return 0; }
1threat
Dapper with .NET Core - injected SqlConnection lifetime/scope : <p>I'm using .NET Core Dependency Injection to instantiate a <code>SqlConnection</code> object during the application startup, which I'm then planning to inject in my repository. This <code>SqlConnection</code> will be used by Dapper to read/write data from the database within my repository implementation. I am going to use <code>async</code> calls with Dapper.</p> <p>The question is: should I inject the <code>SqlConnection</code> as transient or as a singleton? Considering the fact that I want to use <code>async</code> my thought would be to use transient unless Dapper implements some isolation containers internally and my singleton's scope will still be wrapped within whatever the scope Dapper uses internally.</p> <p>Are there any recommendations/best practices regarding the lifetime of the SqlConnection object when working with Dapper? Are there any caveats I might be missing?</p> <p>Thanks in advance.</p>
0debug
Is there a way to reuse enums in other classes? : <p>Is there a way to reuse enums in other classes?</p> <p>For example, I have a class using another class's enums. However, I want to avoid having to type the other class's namespace every time I use that class's enums for my active class.</p>
0debug
I have a pst file as default mail box, i want to copy structure of Pst file to new pst file thru VBA macro : I want to split my default PST file year wise thru VBA macro Such as New Pst File Name may be Year-2015.pst. It should contain the all the mails which are belongs to year 2015 ( all folders ). Regards
0debug
Java Data Structures (Most Efficient Structure For Specific Program) : <p>Question from textbook exercise: </p> <p>A hospital has a capacity of n patients. Each time a patient comes in he is assessed and, if in noncritical condition, has to wait his turn. If in critical condition, he is moved as the next to be treated. If a patient is in the washroom when called, he skips his turn and is treated as a new patient. At any point in time, the hospital needs to know who is being treated, and what capacity there is left.</p> <p>Would it be more efficient to solve this problem with (able to chose more than one answer): 1. deque 2. array 3. circuluar array 4. custom data structure: array + stack 5. stack</p>
0debug
static void commit_complete(BlockJob *job, void *opaque) { CommitBlockJob *s = container_of(job, CommitBlockJob, common); CommitCompleteData *data = opaque; BlockDriverState *active = s->active; BlockDriverState *top = blk_bs(s->top); BlockDriverState *base = blk_bs(s->base); BlockDriverState *overlay_bs = bdrv_find_overlay(active, s->commit_top_bs); int ret = data->ret; bool remove_commit_top_bs = false; bdrv_ref(top); bdrv_ref(overlay_bs); blk_unref(s->base); if (!block_job_is_cancelled(&s->common) && ret == 0) { ret = bdrv_drop_intermediate(active, s->commit_top_bs, base, s->backing_file_str); } else if (overlay_bs) { remove_commit_top_bs = true; } if (s->base_flags != bdrv_get_flags(base)) { bdrv_reopen(base, s->base_flags, NULL); } if (overlay_bs && s->orig_overlay_flags != bdrv_get_flags(overlay_bs)) { bdrv_reopen(overlay_bs, s->orig_overlay_flags, NULL); } g_free(s->backing_file_str); blk_unref(s->top); block_job_completed(&s->common, ret); g_free(data); if (remove_commit_top_bs) { bdrv_set_backing_hd(overlay_bs, top, &error_abort); } }
1threat
Is it normal that transfer learning (VGG16) performs worse on CIFAR-10? : <p><strong>Note:</strong> I am not sure this is the right website to ask these kind of questions. Please tell me where I should ask them before downvoting this "because this isn't the right place to ask". Thanks!</p> <p>I am currently experimenting with deep learning using <a href="https://keras.io" rel="nofollow noreferrer">Keras</a>. I tried already a model similar to the one to be found on <a href="https://keras.io/examples/cifar10_cnn/" rel="nofollow noreferrer">the Keras example</a>. This yields expecting results:</p> <ul> <li>80% after 10-15 epochs without data augmentation before overfitting around the 15th epoch and</li> <li>80% after 50 epochs with data augmentation without any signs of overfitting.</li> </ul> <p>After this I wanted to try transfer learning. I did this by using the <a href="https://keras.io/applications/#vgg16" rel="nofollow noreferrer">VGG16</a> network without retraining its weights (see code below). This gave very poor results: 63% accuracy after 10 epochs with a very shallow curve (see picture below) which seems to be indicating that it will achieve acceptable results only (if ever) after a very long training time (I would expect 200-300 epochs before it reaches 80%).</p> <p><a href="https://i.stack.imgur.com/MWmsT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MWmsT.png" alt="Transfer learning results"></a></p> <p>Is this normal behavior for this kind of application? Here are a few things I could imagine to be the cause of these bad results:</p> <ul> <li>the CIFAR-10 dataset has images of <code>32x32</code> pixels, which might be too few for the VGG16 net</li> <li>The filters of VGG16 are not good for CIFAR-10, which would be solved by setting the weights to <code>trainable</code> or by starting with random weights (only copying the model and not the weights)</li> </ul> <p>Thanks in advance!</p> <hr> <p><strong>My code:</strong></p> <p><em>Note that the inputs are 2 datasets (50000 training images and 10000 testing images) which are labeled images with shape <code>32x32x3</code>. Each pixel value is a float in the range <code>[0.0, 1.0]</code>.</em></p> <pre class="lang-py prettyprint-override"><code>import keras # load and preprocess data... # get VGG16 base model and define new input shape vgg16 = keras.applications.vgg16.VGG16(input_shape=(32, 32, 3), weights='imagenet', include_top=False) # add new dense layers at the top x = keras.layers.Flatten()(vgg16.output) x = keras.layers.Dense(1024, activation='relu')(x) x = keras.layers.Dropout(0.5)(x) x = keras.layers.Dense(128, activation='relu')(x) predictions = keras.layers.Dense(10, activation='softmax')(x) # define and compile model model = keras.Model(inputs=vgg16.inputs, outputs=predictions) for layer in vgg16.layers: layer.trainable = False model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # training and validation model.fit(x_train, y_train, batch_size=256, epochs=10, validation_data=(x_test, y_test)) model.evaluate(x_test, y_test) </code></pre>
0debug
Operator '-' cannot be applied to operands of type 'double' and 'string' : <p>I am asking this question because I have minimal understanding of the c sharp language and the Object-oriented paradigm. The following program was created, based on a few youtube videos and programming articles, from stack-overflow and various other sources.</p> <pre><code> case "-": textBox.Text = (valor - Double.Parse(textBox.Text).ToString()); break; case "*": textBox.Text = (valor * Double.Parse(textBox.Text).ToString()); break; case "/": textBox.Text = (valor / Double.Parse(textBox.Text).ToString()); </code></pre> <p>The following code segment is giving me the following errors Operator '-' cannot be applied to operands of type 'double' and 'string' for the 3 cases</p> <p>Thank you Any sort of help and advice is more than welcome </p>
0debug
vue-router redirect to default path issue : <p>I want to default to a specific page when user navigates to the root path ie when used goes to myapp.com I want to redirect them to myapp.com/defaultpage</p> <p>My current code is</p> <p>index.js</p> <pre><code>import Full from '../containers/Full' import DefaultView from '../views/DefaultView' export default new Router({ mode: 'history', linkActiveClass: 'open active', scrollBehavior: () =&gt; ({ y: 0 }), routes: [ { path: '/', redirect: '/defaultview', name: 'home', component: Full, children: [ { path: '/defaultview', name: 'defaultview', component: DefaultView }, { path: '*', component: NotFoundComponent } } ]}) </code></pre> <p>As it is when user goes to myapp.com I get a '404 page not found' - ie the NotFoundComponent. Only when I type in myapp.com/defaultview can I get to the correct page.</p> <p>Any ideas?</p>
0debug
Cant get a informations that's inside an array : Im trying to get a information that's inside an array but can't, everytime returns and undefined statemen. That's the array, it's inside the variable 'RESULTADO' debug {"recordType":"customrecord5","id":"1","values":{"CUSTRECORD4.custrecord6":[{"value":"11","text":"11 CP BUSINESS : Empresa Teste"}],"CUSTRECORD4.custrecord5":[{"value":"7","text":"LASER"}]}} for (var i = 0; i < resultado.length; i++){ var valores = resultado[i]; log.debug(valores); var dados = valores['value']; // NAO ESTOU CONSEGUINDO PERCORRER A VARIAVEL DADOS log.debug(dados); for (var u = 0; u < dados.length; u++){ valor = dados[u]; log.debug(valor); } } I need to get the information that's inside the index "values" and "CUSTRECORD4.custrecord5", but cant get in...
0debug
how can i implement click on current location and give desired location in mkmap view in ios : - (nullable MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation { if ([annotation isKindOfClass:[MKUserLocation class]]) { return nil; }
0debug
static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *got_frame_ptr, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; AC3DecodeContext *s = avctx->priv_data; int blk, ch, err, ret; const uint8_t *channel_map; const float *output[AC3_MAX_CHANNELS]; if (buf_size >= 2 && AV_RB16(buf) == 0x770B) { int cnt = FFMIN(buf_size, AC3_FRAME_BUFFER_SIZE) >> 1; s->dsp.bswap16_buf((uint16_t *)s->input_buffer, (const uint16_t *)buf, cnt); } else memcpy(s->input_buffer, buf, FFMIN(buf_size, AC3_FRAME_BUFFER_SIZE)); buf = s->input_buffer; init_get_bits(&s->gbc, buf, buf_size * 8); err = parse_frame_header(s); if (err) { switch (err) { case AAC_AC3_PARSE_ERROR_SYNC: av_log(avctx, AV_LOG_ERROR, "frame sync error\n"); return -1; case AAC_AC3_PARSE_ERROR_BSID: av_log(avctx, AV_LOG_ERROR, "invalid bitstream id\n"); break; case AAC_AC3_PARSE_ERROR_SAMPLE_RATE: av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n"); break; case AAC_AC3_PARSE_ERROR_FRAME_SIZE: av_log(avctx, AV_LOG_ERROR, "invalid frame size\n"); break; case AAC_AC3_PARSE_ERROR_FRAME_TYPE: if (s->frame_type == EAC3_FRAME_TYPE_DEPENDENT || s->substreamid) { av_log(avctx, AV_LOG_ERROR, "unsupported frame type : " "skipping frame\n"); *got_frame_ptr = 0; return s->frame_size; } else { av_log(avctx, AV_LOG_ERROR, "invalid frame type\n"); } break; default: av_log(avctx, AV_LOG_ERROR, "invalid header\n"); break; } } else { if (s->frame_size > buf_size) { av_log(avctx, AV_LOG_ERROR, "incomplete frame\n"); err = AAC_AC3_PARSE_ERROR_FRAME_SIZE; } else if (avctx->err_recognition & (AV_EF_CRCCHECK|AV_EF_CAREFUL)) { if (av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, &buf[2], s->frame_size - 2)) { av_log(avctx, AV_LOG_ERROR, "frame CRC mismatch\n"); err = AAC_AC3_PARSE_ERROR_CRC; } } } if (!err) { avctx->sample_rate = s->sample_rate; avctx->bit_rate = s->bit_rate; s->out_channels = s->channels; s->output_mode = s->channel_mode; if (s->lfe_on) s->output_mode |= AC3_OUTPUT_LFEON; if (avctx->request_channels > 0 && avctx->request_channels <= 2 && avctx->request_channels < s->channels) { s->out_channels = avctx->request_channels; s->output_mode = avctx->request_channels == 1 ? AC3_CHMODE_MONO : AC3_CHMODE_STEREO; s->channel_layout = avpriv_ac3_channel_layout_tab[s->output_mode]; } avctx->channels = s->out_channels; avctx->channel_layout = s->channel_layout; s->loro_center_mix_level = gain_levels[s-> center_mix_level]; s->loro_surround_mix_level = gain_levels[s->surround_mix_level]; s->ltrt_center_mix_level = LEVEL_MINUS_3DB; s->ltrt_surround_mix_level = LEVEL_MINUS_3DB; if (s->channels != s->out_channels && !((s->output_mode & AC3_OUTPUT_LFEON) && s->fbw_channels == s->out_channels)) { set_downmix_coeffs(s); } } else if (!s->out_channels) { s->out_channels = avctx->channels; if (s->out_channels < s->channels) s->output_mode = s->out_channels == 1 ? AC3_CHMODE_MONO : AC3_CHMODE_STEREO; } if (avctx->channels != s->out_channels) { av_log(avctx, AV_LOG_ERROR, "channel number mismatching on damaged frame\n"); return AVERROR_INVALIDDATA; } avctx->audio_service_type = s->bitstream_mode; if (s->bitstream_mode == 0x7 && s->channels > 1) avctx->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE; avctx->channels = s->out_channels; s->frame.nb_samples = s->num_blocks * 256; if ((ret = ff_get_buffer(avctx, &s->frame)) < 0) { av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); return ret; } channel_map = ff_ac3_dec_channel_map[s->output_mode & ~AC3_OUTPUT_LFEON][s->lfe_on]; for (ch = 0; ch < AC3_MAX_CHANNELS; ch++) { output[ch] = s->output[ch]; s->outptr[ch] = s->output[ch]; } for (ch = 0; ch < s->channels; ch++) { if (ch < s->out_channels) s->outptr[channel_map[ch]] = (float *)s->frame.data[ch]; } for (blk = 0; blk < s->num_blocks; blk++) { if (!err && decode_audio_block(s, blk)) { av_log(avctx, AV_LOG_ERROR, "error decoding the audio block\n"); err = 1; } if (err) for (ch = 0; ch < s->out_channels; ch++) memcpy(((float*)s->frame.data[ch]) + AC3_BLOCK_SIZE*blk, output[ch], 1024); for (ch = 0; ch < s->out_channels; ch++) { output[ch] = s->outptr[channel_map[ch]]; if (!ch || channel_map[ch]) s->outptr[channel_map[ch]] += AC3_BLOCK_SIZE; } } s->frame.decode_error_flags = err ? FF_DECODE_ERROR_INVALID_BITSTREAM : 0; for (ch = 0; ch < s->out_channels; ch++) memcpy(s->output[ch], output[ch], 1024); *got_frame_ptr = 1; *(AVFrame *)data = s->frame; return FFMIN(buf_size, s->frame_size); }
1threat
static int tpm_passthrough_test_tpmdev(int fd) { struct tpm_req_hdr req = { .tag = cpu_to_be16(TPM_TAG_RQU_COMMAND), .len = cpu_to_be32(sizeof(req)), .ordinal = cpu_to_be32(TPM_ORD_GetTicks), }; struct tpm_resp_hdr *resp; fd_set readfds; int n; struct timeval tv = { .tv_sec = 1, .tv_usec = 0, }; unsigned char buf[1024]; n = write(fd, &req, sizeof(req)); if (n < 0) { return errno; } if (n != sizeof(req)) { return EFAULT; } FD_ZERO(&readfds); FD_SET(fd, &readfds); n = select(fd + 1, &readfds, NULL, NULL, &tv); if (n != 1) { return errno; } n = read(fd, &buf, sizeof(buf)); if (n < sizeof(struct tpm_resp_hdr)) { return EFAULT; } resp = (struct tpm_resp_hdr *)buf; if (be16_to_cpu(resp->tag) != TPM_TAG_RSP_COMMAND || be32_to_cpu(resp->len) != n) { return EBADMSG; } return 0; }
1threat
How to remove highlight on tap of List with SwiftUI? : <p>How to remove highlight on tap of List with SwiftUI?</p> <pre><code>List { }.whatModifierToAddHere? </code></pre> <p>The <a href="https://developer.apple.com/documentation/swiftui/selectionmanager" rel="noreferrer">selection manager documentation</a> doesnt say anything about it.</p>
0debug
Duplicate files in DerivedData folder using CoreData generator : <p>I'm trying to generate NSManagedModels from my datamodel. Generation works but after I got many errors :</p> <blockquote> <p>error: filename "Station+CoreDataProperties.swift" used twice: '/Users/Me/MyApp/Models/CoreData/Station+CoreDataProperties.swift' and '/Users/Me/Library/Developer/Xcode/DerivedData/MyApp-gwacspwrsnabomertjnqfbuhjvwc/Build/Intermediates/MyApp.build/Debug-iphoneos/MyApp.build/DerivedSources/CoreDataGenerated/Model/Station+CoreDataProperties.swift' :0: note: filenames are used to distinguish private declarations with the same name</p> </blockquote> <p>I try clean build folder and derivedData directory hard delete. I'm using Xcode 8 BETA maybe it's a bug ?</p>
0debug
Upload binary file with retrofit 2 in Android : <p>I want to upload a binary file to the server in Android. I test Api method by postman:</p> <p><a href="https://i.stack.imgur.com/fP58X.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fP58X.png" alt="enter image description here"></a></p> <p>And it's OK, as you see there is another option which you can upload files as form data(key, value):</p> <p><a href="https://i.stack.imgur.com/V0Lbt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/V0Lbt.png" alt="enter image description here"></a></p> <p>Every tutorials (like <a href="https://futurestud.io/tutorials/retrofit-2-how-to-upload-files-to-server" rel="noreferrer">this one</a>)describe how to upload files as <code>multipart/form-data</code>:</p> <pre><code> // create RequestBody instance from file RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); // MultipartBody.Part is used to send also the actual file name MultipartBody.Part body = MultipartBody.Part.createFormData("picture", file.getName(), requestFile); </code></pre> <p>I search a lot but couldn't find any way to upload file as binary with retrofit2.</p> <p>There is just one Issue in <strong>retrofit</strong> repository which ask <strong><a href="https://github.com/square/retrofit/issues/1217" rel="noreferrer">How can I POST a image binary in retrofit 2.0 beta?</a></strong>. I use its solution :</p> <p>API Service:</p> <pre><code>@POST("trip/{tripId}/media/photos") Call&lt;MediaPost&gt; postEventPhoto( @Path("eventId") int tripId, @Header("Authorization") String accessToken, @Query("direction") String direction, @Body RequestBody photo); </code></pre> <p>Caller:</p> <pre><code>InputStream in = new FileInputStream(new File(media.getPath())); byte[] buf; buf = new byte[in.available()]; while (in.read(buf) != -1); RequestBody requestBody = RequestBody .create(MediaType.parse("application/octet-stream"), buf); Call&lt;MediaPost&gt; mediaPostCall = tripApiService.postTripPhoto( tripId, ((GlobalInfo) getApplicationContext()).getApiAccessToken(), direction, requestBody); </code></pre> <p>But I got this error:</p> <pre><code>java.lang.IllegalArgumentException: @Body parameters cannot be used with form or multi-part encoding. </code></pre> <p>What's wrong with my code? what should I do?</p>
0debug
When you press the W button with the Robot class, the character does not go forward : To get acquainted with the class robot decided to make a program that would control the character from the game Minecraft, but unfortunately this code does not work in the game. The letter is printed in a notebook, but can not get the character out of the game to walk( import java.awt.*; import java.awt.event.KeyEvent; public class Main { public static void main(String[] args) { try { Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_W); robot.delay(1000); robot.keyRelease(KeyEvent.VK_W); } catch (AWTException e) { e.printStackTrace(); } }
0debug
SFSpeechRecognizer - detect end of utterance : <p>I am hacking a little project using iOS 10 built-in speech recognition. I have working results using device's microphone, my speech is recognized very accurately.</p> <p>My problem is that recognition task callback is called for every available partial transcription, and I want it to <strong>detect person stopped talking</strong> and call the callback with <code>isFinal</code> property set to true. It is not happening - app is listening indefinitely.</p> <p>Is <code>SFSpeechRecognizer</code> ever capable of detecting end of sentence?</p> <p>Here's my code - it is based on example found on the Internets, it is mostly a boilerplate needed to recognize from microphone source. I modified it by adding recognition <code>taskHint</code>. I also set <code>shouldReportPartialResults</code> to false, but it seems it has been ignored.</p> <pre><code> func startRecording() { if recognitionTask != nil { recognitionTask?.cancel() recognitionTask = nil } let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(AVAudioSessionCategoryRecord) try audioSession.setMode(AVAudioSessionModeMeasurement) try audioSession.setActive(true, with: .notifyOthersOnDeactivation) } catch { print("audioSession properties weren't set because of an error.") } recognitionRequest = SFSpeechAudioBufferRecognitionRequest() recognitionRequest?.shouldReportPartialResults = false recognitionRequest?.taskHint = .search guard let inputNode = audioEngine.inputNode else { fatalError("Audio engine has no input node") } guard let recognitionRequest = recognitionRequest else { fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object") } recognitionRequest.shouldReportPartialResults = true recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in var isFinal = false if result != nil { print("RECOGNIZED \(result?.bestTranscription.formattedString)") self.transcriptLabel.text = result?.bestTranscription.formattedString isFinal = (result?.isFinal)! } if error != nil || isFinal { self.state = .Idle self.audioEngine.stop() inputNode.removeTap(onBus: 0) self.recognitionRequest = nil self.recognitionTask = nil self.micButton.isEnabled = true self.say(text: "OK. Let me see.") } }) let recordingFormat = inputNode.outputFormat(forBus: 0) inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in self.recognitionRequest?.append(buffer) } audioEngine.prepare() do { try audioEngine.start() } catch { print("audioEngine couldn't start because of an error.") } transcriptLabel.text = "Say something, I'm listening!" state = .Listening } </code></pre>
0debug
Printing random characters instead of the same ones : <p>sorry for the horrible title, I have no idea how I'd describe my problem.</p> <p>I'm trying to generate a code that contains 15 characters. 7 of these are already given and will be called the "base". The other 8 have to be random from 0 to 9.</p> <p>This is my code</p> <pre><code>numList = "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" whatSerial = input("Serial to generate?").upper() def redmi4A(numList): return "8655920" + numList + numList + numList + numList + numList + numList + numList + numList + " -&gt; Redmi 4A" if whatSerial == "4A": for i in numList: print(redmi4A(i)) </code></pre> <p>however the output looks like this: </p> <pre><code>865592011111111 -&gt; Redmi 4A 865592022222222 -&gt; Redmi 4A 865592033333333 -&gt; Redmi 4A 865592044444444 -&gt; Redmi 4A 865592055555555 -&gt; Redmi 4A 865592066666666 -&gt; Redmi 4A 865592077777777 -&gt; Redmi 4A 865592088888888 -&gt; Redmi 4A 865592099999999 -&gt; Redmi 4A 865592000000000 -&gt; Redmi 4A </code></pre> <p>as you can see it generates the base + 11111, 2222, 3333 etc. I want the numbers after the base to output all possible solutions, so the numbers after the base would be in a random order.</p>
0debug
Why exactly is void async bad? : <p>So I understand why returning void from async would normally make no sense, but I've ran into a situation where I think it would be perfectly valid. Consider the following contrived example:</p> <pre><code>protected override void OnLoad(EventArgs e) { if (CustomTask == null) // Do not await anything, let OnLoad return. PrimeCustomTask(); } private TaskCompletionSource&lt;int&gt; CustomTask; // I DO NOT care about the return value from this. So why is void bad? private async void PrimeCustomTask() { CustomTask = new TaskCompletionSource&lt;int&gt;(); int result = 0; try { // Wait for button click to set the value, but do not block the UI. result = await CustomTask.Task; } catch { // Handle exceptions } CustomTask = null; // Show the value MessageBox.Show(result.ToString()); } private void button1_Click(object sender, EventArgs e) { if (CustomTask != null) CustomTask.SetResult(500); } </code></pre> <p>I realize this is an unusual example, but I tried to make it simple and more generalized. Could someone explain to me why this is horrible code, and also how I could modify it to follow conventions correctly?</p> <p>Thanks for any help.</p>
0debug
how to hold my location after the web page is refreshed : <?php echo " <select data-live-search='true' data-live-search-style='startsWith' class='selectpicker' id='locName'>"; $stmt = $conn->prepare('SELECT LocationName From arealistmain'); $stmt->execute(); { echo " <option>Select Location</option>"; } $stmt->execute(); while($row = $stmt->fetch()) { echo " <option>" .$row['LocationName'] . "</option>"; } echo "</select>"; ?> i have a code like this:need to hold the location after the Web page is refreshed
0debug
How do you get a Kubernetes pod's name from its IP address? : <p>How do I get a pod's name from its IP address? What's the magic incantation of <code>kubectl</code> + <code>sed</code>/<code>awk</code>/<code>grep</code>/etc regardless of where <code>kubectl</code> is invoked?</p>
0debug
int bdrv_dirty_bitmap_get_meta(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector, int nb_sectors) { uint64_t i; int sectors_per_bit = 1 << hbitmap_granularity(bitmap->meta); for (i = sector; i < sector + nb_sectors; i += sectors_per_bit) { if (hbitmap_get(bitmap->meta, i)) { return true; } } return false; }
1threat
Visual Studio Code — Insert New Line at the End of Files : <p>When saving files using Visual Studio Code, I noticed that a new line is not automatically added to the end of files, causing all sorts of potential issues.</p> <p>How does one insert a new line automatically in Visual Studio Code?</p>
0debug
long do_sigreturn(CPUState *env) { struct target_signal_frame *sf; uint32_t up_psr, pc, npc; target_sigset_t set; sigset_t host_set; abi_ulong fpu_save; int err, i; sf = (struct target_signal_frame *)g2h(env->regwptr[UREG_FP]); #if 0 fprintf(stderr, "sigreturn\n"); fprintf(stderr, "sf: %x pc %x fp %x sp %x\n", sf, env->pc, env->regwptr[UREG_FP], env->regwptr[UREG_SP]); #endif #if 0 if (verify_area (VERIFY_READ, sf, sizeof (*sf))) goto segv_and_exit; #endif if (((uint) sf) & 3) goto segv_and_exit; err = __get_user(pc, &sf->info.si_regs.pc); err |= __get_user(npc, &sf->info.si_regs.npc); if ((pc | npc) & 3) goto segv_and_exit; err |= __get_user(up_psr, &sf->info.si_regs.psr); env->psr = (up_psr & (PSR_ICC )) | (env->psr & ~(PSR_ICC )); env->pc = pc; env->npc = npc; err |= __get_user(env->y, &sf->info.si_regs.y); for (i=0; i < 8; i++) { err |= __get_user(env->gregs[i], &sf->info.si_regs.u_regs[i]); } for (i=0; i < 8; i++) { err |= __get_user(env->regwptr[i + UREG_I0], &sf->info.si_regs.u_regs[i+8]); } err |= __get_user(fpu_save, (abi_ulong *)&sf->fpu_save); err |= __get_user(set.sig[0], &sf->info.si_mask); for(i = 1; i < TARGET_NSIG_WORDS; i++) { err |= (__get_user(set.sig[i], &sf->extramask[i - 1])); } target_to_host_sigset_internal(&host_set, &set); sigprocmask(SIG_SETMASK, &host_set, NULL); if (err) goto segv_and_exit; return env->regwptr[0]; segv_and_exit: force_sig(TARGET_SIGSEGV); }
1threat
VS Code: keybinding to move cursor to next occurrence of word under cursor : <p>If my cursor is under word <code>foo</code> in text, is there a keybinding in VS Code that will move the cursor to the next occurrence of the word <code>foo</code> in the text?</p> <p>(I had this feature in my previous IDE, IntelliJ IDEA. It was called <a href="https://www.jetbrains.com/help/idea/2016.1/finding-word-at-caret.html" rel="noreferrer">Find Word at Caret</a>)</p>
0debug
alert('Hello ' + user_input);
1threat
static TranslationBlock *tb_find_slow(target_ulong pc, target_ulong cs_base, uint64_t flags) { TranslationBlock *tb, **ptb1; unsigned int h; tb_page_addr_t phys_pc, phys_page1, phys_page2; target_ulong virt_page2; tb_invalidated_flag = 0; phys_pc = get_page_addr_code(env, pc); phys_page1 = phys_pc & TARGET_PAGE_MASK; phys_page2 = -1; h = tb_phys_hash_func(phys_pc); ptb1 = &tb_phys_hash[h]; for(;;) { tb = *ptb1; if (!tb) goto not_found; if (tb->pc == pc && tb->page_addr[0] == phys_page1 && tb->cs_base == cs_base && tb->flags == flags) { if (tb->page_addr[1] != -1) { virt_page2 = (pc & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE; phys_page2 = get_page_addr_code(env, virt_page2); if (tb->page_addr[1] == phys_page2) goto found; } else { goto found; } } ptb1 = &tb->phys_hash_next; } not_found: tb = tb_gen_code(env, pc, cs_base, flags, 0); found: if (likely(*ptb1)) { *ptb1 = tb->phys_hash_next; tb->phys_hash_next = tb_phys_hash[h]; tb_phys_hash[h] = tb; } env->tb_jmp_cache[tb_jmp_cache_hash_func(pc)] = tb; return tb; }
1threat
static void test_qemu_strtoull_octal(void) { const char *str = "0123"; char f = 'X'; const char *endptr = &f; uint64_t res = 999; int err; err = qemu_strtoull(str, &endptr, 8, &res); g_assert_cmpint(err, ==, 0); g_assert_cmpint(res, ==, 0123); g_assert(endptr == str + strlen(str)); endptr = &f; res = 999; err = qemu_strtoull(str, &endptr, 0, &res); g_assert_cmpint(err, ==, 0); g_assert_cmpint(res, ==, 0123); g_assert(endptr == str + strlen(str)); }
1threat
static int xhci_fire_ctl_transfer(XHCIState *xhci, XHCITransfer *xfer) { XHCITRB *trb_setup, *trb_status; uint8_t bmRequestType, bRequest; uint16_t wValue, wLength, wIndex; XHCIPort *port; USBDevice *dev; int ret; DPRINTF("xhci_fire_ctl_transfer(slot=%d)\n", xfer->slotid); trb_setup = &xfer->trbs[0]; trb_status = &xfer->trbs[xfer->trb_count-1]; if (TRB_TYPE(*trb_status) == TR_EVDATA && xfer->trb_count > 2) { trb_status--; } if (TRB_TYPE(*trb_setup) != TR_SETUP) { fprintf(stderr, "xhci: ep0 first TD not SETUP: %d\n", TRB_TYPE(*trb_setup)); return -1; } if (TRB_TYPE(*trb_status) != TR_STATUS) { fprintf(stderr, "xhci: ep0 last TD not STATUS: %d\n", TRB_TYPE(*trb_status)); return -1; } if (!(trb_setup->control & TRB_TR_IDT)) { fprintf(stderr, "xhci: Setup TRB doesn't have IDT set\n"); return -1; } if ((trb_setup->status & 0x1ffff) != 8) { fprintf(stderr, "xhci: Setup TRB has bad length (%d)\n", (trb_setup->status & 0x1ffff)); return -1; } bmRequestType = trb_setup->parameter; bRequest = trb_setup->parameter >> 8; wValue = trb_setup->parameter >> 16; wIndex = trb_setup->parameter >> 32; wLength = trb_setup->parameter >> 48; if (xfer->data && xfer->data_alloced < wLength) { xfer->data_alloced = 0; g_free(xfer->data); xfer->data = NULL; } if (!xfer->data) { DPRINTF("xhci: alloc %d bytes data\n", wLength); xfer->data = g_malloc(wLength+1); xfer->data_alloced = wLength; } xfer->data_length = wLength; port = &xhci->ports[xhci->slots[xfer->slotid-1].port-1]; dev = xhci_find_device(port, xhci->slots[xfer->slotid-1].devaddr); if (!dev) { fprintf(stderr, "xhci: slot %d port %d has no device\n", xfer->slotid, xhci->slots[xfer->slotid-1].port); return -1; } xfer->in_xfer = bmRequestType & USB_DIR_IN; xfer->iso_xfer = false; xhci_setup_packet(xfer, dev); if (!xfer->in_xfer) { xhci_xfer_data(xfer, xfer->data, wLength, 0, 1, 0); } ret = usb_device_handle_control(dev, &xfer->packet, (bmRequestType << 8) | bRequest, wValue, wIndex, wLength, xfer->data); xhci_complete_packet(xfer, ret); if (!xfer->running_async && !xfer->running_retry) { xhci_kick_ep(xhci, xfer->slotid, xfer->epid); } return 0; }
1threat
static void kvmppc_timer_hack(void *opaque) { qemu_service_io(); qemu_mod_timer(kvmppc_timer, qemu_get_clock_ns(vm_clock) + kvmppc_timer_rate); }
1threat
Need help sorting text file in C# : <p>I dont need to sort the text file I just need to be able to tell if the text file is in alphabetical order or not. like true or false The text file is a list of words like:</p> <p>apple dog cat bed for example this text above would come out as false because it is not in order</p>
0debug
I need to create an array with numbers given by the user : System.out.println("Please enter a coefficients of a polynomial’s terms:"); String coefficents = keyboard.nextLine(); String[] three = coefficents.split(" "); int[] intArray1 = new int[three.length]; //Does anyone know how i can make this work because right not it builds but when i run it, it gives me [I@33909752 //if someone could show me or explain to me what's wrong that would help
0debug
Javascript: Shorter way to format date : <p>i would like format the Date the way i need it to be: I would like to have it that way: YYYY-MM-DD HH:MM:SS</p> <p>I found that solution on the internet:</p> <pre><code>function js_yyyy_mm_dd_hh_mm_ss () { now = new Date(); year = "" + now.getFullYear(); month = "" + (now.getMonth() + 1); if (month.length == 1) { month = "0" + month; } day = "" + now.getDate(); if (day.length == 1) { day = "0" + day; } hour = "" + now.getHours(); if (hour.length == 1) { hour = "0" + hour; } minute = "" + now.getMinutes(); if (minute.length == 1) { minute = "0" + minute; } second = "" + now.getSeconds(); if (second.length == 1) { second = "0" + second; } return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second; } </code></pre> <p>Is there a better or "smaller" way to do it?</p>
0debug
Delete last character printed in python 3.6 : <p>I'm trying to delete the last character I've printed from the previous line in python, e.g if I do print ("hello world") I will get hello world outputted, but I'm wondering after it's been outputted would there be a way to remove the d at the end of the output so it would now only say hello worl... in short is there a way to remove the end character of an already printed line?</p> <p>Thanks </p>
0debug
Python - How to decompile python script? : <p>I have a script and i think its compiled with something like <code>Cpython</code>. I can run this script, but i want to access to source code. Is there any way to do this? </p> <p>Thanks</p>
0debug
What is the size of pointers in c++? : <p>What is the size of pointers in c++?</p> <pre><code>char a; char *b=a; cout&lt;&lt;sizeof(b); </code></pre> <p>Output is 2 I don't know why.</p> <pre><code>cout&lt;&lt;sizeof(const); //o/p is 2 cout&lt;&lt;sizeof(NULL); //o/p is 2 </code></pre>
0debug
username using * in the criteria countif excel : [Hello please help me, i m searching sum of class of each student using countif formula, but any student have unique username like A*di (in the image) and so the calculation is false. And any other student using username like </John>, and 'Angel. and make calculation false][1] [1]: https://i.stack.imgur.com/LrYJ5.jpg
0debug
Is it possible to run a Rails 4.2 app on Ruby 2.4? : <p>I want to try out a Rails 4.2 app on Ruby 2.4.</p> <p>However, when I try doing it, I get errors about the json gem version 1.8.3 failing to install.</p> <pre><code>Gem::Ext::BuildError: ERROR: Failed to build gem native extension. current directory: /Users/agrimm/.rbenv/versions/2.4.0-rc1/lib/ruby/gems/2.4.0/gems/json-1.8.3/ext/json/ext/generator /Users/agrimm/.rbenv/versions/2.4.0-rc1/bin/ruby -r ./siteconf20161223-91367-cql0ne.rb extconf.rb creating Makefile current directory: /Users/agrimm/.rbenv/versions/2.4.0-rc1/lib/ruby/gems/2.4.0/gems/json-1.8.3/ext/json/ext/generator make "DESTDIR=" clean current directory: /Users/agrimm/.rbenv/versions/2.4.0-rc1/lib/ruby/gems/2.4.0/gems/json-1.8.3/ext/json/ext/generator make "DESTDIR=" compiling generator.c generator.c:861:25: error: use of undeclared identifier 'rb_cFixnum' } else if (klass == rb_cFixnum) { ^ generator.c:863:25: error: use of undeclared identifier 'rb_cBignum' } else if (klass == rb_cBignum) { ^ 2 errors generated. make: *** [generator.o] Error 1 make failed, exit code 2 Gem files will remain installed in /Users/agrimm/.rbenv/versions/2.4.0-rc1/lib/ruby/gems/2.4.0/gems/json-1.8.3 for inspection. Results logged to /Users/agrimm/.rbenv/versions/2.4.0-rc1/lib/ruby/gems/2.4.0/extensions/x86_64-darwin-14/2.4.0-static/json-1.8.3/gem_make.out An error occurred while installing json (1.8.3), and Bundler cannot continue. Make sure that `gem install json -v '1.8.3'` succeeds before bundling. </code></pre> <p>which I assume is due to the unification of Fixnum and Bignum into Integer.</p> <p>If I add to the Gemfile a constraint that json has to be version 2.0.0, then it complains that Rails 4.2 requires json ~> 1.7, which forbids 2.0.0.</p> <p>Am I out of luck unless the maintainers of Rails decide to make a change to a non-5.x version of Rails, or the maintainers of the json gem decide to make a new non-2.x version of their gem?</p>
0debug
HTTP request for Github API : <p>I'm developing a web application in C# to search for users with Github accounts but I have no idea how to start it. I don't want to use a framework like Octokit. I want to call everything in c#.</p> <p>How do you link the API with the search box in HTML? </p>
0debug
Printing unicode character from number : <p>In Python I'm trying to print out the character corresponding to a given code like this:</p> <pre><code>a = 159 print unichr(a) </code></pre> <p>It prints out a strange symbol. Can anyone explain why?</p>
0debug
Creating file 'php' after getting data : <p>. I wonder how can my project automatically create php file by itself , after getting some data like product description ?</p>
0debug
Generate random activation code in PHP : <p>How to generate random activation code based on current datetime and username in PHP.</p> <p>The return value should be like this, i.e: </p> <p>201605021955Username</p> <pre><code>function getActivationCode($username){ $activationCode = ""; .... return activationCode; } </code></pre>
0debug
In my application i have 3 date formats PST,CST,EST.but when converting to IST it was showing the any suggestionsdate of 1 day before : In my application i have 3 date formats PST,CST,EST.but when converting to IST it was showing the date of 1 day before any suggestions
0debug