problem
stringlengths
26
131k
labels
class label
2 classes
static const HWAccel *get_hwaccel(enum AVPixelFormat pix_fmt, enum HWAccelID selected_hwaccel_id) { int i; for (i = 0; hwaccels[i].name; i++) if (hwaccels[i].pix_fmt == pix_fmt && (!selected_hwaccel_id || selected_hwaccel_id == HWACCEL_AUTO || hwaccels[i].id == selected_hwaccel_id)) return &hwaccels[i]; return NULL; }
1threat
If I have a 3D array how do I sum up the value given a boundary? : Let's say I have a 3D array such that int[][][] array = { { {1, 2, 3}, { 4, 5, 6}, { 7, 8, 9} }, { {10, 11, 12}, {13, 14, 15}, {16, 17, 18} }, { {19, 20, 21}, {22, 23, 24}, {25, 26, 27} } }; ---------- Now the array is as follow **First Image** 1 2 3 4 5 6 7 8 9 **Second Image** 10 11 12 13 14 15 16 17 18 **Third Image** 19 20 21 22 23 24 25 26 27 ---------- I would like to sum up the value in the 3 X 3 matrix boundary and create a new array such that one example of summation of the top left corner is that **First Example** ((1+2+4+5)+(10+11+13+14)+(19+20+22+23))/ 12 The second example will be to take the centre value and compute the average **Second Example** ((1+2+3+4+5+6+7+8+9)+(10+11+12+13+14+15+16+17+18)+(19+20+21+22+23+24+25+26+27))/ 27 where it will compute the average of all the values that are within a 3 by 3 square centred at the pixel.
0debug
static void s390_print_cpu_model_list_entry(gpointer data, gpointer user_data) { CPUListState *s = user_data; const S390CPUClass *scc = S390_CPU_CLASS((ObjectClass *)data); char *name = g_strdup(object_class_get_name((ObjectClass *)data)); const char *details = ""; if (scc->is_static) { details = "(static, migration-safe)"; } else if (scc->is_migration_safe) { details = "(migration-safe)"; } g_strrstr(name, "-" TYPE_S390_CPU)[0] = 0; (*s->cpu_fprintf)(s->file, "s390 %-15s %-35s %s\n", name, scc->desc, details); g_free(name); }
1threat
String based data encoding: Base64 vs Base64url : <p>What is the difference between Base64 and Base64url that I see in things like JSON web tokens?</p>
0debug
How to use PyCharm for GIMP plugin development? : <p>I need to develop a plugin for GIMP and would like to stay with PyCharm for Python editing, etc.</p> <p>FYI, I'm on Windows.</p> <p>After directing PyCharm to use the Python interpreter included with GIMP:</p> <p><a href="https://i.stack.imgur.com/RbFkW.jpg"><img src="https://i.stack.imgur.com/RbFkW.jpg" alt="Project interpreter"></a></p> <p>I also added a path to <code>gimpfu.py</code> to get rid of the error on <code>from gimpfu import *</code>:</p> <p><a href="https://i.stack.imgur.com/1DYZO.jpg"><img src="https://i.stack.imgur.com/1DYZO.jpg" alt="enter image description here"></a></p> <p>This fixes the error on the import, even when set to <code>Excluded</code>. </p> <p>I experimented with setting this directory to <code>Sources</code>, <code>Resources</code> and <code>Excluded</code> and still get errors for constants such as <code>RGBA-IMAGE</code>, <code>TRANSPARENT_FILL</code>, <code>NORMAL_MODE</code>, etc.</p> <p><a href="https://i.stack.imgur.com/K2EFG.jpg"><img src="https://i.stack.imgur.com/K2EFG.jpg" alt="enter image description here"></a></p> <p>Any idea on how to contort PyCharm into playing nice for GIMP plugin development?</p> <p>Not really running any code from PyCharm, it's really just being used as a nice code editor, facilitate revisions control, etc.</p>
0debug
static void test_visitor_in_native_list_int8(TestInputVisitorData *data, const void *unused) { test_native_list_integer_helper(data, unused, USER_DEF_NATIVE_LIST_UNION_KIND_S8); }
1threat
PDO SQL insert syntax issue : <p>I'm trying to get my page to insert multiple rows into my database at once. All info comes from a previous page. When a certain coordinate is entered, the row isn't saved.</p> <p>While testing, just Alpha gets a coordinate that differs from the excluded coordinate.</p> <p>When I run the code, I get the following error:</p> <pre><code>SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ')' at line 2 </code></pre> <p>This is my code:</p> <pre><code>try { $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password); $dag = mysqli_real_escape_string($conn, $_GET['dag']); $tijd = mysqli_real_escape_string($conn, $_GET['tijd']); $wgs_coordinaat_x_alpha = mysqli_real_escape_string($conn, $_GET["x_alpha"]); $wgs_coordinaat_y_alpha = mysqli_real_escape_string($conn, $_GET["y_alpha"]); $wgs_coordinaat_x_bravo = mysqli_real_escape_string($conn, $_GET["x_bravo"]); $wgs_coordinaat_y_bravo = mysqli_real_escape_string($conn, $_GET["y_bravo"]); $wgs_coordinaat_x_charlie = mysqli_real_escape_string($conn, $_GET["x_charlie"]); $wgs_coordinaat_y_charlie = mysqli_real_escape_string($conn, $_GET["y_charlie"]); $wgs_coordinaat_x_delta = mysqli_real_escape_string($conn, $_GET["x_delta"]); $wgs_coordinaat_y_delta = mysqli_real_escape_string($conn, $_GET["y_delta"]); $wgs_coordinaat_x_echo = mysqli_real_escape_string($conn, $_GET["x_echo"]); $wgs_coordinaat_y_echo = mysqli_real_escape_string($conn, $_GET["y_echo"]); $wgs_coordinaat_x_foxtrot = mysqli_real_escape_string($conn, $_GET["x_foxtrot"]); $wgs_coordinaat_y_foxtrot = mysqli_real_escape_string($conn, $_GET["y_foxtrot"]); // set the PDO error mode to exception $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // begin the transaction $conn-&gt;beginTransaction(); // our SQL statements if ($wgs_coordinaat_x_alpha == "47.9747674834") {} else { $conn-&gt;exec("INSERT INTO markers (id, type, dag, tijd, deelgebied, lat, lng) VALUES (NULL, 'Hint', '$dag', '$tijd', 'Alpha', '$wgs_coordinaat_x_alpha', '$wgs_coordinaat_y_alpha')"); } if ($wgs_coordinaat_x_bravo == "47.9747674834") {} else { $conn-&gt;exec("INSERT INTO markers (id, type, dag, tijd, deelgebied, lat, lng) VALUES (NULL, 'Hint', '$dag', '$tijd', 'Bravo', '$wgs_coordinaat_x_bravo', '$wgs_coordinaat_y_bravo'))"); } if ($wgs_coordinaat_x_charlie == "47.9747674834") {} else { $conn-&gt;exec("INSERT INTO markers (id, type, dag, tijd, deelgebied, lat, lng) VALUES (NULL, 'Hint', '$dag', '$tijd', 'Charlie', '$wgs_coordinaat_x_charlie', '$wgs_coordinaat_y_charlie')"); } if ($wgs_coordinaat_x_delta == "47.9747674834") {} else { $conn-&gt;exec("INSERT INTO markers (id, type, dag, tijd, deelgebied, lat, lng) VALUES (NULL, 'Hint', '$dag', '$tijd', 'Delta', '$wgs_coordinaat_x_delta', '$wgs_coordinaat_y_delta')"); } if ($wgs_coordinaat_x_echo == "47.9747674834") {} else { $conn-&gt;exec("INSERT INTO markers (id, type, dag, tijd, deelgebied, lat, lng) VALUES (NULL, 'Hint', '$dag', '$tijd', 'Echo', '$wgs_coordinaat_x_echo', '$wgs_coordinaat_y_echo')"); } if ($wgs_coordinaat_x_foxtrot == "47.9747674834") {} else { $conn-&gt;exec("INSERT INTO markers (id, type, dag, tijd, deelgebied, lat, lng) VALUES (NULL, 'Hint', '$dag', '$tijd', 'Foxtrot', '$wgs_coordinaat_x_foxtrot', '$wgs_coordinaat_y_foxtrot')"); } // commit the transaction $conn-&gt;commit(); echo "Hint succesvol toegevoegd!"; } catch(PDOException $e) { // roll back the transaction if something failed $conn-&gt;rollback(); echo "Opes! Iets is fout gegaan: " . $e-&gt;getMessage(); } $conn = null; </code></pre> <p>I'm out of ideas. Thanks!</p>
0debug
void RENAME(swri_noise_shaping)(SwrContext *s, AudioData *dsts, const AudioData *srcs, const AudioData *noises, int count){ int i, j, pos, ch; int taps = s->dither.ns_taps; float S = s->dither.ns_scale; float S_1 = s->dither.ns_scale_1; av_assert2((taps&3) != 2); av_assert2((taps&3) != 3 || s->dither.ns_coeffs[taps] == 0); for (ch=0; ch<srcs->ch_count; ch++) { const float *noise = ((const float *)noises->ch[ch]) + s->dither.noise_pos; const DELEM *src = (const DELEM*)srcs->ch[ch]; DELEM *dst = (DELEM*)dsts->ch[ch]; float *ns_errors = s->dither.ns_errors[ch]; const float *ns_coeffs = s->dither.ns_coeffs; pos = s->dither.ns_pos; for (i=0; i<count; i++) { double d1, d = src[i]*S_1; for(j=0; j<taps-2; j+=4) { d -= ns_coeffs[j ] * ns_errors[pos + j ] +ns_coeffs[j + 1] * ns_errors[pos + j + 1] +ns_coeffs[j + 2] * ns_errors[pos + j + 2] +ns_coeffs[j + 3] * ns_errors[pos + j + 3]; } if(j < taps) d -= ns_coeffs[j] * ns_errors[pos + j]; pos = pos ? pos - 1 : taps - 1; d1 = rint(d + noise[i]); ns_errors[pos + taps] = ns_errors[pos] = d1 - d; d1 *= S; CLIP(d1); dst[i] = d1; } } s->dither.ns_pos = pos; }
1threat
JupyterLab autocomplete without tab : <p>Pressing tab each time you want to automcomplete seems time-consuming. Ideally, you just type in the first couple of letters and you get a drop down list without pressing tab.</p> <p>In Jupyter notebook, there were some extensions that you could install to get this functionality. <a href="https://github.com/ipython-contrib/jupyter_contrib_nbextensions" rel="noreferrer">https://github.com/ipython-contrib/jupyter_contrib_nbextensions</a></p> <p>Is it possible to get this on JupyterLab?</p> <p>Thanks</p>
0debug
Observable returning value after method call finished : <p>getModel() method always return array with empty name array even when languages Observable returns value. why?</p> <pre><code> export interface Category extends BaseModel { code: string; name: LocalizedValue[]; description: LocalizedValue[]; active: boolean; } getAllLanguages(): Observable&lt;Language[]&gt; { // this return list of languages } protected getModel(): Category { let model: Category = { id: '', code: '', name: [], description: [], active: false, }; let nameField: LocalizedValue[] = []; this.languageService.getAllLanguages().subscribe(list =&gt; { list.forEach(l =&gt; { let n: LocalizedValue = { language: l.code, value: '', }; nameField.push(n); }); }); model.name = nameField; return model; } </code></pre>
0debug
int ff_h264_decode_picture_parameter_set(H264Context *h, int bit_length){ MpegEncContext * const s = &h->s; unsigned int pps_id= get_ue_golomb(&s->gb); PPS *pps; const int qp_bd_offset = 6*(h->sps.bit_depth_luma-8); int bits_left; if(pps_id >= MAX_PPS_COUNT) { av_log(h->s.avctx, AV_LOG_ERROR, "pps_id (%d) out of range\n", pps_id); return -1; } pps= av_mallocz(sizeof(PPS)); if(pps == NULL) return -1; pps->sps_id= get_ue_golomb_31(&s->gb); if((unsigned)pps->sps_id>=MAX_SPS_COUNT || h->sps_buffers[pps->sps_id] == NULL){ av_log(h->s.avctx, AV_LOG_ERROR, "sps_id out of range\n"); goto fail; } pps->cabac= get_bits1(&s->gb); pps->pic_order_present= get_bits1(&s->gb); pps->slice_group_count= get_ue_golomb(&s->gb) + 1; if(pps->slice_group_count > 1 ){ pps->mb_slice_group_map_type= get_ue_golomb(&s->gb); av_log(h->s.avctx, AV_LOG_ERROR, "FMO not supported\n"); switch(pps->mb_slice_group_map_type){ case 0: #if 0 | for( i = 0; i <= num_slice_groups_minus1; i++ ) | | | | run_length[ i ] |1 |ue(v) | #endif break; case 2: #if 0 | for( i = 0; i < num_slice_groups_minus1; i++ ) | | | |{ | | | | top_left_mb[ i ] |1 |ue(v) | | bottom_right_mb[ i ] |1 |ue(v) | | } | | | #endif break; case 3: case 4: case 5: #if 0 | slice_group_change_direction_flag |1 |u(1) | | slice_group_change_rate_minus1 |1 |ue(v) | #endif break; case 6: #if 0 | slice_group_id_cnt_minus1 |1 |ue(v) | | for( i = 0; i <= slice_group_id_cnt_minus1; i++ | | | |) | | | | slice_group_id[ i ] |1 |u(v) | #endif break; } } pps->ref_count[0]= get_ue_golomb(&s->gb) + 1; pps->ref_count[1]= get_ue_golomb(&s->gb) + 1; if(pps->ref_count[0]-1 > 32-1 || pps->ref_count[1]-1 > 32-1){ av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow (pps)\n"); goto fail; } pps->weighted_pred= get_bits1(&s->gb); pps->weighted_bipred_idc= get_bits(&s->gb, 2); pps->init_qp= get_se_golomb(&s->gb) + 26 + qp_bd_offset; pps->init_qs= get_se_golomb(&s->gb) + 26 + qp_bd_offset; pps->chroma_qp_index_offset[0]= get_se_golomb(&s->gb); pps->deblocking_filter_parameters_present= get_bits1(&s->gb); pps->constrained_intra_pred= get_bits1(&s->gb); pps->redundant_pic_cnt_present = get_bits1(&s->gb); pps->transform_8x8_mode= 0; h->dequant_coeff_pps= -1; memcpy(pps->scaling_matrix4, h->sps_buffers[pps->sps_id]->scaling_matrix4, sizeof(pps->scaling_matrix4)); memcpy(pps->scaling_matrix8, h->sps_buffers[pps->sps_id]->scaling_matrix8, sizeof(pps->scaling_matrix8)); bits_left = bit_length - get_bits_count(&s->gb); if(bits_left > 0){ pps->transform_8x8_mode= get_bits1(&s->gb); decode_scaling_matrices(h, h->sps_buffers[pps->sps_id], pps, 0, pps->scaling_matrix4, pps->scaling_matrix8); pps->chroma_qp_index_offset[1]= get_se_golomb(&s->gb); } else { pps->chroma_qp_index_offset[1]= pps->chroma_qp_index_offset[0]; } build_qp_table(pps, 0, pps->chroma_qp_index_offset[0], h->sps.bit_depth_luma); build_qp_table(pps, 1, pps->chroma_qp_index_offset[1], h->sps.bit_depth_luma); if(pps->chroma_qp_index_offset[0] != pps->chroma_qp_index_offset[1]) pps->chroma_qp_diff= 1; if(s->avctx->debug&FF_DEBUG_PICT_INFO){ av_log(h->s.avctx, AV_LOG_DEBUG, "pps:%u sps:%u %s slice_groups:%d ref:%d/%d %s qp:%d/%d/%d/%d %s %s %s %s\n", pps_id, pps->sps_id, pps->cabac ? "CABAC" : "CAVLC", pps->slice_group_count, pps->ref_count[0], pps->ref_count[1], pps->weighted_pred ? "weighted" : "", pps->init_qp, pps->init_qs, pps->chroma_qp_index_offset[0], pps->chroma_qp_index_offset[1], pps->deblocking_filter_parameters_present ? "LPAR" : "", pps->constrained_intra_pred ? "CONSTR" : "", pps->redundant_pic_cnt_present ? "REDU" : "", pps->transform_8x8_mode ? "8x8DCT" : "" ); } av_free(h->pps_buffers[pps_id]); h->pps_buffers[pps_id]= pps; return 0; fail: av_free(pps); return -1; }
1threat
Angular 4 setTimeout does not wait : <p>I am creating an angular 4 app with typescript.</p> <p>I'm having a function that needs to be executed every 10 seconds untill a specified stopcondition. I created a loop with some testcode using setTimeout to see if it would work. </p> <p>My Testcode:</p> <pre><code>public run() { let i = 0; while (i &lt; 4) { setTimeout(this.timer,3000); i++; } } public timer(){ console.log("done") } </code></pre> <p>However this seems to wait for 3 seconds, or browser is just slow... and then it prints 4 times done. So the code isn't working. Am I doing this wrong or are there other possibilities to do this kind of things?</p>
0debug
CodeName One Transitions : <p>I'm trying to transition part of a form, ie: when you click on a multiline button, just the content part of the form moves, while the header remains static. I'm not sure how to accomplish this or if it is possible. From what I can tell, you can do the whole form, but not parts?</p>
0debug
how to search by drop down list in ASP.NET MVC : I'm use ASP.NET MVC , I have student table in sql server and I want to do (search by) name and search by grade in student view by using dropdown list the problem is the search not working when i click on search button it's only refresh the page as it with all students. This is the student controller code public ActionResult Index(string searching,string searchby,int? page) { var student= db.Supervisors; if(searchby=="Name") return View(student.Where(x => x.name.Contains(searching)|| searching==null).ToList().ToPagedList(page ?? 1,8)); else return View(student.Where(x => x.grade.Contains(searching) || searching == null).ToList().ToPagedList(page ?? 1, 8)); } This is razor code @using (Html.BeginForm("Index", "student",FormMethod.Get)) { @Html.DropDownList("Searchby", new SelectList(new[] { "Name", "Grade" })) @Html.TextBox("search") <input type="submit" value="Search" /> }
0debug
Room: Receiving error when using @Transaction : <p>I'm have a method annotated with @Transaction in my DAO class, which is causing the following error:</p> <blockquote> <p>A DAO method can be annotated with only one of the following:Insert,Delete,Query,Update</p> </blockquote> <p>Here's my class:</p> <pre><code>@Dao interface Dao { @Insert(onConflict = REPLACE) fun insertList(chacaras: List&lt;String&gt;) @Query("SELECT * FROM chacara WHERE cityId = :cityId") fun getListOfCity(cityId: String): LiveData&lt;List&lt;String&gt;&gt; @Delete fun deleteList(chacaraList: List&lt;String&gt;) @Transaction fun updateList(list: List&lt;String&gt;){ deleteList(list) insertList(list) } } </code></pre> <p>When I remove the method annotated with @Transaction it compiles normally. Is there anyway to fix this?</p>
0debug
JSON: error expecting property name line 1 column 2 (char 1) : This may be a dumb question but I cannot figure it out for the life of me Please excuse my confusing variable naming I would be ecstatic ef anyone could tell me why the error in the title is happening and/or any other mistakes any my code import json import twitter a = twitter.get_account("@Suppert2") q = "cxdffcfctftcvft" ac = twitter.search(a,q, count=1, parameters=None) abg = str(ac) print (abg) ah = json.loads(abg) #here is where the error is accruing print ah["completed_in"] And when you print abg it comes out as: {u'search_metadata': {u'count': 1, u'completed_in': 0.048, u'max_id_str': u'718234026394443782', u'since_id_str': u'0', u'refresh_url': u'?since_id=718234026394443782&q=x597567654dfv&include_entities=1', u'since_id': 0, u'query': u'x597567654dfv', u'max_id': 718234026394443782L}, u'statuses': []} thank you for reading
0debug
redux-saga when to use fork? : <p>what would be the difference between the two approaches below?</p> <pre class="lang-js prettyprint-override"><code>export function* watchLoginUser() { yield takeEvery(USER_LOGIN, loginUser) } export function* watchLogoutUser() { yield takeEvery(USER_LOGOUT, logoutUser) } export function* watchGetParties() { yield takeEvery(PARTIES_GET, getParties) } export default function* root() { yield [ fork(watchLoginUser), fork(watchLogoutUser), fork(watchGetParties) ] } </code></pre> <pre class="lang-js prettyprint-override"><code>export default function* root() { yield [ takeEvery(USER_LOGIN, loginUser), takeEvery(USER_LOGOUT, logoutUser), takeEvery(PARTIES_GET, getParties) ] } </code></pre> <p>When do I need to use fork and when not?</p>
0debug
How to get current timestamp in nanoseconds in C++ without using chrono? : <p>Since chrono is not supported in the Network Simulator -3 tool, I need to code in C++ without using chrono in order to get timestamp in nanoseconds.</p>
0debug
SYNTH_FILTER_FUNC(sse2) SYNTH_FILTER_FUNC(avx) SYNTH_FILTER_FUNC(fma3) #endif av_cold void ff_synth_filter_init_x86(SynthFilterContext *s) { #if HAVE_YASM int cpu_flags = av_get_cpu_flags(); #if ARCH_X86_32 if (EXTERNAL_SSE(cpu_flags)) { s->synth_filter_float = synth_filter_sse; } #endif if (EXTERNAL_SSE2(cpu_flags)) { s->synth_filter_float = synth_filter_sse2; } if (EXTERNAL_AVX(cpu_flags)) { s->synth_filter_float = synth_filter_avx; } if (EXTERNAL_FMA3(cpu_flags)) { s->synth_filter_float = synth_filter_fma3; } #endif }
1threat
Advantages of using immutable.js over Object.assign or spread operators : <p>So far most of "starter boilerplates" and some posts about react / redux I've seen encourage usage of <a href="https://facebook.github.io/immutable-js/" rel="noreferrer">immutable.js</a> to address mutability. I personally rely on <code>Object.assign</code> or spread operators to handle this, hence don't really see advantage in immutable.js as it adds additional learning and shifts a bit from vanilla js techniques used for mutability. I was trying to find valid reasons for a switch, but wasn't able to hence I am asking here to see why it is so popular.</p>
0debug
Html pattern how to input specific character? : I need a input field only accpet string 6-10 Upper case and lower case <input type"text" pattern>
0debug
static void smbios_build_type_1_table(void) { SMBIOS_BUILD_TABLE_PRE(1, 0x100, true); SMBIOS_TABLE_SET_STR(1, manufacturer_str, type1.manufacturer); SMBIOS_TABLE_SET_STR(1, product_name_str, type1.product); SMBIOS_TABLE_SET_STR(1, version_str, type1.version); SMBIOS_TABLE_SET_STR(1, serial_number_str, type1.serial); if (qemu_uuid_set) { smbios_encode_uuid(&t->uuid, qemu_uuid); } else { memset(&t->uuid, 0, 16); } t->wake_up_type = 0x06; SMBIOS_TABLE_SET_STR(1, sku_number_str, type1.sku); SMBIOS_TABLE_SET_STR(1, family_str, type1.family); SMBIOS_BUILD_TABLE_POST; }
1threat
Flowtype - string incompatible with string enum : <p>I have a value that comes from a select input and is of type string, however I want to pass it into a function (<em>updateLanguage</em>) that receives as argument a string enum with a type alias (<em>Language</em>). </p> <p>The problem I'm facing is that Flow only allows me to call <em>updateLanguage</em> if I explicitly compare my string value with the enum strings and I want to use an array function like array.includes.</p> <p>This is a code simplification of my problem:</p> <pre><code>// @flow type SelectOption = { value: string }; const selectedOption: SelectOption = {value: 'en'}; type Language = 'en' | 'pt' | 'es'; const availableLanguages: Language[] = ['en', 'pt']; function updateLanguage(lang: Language) { // do nothing } // OK if(selectedOption.value === 'en' || selectedOption.value === 'pt') { updateLanguage(selectedOption.value); } // FLOWTYPE ERRORS if(availableLanguages.includes(selectedOption.value)) { updateLanguage(selectedOption.value); } </code></pre> <p>running flow v0.30.0 gives the following output:</p> <pre><code>example.js:21 21: if(availableLanguages.includes(selectedOption.value)) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ call of method `includes` 21: if(availableLanguages.includes(selectedOption.value)) { ^^^^^^^^^^^^^^^^^^^^ string. This type is incompatible with 9: const availableLanguages: Language[] = ['en', 'pt']; ^^^^^^^^ string enum example.js:22 22: updateLanguage(selectedOption.value); ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function call 22: updateLanguage(selectedOption.value); ^^^^^^^^^^^^^^^^^^^^ string. This type is incompatible with 11: function updateLanguage(lang: Language) { ^^^^^^^^ string enum Found 2 errors </code></pre> <p>How can I check that the string value is part of the enum in a scalable manner?</p>
0debug
JSON stringify ES6 class property with getter/setter : <p>I have a JavaScript ES6 class that has a property set with <code>set</code> and accessed with <code>get</code> functions. It is also a constructor parameter so the class can be instantiated with said property.</p> <pre><code>class MyClass { constructor(property) { this.property = property } set property(prop) { // Some validation etc. this._property = prop } get property() { return this._property } } </code></pre> <p>I use <code>_property</code> to escape the JS gotcha of using get/set that results in an infinite loop if I set directly to <code>property</code>.</p> <p>Now I need to stringify an instance of MyClass to send it with a HTTP request. The stringified JSON is an object like:</p> <pre><code>{ //... _property: } </code></pre> <p>I need the resulting JSON string to preserve <code>property</code> so the service I am sending it to can parse it correctly. I also need <code>property</code> to remain in the constructor because I need to construct instances of MyClass from JSON sent by the service (which is sending objects with <code>property</code> not <code>_property</code>).</p> <p>How do I get around this? Should I just intercept the MyClass instance before sending it to the HTTP request and mutate <code>_property</code> to <code>property</code> using regex? This seems ugly, but I will be able to keep my current code.</p> <p>Alternatively I can intercept the JSON being sent to the client from the service and instantiate MyClass with a totally different property name. However this means a different representation of the class either side of the service.</p>
0debug
Is there a generic way to avoid HTML content in ADF input fields : <p>My application is developed using Oracle ADF. I'm using <code>&lt;af:inputText&gt;</code> input fields in my forms.</p> <p>Here I have to avoid HTML content in input fields. Is there a way in ADF to avoid HTML content in form input fields.</p>
0debug
static void cmd_mode_sense(IDEState *s, uint8_t *buf) { int action, code; int max_len; if (buf[0] == GPCMD_MODE_SENSE_10) { max_len = ube16_to_cpu(buf + 7); } else { max_len = buf[4]; } action = buf[2] >> 6; code = buf[2] & 0x3f; switch(action) { case 0: switch(code) { case MODE_PAGE_R_W_ERROR: cpu_to_ube16(&buf[0], 16 + 6); buf[2] = 0x70; buf[3] = 0; buf[4] = 0; buf[5] = 0; buf[6] = 0; buf[7] = 0; buf[8] = MODE_PAGE_R_W_ERROR; buf[9] = 16 - 10; buf[10] = 0x00; buf[11] = 0x05; buf[12] = 0x00; buf[13] = 0x00; buf[14] = 0x00; buf[15] = 0x00; ide_atapi_cmd_reply(s, 16, max_len); break; case MODE_PAGE_AUDIO_CTL: cpu_to_ube16(&buf[0], 24 + 6); buf[2] = 0x70; buf[3] = 0; buf[4] = 0; buf[5] = 0; buf[6] = 0; buf[7] = 0; buf[8] = MODE_PAGE_AUDIO_CTL; buf[9] = 24 - 10; buf[17] = 0; buf[19] = 0; buf[21] = 0; buf[23] = 0; ide_atapi_cmd_reply(s, 24, max_len); break; case MODE_PAGE_CAPABILITIES: cpu_to_ube16(&buf[0], 28 + 6); buf[2] = 0x70; buf[3] = 0; buf[4] = 0; buf[5] = 0; buf[6] = 0; buf[7] = 0; buf[8] = MODE_PAGE_CAPABILITIES; buf[9] = 28 - 10; buf[10] = 0x00; buf[11] = 0x00; buf[12] = 0x71; buf[13] = 3 << 5; buf[14] = (1 << 0) | (1 << 3) | (1 << 5); if (s->tray_locked) { buf[6] |= 1 << 1; } buf[15] = 0x00; cpu_to_ube16(&buf[16], 706); buf[18] = 0; buf[19] = 2; cpu_to_ube16(&buf[20], 512); cpu_to_ube16(&buf[22], 706); buf[24] = 0; buf[25] = 0; buf[26] = 0; buf[27] = 0; ide_atapi_cmd_reply(s, 28, max_len); break; default: goto error_cmd; } break; case 1: goto error_cmd; case 2: goto error_cmd; default: case 3: ide_atapi_cmd_error(s, ILLEGAL_REQUEST, ASC_SAVING_PARAMETERS_NOT_SUPPORTED); break; } return; error_cmd: ide_atapi_cmd_error(s, ILLEGAL_REQUEST, ASC_INV_FIELD_IN_CMD_PACKET); }
1threat
static int wsaud_read_packet(AVFormatContext *s, AVPacket *pkt) { AVIOContext *pb = s->pb; unsigned char preamble[AUD_CHUNK_PREAMBLE_SIZE]; unsigned int chunk_size; int ret = 0; AVStream *st = s->streams[0]; if (avio_read(pb, preamble, AUD_CHUNK_PREAMBLE_SIZE) != AUD_CHUNK_PREAMBLE_SIZE) return AVERROR(EIO); if (AV_RL32(&preamble[4]) != AUD_CHUNK_SIGNATURE) return AVERROR_INVALIDDATA; chunk_size = AV_RL16(&preamble[0]); if (st->codec->codec_id == AV_CODEC_ID_WESTWOOD_SND1) { int out_size = AV_RL16(&preamble[2]); if ((ret = av_new_packet(pkt, chunk_size + 4))) return ret; if ((ret = avio_read(pb, &pkt->data[4], chunk_size)) != chunk_size) return ret < 0 ? ret : AVERROR(EIO); AV_WL16(&pkt->data[0], out_size); AV_WL16(&pkt->data[2], chunk_size); pkt->duration = out_size; } else { ret = av_get_packet(pb, pkt, chunk_size); if (ret != chunk_size) return AVERROR(EIO); pkt->duration = (chunk_size * 2) / st->codec->channels; } pkt->stream_index = st->index; return ret; }
1threat
The real difference between float32 and float64 : <p>I want to understand the actual difference between <code>float16</code> and <code>float32</code> in terms of the result precision. For instance, <code>Numpy</code> allows you to choose the range of the datatype you want <code>(np.float16, np.float32, np.float64)</code>. My concern is that if I decide to go with float 16 to reserve memory and avoid possible overflow, would that create a loss of the final results comparing with float32 for instance?</p> <p>Thank you</p>
0debug
getting the error that location_marker.addListener is not a function? : function initAutocomplete() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: 31.7917 , lng: 7.0926}, zoom: 3, mapTypeId: 'roadmap' }); >initialize map var location_marker; for (var i = 0; i < locations.length; i++) { location_marker = markers.push(new google.maps.Marker({ map: map, title: locations[i].title, position: locations[i].location })); } > running through a list of locations and placing a marker for each var infowindow = new google.maps.InfoWindow({ content: location_marker.title }); location_marker.addListener('click', function() { infowindow.open(map, location_marker); }); }; > create an info window that displays every marker's title getting the error that location_marker.addListener is not a function, even though the syntax looks correct
0debug
How to transform String[] into collection? : <p>I am trying to get a String Collection in my Java code, so i'm trying something like this:</p> <pre><code>Collection c = new String[]{}; </code></pre> <p>But i get this error: <code>incompatible types: String[] cannot be converted to Collection</code>.<br> Is there a way to convert <strong>String[]</strong> into <strong>Collection</strong> without doing something like this:</p> <pre><code>var array = new String[]{"Apple", "Banana"}; var arrayList = new ArrayList&lt;String&gt;(); for (String fruit : array) { arrayList.add(fruit); } Collection c = arrayList; </code></pre>
0debug
SQL query: How to join two different tables in one query : i have two tables grades and scholars. grades has fields: id, subject_code, subject_description,midterm, final, and final_remarks AND scholars has fields:id, Id Number, Lastname,Firstname, Middlename ,School, Year, Semester, Course,Action how can i join them? i wanna get the subject_code, subject_description,midterm, final, and final_remarks from grades and fullname from scholars? THANK YOU!PLEASE HELP ME WITH THIS.
0debug
How to print i and i+1 in for-loop in android? : I have an array full of names. Im using a for-loop to print my names but the problem is that i want to print 2 names: i(the name) and i+1(the next name). you may not get what i said, look at my code: My code: ======= "text" is my textview and "people" is the array: for (int i=0; i< people.size(); i = i+2) { text.append(people.get(i) + " with " + people.get(i+1)); } ## the problem is it prints this: ## (these are the names in the array : "Kim","John","Sam","Edison") Kim with Kim Sam with Sam ### instead of this : ### Kim with John Sam with Edison
0debug
Hide powershell output : <p>I have the following script:</p> <p>param([Parameter(Mandatory=$true)][string]$dest)</p> <pre><code>New-Item -force -path "$dest\1\" -itemtype directory New-Item -force -path "$dest\2\" -itemtype directory New-Item -force -path "$dest\3\" -itemtype directory Copy-Item -path "C:\Development\1\bin\Debug\*" -destination "$dest\1\" -container -recurse -force Copy-Item -path "C:\Development\2\bin\Debug\*" -destination "$dest\2\" -container -recurse -force Copy-Item -path "C:\Development\3\bin\Debug\*" -destination "$dest\3\" -container -recurse -force </code></pre> <p>The script takes a string and copies all files and folders from the static origin path to the given root string, amending some folders for structure clarity.</p> <p>It works fine but prints out the results from the "New-Item" commands and I would like to hide that. I've looked at the net and other questions on SE but no definitive answers to my problem were found.</p> <p>In case someone is wondering - I am using "New-item" at the beginning in order to circumvent a flaw in PS' -recurse parameter not copying all subfolders correctly if the destination folder does not exist. (I.e. they are mandatory)</p>
0debug
static int configure_video_filters(AVFilterGraph *graph, VideoState *is, const char *vfilters) { static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE }; char sws_flags_str[128]; char buffersrc_args[256]; int ret; AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc(); AVFilterContext *filt_src = NULL, *filt_out = NULL, *filt_format, *filt_crop; AVCodecContext *codec = is->video_st->codec; snprintf(sws_flags_str, sizeof(sws_flags_str), "flags=%d", sws_flags); graph->scale_sws_opts = av_strdup(sws_flags_str); snprintf(buffersrc_args, sizeof(buffersrc_args), "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d", codec->width, codec->height, codec->pix_fmt, is->video_st->time_base.num, is->video_st->time_base.den, codec->sample_aspect_ratio.num, codec->sample_aspect_ratio.den); if ((ret = avfilter_graph_create_filter(&filt_src, avfilter_get_by_name("buffer"), "ffplay_buffer", buffersrc_args, NULL, graph)) < 0) return ret; buffersink_params->pixel_fmts = pix_fmts; ret = avfilter_graph_create_filter(&filt_out, avfilter_get_by_name("ffbuffersink"), "ffplay_buffersink", NULL, buffersink_params, graph); av_freep(&buffersink_params); if (ret < 0) return ret; if ((ret = avfilter_graph_create_filter(&filt_crop, avfilter_get_by_name("crop"), "ffplay_crop", "floor(in_w/2)*2:floor(in_h/2)*2", NULL, graph)) < 0) return ret; if ((ret = avfilter_graph_create_filter(&filt_format, avfilter_get_by_name("format"), "format", "yuv420p", NULL, graph)) < 0) return ret; if ((ret = avfilter_link(filt_crop, 0, filt_format, 0)) < 0) return ret; if ((ret = avfilter_link(filt_format, 0, filt_out, 0)) < 0) return ret; if ((ret = configure_filtergraph(graph, vfilters, filt_src, filt_crop)) < 0) return ret; is->in_video_filter = filt_src; is->out_video_filter = filt_out; return ret; }
1threat
Should I share the Materializer instance or always create a new one when needed? : <p>I'm currently working on a project that extensively uses Akka and Akka Streams.</p> <p>One question/problem keeps coming up while working with it: What is the best practice for the Materializer which is needed in all places where streams are used. Especially when I'm inside an Actor, where I only can access the ActorSystem, should I manually pass in an existing Materializer instance or just create one when I need it?</p> <p>I'm especially worried about the resource usage and performance when instantiating Materializers on demand.</p>
0debug
Laravel get file content : <pre><code>Route::get('marquee', function(){ echo File::get('\storage\app\marquee.json'); }); </code></pre> <p>I have a json file place inside storage/app</p> <p>My question is how can I read this content from controller or route?</p>
0debug
Sass-loader requires node-sass >=4 even if that exist : <p>I executed a update to angular 6. And during ng serve -o I receive error that sass-loader expect node-sass. After run ng serve -o I receive:</p> <pre><code>ERROR in ./src/sass/styles.scss (./node_modules/raw-loader!./node_modules/postcss-loader/lib??embedded!./node_modules/sass-loader/lib/loader.js??ref--14-3!./src/sass/styles.scss) Module build failed: Error: `sass-loader` requires `node-sass` &gt;=4. Please install a compatible version. at Object.sassLoader (node_modules\sass-loader\lib\loader.js:31:19) ERROR in ./src/app/app.component.scss Module build failed: Error: `sass-loader` requires `node-sass` &gt;=4. Please install a compatible version. at Object.sassLoader (node_modules\sass-loader\lib\loader.js:31:19) ERROR in x.component.scss Module build failed: Error: `sass-loader` requires `node-sass` &gt;=4. Please install a compatible version. at Object.sassLoader (\node_modules\sass-loader\lib\loader.js:31:19) ERROR in x.component.scss Module build failed: Error: `sass-loader` requires `node-sass` &gt;=4. Please install a compatible version. at Object.sassLoader (loader.js:31:19) ERROR in .x.component.scss Module build failed: Error: `sass-loader` requires `node-sass` &gt;=4. Please install a compatible version. at Object.sassLoader (node_modules\sass-loader\lib\loader.js:31:19) </code></pre> <p>Obvisously I check everything (in my opinion) and I don't have idea what's going on.</p> <p>Package.Json:</p> <pre><code>"devDependencies": { "@angular-devkit/build-angular": "~0.6.0", "@angular/cli": "6.0.0", "@angular/compiler-cli": "6.0.0", "@angular/language-service": "6.0.0", "@types/jasmine": "~2.8.3", "@types/jasminewd2": "~2.0.2", "@types/node": "~6.0.106", "codelyzer": "^4.0.1", "jasmine-core": "~2.8.0", "jasmine-spec-reporter": "~4.2.1", "karma": "~2.0.0", "karma-chrome-launcher": "~2.2.0", "karma-html-detailed-reporter": "^1.1.21", "karma-jasmine": "~1.1.0", "karma-jasmine-html-reporter": "^0.2.2", "karma-phantomjs-launcher": "^1.0.4", "karma-teamcity-reporter": "^1.1.0", "phantomjs-prebuilt": "^2.1.16", "protractor": "~5.1.2", "node-sass": "^4.9.0", "sass-loader": "^7.0.1", "ts-node": "~4.1.0", "tslint": "~5.9.1", "typescript": "2.7.2" } </code></pre> <p>dir -l node_modules says:</p> <pre><code>... 05/07/2018 08:53 AM &lt;DIR&gt; node-sass ... 05/07/2018 08:53 AM &lt;DIR&gt; sass-loader ... </code></pre> <p>I executed:</p> <pre><code>npm rebuild node-sass </code></pre> <p>and secod approach: I removed local node-module together with %User%\AppData\Roaming\npm-cache. then I removed lock file and execuded npm </p> <pre><code>npm cache clear --force npm install </code></pre> <p>But still no success.</p> <p>What do I miss ?</p>
0debug
Why does the Formatter(String fileName) constructor not work without handling FileNotFoundException? : <p>The constructor Formatter(String fileName) doesn't seem to compile when I don't handle FileNotFoundException even if the file already exists.</p> <p>Here's the code that works:</p> <pre><code>import java.util.*; public class CreatingFiles { public static void main(String[] args) { final Formatter MYFILE; try { MYFILE = new Formatter("john.txt"); System.out.println("File created"); } catch (Exception e) { System.out.println("Error!"); } } } </code></pre> <p>However when I remove the try/catch block:</p> <pre><code>import java.util.*; public class CreatingFiles { public static void main(String[] args) { final Formatter MYFILE; MYFILE = new Formatter("john.txt"); } } </code></pre> <p>The compiler tells me that I have to either throw or catch the exception. So why doesn't it work without handling the exception?</p>
0debug
How to change color of vector drawable path on button click : <p>With the new android support update, vector drawables get backward compatibility. I have a vector image with various paths. I want the color of the paths to change on click of a button or programmatically based on an input value. Is it possible to access the name parameter of the vector path? And then change the color.</p>
0debug
static void coroutine_fn aio_read_response(void *opaque) { SheepdogObjRsp rsp; BDRVSheepdogState *s = opaque; int fd = s->fd; int ret; AIOReq *aio_req = NULL; SheepdogAIOCB *acb; uint64_t idx; ret = qemu_co_recv(fd, &rsp, sizeof(rsp)); if (ret != sizeof(rsp)) { error_report("failed to get the header, %s", strerror(errno)); goto err; } QLIST_FOREACH(aio_req, &s->inflight_aio_head, aio_siblings) { if (aio_req->id == rsp.id) { break; } } if (!aio_req) { error_report("cannot find aio_req %x", rsp.id); goto err; } acb = aio_req->aiocb; switch (acb->aiocb_type) { case AIOCB_WRITE_UDATA: s->co_recv = NULL; if (!is_data_obj(aio_req->oid)) { break; } idx = data_oid_to_idx(aio_req->oid); if (s->inode.data_vdi_id[idx] != s->inode.vdi_id) { if (rsp.result == SD_RES_SUCCESS) { s->inode.data_vdi_id[idx] = s->inode.vdi_id; s->max_dirty_data_idx = MAX(idx, s->max_dirty_data_idx); s->min_dirty_data_idx = MIN(idx, s->min_dirty_data_idx); } send_pending_req(s, aio_req->oid); } break; case AIOCB_READ_UDATA: ret = qemu_co_recvv(fd, acb->qiov->iov, acb->qiov->niov, aio_req->iov_offset, rsp.data_length); if (ret != rsp.data_length) { error_report("failed to get the data, %s", strerror(errno)); goto err; } break; case AIOCB_FLUSH_CACHE: if (rsp.result == SD_RES_INVALID_PARMS) { DPRINTF("disable cache since the server doesn't support it\n"); s->cache_flags = SD_FLAG_CMD_DIRECT; rsp.result = SD_RES_SUCCESS; } break; case AIOCB_DISCARD_OBJ: switch (rsp.result) { case SD_RES_INVALID_PARMS: error_report("sheep(%s) doesn't support discard command", s->host_spec); rsp.result = SD_RES_SUCCESS; s->discard_supported = false; break; case SD_RES_SUCCESS: idx = data_oid_to_idx(aio_req->oid); s->inode.data_vdi_id[idx] = 0; break; default: break; } } switch (rsp.result) { case SD_RES_SUCCESS: break; case SD_RES_READONLY: if (s->inode.vdi_id == oid_to_vid(aio_req->oid)) { ret = reload_inode(s, 0, ""); if (ret < 0) { goto err; } } if (is_data_obj(aio_req->oid)) { aio_req->oid = vid_to_data_oid(s->inode.vdi_id, data_oid_to_idx(aio_req->oid)); } else { aio_req->oid = vid_to_vdi_oid(s->inode.vdi_id); } resend_aioreq(s, aio_req); goto out; default: acb->ret = -EIO; error_report("%s", sd_strerror(rsp.result)); break; } free_aio_req(s, aio_req); if (!acb->nr_pending) { acb->aio_done_func(acb); } out: s->co_recv = NULL; return; err: s->co_recv = NULL; reconnect_to_sdog(opaque); }
1threat
Missing response body from 422 in c# : <p>I am helping a user get integrated with my API and he is using C# to do so. If he sends me malformed JSON I send him a 422 and then send him the reason for the failure of his request in the response body. The response body seems to be missing in the web exception so he never gets the reason for his error and can't correct it. Where is this response body can I get the WebClient not to throw and exception just because the status code in the response is negative?</p> <pre><code>using (var clientRequest = new WebClient()) { clientRequest.Headers[HttpRequestHeader.ContentType] = "application/json"; clientRequest.Headers[HttpRequestHeader.Authorization] = "Token token=" + APITOKEN; try { jsonResponse = clientRequest.UploadString(apiMethodUrl, "POST", json); Console.WriteLine("REcived Message from the server"); Console.WriteLine(jsonResponse); Console.WriteLine("See the MEssage"); } catch (WebException ex) { Console.WriteLine(ex.Message); } } </code></pre> <p>Can someone help?</p>
0debug
void bdrv_get_geometry_hint(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs) { *pcyls = bs->cyls; *pheads = bs->heads; *psecs = bs->secs; }
1threat
super slow node npm commands : <p>I have node v.4.4 with npm v.2.14.20 (default bundled with windows installer). My OS: Windows 7 64bit. Hardware: Dell laptop, 16GB RAM, SSD, core i7.</p> <p>I'm facing a problem with extremely slow npm. For example when I want to check version of node with</p> <pre><code>node --version v4.4.0 </code></pre> <p>I receive output <code>4.4.0</code> within miliseconds. But when I type</p> <pre><code>npm --version </code></pre> <p>I need to wait ridiculous <strong>8-15 seconds</strong> to receive an output! And it's the same with every single npm command. </p> <p>What i tried: update npm (to most recent 3.x version), update node to 5.9.0, i also tried my luck with x86 versions - same thing.</p> <ol> <li>Any clues what can cause such "sleep" (it's only with <code>npm</code>, every other cmd command works fine, system works fine)?</li> <li>I will appreciate any tips how I can debug this thing to see what's going on under the hood</li> </ol>
0debug
void OPPROTO op_addq_ESI_T0(void) { ESI = (ESI + T0); }
1threat
void qmp_block_commit(const char *device, bool has_base, const char *base, const char *top, bool has_speed, int64_t speed, Error **errp) { BlockDriverState *bs; BlockDriverState *base_bs, *top_bs; Error *local_err = NULL; BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT; bdrv_drain_all(); bs = bdrv_find(device); if (!bs) { error_set(errp, QERR_DEVICE_NOT_FOUND, device); return; } if (base && has_base) { base_bs = bdrv_find_backing_image(bs, base); } else { base_bs = bdrv_find_base(bs); } if (base_bs == NULL) { error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL"); return; } top_bs = bs; if (top) { if (strcmp(bs->filename, top) != 0) { top_bs = bdrv_find_backing_image(bs, top); } } if (top_bs == NULL) { error_setg(errp, "Top image file %s not found", top ? top : "NULL"); return; } commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs, &local_err); if (local_err != NULL) { error_propagate(errp, local_err); return; } drive_get_ref(drive_get_by_blockdev(bs)); }
1threat
vdi_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags) { BDRVVdiState *s = bs->opaque; QEMUIOVector local_qiov; uint32_t bmap_entry; uint32_t block_index; uint32_t offset_in_block; uint32_t n_bytes; uint32_t bmap_first = VDI_UNALLOCATED; uint32_t bmap_last = VDI_UNALLOCATED; uint8_t *block = NULL; uint64_t bytes_done = 0; int ret = 0; logout("\n"); qemu_iovec_init(&local_qiov, qiov->niov); while (ret >= 0 && bytes > 0) { block_index = offset / s->block_size; offset_in_block = offset % s->block_size; n_bytes = MIN(bytes, s->block_size - offset_in_block); logout("will write %u bytes starting at offset %" PRIu64 "\n", n_bytes, offset); bmap_entry = le32_to_cpu(s->bmap[block_index]); if (!VDI_IS_ALLOCATED(bmap_entry)) { uint64_t data_offset; bmap_entry = s->header.blocks_allocated; s->bmap[block_index] = cpu_to_le32(bmap_entry); s->header.blocks_allocated++; data_offset = s->header.offset_data + (uint64_t)bmap_entry * s->block_size; if (block == NULL) { block = g_malloc(s->block_size); bmap_first = block_index; } bmap_last = block_index; memset(block, 0, offset_in_block); qemu_iovec_to_buf(qiov, bytes_done, block + offset_in_block, n_bytes); memset(block + offset_in_block + n_bytes, 0, s->block_size - n_bytes - offset_in_block); qemu_co_mutex_lock(&s->write_lock); ret = bdrv_pwrite(bs->file, data_offset, block, s->block_size); qemu_co_mutex_unlock(&s->write_lock); } else { uint64_t data_offset = s->header.offset_data + (uint64_t)bmap_entry * s->block_size + offset_in_block; qemu_co_mutex_lock(&s->write_lock); qemu_co_mutex_unlock(&s->write_lock); qemu_iovec_reset(&local_qiov); qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes); ret = bdrv_co_pwritev(bs->file, data_offset, n_bytes, &local_qiov, 0); } bytes -= n_bytes; offset += n_bytes; bytes_done += n_bytes; logout("%u bytes written\n", n_bytes); } qemu_iovec_destroy(&local_qiov); logout("finished data write\n"); if (ret < 0) { return ret; } if (block) { VdiHeader *header = (VdiHeader *) block; uint8_t *base; uint64_t offset; uint32_t n_sectors; logout("now writing modified header\n"); assert(VDI_IS_ALLOCATED(bmap_first)); *header = s->header; vdi_header_to_le(header); ret = bdrv_write(bs->file, 0, block, 1); g_free(block); block = NULL; if (ret < 0) { return ret; } logout("now writing modified block map entry %u...%u\n", bmap_first, bmap_last); bmap_first /= (SECTOR_SIZE / sizeof(uint32_t)); bmap_last /= (SECTOR_SIZE / sizeof(uint32_t)); n_sectors = bmap_last - bmap_first + 1; offset = s->bmap_sector + bmap_first; base = ((uint8_t *)&s->bmap[0]) + bmap_first * SECTOR_SIZE; logout("will write %u block map sectors starting from entry %u\n", n_sectors, bmap_first); ret = bdrv_write(bs->file, offset, base, n_sectors); } return ret; }
1threat
Create "Karaoke" Type Functionality in DraftJS : <p>I am attempting to implement a DraftJS editor that highlights words in a transcription while its recorded audio is playing (kind of like karaoke).</p> <p>I receive the data in this format:</p> <pre><code>[ { transcript: "This is the first block", timestamps: [0, 1, 2.5, 3.2, 4.1, 5], }, { transcript: "This is the second block. Let's sync the audio with the words", timestamps: [6, 7, 8.2, 9, 10, 11.3, 12, 13, 14, 15, 16, 17.2], }, ... ] </code></pre> <p>I then map this received data to <code>ContentBlocks</code> and initialize the editor's <code>ContentState</code> with them by using <code>ContentState.createFromBlockArray(blocks)</code></p> <p>It seems like the "DraftJS" way of storing the timestamp metadata would be to create an <code>Entity</code> for each word with its respective timestamp, and then scan through the <code>currentContent</code> as the audio plays and highlight entities up until the current elapsed time. But I am not sure if this is the right way to do this, as it doesn't seem performant for large transcriptions.</p> <p>Note: the transcript needs to remain editable while maintaining this karaoke functionality</p> <p>Any help or discussion is appreciated!</p>
0debug
Initializer for conditional binding must have Optional type, not 'NSNumber' in swift3 code executing in xcode10 : getting error in below code - Initializer for conditional binding must have Optional type, not 'NSNumber' if let MId = (M as AnyObject).gid { if let id = MId { fetchvalue(id, limit: limit, delegate: delegate) } } please help me
0debug
The SQL Server Network Interface library could not deregister the Service Principal Name (SPN) : <p>I've set up a SQL Server service account with permissions to read and write service principal names. When SQL Server starts up I get the expected message in the logs showing that the service account has successfully registered the SPN:</p> <blockquote> <p>The SQL Server Network Interface library successfully registered the Service Principal Name (SPN) [MySPN] for the SQL Server service.</p> </blockquote> <p>Connections to the database server use Kerberos authentication as expected and all seems well.</p> <p>However, when I shut down SQL Server a message is entered in the logs showing that the SPN could not be deregistered:</p> <blockquote> <p>The SQL Server Network Interface library could not deregister the Service Principal Name (SPN) [MySPN] for the SQL Server service. Error: 0x6d3, state: 4. Administrator should deregister this SPN manually to avoid client authentication errors.</p> </blockquote> <p>I've checked that there are no duplicate SPNs and checked that the SPN is registered to the correct service account, and only to that account. The server has been rebooted several times. Microsoft's Kerberos Config Manager doesn't offer any insight.</p> <p>I don't understand why the service account would be permitted to create the SPN but not permitted to delete it.</p>
0debug
How do i get this in my website? : [I want something like this in my website. What is it called? How can i include something like this. I need all those Options too.][1] [1]: http://i.stack.imgur.com/I2rMN.jpg
0debug
Using tqdm progress bar in a while loop : <p>I am making a code that simulates a pawn going around a monopoly board a million times. I would like to have a tqdm progress bar that is updated every time a turn around the board is achieved.</p> <p><strong>Below is my current code.</strong> I am using a while loop which stops when the number of turns around the board surpasses the desired number.</p> <pre><code>import os from openpyxl import Workbook from monopolyfct import * def main(runs, fileOutput): ### EXCEL SETUP ### theWorkbook = Workbook() # Creates the workbook interface. defaultSheet = theWorkbook.active # Creates the used worksheet. currentData = ["Current Table Turn", "Current Tile"] # Makes EXCEL column titles. defaultSheet.append(currentData) # Appends column titles. ### CONTENT SETUP ### currentData = [1, 0] # Sets starting position. defaultSheet.append(currentData) # Appends starting position. while currentData[0] &lt;= runs: ### ROLLING THE DICES PROCESS ### dices = twinDiceRoll() currentData[1] += dices[2] # Updating the current tile ### SURPASSING THE NUMBER OF TILES ONBOARD ### if currentData[1] &gt; 37: # If more than a table turn is achieved, currentData[0] += 1 # One more turn is registered currentData[1] -= 38 # Update the tile to one coresponding to a board tile. else: pass ### APPENDING AQUIRED DATA ### defaultSheet.append(currentData) ### MANAGIING SPECIAL TILES ### if currentData[1] == 2 or 15 or 31: # Community chess pass #TODO: Make a mechanic simulating the community chest card draw and it's related action. elif currentData[1] == 5 or 20 or 34: # Chance pass #TODO: Make a mechanic simulating the chance card draw and it's related action. elif currentData[1] == 28: # Go to Jail pass #TODO: Make a mechanic simulating the entire jail process ### TWIN DICE ROLL EXCEPTION ### if dices[3] is True: # If the dices roll a double, pass #TODO: Make a mechanic considering that three doubles sends one to Jail. ### STORING THE ACCUMULATED DATA ### theWorkbook.save(fileOutput) # Compiles the data in a .xlxs file. if __name__ == "__main__": terminalWidth = os.get_terminal_size().columns # Gets current terminal width. space(3) print("Python Monopoly Statistics Renderer".upper().center(terminalWidth)) # Prints the title. print("(PMSR)".center(terminalWidth)) # Prints the acronym. space(2) runs = int(request("For how many table turns do you want the simulation to run?")) # Prompts for the desired run ammount #runs = 1000 fileOutput = request("What should be the name of the file in which statistics are stored?") # Prompts for the desired store filename #fileOutput = "test" fileOutput += ".xlsx" # Adds file extension to filename main(runs, fileOutput) </code></pre>
0debug
public static void println(int[] seq) : public static void println(int[] seq) Post: Print the values in seq on 1 line, separated by a space. After that the cursor should be on the next line. ex: println(new int[]{1, 2}) → 1 2
0debug
am i making synchronous call for this service and using that service properly in controller. please help me : > my brother said to write synchronous call for service and below > getting error. can u please explain and give me the right one, thanks > you. below i gave my angular service and Controller > my brother said to write synchronous call for service and below > getting error. can u please explain and give me the right one, thanks > you. below i gave my angular service and Controller <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> app.service("StateService", function ($http, $q) { var factory = $q.defer(); factory.getStateData = function () { return $http.get("/State/GetStateData") .then(function (response) { factory.resolve(response.data); return factory.promise; }, function (response) { factory.reject(response); return factory.promise; }); }; factory.getCountryById = function (Id) { return $http.post('/Country/GetCountryById?Id=' + Id) .then(function (response) { factory.resolve(response.data); return factory.promise; }, function (response) { factory.reject(response); return factory.promise; }); }; }; app.controller("statecontroller", function ($scope, StateService, $http, $timeout) { // get function $scope.GetStateData = function () { StateService.getStateData().then(function (d) { $scope.States = d.data; $scope.fillAllData(); }, function (response) { alert('error occurred' + response.data.ExceptionMesage); }); }; $scope.fillAllData = function () { for (var i = 0; i < $scope.States.length; i++) { if ($scope.States[i].CountryId) { // var val = $scope.GetCountryById($scope.States[i].CountryId); var cName = ""; var Id = $scope.States[i].CountryId; StateService.getCountryById(Id).then(function (d) { if (d.data) cName = d.data.CountryName; }, function (response) { console.log('error occurred' + response.data.ExceptionMesage); }); $scope.States[i].CountryName = cName; } else $scope.States[i].CountryName = null; } } }; <!-- end snippet -->
0debug
How can I do this program with arrays? : <p>I have a doubt with a problem about arrays, I have array that only recieves 1 and 0, for example {0,1,0,1,0}, after that I need to select 2 positions inside of the array, in this case p1 = 0 and p2=2, then I need to print the number between p1 and p2, in this case 010, after that I need convert that numer to decimal, how can I do that? Im a beginner, really I tried but I can't did it</p>
0debug
Chrome Custom Tabs redirect to Android app will close the app : <p>I am trying to implement an OAuth2 flow with an Android Chrome Custom Tab but my app is always closed (no crash) when the Chrome Custom Tab is receiving the 302 with the location/scheme of my app.</p> <p>If I create a HTML page with ahref link and touch manually on it the Chrome Custom Tab is correctly switching to my app.</p> <p>Seems like when handling the server 302 redirect in the Chrome Custom Tab it will not correctly handle my custom app scheme... but why? </p> <p>If I try the same redirect URL in a stock browser or with a WebView everything is working too.</p> <p>Here is my current setup:</p> <p>MainActiviy.java</p> <pre><code> Button btnChromeCustomTab = (Button) findViewById(R.id.btnChromeCustomTab); btnChromeCustomTab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder().build(); String packageName = CustomTabsHelper.getPackageNameToUse(MainActivity.this); customTabsIntent.intent.setPackage(packageName); Uri theLocationUri = Uri.parse(URL); customTabsIntent.launchUrl(MainActivity.this, theLocationUri); } }); </code></pre> <p>AndroidManifest.xml</p> <pre><code> &lt;activity android:name=".MainActivity" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;intent-filter android:label="@string/filter_title"&gt; &lt;action android:name="android.intent.action.VIEW" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;category android:name="android.intent.category.BROWSABLE" /&gt; &lt;data android:scheme="myappscheme" android:host="oauth" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; </code></pre> <p>This is the redirect URL that the app received with HTTP 302 code: </p> <p>myappscheme://oauth?code=1234567&amp;state=tokenCheck123</p> <p>build.gradle</p> <pre><code>android { compileSdkVersion 23 buildToolsVersion "23.0.2" defaultConfig { applicationId "de.myapptest.webviewtest" minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "1.0" } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.2.1' compile 'com.android.support:design:23.2.1' compile 'com.android.support:customtabs:23.0.0+' } </code></pre> <p>Thanks for any help...</p>
0debug
static int mp3info(void *data, int *byteSize, int *samplesPerFrame, int *sampleRate, int *isMono ) { uint8_t *dataTmp = (uint8_t *)data; uint32_t header = ( (uint32_t)dataTmp[0] << 24 ) | ( (uint32_t)dataTmp[1] << 16 ) | ( (uint32_t)dataTmp[2] << 8 ) | (uint32_t)dataTmp[3]; int layerID = 3 - ((header >> 17) & 0x03); int bitRateID = ((header >> 12) & 0x0f); int sampleRateID = ((header >> 10) & 0x03); int bitRate = 0; int bitsPerSlot = sBitsPerSlot[layerID]; int isPadded = ((header >> 9) & 0x01); if ( (( header >> 21 ) & 0x7ff) != 0x7ff ) { return 0; } if ( !isPadded ) { printf("Fatal error: mp3 data is not padded!\n"); exit(0); } *isMono = ((header >> 6) & 0x03) == 0x03; if ( (header >> 19 ) & 0x01 ) { *sampleRate = sSampleRates[0][sampleRateID]; bitRate = sBitRates[0][layerID][bitRateID] * 1000; *samplesPerFrame = sSamplesPerFrame[0][layerID]; } else { if ( (header >> 20) & 0x01 ) { *sampleRate = sSampleRates[1][sampleRateID]; bitRate = sBitRates[1][layerID][bitRateID] * 1000; *samplesPerFrame = sSamplesPerFrame[1][layerID]; } else { *sampleRate = sSampleRates[2][sampleRateID]; bitRate = sBitRates[1][layerID][bitRateID] * 1000; *samplesPerFrame = sSamplesPerFrame[2][layerID]; } } *byteSize = ( ( ( ( *samplesPerFrame * (bitRate / bitsPerSlot) ) / *sampleRate ) + isPadded ) * bitsPerSlot); return 1; }
1threat
How to avoid adding "async" to hundreds of locations in my code when adding a simple fetch call? : <p>I'm working on a big project with complex code that is not well written, it looks like spaghetti, with a lot of imbrications, functions calling each other with a lot of stack depth.</p> <p>Please note that as of now, <strong>the project code is 100% synchronous</strong> (no promises, no API calls, no database, no IO - it's a very complex test project that relies on hardcoded scenarios).</p> <p><strong>The evolution I need to code:</strong></p> <p>In a very deep sub-function, I need to do a very simple API call (using fetch) to return a simple integer value to the parent function, instead of an hardcoded value.</p> <p><strong>The problem I get:</strong></p> <p>Obviously, I need to change this function to async and I need to await for the result.</p> <p>But now, in the functions calling it, I need to await for the result, which means I need to set those parent functions to async as well, but then their parents need to await and to become async... All the way to the top, which, in this project, I estimate to around 100 functions to update.</p> <p>Is there a way to do this that wouldn't require refactoring so much occurences?</p>
0debug
Unfortunately App has stopped? Please help me : I am new to android development. I m trying to create a create account form through SQLITE database but when i am trying to run on phone or Emulator it shows "Unfortunately APP has stopped" . this si my Mnifest File code <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.mubbasher.howdy" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/Theme.AppCompat" > <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> this is my MainActivity public class MainActivity extends AppCompatActivity { DatabaseHelper myDb; EditText editName, editPassword, editEmail; Button buttonRegister; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myDb=new DatabaseHelper(this); editName = (EditText) findViewById(R.id.edit_name); editEmail = (EditText) findViewById(R.id.edit_email); editPassword = (EditText) findViewById(R.id.edit_password); buttonRegister = (Button) findViewById(R.id.ButtonRegister); Reg(); } public void Reg(){ buttonRegister.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { boolean isInserted=myDb.insertData(editName.getText().toString(), editEmail.getText().toString(), editPassword.getText().toString()); if(isInserted==true) Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_SHORT).show(); else Toast.makeText(MainActivity.this,"Data not Inserted",Toast.LENGTH_SHORT).show(); } } ); } } And this is my DatabaseHelper Class public class DatabaseHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION=1; private static final String DATABASE_NAME="USER.db"; private static final String TABLE_NAME="USER"; private static final String COL_1="ID"; private static final String COL_2="NAME"; private static final String COL_3="EMAIL"; private static final String COL_4="PASS"; SQLiteDatabase db; public DatabaseHelper(Context context) { super(context,DATABASE_NAME,null,DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table" + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, EMAIL TEXT, PASS TEXT)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXIST"+TABLE_NAME); onCreate(db); } public boolean insertData(String name, String email, String pass) { SQLiteDatabase db=this.getWritableDatabase(); ContentValues values=new ContentValues(); ContentValues contentValues=new ContentValues(); contentValues.put(COL_2,name); contentValues.put(COL_3,email); contentValues.put(COL_4,pass); long result=db.insert(TABLE_NAME, null, contentValues); if (result==-1) return false; else return true; } } this is my XML FILE <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:showIn="@layout/activity_main" tools:context=".MainActivity"> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:text="Name" android:ems="10" android:id="@+id/edit_name" android:layout_alignParentTop="true" android:layout_alignParentStart="true" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textEmailAddress" android:ems="10" android:id="@+id/edit_password" android:hint="Password" android:layout_below="@+id/edit_email" android:layout_alignParentStart="true" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textEmailAddress" android:ems="10" android:id="@+id/edit_email" android:layout_below="@+id/edit_name" android:layout_alignParentStart="true" android:hint="Email" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Register" android:id="@+id/ButtonRegister" android:layout_centerVertical="true" android:layout_centerHorizontal="true" /> </RelativeLayout>
0debug
static int decode_interrupt_cb(void *ctx) { return received_nb_signals > transcode_init_done; }
1threat
read a specific area in excel using R : <p>I am using R and I need to read data form specific area in my excel file. For example read data in this area : C8:I21</p> <p>How can we do that using R ? there is a specific package for it ?</p> <p>some help would be appreciated</p>
0debug
Python. How to call a function from a dictionary? : <p>I want to have a dictionary where a certain key calls a value... that value is a function and I would want that function to execute. Below is my attempt to do it but all I get is the value of where it is stored in memory.</p> <pre><code>class Testing: def __init__(self): self.method = {'Method1': self.another, 'Method2': self.there} def launch(self, input): print(self.method[input]) @staticmethod def another(): print('This print statement should pop out.') @staticmethod def there(): print('This should not appear.') new = Testing() new.launch('Method1') </code></pre> <p>The result that I get from that is:</p> <pre><code>&lt;function Testing.another at 0x01519540&gt; </code></pre> <p>Is there a way to do this?</p>
0debug
how i can monitor gpu sensors using c# winform? : im using OpenHardwareMonitor.Hardware dll for tracking the gpu sensors , but im not getting fan speed . please help it . private void Get_GPU_Configuration() { try { Computer _comp = new Computer(); _comp.GPUEnabled = true; _comp.Open(); dgv_Main_Window.Rows.Clear(); foreach (var hardwareItem in _comp.Hardware) { if ((hardwareItem.HardwareType == HardwareType.GpuAti) || (hardwareItem.HardwareType == HardwareType.GpuNvidia)) { int index = dgv_Main_Window.Rows.Add(); string _device_Name = hardwareItem.Name.Trim();// Radeon(TM) R5 M430 hardwareItem.Update(); dgv_Main_Window.Rows[index].Cells[int_Device].Value = _device_Name; foreach (var sensor in hardwareItem.Sensors) { string str = sensor.SensorType.ToString(); if (str == "Temperature") { dgv_Main_Window.Rows[index].Cells[int_Temperature].Value = sensor.Value.ToString(); } if (str == "Clock") { if (sensor.Name == "GPU Core") { dgv_Main_Window.Rows[index].Cells[int_CoreClock].Value = sensor.Value.ToString(); } else { dgv_Main_Window.Rows[index].Cells[int_MemoryClock].Value = sensor.Value.ToString(); } } if(str=="Fan") { if (sensor.Name == "GPU Fan") { dgv_Main_Window.Rows[index].Cells[int_FanSpeed].Value = sensor.Value; } } } string[] _deviceName_Array = new string[dgv_Main_Window.Rows.Count]; foreach (DataGridViewRow _drow in dgv_Main_Window.Rows) { int i = 0; _deviceName_Array[i] = _drow.Cells[int_Device].Value.ToString(); i++; } ManagementScope ms = new ManagementScope(@"root\cimv2"); ObjectQuery oq2 = new ObjectQuery("select * from Win32_VideoController"); ManagementObjectSearcher _Video = new ManagementObjectSearcher(ms, oq2); foreach (ManagementObject obj in _Video.Get()) { foreach (PropertyData PC in obj.Properties) { } foreach (var _data in _deviceName_Array) { if (_data == obj["Name"].ToString()) { foreach (DataGridViewRow _drow in dgv_Main_Window.Rows) { if (_drow.Cells[int_Device].Value.ToString() == _data) { _drow.Cells[int_Id].Value = obj["DeviceID"].ToString(); _drow.Cells[int_Driver].Value = obj["DriverVersion"].ToString(); } } } } } } } } catch (Exception ex) { } }
0debug
CORRECT WAY TO USE BUTTONS IN SPRITEKIT XCODE : i am creating my second app but first iOS game I am all done with coding and levels but at the end i am struggling to use the buttons in sprite kit so i can create share, like or to implement setting menu in it the one way i am using is proving below Button = UIButton(type: UIButtonType.custom) Button.frame = CGRect(x: 0, y: 0, width: 50, height: 50) Button.center = CGPoint(x: (self.view?.frame.width)! - 30, y: 60) Button.setImage(UIImage(named: "Pause"), for: UIControlState.normal) Button.addTarget(self, action: #selector(PauseGame), for: UIControlEvents.touchUpInside) self.view?.addSubview(Button) now the problem with this button is that it is always enable and displayed, no matter what screen or scene i am in. just want to ask if there is any other way of using the buttons or may be i have to use storyboard in spritekit project for all the settings, menuscreen and extra buttons (eg. like, share) plz plz help me out thanks in advance
0debug
Understanding special type of access C++/C array : <p>I have the following code snippet:</p> <pre><code>int ndigit[10] = {0,0,0,0,0,0,0,0,0,0}; void count() { char c; while (cin.get(c)) { if (c&gt;='0' &amp;&amp; c&lt;='9') { ndigit[c-'0']++; } } </code></pre> <p>So <code>c</code> has to be between 0 and 9 (with 0 and 9), so why it is necessary to index the array like <code>ndigit[c-'0']</code> instead of just <code>ndigit[c]</code> ?</p> <p>If I am right, in both cases a <code>c</code> value can occur more then once, so a the value of <code>ndigit[c-'0']</code> gets overwritten anyway...</p> <p>I appreciate your wisdom!</p>
0debug
get the length of a string and assign it to an array : <p>Total c++ newbie here.</p> <p>I have a problem, where I can not assign the number of character in a string to an array size, like so..😓</p> <pre><code>string outStr; ifstream input("read.txt"); getline(input, outStr); int const n = outStr.length(); int arr[n]; </code></pre> <p>error msg --> expression must have a constant value. although i have declared the "const"</p> <p>Thanks in advance✌.</p>
0debug
pouchdb db.login is not a function : <p>Tried using these imports</p> <pre><code>import PouchDB from 'pouchdb'; import PouchDBAuth from 'pouchdb-authentication'; PouchDB.plugin(PouchDBAuth) </code></pre> <p>Module ''pouchdb-authentication'' has no default export is the error generated while using these imports.</p> <pre><code>PouchDB.plugin(require('pouchdb-authentication')); </code></pre> <p>Using require is removing the error but still showing db.login() is not a function.Can anyone suggest where the issue is?</p>
0debug
static int unix_open(URLContext *h, const char *filename, int flags) { UnixContext *s = h->priv_data; int fd, ret; av_strstart(filename, "unix:", &filename); s->addr.sun_family = AF_UNIX; av_strlcpy(s->addr.sun_path, filename, sizeof(s->addr.sun_path)); if ((fd = ff_socket(AF_UNIX, s->type, 0)) < 0) return ff_neterrno(); if (s->listen) { fd = ff_listen_bind(fd, (struct sockaddr *)&s->addr, sizeof(s->addr), s->timeout, h); if (fd < 0) { ret = fd; goto fail; } } else { ret = ff_listen_connect(fd, (struct sockaddr *)&s->addr, sizeof(s->addr), s->timeout, h, 0); if (ret < 0) goto fail; } s->fd = fd; return 0; fail: if (s->listen && AVUNERROR(ret) != EADDRINUSE) unlink(s->addr.sun_path); if (fd >= 0) closesocket(fd); return ret; }
1threat
Selecting parent item using css : <p>Is there a way that I can select parent item using css? I mean my structure is this</p> <pre><code>&lt;label&gt; &lt;input /&gt; &lt;label&gt; </code></pre> <p>In my css I am trying to do something like this,</p> <pre><code>input['_type_']:checked _parent_ label:after{ some css } </code></pre> <p>I cannot use, attribute <em>for</em> in label.</p>
0debug
initalizer for conditional binding must have optional type, not int : if let hrAverage: Int = (oldHR1+oldHR2+oldHR3+oldHR4+heartRate!)/5 { print(hrAverage) } else { let hrAverage = (oldHR1+oldHR2+oldHR3+oldHR4) / 4 print(hrAverage) } Getting this error that tells us "initalizer for conditional binding must have optional type, not int" I've been stuck on how to get rid of it. I have to unwrap value heartrate using optional binding! help!
0debug
static void gen_wrteei(DisasContext *ctx) { #if defined(CONFIG_USER_ONLY) gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC); #else if (unlikely(ctx->pr)) { gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC); return; } if (ctx->opcode & 0x00008000) { tcg_gen_ori_tl(cpu_msr, cpu_msr, (1 << MSR_EE)); gen_stop_exception(ctx); } else { tcg_gen_andi_tl(cpu_msr, cpu_msr, ~(1 << MSR_EE)); } #endif }
1threat
setup_sigcontext(struct target_sigcontext *sc, CPUM68KState *env, abi_ulong mask) { int err = 0; __put_user(mask, &sc->sc_mask); __put_user(env->aregs[7], &sc->sc_usp); __put_user(env->dregs[0], &sc->sc_d0); __put_user(env->dregs[1], &sc->sc_d1); __put_user(env->aregs[0], &sc->sc_a0); __put_user(env->aregs[1], &sc->sc_a1); __put_user(env->sr, &sc->sc_sr); __put_user(env->pc, &sc->sc_pc); return err; }
1threat
I am having trouble with getting my image to rotate anti-clockwise, i feel i may be missing a simple step, here is my code : : `.image { position: absolute; top: 30%; left: 37%; width: 430px; height: 430px; margin:210px 0 0 -60px; -webkit-animation:spin 75s linear infinite; -moz-animation:spin 75s linear infinite; animation:spin 75s linear infinite; } `.redline { position: absolute; top: 30%; left: 37%; width: 430px; height: 430px; margin:210px 0 0 -60px; -webkit-animation:spin 35s linear infinite; -moz-animation:spin 35s linear infinite; animation:spin 35s linear infinite; } @-moz-keyframes spin { 100% { transform-moz-transform: spin(-720deg); } }`
0debug
Exception error with class and files : <p>I have a file on my computer called records.txt with a few lines on it. Each line has the format "firstname - lastname - address - age - gpa"</p> <p>Adam - Michael - Gainesville florida - 16 - 75</p> <p>Alice - Barry - Jacksonville florida - 17 - 40</p> <p>Kevin - Adam - Orlando florida - 20 - 65</p> <p>Jacob - Michael - Miami florida - 16 - 88</p> <p>Sabrina - Matthew - Gainesville florida - 18 - 90</p> <p>My program is supposed to separate those and display the information using a class of students. The cgpa is the letter grade given by the bounds shown in my code for the gpa. This is the error my code gives me.</p> <pre><code> Exception in thread "main" java.lang.NullPointerException at hw6_hamilton_daniel.HW6_Hamilton_Daniel.main(HW6_Hamilton_Daniel.java:41) C:\Users\dhami\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1 BUILD FAILED (total time: 0 seconds) </code></pre> <p>Here is my coding:</p> <p>MAIN:</p> <pre><code>package hw6_hamilton_daniel; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; /** * * @author dhami */ public class HW6_Hamilton_Daniel { /** * @param args the command line arguments */ public static void main(String[] args) { try { File records = new File("C:\\Users\\dhami\\Desktop\\records.txt"); Scanner input = new Scanner(records); int count = 0; while (input.hasNextLine()) { count = count + 1; break; } input.close(); student[] students = new student[count]; Scanner input2 = new Scanner(records); for (int i = 0; i &lt; count; i++) { String line = input2.nextLine(); String[] Split = line.split(" - "); students[i].set_firstname(Split[0]); students[i].set_lastname(Split[1]); students[i].set_address(Split[2]); students[i].set_age(Split[3]); students[i].set_gpa(Split[4]); students[i].Display_info(); break; } input2.close(); } catch (FileNotFoundException ex) { System.out.println("File Not Found"); }//IF FILE IS NOT ON MACHINE } </code></pre> <p>}</p> <p>CLASS:</p> <pre><code>public class student { private String firstname; private String lastname; private String address; private int age; private int gpa; private char cgpa; student() { firstname = "Default_FName"; lastname = "Default_LName"; address = "Default_Address"; age = 0; gpa = 0; cgpa = 'X'; }//Default constructor void set_firstname (String new_name) { firstname = new_name; } String get_firstname () { return firstname; }//firstname------------- void set_lastname (String new_lastname) { lastname = new_lastname; } String get_lastname () { return lastname; }//lastname-------------- void set_address (String new_address) { address = new_address; } String get_address () { return address; }//address--------------- void set_age (String new_age) { age = Integer.parseInt(new_age); } int get_age () { return age; }//age------------------- void set_gpa (String new_gpa) { gpa = Integer.parseInt(new_gpa); if (gpa &gt;= 85 &amp;&amp; gpa &lt;= 100) { cgpa = 'A'; } if (gpa &gt;=60 &amp;&amp; gpa &lt;= 85) { cgpa = 'B'; } else { cgpa = 'C'; } } int get_gpa () { return gpa; }//gpa------------------- char get_cgpa () { return cgpa; } void Display_info() { System.out.println("First Name: "+firstname); System.out.println("Last Name: "+lastname); System.out.println("Address: "+address); System.out.println("Age: "+age); System.out.println("GPA: "+gpa+" ("+cgpa+")\r\n"); } } </code></pre>
0debug
yuv2mono_X_c_template(SwsContext *c, const int16_t *lumFilter, const int16_t **lumSrc, int lumFilterSize, const int16_t *chrFilter, const int16_t **chrUSrc, const int16_t **chrVSrc, int chrFilterSize, const int16_t **alpSrc, uint8_t *dest, int dstW, int y, enum AVPixelFormat target) { const uint8_t * const d128=dither_8x8_220[y&7]; int i; unsigned acc = 0; int err = 0; for (i = 0; i < dstW; i += 2) { int j; int Y1 = 1 << 18; int Y2 = 1 << 18; for (j = 0; j < lumFilterSize; j++) { Y1 += lumSrc[j][i] * lumFilter[j]; Y2 += lumSrc[j][i+1] * lumFilter[j]; } Y1 >>= 19; Y2 >>= 19; if ((Y1 | Y2) & 0x100) { Y1 = av_clip_uint8(Y1); Y2 = av_clip_uint8(Y2); } if (c->flags & SWS_ERROR_DIFFUSION) { Y1 += (7*err + 1*c->dither_error[0][i] + 5*c->dither_error[0][i+1] + 3*c->dither_error[0][i+2] + 8 - 256)>>4; c->dither_error[0][i] = err; acc = 2*acc + (Y1 >= 128); Y1 -= 220*(acc&1); err = Y2 + ((7*Y1 + 1*c->dither_error[0][i+1] + 5*c->dither_error[0][i+2] + 3*c->dither_error[0][i+3] + 8 - 256)>>4); c->dither_error[0][i+1] = Y1; acc = 2*acc + (err >= 128); err -= 220*(acc&1); } else { accumulate_bit(acc, Y1 + d128[(i + 0) & 7]); accumulate_bit(acc, Y2 + d128[(i + 1) & 7]); } if ((i & 7) == 6) { output_pixel(*dest++, acc); } } c->dither_error[0][i] = err; if (i & 6) { output_pixel(*dest, acc); } }
1threat
static int qemu_chr_open_pp(QemuOpts *opts, CharDriverState **_chr) { const char *filename = qemu_opt_get(opts, "path"); CharDriverState *chr; int fd; fd = qemu_open(filename, O_RDWR); if (fd < 0) { return -errno; } chr = g_malloc0(sizeof(CharDriverState)); chr->opaque = (void *)(intptr_t)fd; chr->chr_write = null_chr_write; chr->chr_ioctl = pp_ioctl; *_chr = chr; return 0; }
1threat
Can somebody explain how to make vscode the default editor on osx? : <p>Xcode is the current default editor when opening files and I'd like to switch it to vscode</p>
0debug
What is the best resource to deploy a .Net Core WebAPI in Azure : <p>As the title implies, I am developing a .Net core WebAPI app and am wondering if there is a better resource (there are so damn many now) that a basic <strong>Web App</strong> to deploy my WebAPI? Any input is greatly appreciated, as you know the MS docs are sometimes a bit frustrating!</p>
0debug
variable not work on div created in jquery : this is simple code which works fine, but i want to figure it out how to set a variable for novy.fadeIn(2000). For example one day will my js file had 300 lines and i want to change variable from one place -> fadeIn to fadeOUt or something like that. var novy = $('<div/>', {id:'namaste'}); var text = {textAlign : 'center', color : '#fff', fontSize: 'xx-large'} // var example = novy.fadeIn(2000) this is not working novy.appendTo('body').text('this code is .ITCHI.').css(text).hide(); $(document).on('click', function(){ novy.fadeIn(2000); // example; }) for better view please look here: [https://jsfiddle.net/t305qap2/][1] [1]: https://jsfiddle.net/t305qap2/
0debug
Newtonsoft exception throws, "Input string '08' is not a valid number" : <p>I am trying to make a basic c# code copied from the web (<a href="http://scriptopia.co.uk/Post.php?id=8" rel="nofollow noreferrer">http://scriptopia.co.uk/Post.php?id=8</a>) so as to familiarize myself with firebase. The code seems to work fine by sending the Time data to the database except for the 8th second. Can someone tell me why this strange behavior? </p> <pre><code> while (true) { DateTime date = DateTime.Now; string hour = date.ToString("HH"); string minutes = date.ToString("mm"); string seconds = date.ToString("ss"); string jsondata = "{'Time':{'Hour': " + hour + ",'Minute': " + minutes + ", 'Second': " + seconds + ", }}"; JObject data = JObject.Parse(jsondata); string json = JsonConvert.SerializeObject(data); var request = System.Net.WebRequest.CreateHttp("https://******.firebaseio.com/.json?auth=***db**secret***"); request.Method = "PATCH"; request.ContentType = "json"; var buffer = Encoding.UTF8.GetBytes(json); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); var response = request.GetResponse(); json = (new System.IO.StreamReader(response.GetResponseStream())).ReadToEnd(); } </code></pre> <p>I was hoping to receive continuous time data without any error, however in this case at the 8th second of every minute the code crashes. I tried running it in an online compiler and observed the same results.</p>
0debug
static int v4l2_receive_packet(AVCodecContext *avctx, AVPacket *avpkt) { V4L2m2mContext *s = avctx->priv_data; V4L2Context *const capture = &s->capture; V4L2Context *const output = &s->output; int ret; if (s->draining) goto dequeue; if (!output->streamon) { ret = ff_v4l2_context_set_status(output, VIDIOC_STREAMON); if (ret) { av_log(avctx, AV_LOG_ERROR, "VIDIOC_STREAMOFF failed on output context\n"); return ret; } } if (!capture->streamon) { ret = ff_v4l2_context_set_status(capture, VIDIOC_STREAMON); if (ret) { av_log(avctx, AV_LOG_ERROR, "VIDIOC_STREAMON failed on capture context\n"); return ret; } } dequeue: return ff_v4l2_context_dequeue_packet(capture, avpkt); }
1threat
Python 2.6 - Split one list evenly into two : <p>My goal is simple</p> <p>I have a list, in e.g:</p> <pre><code>a = ['a', 'b', 'c', 'd'] </code></pre> <p>And I want split that randomly and evenly into two different lists, in e.g:</p> <pre><code>b = ['c', 'a'] c = ['d', 'b'] </code></pre> <p>Thanks in advance.</p>
0debug
Can someone explain what this following regex means : <p><code>/(.*?)((http:\/\/|https:\/\/)?[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,6}(\/[a-zA-Z0-9\-\.]+)*){1}(.*?)/g</code></p> <p>I could only make some assumptions about the above regex. But most of it is cryptic to me.</p> <p><code>(http:\/\/|https:\/\/)</code> - It contains either <code>http</code> or <code>https</code> protocol.</p> <p><code>[a-zA-Z]{2,6}</code> - Contain any of the lower or uppercase characters between 2 and 6 times.</p> <p><code>/g</code> - Search for it recursively</p> <p>But was not able to put all of the blocks together.</p>
0debug
how to make a series of number jumps based on the numbers of variables : <p>I want to make row of number jumps, example I have <code>$a = 1</code> and <code>$b = 2</code>. then I want loop $a and $b and the result is <code>$a = '1', '5', '9', '13', '17'</code> and <code>$b = '2', '6', '10', '14', '18'</code> . How to make it?</p>
0debug
Typescript 2.0 @types not automatically referenced : <p>using TS 2.0 Beta I can't get the new @types working. somewhere in my code:</p> <pre><code>import * as angular from 'angular'; </code></pre> <p>TS 2.0 @types:</p> <pre><code>npm install --save @types/angular tsc </code></pre> <p>the compiler doesn't find the d.ts files though: Error:(1, 26) TS2307: Cannot find module 'angular'.</p> <p>no issues with current (old) method of using the typings tool and global (before ambient) dependencies.</p> <p>I expected the d.ts lookup to work automatically with 2.0 as described here:</p> <p><a href="https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/">https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/</a></p> <p>perhaps I am missing something?</p>
0debug
How to solve the conflict dependency on RxJava version 1 and 2 : I only used RxJava2 ,but Why occured conflict with RxJava1.1.5 Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'. > com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/rxjava.properties File1: /home/panhao/Android/myGradle/caches/modules-2/files-2.1/io.reactivex.rxjava2/rxjava/2.0.0-RC5/ecd92d1147d9858c23087801a3bc2f323d481472/rxjava-2.0.0-RC5.jar File2: /home/panhao/Android/myGradle/caches/modules-2/files-2.1/io.reactivex/rxjava/1.1.5/ece7b5d0870e66d8226dab6dcf47a2b12afff061/rxjava-1.1.5.jar
0debug
How to get length of exact word in sentence? Python : <p>need help in finding exact length of word with number "n" in sentence WordLength(s,n) It has toget lentgh not of all sentence, i managed finding out how to do that, but i need to find length of exact word and i don't know how to do that</p>
0debug
static int decode_mips16_opc (CPUMIPSState *env, DisasContext *ctx, int *is_branch) { int rx, ry; int sa; int op, cnvt_op, op1, offset; int funct; int n_bytes; op = (ctx->opcode >> 11) & 0x1f; sa = (ctx->opcode >> 2) & 0x7; sa = sa == 0 ? 8 : sa; rx = xlat((ctx->opcode >> 8) & 0x7); cnvt_op = (ctx->opcode >> 5) & 0x7; ry = xlat((ctx->opcode >> 5) & 0x7); op1 = offset = ctx->opcode & 0x1f; n_bytes = 2; switch (op) { case M16_OPC_ADDIUSP: { int16_t imm = ((uint8_t) ctx->opcode) << 2; gen_arith_imm(ctx, OPC_ADDIU, rx, 29, imm); } break; case M16_OPC_ADDIUPC: gen_addiupc(ctx, rx, ((uint8_t) ctx->opcode) << 2, 0, 0); break; case M16_OPC_B: offset = (ctx->opcode & 0x7ff) << 1; offset = (int16_t)(offset << 4) >> 4; gen_compute_branch(ctx, OPC_BEQ, 2, 0, 0, offset); break; case M16_OPC_JAL: offset = cpu_lduw_code(env, ctx->pc + 2); offset = (((ctx->opcode & 0x1f) << 21) | ((ctx->opcode >> 5) & 0x1f) << 16 | offset) << 2; op = ((ctx->opcode >> 10) & 0x1) ? OPC_JALXS : OPC_JALS; gen_compute_branch(ctx, op, 4, rx, ry, offset); n_bytes = 4; *is_branch = 1; break; case M16_OPC_BEQZ: gen_compute_branch(ctx, OPC_BEQ, 2, rx, 0, ((int8_t)ctx->opcode) << 1); break; case M16_OPC_BNEQZ: gen_compute_branch(ctx, OPC_BNE, 2, rx, 0, ((int8_t)ctx->opcode) << 1); break; case M16_OPC_SHIFT: switch (ctx->opcode & 0x3) { case 0x0: gen_shift_imm(ctx, OPC_SLL, rx, ry, sa); break; case 0x1: #if defined(TARGET_MIPS64) check_mips_64(ctx); gen_shift_imm(ctx, OPC_DSLL, rx, ry, sa); #else generate_exception(ctx, EXCP_RI); #endif break; case 0x2: gen_shift_imm(ctx, OPC_SRL, rx, ry, sa); break; case 0x3: gen_shift_imm(ctx, OPC_SRA, rx, ry, sa); break; } break; #if defined(TARGET_MIPS64) case M16_OPC_LD: check_mips_64(ctx); gen_ld(ctx, OPC_LD, ry, rx, offset << 3); break; #endif case M16_OPC_RRIA: { int16_t imm = (int8_t)((ctx->opcode & 0xf) << 4) >> 4; if ((ctx->opcode >> 4) & 1) { #if defined(TARGET_MIPS64) check_mips_64(ctx); gen_arith_imm(ctx, OPC_DADDIU, ry, rx, imm); #else generate_exception(ctx, EXCP_RI); #endif } else { gen_arith_imm(ctx, OPC_ADDIU, ry, rx, imm); } } break; case M16_OPC_ADDIU8: { int16_t imm = (int8_t) ctx->opcode; gen_arith_imm(ctx, OPC_ADDIU, rx, rx, imm); } break; case M16_OPC_SLTI: { int16_t imm = (uint8_t) ctx->opcode; gen_slt_imm(ctx, OPC_SLTI, 24, rx, imm); } break; case M16_OPC_SLTIU: { int16_t imm = (uint8_t) ctx->opcode; gen_slt_imm(ctx, OPC_SLTIU, 24, rx, imm); } break; case M16_OPC_I8: { int reg32; funct = (ctx->opcode >> 8) & 0x7; switch (funct) { case I8_BTEQZ: gen_compute_branch(ctx, OPC_BEQ, 2, 24, 0, ((int8_t)ctx->opcode) << 1); break; case I8_BTNEZ: gen_compute_branch(ctx, OPC_BNE, 2, 24, 0, ((int8_t)ctx->opcode) << 1); break; case I8_SWRASP: gen_st(ctx, OPC_SW, 31, 29, (ctx->opcode & 0xff) << 2); break; case I8_ADJSP: gen_arith_imm(ctx, OPC_ADDIU, 29, 29, ((int8_t)ctx->opcode) << 3); break; case I8_SVRS: { int do_ra = ctx->opcode & (1 << 6); int do_s0 = ctx->opcode & (1 << 5); int do_s1 = ctx->opcode & (1 << 4); int framesize = ctx->opcode & 0xf; if (framesize == 0) { framesize = 128; } else { framesize = framesize << 3; } if (ctx->opcode & (1 << 7)) { gen_mips16_save(ctx, 0, 0, do_ra, do_s0, do_s1, framesize); } else { gen_mips16_restore(ctx, 0, 0, do_ra, do_s0, do_s1, framesize); } } break; case I8_MOV32R: { int rz = xlat(ctx->opcode & 0x7); reg32 = (((ctx->opcode >> 3) & 0x3) << 3) | ((ctx->opcode >> 5) & 0x7); gen_arith(ctx, OPC_ADDU, reg32, rz, 0); } break; case I8_MOVR32: reg32 = ctx->opcode & 0x1f; gen_arith(ctx, OPC_ADDU, ry, reg32, 0); break; default: generate_exception(ctx, EXCP_RI); break; } } break; case M16_OPC_LI: { int16_t imm = (uint8_t) ctx->opcode; gen_arith_imm(ctx, OPC_ADDIU, rx, 0, imm); } break; case M16_OPC_CMPI: { int16_t imm = (uint8_t) ctx->opcode; gen_logic_imm(ctx, OPC_XORI, 24, rx, imm); } break; #if defined(TARGET_MIPS64) case M16_OPC_SD: check_mips_64(ctx); gen_st(ctx, OPC_SD, ry, rx, offset << 3); break; #endif case M16_OPC_LB: gen_ld(ctx, OPC_LB, ry, rx, offset); break; case M16_OPC_LH: gen_ld(ctx, OPC_LH, ry, rx, offset << 1); break; case M16_OPC_LWSP: gen_ld(ctx, OPC_LW, rx, 29, ((uint8_t)ctx->opcode) << 2); break; case M16_OPC_LW: gen_ld(ctx, OPC_LW, ry, rx, offset << 2); break; case M16_OPC_LBU: gen_ld(ctx, OPC_LBU, ry, rx, offset); break; case M16_OPC_LHU: gen_ld(ctx, OPC_LHU, ry, rx, offset << 1); break; case M16_OPC_LWPC: gen_ld(ctx, OPC_LWPC, rx, 0, ((uint8_t)ctx->opcode) << 2); break; #if defined (TARGET_MIPS64) case M16_OPC_LWU: check_mips_64(ctx); gen_ld(ctx, OPC_LWU, ry, rx, offset << 2); break; #endif case M16_OPC_SB: gen_st(ctx, OPC_SB, ry, rx, offset); break; case M16_OPC_SH: gen_st(ctx, OPC_SH, ry, rx, offset << 1); break; case M16_OPC_SWSP: gen_st(ctx, OPC_SW, rx, 29, ((uint8_t)ctx->opcode) << 2); break; case M16_OPC_SW: gen_st(ctx, OPC_SW, ry, rx, offset << 2); break; case M16_OPC_RRR: { int rz = xlat((ctx->opcode >> 2) & 0x7); int mips32_op; switch (ctx->opcode & 0x3) { case RRR_ADDU: mips32_op = OPC_ADDU; break; case RRR_SUBU: mips32_op = OPC_SUBU; break; #if defined(TARGET_MIPS64) case RRR_DADDU: mips32_op = OPC_DADDU; check_mips_64(ctx); break; case RRR_DSUBU: mips32_op = OPC_DSUBU; check_mips_64(ctx); break; #endif default: generate_exception(ctx, EXCP_RI); goto done; } gen_arith(ctx, mips32_op, rz, rx, ry); done: ; } break; case M16_OPC_RR: switch (op1) { case RR_JR: { int nd = (ctx->opcode >> 7) & 0x1; int link = (ctx->opcode >> 6) & 0x1; int ra = (ctx->opcode >> 5) & 0x1; if (link) { op = nd ? OPC_JALRC : OPC_JALRS; } else { op = OPC_JR; } gen_compute_branch(ctx, op, 2, ra ? 31 : rx, 31, 0); if (!nd) { *is_branch = 1; } } break; case RR_SDBBP: check_insn(ctx, ISA_MIPS32); if (!(ctx->hflags & MIPS_HFLAG_DM)) { generate_exception(ctx, EXCP_DBp); } else { generate_exception(ctx, EXCP_DBp); } break; case RR_SLT: gen_slt(ctx, OPC_SLT, 24, rx, ry); break; case RR_SLTU: gen_slt(ctx, OPC_SLTU, 24, rx, ry); break; case RR_BREAK: generate_exception(ctx, EXCP_BREAK); break; case RR_SLLV: gen_shift(ctx, OPC_SLLV, ry, rx, ry); break; case RR_SRLV: gen_shift(ctx, OPC_SRLV, ry, rx, ry); break; case RR_SRAV: gen_shift(ctx, OPC_SRAV, ry, rx, ry); break; #if defined (TARGET_MIPS64) case RR_DSRL: check_mips_64(ctx); gen_shift_imm(ctx, OPC_DSRL, ry, ry, sa); break; #endif case RR_CMP: gen_logic(ctx, OPC_XOR, 24, rx, ry); break; case RR_NEG: gen_arith(ctx, OPC_SUBU, rx, 0, ry); break; case RR_AND: gen_logic(ctx, OPC_AND, rx, rx, ry); break; case RR_OR: gen_logic(ctx, OPC_OR, rx, rx, ry); break; case RR_XOR: gen_logic(ctx, OPC_XOR, rx, rx, ry); break; case RR_NOT: gen_logic(ctx, OPC_NOR, rx, ry, 0); break; case RR_MFHI: gen_HILO(ctx, OPC_MFHI, 0, rx); break; case RR_CNVT: switch (cnvt_op) { case RR_RY_CNVT_ZEB: tcg_gen_ext8u_tl(cpu_gpr[rx], cpu_gpr[rx]); break; case RR_RY_CNVT_ZEH: tcg_gen_ext16u_tl(cpu_gpr[rx], cpu_gpr[rx]); break; case RR_RY_CNVT_SEB: tcg_gen_ext8s_tl(cpu_gpr[rx], cpu_gpr[rx]); break; case RR_RY_CNVT_SEH: tcg_gen_ext16s_tl(cpu_gpr[rx], cpu_gpr[rx]); break; #if defined (TARGET_MIPS64) case RR_RY_CNVT_ZEW: check_mips_64(ctx); tcg_gen_ext32u_tl(cpu_gpr[rx], cpu_gpr[rx]); break; case RR_RY_CNVT_SEW: check_mips_64(ctx); tcg_gen_ext32s_tl(cpu_gpr[rx], cpu_gpr[rx]); break; #endif default: generate_exception(ctx, EXCP_RI); break; } break; case RR_MFLO: gen_HILO(ctx, OPC_MFLO, 0, rx); break; #if defined (TARGET_MIPS64) case RR_DSRA: check_mips_64(ctx); gen_shift_imm(ctx, OPC_DSRA, ry, ry, sa); break; case RR_DSLLV: check_mips_64(ctx); gen_shift(ctx, OPC_DSLLV, ry, rx, ry); break; case RR_DSRLV: check_mips_64(ctx); gen_shift(ctx, OPC_DSRLV, ry, rx, ry); break; case RR_DSRAV: check_mips_64(ctx); gen_shift(ctx, OPC_DSRAV, ry, rx, ry); break; #endif case RR_MULT: gen_muldiv(ctx, OPC_MULT, 0, rx, ry); break; case RR_MULTU: gen_muldiv(ctx, OPC_MULTU, 0, rx, ry); break; case RR_DIV: gen_muldiv(ctx, OPC_DIV, 0, rx, ry); break; case RR_DIVU: gen_muldiv(ctx, OPC_DIVU, 0, rx, ry); break; #if defined (TARGET_MIPS64) case RR_DMULT: check_mips_64(ctx); gen_muldiv(ctx, OPC_DMULT, 0, rx, ry); break; case RR_DMULTU: check_mips_64(ctx); gen_muldiv(ctx, OPC_DMULTU, 0, rx, ry); break; case RR_DDIV: check_mips_64(ctx); gen_muldiv(ctx, OPC_DDIV, 0, rx, ry); break; case RR_DDIVU: check_mips_64(ctx); gen_muldiv(ctx, OPC_DDIVU, 0, rx, ry); break; #endif default: generate_exception(ctx, EXCP_RI); break; } break; case M16_OPC_EXTEND: decode_extended_mips16_opc(env, ctx, is_branch); n_bytes = 4; break; #if defined(TARGET_MIPS64) case M16_OPC_I64: funct = (ctx->opcode >> 8) & 0x7; decode_i64_mips16(ctx, ry, funct, offset, 0); break; #endif default: generate_exception(ctx, EXCP_RI); break; } return n_bytes; }
1threat
Java- I'm unable to execute my if-else statement : I've been figuring out my code for hours and I can't find any solution for my code The game GUI shouldn't be display anymore when I have clicked on either my Water , Fire Or Nature button,because every button will add 1 to store into my gamePlayed and the maximum would only store up to 5 times,I really cant figure it this out please help me ! Really appreciate that. public class Game { private JPanel Game; private JButton Water; private JButton Nature; private JButton Fire; private int myChoice; private int computerChoice; int gamePlayed = 0; //store the times of game played public Game() { JFrame frame = new JFrame("The Elements"); frame.setContentPane(this.Game); frame.setMinimumSize(new Dimension(500, 500)); frame.pack(); frame.setVisible(true); if (gamePlayed <= 5) { //if the times of game played is less than 5 times , execute the following code Water.addActionListener(new ActionListener() { @Override //Water counter Fire , Nature counter water public void actionPerformed(ActionEvent e) { int select; select = JOptionPane.showConfirmDialog(null, "You're using the power of water", "Water", JOptionPane.YES_NO_OPTION); if (select == JOptionPane.YES_OPTION) { myChoice = 0; computerChoice = computerPlays(); conditionsDisplayResults(myChoice, computerChoice); gamePlayed+=1;//add 1 time of played game when the yes option clicked } } }); Fire.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int select = JOptionPane.showConfirmDialog(null, "You're using the power of fire", "Fire", JOptionPane.YES_NO_OPTION); if (select == JOptionPane.YES_OPTION) { myChoice = 1; computerChoice = computerPlays(); conditionsDisplayResults(myChoice, computerChoice); gamePlayed+=1;//add 1 time of played game when the yes option clicked } } }); Nature.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int select = JOptionPane.showConfirmDialog(null, "You're using the power of nature", "Nature", JOptionPane.YES_NO_OPTION); if (select == JOptionPane.YES_OPTION) { myChoice = 2; computerChoice = computerPlays(); conditionsDisplayResults(myChoice, computerChoice); gamePlayed+=1;//add 1 time of played game when the yes option clicked } } }); else{ //else which when the times of game played is more than 5 times , execute the following code GameResult(); MainMenu mainMenu = new MainMenu(); } }
0debug
Firebase android : make username unique : <p>Parse will shut down at the end of the year, so I decided to start using Firebase. I need to implement a register process with 3 fields : email, username, password (<strong>Email &amp; username</strong> must be unique for my app). </p> <p>Since, Firebase is not providing an easy way to manage username like Parse, I decided to use only the email/password registration and save some additional data like username. Here is my users data structure :</p> <pre><code>app : { users: { "some-user-uid": { email: "test@test.com" username: "myname" } } } </code></pre> <p>But, what I want to do is to make the username unique and to check it before creating an account. These are my rules :</p> <pre><code>{ "rules": { ".read": true, ".write": true, "users": { "$uid": { ".write": "auth !== null &amp;&amp; auth.uid === $uid", ".read": "auth !== null &amp;&amp; auth.provider === 'password'", "username": {".validate": "!root.child('users').child(newData.child('username').val()).exists()"} } } } } </code></pre> <p>Thank you very much for your help</p>
0debug
Using the '?', '$' and ':' sign in C# : <p>I recently came across this bit of code:</p> <pre><code> public void AppendTextColour(string text, Color color, bool AddNewLine = false) { rtbDisplay.SuspendLayout(); rtbDisplay.SelectionColor = color; rtbDisplay.AppendText(AddNewLine ? $"{text}{Environment.NewLine}" : text); rtbDisplay.ScrollToCaret(); rtbDisplay.ResumeLayout(); } </code></pre> <p>What fascinates me about it is the restructuring of <code>AppendText();</code> bit here:</p> <pre><code>rtbDisplay.AppendText(AddNewLine? $"{text}{Environment.NewLine}": text); </code></pre> <p>I can only guess that the question mark is used to instantiate the boolean value, however the dollar sign and the double dots sign here are absolutely obscure. Can anyone dissect this bit and explain it to me? </p> <p>I apologise if I am being a bit ambiguous but I was unable to find any relevant information anywhere. :/</p>
0debug
Add some element on one list on matching particular element from another list : I want help in below query, I have 2 lists, 1)Person with attributes: name, age, address, phone 2)Account with attributes: accHolderName, type, age, address I want Person list if person's name is present in Account List and on match I want to set age, address of Person from Account POJO.
0debug
Simple fap page with php and jquery : I am trying to create a faq page where questions and answers are saved in arrays. When the page is loaded the user only sees the questions and whenever he clicks on a question, the answer to that question will be shown. I found some jquery scripts online and combined it with arrays but the result is not what I expected. here is the code for the array part which is in a folder called "includes": <?php $faqArrays= array( array( "question" => "this is question 1", "answer" => "this is the answer for the first question" ), array( "question" => "this is question 2", "answer" => "this is the answer for the 2 question" ), ,array( "question"=>"this is question 7", "answer"=>"this is the answer for the 7 question" ) ); ?> and here is the html+jqury code <?php include('includes/arrays.php'); ?> <script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script> $(document).ready(function() { $('.faq_question').click(function() { if ($(this).parent().is('.open')){ $(this).closest('.faq').find('.faq_answer_container').animate({'height':'0'},500); $(this).closest('.faq').removeClass('open'); }else{ var newHeight =$(this).closest('.faq').find('.faq_answer').height() +'px'; $(this).closest('.faq').find('.faq_answer_container').animate({'height':newHeight},500); $(this).closest('.faq').addClass('open'); } }); }); </script> <style> /*FAQS*/ .faq_question { margin: 0px; padding: 0px 0px 5px 0px; display: inline-block; cursor: pointer; font-weight: bold; } .faq_answer_container { height: 0px; overflow: hidden; padding: 0px; } </style> <div class="faq_container"> <div class="faq"> <div class="faq_question"> <?php foreach($faqArrays as $faqArray){ echo "<h1>$faqArray[question]</h1>"; } ;?> </div> <div class="faq_answer_container"> <div class="faq_answer"><?php $faqArray[answer];?></div> </div> </div> </div> Thanks,
0debug
static int bdrv_has_snapshot(BlockDriverState *bs) { return (bs && !bdrv_is_removable(bs) && !bdrv_is_read_only(bs)); }
1threat
static void mov_read_chapters(AVFormatContext *s) { MOVContext *mov = s->priv_data; AVStream *st = NULL; MOVStreamContext *sc; int64_t cur_pos; int i; for (i = 0; i < s->nb_streams; i++) if (s->streams[i]->id == mov->chapter_track) { st = s->streams[i]; break; } if (!st) { av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n"); return; } st->discard = AVDISCARD_ALL; sc = st->priv_data; cur_pos = avio_tell(sc->pb); for (i = 0; i < st->nb_index_entries; i++) { AVIndexEntry *sample = &st->index_entries[i]; int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration; uint8_t *title; uint16_t ch; int len, title_len; if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) { av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i); goto finish; } len = avio_rb16(sc->pb); if (len > sample->size-2) continue; title_len = 2*len + 1; if (!(title = av_mallocz(title_len))) goto finish; ch = avio_rb16(sc->pb); if (ch == 0xfeff) avio_get_str16be(sc->pb, len, title, title_len); else if (ch == 0xfffe) avio_get_str16le(sc->pb, len, title, title_len); else { AV_WB16(title, ch); avio_get_str(sc->pb, len - 2, title + 2, title_len - 2); } ff_new_chapter(s, i, st->time_base, sample->timestamp, end, title); av_freep(&title); } finish: avio_seek(sc->pb, cur_pos, SEEK_SET); }
1threat
React component closing tag : <p>I'm new to React and I'm trying to figure out the purpose/use of &lt;MyComponent&gt;&lt;/MyComponent&gt; vs &lt;MyComponent /&gt;. I can't seem to find information on anything except self-closing tags.</p> <p>I've created a basic tab scroller as a <a href="https://jsfiddle.net/ChimeraZen/hym59xy3/" rel="noreferrer">JSFiddle</a> using the self-closing &lt;MyComponent /&gt; and subsequent props, and I'm wondering if there's a better way to write in React than what I've done.</p> <pre class="lang-js prettyprint-override"><code>class TabScroller extends React.Component { render() { return ( &lt;div className="tabScroller"&gt; &lt;div className="NavList"&gt; &lt;TabNav handleClick={this.handleNavClick} /&gt; &lt;TabList tabs={this.state.tabs} activeTab={this.state.activeTab} scrollPosition={this.state.scrollPosition} handleClick={this.handleTabClick} /&gt; &lt;/div&gt; &lt;TabContent content={this.state.tabs[this.state.activeTab].content} /&gt; &lt;/div&gt; ); } } // ======================================== ReactDOM.render( &lt;TabScroller /&gt;, document.getElementById('root') ); </code></pre>
0debug
How do you pass a 2D int array of size n to a function in C++? : <p>I simply want to pass a 2d array to a function but C++ is not like JAVA and won't let a function take in 'int[][] square' as its parameter. Apparently I need to specify its size, but it's size is a variable n by n, which the user inputs.</p>
0debug
static av_cold int vaapi_encode_h265_init_fixed_qp(AVCodecContext *avctx) { VAAPIEncodeContext *ctx = avctx->priv_data; VAAPIEncodeH265Context *priv = ctx->priv_data; VAAPIEncodeH265Options *opt = ctx->codec_options; priv->fixed_qp_p = opt->qp; if (avctx->i_quant_factor > 0.0) priv->fixed_qp_idr = (int)((priv->fixed_qp_p * avctx->i_quant_factor + avctx->i_quant_offset) + 0.5); else priv->fixed_qp_idr = priv->fixed_qp_p; if (avctx->b_quant_factor > 0.0) priv->fixed_qp_b = (int)((priv->fixed_qp_p * avctx->b_quant_factor + avctx->b_quant_offset) + 0.5); else priv->fixed_qp_b = priv->fixed_qp_p; av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = " "%d / %d / %d for IDR- / P- / B-frames.\n", priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b); return 0; }
1threat
How to get number of days between two date in SQl Server? : I need to get number of days between 2 date from history booking room from one customer in SQLServer. in that data that have 3 status(in, stay and out) #record :# id | room | status | date<br/> 1 | A | In | 2018-01-10<br/> 2 | A | Stay | 2018-01-11<br/> 3 | A | out | 2018-01-12<br/> 4 | B | In | 2018-01-12<br/> 5 | B | Stay | 2018-01-13<br/> 6 | B | Out | 2018-01-14<br/> 7 | A | In | 2018-01-14<br/> 8 | A | Stay | 2018-01-15<br/> 9 | A | Stay | 2018-01-16<br/> 10 | A | Out | 2018-01-17<br/> I expect the result for that customer, number of days in room A is 7 days and in room B is 3 days. I already try to use min and max but the result is not valid because in the data that customer in the end is back to room A again
0debug
static void common_init(MpegEncContext * s) { static int inited=0; switch(s->msmpeg4_version){ case 1: case 2: s->y_dc_scale_table= s->c_dc_scale_table= ff_mpeg1_dc_scale_table; break; case 3: if(s->workaround_bugs){ s->y_dc_scale_table= old_ff_y_dc_scale_table; s->c_dc_scale_table= old_ff_c_dc_scale_table; } else{ s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table; s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table; } break; case 4: case 5: s->y_dc_scale_table= wmv1_y_dc_scale_table; s->c_dc_scale_table= wmv1_c_dc_scale_table; break; #if defined(CONFIG_WMV3_DECODER)||defined(CONFIG_VC1_DECODER) case 6: s->y_dc_scale_table= wmv3_dc_scale_table; s->c_dc_scale_table= wmv3_dc_scale_table; break; #endif } if(s->msmpeg4_version>=4){ ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable , wmv1_scantable[1]); ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, wmv1_scantable[2]); ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, wmv1_scantable[3]); ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable , wmv1_scantable[0]); } if(!inited){ inited=1; init_h263_dc_for_msmpeg4(); } }
1threat
static void tcx_init(target_phys_addr_t addr, int vram_size, int width, int height, int depth) { DeviceState *dev; SysBusDevice *s; dev = qdev_create(NULL, "SUNW,tcx"); qdev_prop_set_taddr(dev, "addr", addr); qdev_prop_set_uint32(dev, "vram_size", vram_size); qdev_prop_set_uint16(dev, "width", width); qdev_prop_set_uint16(dev, "height", height); qdev_prop_set_uint16(dev, "depth", depth); qdev_init(dev); s = sysbus_from_qdev(dev); sysbus_mmio_map(s, 0, addr + 0x00800000ULL); sysbus_mmio_map(s, 1, addr + 0x00200000ULL); sysbus_mmio_map(s, 2, addr + 0x00700000ULL); sysbus_mmio_map(s, 3, addr + 0x00301000ULL); if (depth == 24) { sysbus_mmio_map(s, 4, addr + 0x02000000ULL); sysbus_mmio_map(s, 5, addr + 0x0a000000ULL); } else { sysbus_mmio_map(s, 4, addr + 0x00300000ULL); } }
1threat