problem
stringlengths
26
131k
labels
class label
2 classes
macOS (10.13 High Sierra) no longer stores screensaver settings in com.apple.screensaver : <p>So far my project had been relying on the following commands in order to tweak screensaver settings:</p> <pre><code>defaults write com.apple.screensaver askForPasswordDelay 0 defaults write com.apple.screensaver askForPassword true </code></pre> <p>As of macOS High Sierra (10.13) it seems like these settings are no longer stored in com.apple.screensaver</p> <p>I'd like to avoid Apple Script to achieve such thing, any suggestions?</p>
0debug
static uint32_t pci_up_read(void *opaque, uint32_t addr) { PIIX4PMState *s = opaque; uint32_t val = s->pci0_status.up; PIIX4_DPRINTF("pci_up_read %x\n", val); return val; }
1threat
How to retrive a Tags from database? : I'm trying to retrieve a tags from database in my view and show it in post . but I have no idea of how I can done this .. Here is my controller : public async Task<ActionResult> Create(Book model) { if (ModelState.IsValid) { if(model.TagsListing != null) { Collection<Tag> postTags = new Collection<Tag>(); var s = model.TagsListing.ToString(); string[] newTags = s.Split(','); foreach (var val in newTags) { Tag iTag = new Tag { Name = val }; db.Tags.Add(iTag); postTags.Add(iTag); } model.Tags = postTags; } db.Books.Add(model); await db.SaveChangesAsync(); return RedirectToAction("Index"); } ViewBag.User_ID = new SelectList(db.AspNetUsers, "Id", "Email"); ViewBag.Category_id = new SelectList(db.Categories, "Category_id", "Category_name"); return View(model); } and here is few pictures for my database : http://i.stack.imgur.com/Ari6k.png http://i.stack.imgur.com/7rSVE.png
0debug
static void apply_channel_coupling(AC3EncodeContext *s) { LOCAL_ALIGNED_16(CoefType, cpl_coords, [AC3_MAX_BLOCKS], [AC3_MAX_CHANNELS][16]); #if CONFIG_AC3ENC_FLOAT LOCAL_ALIGNED_16(int32_t, fixed_cpl_coords, [AC3_MAX_BLOCKS], [AC3_MAX_CHANNELS][16]); #else int32_t (*fixed_cpl_coords)[AC3_MAX_CHANNELS][16] = cpl_coords; #endif int blk, ch, bnd, i, j; CoefSumType energy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}}; int cpl_start, num_cpl_coefs; memset(cpl_coords, 0, AC3_MAX_BLOCKS * sizeof(*cpl_coords)); #if CONFIG_AC3ENC_FLOAT memset(fixed_cpl_coords, 0, AC3_MAX_BLOCKS * sizeof(*cpl_coords)); #endif cpl_start = s->start_freq[CPL_CH] - 1; num_cpl_coefs = FFALIGN(s->num_cpl_subbands * 12 + 1, 32); cpl_start = FFMIN(256, cpl_start + num_cpl_coefs) - num_cpl_coefs; for (blk = 0; blk < s->num_blocks; blk++) { AC3Block *block = &s->blocks[blk]; CoefType *cpl_coef = &block->mdct_coef[CPL_CH][cpl_start]; if (!block->cpl_in_use) continue; memset(cpl_coef, 0, num_cpl_coefs * sizeof(*cpl_coef)); for (ch = 1; ch <= s->fbw_channels; ch++) { CoefType *ch_coef = &block->mdct_coef[ch][cpl_start]; if (!block->channel_in_cpl[ch]) continue; for (i = 0; i < num_cpl_coefs; i++) cpl_coef[i] += ch_coef[i]; } clip_coefficients(&s->dsp, cpl_coef, num_cpl_coefs); } bnd = 0; i = s->start_freq[CPL_CH]; while (i < s->cpl_end_freq) { int band_size = s->cpl_band_sizes[bnd]; for (ch = CPL_CH; ch <= s->fbw_channels; ch++) { for (blk = 0; blk < s->num_blocks; blk++) { AC3Block *block = &s->blocks[blk]; if (!block->cpl_in_use || (ch > CPL_CH && !block->channel_in_cpl[ch])) continue; for (j = 0; j < band_size; j++) { CoefType v = block->mdct_coef[ch][i+j]; MAC_COEF(energy[blk][ch][bnd], v, v); } } } i += band_size; bnd++; } for (blk = 0; blk < s->num_blocks; blk++) { AC3Block *block = &s->blocks[blk]; if (!block->cpl_in_use) continue; for (ch = 1; ch <= s->fbw_channels; ch++) { if (!block->channel_in_cpl[ch]) continue; for (bnd = 0; bnd < s->num_cpl_bands; bnd++) { cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy[blk][ch][bnd], energy[blk][CPL_CH][bnd]); } } } for (blk = 0; blk < s->num_blocks; blk++) { AC3Block *block = &s->blocks[blk]; AC3Block *block0 = blk ? &s->blocks[blk-1] : NULL; memset(block->new_cpl_coords, 0, sizeof(block->new_cpl_coords)); if (block->cpl_in_use) { if (blk == 0 || !block0->cpl_in_use) { for (ch = 1; ch <= s->fbw_channels; ch++) block->new_cpl_coords[ch] = 1; } else { for (ch = 1; ch <= s->fbw_channels; ch++) { if (!block->channel_in_cpl[ch]) continue; if (!block0->channel_in_cpl[ch]) { block->new_cpl_coords[ch] = 1; } else { CoefSumType coord_diff = 0; for (bnd = 0; bnd < s->num_cpl_bands; bnd++) { coord_diff += FFABS(cpl_coords[blk-1][ch][bnd] - cpl_coords[blk ][ch][bnd]); } coord_diff /= s->num_cpl_bands; if (coord_diff > NEW_CPL_COORD_THRESHOLD) block->new_cpl_coords[ch] = 1; } } } } } for (bnd = 0; bnd < s->num_cpl_bands; bnd++) { blk = 0; while (blk < s->num_blocks) { int av_uninit(blk1); AC3Block *block = &s->blocks[blk]; if (!block->cpl_in_use) { blk++; continue; } for (ch = 1; ch <= s->fbw_channels; ch++) { CoefSumType energy_ch, energy_cpl; if (!block->channel_in_cpl[ch]) continue; energy_cpl = energy[blk][CPL_CH][bnd]; energy_ch = energy[blk][ch][bnd]; blk1 = blk+1; while (!s->blocks[blk1].new_cpl_coords[ch] && blk1 < s->num_blocks) { if (s->blocks[blk1].cpl_in_use) { energy_cpl += energy[blk1][CPL_CH][bnd]; energy_ch += energy[blk1][ch][bnd]; } blk1++; } cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy_ch, energy_cpl); } blk = blk1; } } for (blk = 0; blk < s->num_blocks; blk++) { AC3Block *block = &s->blocks[blk]; if (!block->cpl_in_use) continue; #if CONFIG_AC3ENC_FLOAT s->ac3dsp.float_to_fixed24(fixed_cpl_coords[blk][1], cpl_coords[blk][1], s->fbw_channels * 16); #endif s->ac3dsp.extract_exponents(block->cpl_coord_exp[1], fixed_cpl_coords[blk][1], s->fbw_channels * 16); for (ch = 1; ch <= s->fbw_channels; ch++) { int bnd, min_exp, max_exp, master_exp; if (!block->new_cpl_coords[ch]) continue; min_exp = max_exp = block->cpl_coord_exp[ch][0]; for (bnd = 1; bnd < s->num_cpl_bands; bnd++) { int exp = block->cpl_coord_exp[ch][bnd]; min_exp = FFMIN(exp, min_exp); max_exp = FFMAX(exp, max_exp); } master_exp = ((max_exp - 15) + 2) / 3; master_exp = FFMAX(master_exp, 0); while (min_exp < master_exp * 3) master_exp--; for (bnd = 0; bnd < s->num_cpl_bands; bnd++) { block->cpl_coord_exp[ch][bnd] = av_clip(block->cpl_coord_exp[ch][bnd] - master_exp * 3, 0, 15); } block->cpl_master_exp[ch] = master_exp; for (bnd = 0; bnd < s->num_cpl_bands; bnd++) { int cpl_exp = block->cpl_coord_exp[ch][bnd]; int cpl_mant = (fixed_cpl_coords[blk][ch][bnd] << (5 + cpl_exp + master_exp * 3)) >> 24; if (cpl_exp == 15) cpl_mant >>= 1; else cpl_mant -= 16; block->cpl_coord_mant[ch][bnd] = cpl_mant; } } } if (CONFIG_EAC3_ENCODER && s->eac3) ff_eac3_set_cpl_states(s); }
1threat
Retrieve data from a text file stored in firebase using an android app : I want to know how to retrieve data from a text file stored in the firebase using an app? I am doing an IoT project where i have sensors,which will send data through the arduino board to the cloud as a text file. Different sensors will send different text files.So i wanted to know that is it possible to retrieve data from a text file stored in firebase using an android app?
0debug
Trying to create a simple recyclerView in Kotlin, but the adapter is not applying properly : <p>I'm trying to create a simple recyclerView in Kotlin with data that I get via Volley (which I have confirmed returns the correct data), I keep running to the error <code>E/RecyclerView: No adapter attached; skipping layout</code> when in fact I have specified an adapter with the custom adapter class that I created:</p> <pre><code>class ImageAdapter(var c: Context, var list: ArrayList&lt;Image&gt;) : RecyclerView.Adapter&lt;ImageAdapter.ViewHolder&gt;() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder? { val layoutInflater = LayoutInflater.from(parent.context) return ViewHolder(layoutInflater.inflate(R.layout.image_cardview, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val imageUrl = list[position].url val submitter = list[position].submitter val color = list[position].color holder.submitterTV.text = submitter holder.card.setCardBackgroundColor(Color.parseColor(color)) } override fun getItemCount() = list.size class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){ val card = itemView.card val submitterTV = itemView.submitter val imageView = itemView.image } } </code></pre> <p>This is my MainActivty class, where I make the actual call for the JSON and attempt to attach my adapter with my ArrayList that I have created:</p> <pre><code>class MainActivity : AppCompatActivity() { val images = ArrayList&lt;Image&gt;() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) imageList.layoutManager = LinearLayoutManager(applicationContext) request("https://api.unsplash.com/photos/curated/?client_id=API_KEY") imageList.adapter = ImageAdapter(applicationContext, images) } private fun request(url: String) { val queue = Volley.newRequestQueue(this) val stringRequest = JsonArrayRequest(url, Response.Listener&lt;JSONArray&gt; { response -&gt; try { for (i in 0..(response.length() - 1)) { val image: Image = Image(response.getJSONObject(i).getJSONObject("urls").getString("full"), response.getJSONObject(i).getJSONObject("user").getString("username"), response.getJSONObject(i).getString("color")) images.add(image) } imageList.adapter.notifyDataSetChanged() } catch (e: JSONException) { e.printStackTrace() } }, Response.ErrorListener { }) queue.add(stringRequest) } } </code></pre> <p>I have created a custom data class <code>Image</code> which stores three fields: the imageUrl, submitter and color, all of which are derived from the JSON. I thought that calling <code>notifyDataSetChanged()</code> on my adapter after the request was completed would allow the recyclerView to get updated and show the items, but nothing at all shows up on the screen. Does anyone have any idea as to where I messed up?</p>
0debug
how can we use socket.io with Angular.? : this is my code. import { Component } from '@angular/core'; import { createServer, Server } from 'http'; import * as express from 'express'; import * as socketIo from 'socket.io'; const SERVER_URL = 'localhost:4200'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { public static readonly PORT:number = 8080; private app: express.Application; private server: Server; **"private io: SocketIO.server;"** ////at this line i get error that cannot find namespace SocketIO private port: string | number; } i am trying to use socket.io in my angular app. and i get the error in at the bold line.can any one help me that why i am getting this error.
0debug
static int nbd_send_reply(int csock, struct nbd_reply *reply) { uint8_t buf[4 + 4 + 8]; cpu_to_be32w((uint32_t*)buf, NBD_REPLY_MAGIC); cpu_to_be32w((uint32_t*)(buf + 4), reply->error); cpu_to_be64w((uint64_t*)(buf + 8), reply->handle); TRACE("Sending response to client"); if (write_sync(csock, buf, sizeof(buf)) != sizeof(buf)) { LOG("writing to socket failed"); errno = EINVAL; return -1; } return 0; }
1threat
static int raw_pread(BlockDriverState *bs, int64_t offset, uint8_t *buf, int count) { BDRVRawState *s = bs->opaque; int size, ret, shift, sum; sum = 0; if (s->aligned_buf != NULL) { if (offset & 0x1ff) { shift = offset & 0x1ff; size = (shift + count + 0x1ff) & ~0x1ff; if (size > ALIGNED_BUFFER_SIZE) size = ALIGNED_BUFFER_SIZE; ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size); if (ret < 0) return ret; size = 512 - shift; if (size > count) size = count; memcpy(buf, s->aligned_buf + shift, size); buf += size; offset += size; count -= size; sum += size; if (count == 0) return sum; } if (count & 0x1ff || (uintptr_t) buf & 0x1ff) { while (count) { size = (count + 0x1ff) & ~0x1ff; if (size > ALIGNED_BUFFER_SIZE) size = ALIGNED_BUFFER_SIZE; ret = raw_pread_aligned(bs, offset, s->aligned_buf, size); if (ret < 0) { return ret; } else if (ret == 0) { fprintf(stderr, "raw_pread: read beyond end of file\n"); abort(); } size = ret; if (size > count) size = count; memcpy(buf, s->aligned_buf, size); buf += size; offset += size; count -= size; sum += size; } return sum; } } return raw_pread_aligned(bs, offset, buf, count) + sum; }
1threat
CSS textsize & padding : <p>I have some buttons that should all look the same.</p> <p>1 contains the word "Anmäl" and the other contains "Information". This results in the button with the longer word being bigger and i don't want that!</p> <p>I want the buttons to look the same even though the words are differently long.</p> <p>I'm using padding to make them bigger, i tried "width" but it dosen't work.</p> <p>any help is appreciated!</p> <p>CSS:</p> <pre><code>.startLink { padding: 20px; padding-left: 90px; padding-right: 90px; color: white; background: #8d68dc; border-radius: 5px; font-size: 16px; box-shadow: 0px 5px 10px #000; webkit-transition: all 200ms ease-in; -moz-transition: all 200ms ease-in; -o-transition: all 200ms ease-in; -ms-transition: all 200ms ease-in; transition: all 200ms ease-in;; } </code></pre> <p>HTML:</p> <pre><code>&lt;a href="index.php?anmal" class="startLink"&gt;Anmäl&lt;/a&gt; &lt;a href="index.php?info" class="startLink"&gt;Information&lt;/a&gt; </code></pre>
0debug
static void qmp_output_end_list(Visitor *v) { QmpOutputVisitor *qov = to_qov(v); qmp_output_pop(qov); }
1threat
Xcode Lost connection to iPhone : <p>When running my app on device and than testing offline mode by clicking flight mode on device itself, after 3 seconds i'm getting this message: </p> <blockquote> <p>Restore the connection to "iPhone 6" and run "APP_NAME" again, or if "APP_NAME" is still running, you can attach to it by selecting Debug > Attach to Process > APP_NAME.</p> </blockquote> <ul> <li>iPhone version 9.2.1</li> <li>Xcode version 7.2.1</li> </ul> <p>Does anyone have a clue?</p>
0debug
aws s3 ls The read operation timed out : <p>I try to get a huge list of files from AWS S3 bucket with this command:</p> <pre><code>aws s3 ls --human-readable --recursive my-directory </code></pre> <p>This directory contains tens of thousands of files, so <em>sometimes</em>, after long pause, I get this error:</p> <pre><code>('The read operation timed out',) </code></pre> <p>I've tried parameter <code>--page-size</code> with different values, but it didn't help. How can I fix this error?</p>
0debug
Git pull but never push file : <p>I couldn't find anything specific to this but if I missed it please let me know.</p> <p>I have a file in git which needs to be there. Once pulled down each individual will need to edit it to add their own credentials to it. When edited by the individual I do not want it to show up as having been changed or anything because we want to keep the generic file without credentials in our repo. Is there an option to have a file set up as "Pull this file but never push it"? Currently the setup we have is the file is named Upload.bat_COPY_EDIT_RENAME, which hopefully makes it obvious what to do, and I have Upload.bat in the .gitignore. I'd like something more idiot proof.</p> <p>I know there are options like --assume-unchanged but I don't want to have to run that every time and it seems kind of like a bandaid fix which could potentially cause problems later.</p> <p>Thanks for your help!</p>
0debug
serviceHub.Host.CLR.x86 taking a lot of memory and CPC : <p>serviceHub.Host.CLR.x86 taking a lot of memory and CPC in my Visual Studio 2017 solution. This causes Visual Studio to crash.</p> <p>Any ideas on what the underlying cause is?</p>
0debug
BAT file with C# console app, stop the BAt file from excuting , HOW? : I have a BAT file. I also have a C# CONSOLE APP that checks whether a certain set of files exist in a certain directory. what I need is: If the files are present then continue to run the next steps in the BAT file. Otherwise EXIT. i need some help with how the console app can talk to the BAT file ( you know what I mean ) and then stop the rest of the bat file from running if the input files were not present.
0debug
static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type) { ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP || mode == ARM_CPU_MODE_HYP)) { switch (mode) { case ARM_CPU_MODE_USR: return 0; case ARM_CPU_MODE_SYS: case ARM_CPU_MODE_SVC: case ARM_CPU_MODE_ABT: case ARM_CPU_MODE_UND: case ARM_CPU_MODE_IRQ: case ARM_CPU_MODE_FIQ: /* Note that we don't implement the IMPDEF NSACR.RFR which in v7 * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.) return 0; case ARM_CPU_MODE_HYP: return !arm_feature(env, ARM_FEATURE_EL2) || arm_current_el(env) < 2 || arm_is_secure(env); case ARM_CPU_MODE_MON: return arm_current_el(env) < 3; default:
1threat
Does Java's lack of multiple inheritance hurt its potential for Android game development? : <p>I'm currently enrolled in a mobile app development class, and I have an idea for a game that I'd like to do that involves virtual pets. I'm confident that I'll be able to utilize Java's capabilities for this class without a problem, but further down the line if I wanted to, say, fuse pets and/or breed, I imagine it might become difficult to implement my ideas using Java. </p> <p>I know that objects can inherit from multiple interfaces and there are ways of obtaining variables through other means, but in terms of code and app efficiency, would I be better off using another language down the line?</p> <p>Really looking forward to this discussion, as I enjoy hearing the pros and cons of each side. Java's my favorite language at the moment because I'm most familiar with it, but even so... I'd love to branch out if I'd be better off doing so. I've looked this up using search engines many times but I thought this would be a more hands-on approach to engage with people in conversation as opposed to simply reading past threads. </p> <p>Thanks in advance!</p>
0debug
"Cannot resolve method" with mockito : <p>I use <code>org.springframework.security.core.Authentication</code> which has a method:</p> <pre><code>Collection&lt;? extends GrantedAuthority&gt; getAuthorities(); </code></pre> <p>I want to mock it as below:</p> <pre><code>when(authentication.getAuthorities()).thenReturn(grantedAuthorities); </code></pre> <p>with authorities collection:</p> <pre><code>Collection&lt;SimpleGrantedAuthority&gt; grantedAuthorities = Lists.newArrayList( new SimpleGrantedAuthority(AuthoritiesConstants.USER)); </code></pre> <p>And I am using <code>org.springframework.security.core.authority.SimpleGrantedAuthority</code> which extends <code>GrantedAuthority</code></p> <p>And Intellij gives me below compile error:</p> <pre><code>Cannot resolve method 'thenReturn(java.util.Collection&lt;org.spring.security.core.authority.SimpleGrantedAuthority&gt;)' </code></pre> <p>I use Mockito <code>2.15.0</code> and <code>thenReturn()</code> method from it is:</p> <pre><code>OngoingStubbing&lt;T&gt; thenReturn(T value); </code></pre> <p>What is the problem?</p>
0debug
I need to implement a function that can be used multiple times. For that i have swift code. Can anyone convert it into objective C : func getdata(_ send: NSString) { let url=URL(string:send as String) do { let allContactsData = try Data(contentsOf: url!) let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject] print(allContacts) if let musicJob = allContacts["Attendance"] as? [Any], !musicJob.isEmpty { print(musicJob) dataArray = allContacts["Attendance"] as! NSArray print(dataArray) } let send: String = String(format:"http:xyz",loadedUserName,studentId,row+1) self.getdata(send as NSString) > How to convert this into objective C, Any help pls. I need to use this func getdata(_ send: NSString) multiple times
0debug
Event Data Collected by Firebase Analytics DebugView Is Incomplete : <p>I'm sending events to Firebase Analytics and find out that part of the event parameters is missing in DebugView.</p> <p>Below are two identical events sending to Firebase and I've checked that all the parameters are there in Xcode debug console.</p> <p><a href="https://i.stack.imgur.com/MX6UY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MX6UY.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/HuqW7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HuqW7.png" alt="enter image description here"></a></p> <p>The missing parameters seem to be random. Sometimes there's no custom param at all, only auto-collected data.</p> <p>Is there anyone also encounters this problem or does anyone know what causes this?</p> <p>I'm using FirebaseAnalytics (= 5.8.1)</p>
0debug
Import Dependency Management with Exclusion : <p>I have a beautiful BOM with a lot of dependencies in its dependencyManagement section and I would like to <strong>create another BOM</strong> that imports all that dependencies <strong>except one</strong>. I tried doing this:</p> <pre><code>... in my dependencyManagement section &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-dependencies&lt;/artifactId&gt; &lt;version&gt;${spring-boot-version}&lt;/version&gt; &lt;type&gt;pom&lt;/type&gt; &lt;scope&gt;import&lt;/scope&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;com.google.code.gson&lt;/groupId&gt; &lt;artifactId&gt;gson&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; ... </code></pre> <p>The POM is formally correct and everything compiles. <strong>But the exclusion is simply ignored. What am I missing? Is this approach correct?</strong></p> <p>I'm using Maven 3+.</p>
0debug
Double tap gesture works only once : I'm trying to add double tap gesture recognizer on `imageView`. Double tap recognizer works only for once and if image is double tapped for second time, selector doesn't response. Below is code I'm trying productImageView.isUserInteractionEnabled = true let doubleTap = UITapGestureRecognizer.init(target: self, action: #selector(self.sampleTapGestureTapped(recognizer:))) doubleTap.numberOfTapsRequired = 2 productImageView.addGestureRecognizer(doubleTap)
0debug
static int local_symlink(FsContext *fs_ctx, const char *oldpath, V9fsPath *dir_path, const char *name, FsCred *credp) { int err = -1; int serrno = 0; char *newpath; V9fsString fullname; char *buffer; v9fs_string_init(&fullname); v9fs_string_sprintf(&fullname, "%s/%s", dir_path->data, name); newpath = fullname.data; if (fs_ctx->export_flags & V9FS_SM_MAPPED) { int fd; ssize_t oldpath_size, write_size; buffer = rpath(fs_ctx, newpath); fd = open(buffer, O_CREAT|O_EXCL|O_RDWR|O_NOFOLLOW, SM_LOCAL_MODE_BITS); if (fd == -1) { g_free(buffer); err = fd; goto out; } oldpath_size = strlen(oldpath); do { write_size = write(fd, (void *)oldpath, oldpath_size); } while (write_size == -1 && errno == EINTR); if (write_size != oldpath_size) { serrno = errno; close(fd); err = -1; goto err_end; } close(fd); credp->fc_mode = credp->fc_mode|S_IFLNK; err = local_set_xattr(buffer, credp); if (err == -1) { serrno = errno; goto err_end; } } else if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) { int fd; ssize_t oldpath_size, write_size; buffer = rpath(fs_ctx, newpath); fd = open(buffer, O_CREAT|O_EXCL|O_RDWR|O_NOFOLLOW, SM_LOCAL_MODE_BITS); if (fd == -1) { g_free(buffer); err = fd; goto out; } oldpath_size = strlen(oldpath); do { write_size = write(fd, (void *)oldpath, oldpath_size); } while (write_size == -1 && errno == EINTR); if (write_size != oldpath_size) { serrno = errno; close(fd); err = -1; goto err_end; } close(fd); credp->fc_mode = credp->fc_mode|S_IFLNK; err = local_set_mapped_file_attr(fs_ctx, newpath, credp); if (err == -1) { serrno = errno; goto err_end; } } else if ((fs_ctx->export_flags & V9FS_SM_PASSTHROUGH) || (fs_ctx->export_flags & V9FS_SM_NONE)) { buffer = rpath(fs_ctx, newpath); err = symlink(oldpath, buffer); if (err) { g_free(buffer); goto out; } err = lchown(buffer, credp->fc_uid, credp->fc_gid); if (err == -1) { if ((fs_ctx->export_flags & V9FS_SEC_MASK) != V9FS_SM_NONE) { serrno = errno; goto err_end; } else err = 0; } } goto out; err_end: remove(buffer); errno = serrno; g_free(buffer); out: v9fs_string_free(&fullname); return err; }
1threat
ReactJS delay onChange while typing : <p>I need the state to change to maintain the string the user is typing. However I want to delay an action until the user stops typing. But I can't quite place my finger on how to do both.</p> <p>So When the user stops typing I want an action to be triggered, but not before. Any suggestions?</p>
0debug
How to show all images in a folder? : <p>I'm trying to make a page where I can share pictures. For the time being, I'm not using a database, just uploading them into my htdocs. All of my pictures will be PNG, and saved in a folder called <code>myimages</code>. I want a page to list all of these images, if it's possible. Thanks for the help!</p>
0debug
static int decode_unit(SCPRContext *s, PixelModel *pixel, unsigned step, unsigned *rval) { GetByteContext *gb = &s->gb; RangeCoder *rc = &s->rc; unsigned totfr = pixel->total_freq; unsigned value, x = 0, cumfr = 0, cnt_x = 0; int i, j, ret, c, cnt_c; if ((ret = s->get_freq(rc, totfr, &value)) < 0) return ret; while (x < 16) { cnt_x = pixel->lookup[x]; if (value >= cumfr + cnt_x) cumfr += cnt_x; else break; x++; } c = x * 16; cnt_c = 0; while (c < 256) { cnt_c = pixel->freq[c]; if (value >= cumfr + cnt_c) cumfr += cnt_c; else break; c++; } s->decode(gb, rc, cumfr, cnt_c, totfr); pixel->freq[c] = cnt_c + step; pixel->lookup[x] = cnt_x + step; totfr += step; if (totfr > BOT) { totfr = 0; for (i = 0; i < 256; i++) { unsigned nc = (pixel->freq[i] >> 1) + 1; pixel->freq[i] = nc; totfr += nc; } for (i = 0; i < 16; i++) { unsigned sum = 0; unsigned i16_17 = i << 4; for (j = 0; j < 16; j++) sum += pixel->freq[i16_17 + j]; pixel->lookup[i] = sum; } } pixel->total_freq = totfr; *rval = c & s->cbits; return 0; }
1threat
Get absolute file path of FileField of a model instance in Django : <p>I have a page where people can upload files to my server.</p> <p>I want to do something with the file in Celery. So, I need to know the absolute filepath of the uploaded FileFiled of my Model.</p> <p>Let's say I queried the model and got the instance. Now I need to get the absolute file path including the filepath.</p> <p><code>obj = Audio.objects.get(pk=1)</code></p> <p>I'm currently trying <code>obj.filename</code> and it's only printing the file name and not the absolute path.</p> <p>I know I can get the upload path I input into <code>upload_to</code> and media directory, but I was wondering if there was a more DRY and automatic approach.</p> <p>How do I get the <code>absolute path</code> of <code>file</code> which is a file filed in <code>obj</code>?</p>
0debug
How to get last number from a string in javascript : Trying to get last numbers from a string in javascript. var source="MA01"; I want to get only 1 from the string.How to get it?
0debug
Travis CI Build Failing : <p>I am having an issue with Travis CI - the commits that I push all fail with the same error:</p> <blockquote> <p>0.06s$ curl -sSL "<a href="http://llvm.org/apt/llvm-snapshot.gpg.key">http://llvm.org/apt/llvm-snapshot.gpg.key</a>" | sudo -E apt-key add - gpg: no valid OpenPGP data found. The command "curl -sSL "<a href="http://llvm.org/apt/llvm-snapshot.gpg.key">http://llvm.org/apt/llvm-snapshot.gpg.key</a>" | sudo -E apt-key add -" failed and exited with 2 during . Your build has been stopped.</p> </blockquote> <p>I tried to rebuild a previous commit that built successfully and the same error occurs. Any suggestions as to how to troubleshoot the issue?</p>
0debug
static void v9fs_getlock(void *opaque) { size_t offset = 7; struct stat stbuf; V9fsFidState *fidp; V9fsGetlock *glock; int32_t fid, err = 0; V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; glock = g_malloc(sizeof(*glock)); pdu_unmarshal(pdu, offset, "dbqqds", &fid, &glock->type, &glock->start, &glock->length, &glock->proc_id, &glock->client_id); trace_v9fs_getlock(pdu->tag, pdu->id, fid, glock->type, glock->start, glock->length); fidp = get_fid(pdu, fid); if (fidp == NULL) { err = -ENOENT; goto out_nofid; } err = v9fs_co_fstat(pdu, fidp, &stbuf); if (err < 0) { goto out; } glock->type = P9_LOCK_TYPE_UNLCK; offset += pdu_marshal(pdu, offset, "bqqds", glock->type, glock->start, glock->length, glock->proc_id, &glock->client_id); err = offset; trace_v9fs_getlock_return(pdu->tag, pdu->id, glock->type, glock->start, glock->length, glock->proc_id); out: put_fid(pdu, fidp); out_nofid: complete_pdu(s, pdu, err); v9fs_string_free(&glock->client_id); g_free(glock); }
1threat
How to Change List paranthesis from [] to none : short Question in Code: i=0 k_start[i] [8515] i=1 k_start[i] 139253 How can i avoid the parenthesis in this example? Or Why at least do they appear with when i is 0? Thanks and best Regards Bastian
0debug
def discriminant_value(x,y,z): discriminant = (y**2) - (4*x*z) if discriminant > 0: return ("Two solutions",discriminant) elif discriminant == 0: return ("one solution",discriminant) elif discriminant < 0: return ("no real solution",discriminant)
0debug
static int coroutine_fn bdrv_co_do_zero_pwritev(BlockDriverState *bs, int64_t offset, unsigned int bytes, BdrvRequestFlags flags, BdrvTrackedRequest *req) { uint8_t *buf = NULL; QEMUIOVector local_qiov; struct iovec iov; uint64_t align = bs->bl.request_alignment; unsigned int head_padding_bytes, tail_padding_bytes; int ret = 0; head_padding_bytes = offset & (align - 1); tail_padding_bytes = align - ((offset + bytes) & (align - 1)); assert(flags & BDRV_REQ_ZERO_WRITE); if (head_padding_bytes || tail_padding_bytes) { buf = qemu_blockalign(bs, align); iov = (struct iovec) { .iov_base = buf, .iov_len = align, }; qemu_iovec_init_external(&local_qiov, &iov, 1); } if (head_padding_bytes) { uint64_t zero_bytes = MIN(bytes, align - head_padding_bytes); mark_request_serialising(req, align); wait_serialising_requests(req); bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD); ret = bdrv_aligned_preadv(bs, req, offset & ~(align - 1), align, align, &local_qiov, 0); if (ret < 0) { goto fail; } bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD); memset(buf + head_padding_bytes, 0, zero_bytes); ret = bdrv_aligned_pwritev(bs, req, offset & ~(align - 1), align, align, &local_qiov, flags & ~BDRV_REQ_ZERO_WRITE); if (ret < 0) { goto fail; } offset += zero_bytes; bytes -= zero_bytes; } assert(!bytes || (offset & (align - 1)) == 0); if (bytes >= align) { uint64_t aligned_bytes = bytes & ~(align - 1); ret = bdrv_aligned_pwritev(bs, req, offset, aligned_bytes, align, NULL, flags); if (ret < 0) { goto fail; } bytes -= aligned_bytes; offset += aligned_bytes; } assert(!bytes || (offset & (align - 1)) == 0); if (bytes) { assert(align == tail_padding_bytes + bytes); mark_request_serialising(req, align); wait_serialising_requests(req); bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL); ret = bdrv_aligned_preadv(bs, req, offset, align, align, &local_qiov, 0); if (ret < 0) { goto fail; } bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL); memset(buf, 0, bytes); ret = bdrv_aligned_pwritev(bs, req, offset, align, align, &local_qiov, flags & ~BDRV_REQ_ZERO_WRITE); } fail: qemu_vfree(buf); return ret; }
1threat
Excel VBA, code to count the # of filled cells, then find highest and 2nd highest and subtract the corresponding column #'s : <p>I'm looking to count the # of items in a list from A11 to A90. And if that number is even subtract the max value from the 2nd max and then 3rd max from 4th max, etc.. If it's odd then it would start at the 2nd max minus the 3rd, and 4th to 5th etc.. Until all numbers have been subtracted from their counterpart. The tricky part is that the numbers which need to be subtracted are in a different column, C11 to C90. </p> <p>I'm basically trying to find the number of consecutive negative outcomes from column C using the 2 closest values from column A. </p> <p>Any input would be greatly appreciated!!</p>
0debug
Count from long to wide format : <p>Having a long format like this:</p> <pre><code>df &lt;- data.frame(id = c(1,1,1,2,2), text = c("stock","arrange","stock","arrange","arrange")) </code></pre> <p>How is it possible to receive the wide format of making the variables in text column new columns which have as values the number the exist? Example of expected output:</p> <pre><code>data.frame(id = c(1,2) stock = c(2,0), arrange = c(1,2)) </code></pre>
0debug
How to remove common rows in two dataframes in Pandas? : <p>I have two dataframes - <code>df1</code> and <code>df2</code>.</p> <pre><code>df1 has row1,row2,row3,row4,row5 df2 has row2,row5 </code></pre> <p>I want to have a new dataframe such that <code>df1-df2</code>. That is, the resultant dataframe should have rows as - <code>row1,row3,row4</code>. </p>
0debug
Angular 2 - Form is invalid when browser autofill : <p>I have a Login Form which has email and password fields.</p> <p>I've chosen for browser autofill.</p> <p>The problems is: When browser autofills login form, both fields are pristine and untouched, so the submit button is disabled.</p> <p>If I click on disabled button, it enables and fires submit action, what is nice. But the default disabled aspect is pretty bad what can make some users disappointed.</p> <p>Do you have some ideas about how to deal with?</p>
0debug
Java - Threads using a loop : Having trouble printing the contents of my array in a non synchronized way. I am looking to iterate through and output the letters "A" , "B" , "C" in a non sequential manner from a static array of strings using Threads to print the loop. Here is my Code public class ThreadWithExtends extends Thread { public ThreadWithExtends() { super(); } public void run() { String[] arr = { "A", "B", "C" }; int num = 10; try { for (int j = 0; j < num; j++) { for (int i = 0; i < arr.length; i++) { sleep((int) (Math.random() * 1000)); System.out.print(arr[i] + " "); } } } catch (InterruptedException e) { System.out.println("Finished"); } } } My TestThread class public class TestThread { public static void main(String args[]) { new ThreadWithExtends().start(); } } My Output : A B C A B C A B C A B C A B C A B C A B C A B C A B C A B C My Desired Output : C A B A B C B A C .. etc , not sequential like above.
0debug
URGENT HELP! multiple nCr program : Okay, so I have to create a nCr program. I need to allow the user to input the amount of nCr values they wish to calculate ( between 2 and 12 inclusive). Then input the n and r values accordingly, making sure n is greater than r (n > r) Afterwards i need to calculate and store the nCr value in an array and output the values I wish to output the values in the format of a 2d array in the form of: n | c | nCr ----------- (without the grids) So far my code is as follows: public class nCr { public static void main (String[] args) { int nCrValues; System.out.println("Enter amount of nCr values you wish to calculate: "); nCrValues = input(); while ((nCrValues < 2) || (nCrValues > 10)){ System.out.println("Must be between 2 and 12 inclusive"); nCrValues = input(); }//END while values(nCrValues); }//END main public static void values(int nCrValues){ //I know I need a loop to nCrValues to input 'n' and 'r' as an array, not sure how int n, r; System.out.println("Enter n value: "); n = input(); System.out.println("Enter r value: "); r = input(); calculatenCr(n,r); }//END values public static int calculatenCr(int n, int r){ int nCr; nCr = fact(n) / (fact(n-r) * fact(t)); //store nCr values in array }//END calculatenCr public static int fact(int num){ int count; int factor = 1; for (count = 1; count <= num; count++){ factor *= count; }//END for return factor; }//END fact public static int input(){ int input; Scanner sc = new Scanner(System.in); input = sc.nextInt(); while (input < 0){ System.out.println("Must be a positive number.")' input = sc.nextInt(); }//END while return input; }//END input }//END CLASS I need a method that outputs the arrays int the form n | c | nCr | ------------- how do i go by that and is all my coding correct so far? Thank you very much
0debug
Android Data Binding: how to pass variable to include layout : <p>Google documentation says that variables may be passed into an included layout's binding from the containing layout but I can't make it work but get data binding error ****msg:Identifiers must have user defined types from the XML file. handler is missing it. The including XML looks like this:</p> <pre><code>&lt;layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:bind="http://schemas.android.com/apk/res-auto"&gt; &lt;data&gt; &lt;import type="com.example.FocusChangeHandler"/&gt; &lt;variable name="handler" type="FocusChangeHandler"/&gt; &lt;/data&gt; &lt;!-- Some other views ---&gt; &lt;include android:id="@+id/inputs" layout="@layout/input_fields" bind:handler="@{handler}"/&gt; &lt;/layout&gt; </code></pre> <p>And the included XML like this: </p> <pre><code>&lt;layout xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;EditText android:id="@+id/nameEdit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onFocusChange="@{handler.onFocusChange}"/&gt; &lt;/layout&gt; </code></pre> <p>I'm able to refer the Views from included layout through generated binding class but passing a variable just doesn't work. </p>
0debug
static int handle_packets(AVFormatContext *s, int nb_packets) { MpegTSContext *ts = s->priv_data; ByteIOContext *pb = &s->pb; uint8_t packet[TS_FEC_PACKET_SIZE]; int packet_num, len; ts->stop_parse = 0; packet_num = 0; for(;;) { if (ts->stop_parse) break; packet_num++; if (nb_packets != 0 && packet_num >= nb_packets) break; len = get_buffer(pb, packet, ts->raw_packet_size); if (len != ts->raw_packet_size) return AVERROR_IO; if (packet[0] != 0x47) return AVERROR_INVALIDDATA; handle_packet(s, packet); } return 0; }
1threat
How do I turn a dict and an array into a list? : <p>I have a dictionary "a" and an array "b" </p> <p>"a" looks somewhat like this: </p> <pre><code>{Volvo: 657898, Volkswagen: 387564}... etc </code></pre> <p>and "b" looks like this: </p> <pre><code>[['Volvo' 'VO'] ['Volkswagen' 'VW']] ... etc </code></pre> <p>How do I compare them, and make a list that looks like this:</p> <pre><code>[['Volvo', 'VO', 657898], ['Volkswagen', 'VW', 387564], etc... </code></pre>
0debug
Is there any command that I can use gsutil rm to delete the subversion? : I am learning how to use google cloud I used this command: <br> "gsutil ls -la gs://bucket01/*"<br> And I get the follow information:<br> <br> display.json01<br> display.json02<br> display.json03<br> display.json04<br> display.json05<br> How can I delete all the previous version and just to keep the new file that would be display.json05? <br> thanks for any help, I really need a solution!
0debug
How to initialize new object with a data type List<T>? : <p>I am a beginner in C# and I want to initialize a new object which contains the datatype string as well a data type list&lt;> from a enumeration. How does the structure/semantics looks like if I put a List into a new object ? Thank you for your help.</p> <p>I have searched on stackoverflow and also on MSDN and didn't found a proper solution.</p> <p>This is my code:</p> <pre><code>Vegetables Veg1 = new Vegetables("Apple", List&lt;Colour&gt;("red, green, yellow")); </code></pre>
0debug
void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd, int64_t bps_wr, int64_t iops, int64_t iops_rd, int64_t iops_wr, bool has_bps_max, int64_t bps_max, bool has_bps_rd_max, int64_t bps_rd_max, bool has_bps_wr_max, int64_t bps_wr_max, bool has_iops_max, int64_t iops_max, bool has_iops_rd_max, int64_t iops_rd_max, bool has_iops_wr_max, int64_t iops_wr_max, bool has_iops_size, int64_t iops_size, bool has_group, const char *group, Error **errp) { ThrottleConfig cfg; BlockDriverState *bs; BlockBackend *blk; AioContext *aio_context; blk = blk_by_name(device); if (!blk) { error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND, "Device '%s' not found", device); return; } aio_context = blk_get_aio_context(blk); aio_context_acquire(aio_context); bs = blk_bs(blk); if (!bs) { error_setg(errp, "Device '%s' has no medium", device); goto out; } memset(&cfg, 0, sizeof(cfg)); cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps; cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd; cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr; cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops; cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd; cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr; if (has_bps_max) { cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max; } if (has_bps_rd_max) { cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max; } if (has_bps_wr_max) { cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max; } if (has_iops_max) { cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max; } if (has_iops_rd_max) { cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max; } if (has_iops_wr_max) { cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max; } if (has_iops_size) { cfg.op_size = iops_size; } if (!check_throttle_config(&cfg, errp)) { goto out; } if (throttle_enabled(&cfg)) { if (!bs->io_limits_enabled) { bdrv_io_limits_enable(bs, has_group ? group : device); } else if (has_group) { bdrv_io_limits_update_group(bs, group); } bdrv_set_io_limits(bs, &cfg); } else if (bs->io_limits_enabled) { bdrv_io_limits_disable(bs); } out: aio_context_release(aio_context); }
1threat
Why is this call to strstr not returning false? : <p>I've stumbled upon an issue with <a href="https://secure.php.net/manual/en/function.strstr.php" rel="noreferrer">strstr</a> in an old legacy codebase. There's lot of code, but basically the test case would come down to this:</p> <pre><code>$value = 2660; $link = 'affiliateid=1449&amp;zoneid=6011&amp;placement_id=11736&amp;publisher_id=1449&amp;period_preset=yesterday&amp;period_start=2017-03-27&amp;period_end=2017-03-27'; var_dump(strstr($link, $value)); </code></pre> <p>I would expect this to return <code>false</code> since "2660" is not in the string however it returns <code>d=1449&amp;zoneid=6011&amp;placement_id=11736&amp;publisher_id=1449&amp;period_preset=yesterday&amp;period_start=2017-03-27&amp;period_end=2017-03-27</code>.</p> <p>I realise that <code>$value</code> should be a string but still I don't understand why it's not casted to a string by PHP and why it's finding this number in the link.</p> <p>Actually, if I try with <code>$value = '2660';</code> it returns <code>false</code> as expected.</p> <p>Any idea what's happening?</p>
0debug
tar/zip AND transfer to another server with limited space remaining : <p>I have a folder which is 60Gigabytes in size on a server I need to destroy. But, I only have 6G of space remaining on the server.</p> <p>Besides the size of the folder, there are literally hundreds of thousands of small files in it. So doing a simple <code>scp</code> would take forever. I really want to <code>tar czf</code> the folder, but again, I don't have the space.</p> <p>Is there any way to do this?</p>
0debug
How to convert a list of strings into a tensor in pytorch? : <p>I am working on classification problem in which I have a list of strings as class labels and I want to convert them into a tensor. So far I have tried converting the list of strings into a <code>numpy array</code> using the <code>np.array</code> function provided by the numpy module. </p> <p><code>truth = torch.from_numpy(np.array(truths))</code></p> <p>but I am getting the following error.</p> <p><code>RuntimeError: can't convert a given np.ndarray to a tensor - it has an invalid type. The only supported types are: double, float, int64, int32, and uint8.</code></p> <p>Can anybody suggest an alternative approach? Thanks</p>
0debug
static int qsv_decode(AVCodecContext *avctx, QSVContext *q, AVFrame *frame, int *got_frame, AVPacket *avpkt) { QSVFrame *out_frame; mfxFrameSurface1 *insurf; mfxFrameSurface1 *outsurf; mfxSyncPoint *sync; mfxBitstream bs = { { { 0 } } }; int ret; if (avpkt->size) { bs.Data = avpkt->data; bs.DataLength = avpkt->size; bs.MaxLength = bs.DataLength; bs.TimeStamp = avpkt->pts; } sync = av_mallocz(sizeof(*sync)); if (!sync) { av_freep(&sync); return AVERROR(ENOMEM); } do { ret = get_surface(avctx, q, &insurf); if (ret < 0) return ret; ret = MFXVideoDECODE_DecodeFrameAsync(q->session, avpkt->size ? &bs : NULL, insurf, &outsurf, sync); if (ret == MFX_WRN_DEVICE_BUSY) av_usleep(500); } while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_ERR_MORE_SURFACE); if (ret != MFX_ERR_NONE && ret != MFX_ERR_MORE_DATA && ret != MFX_WRN_VIDEO_PARAM_CHANGED && ret != MFX_ERR_MORE_SURFACE) { av_log(avctx, AV_LOG_ERROR, "Error during QSV decoding.\n"); av_freep(&sync); return ff_qsv_error(ret); } if (!*sync && !bs.DataOffset) { av_log(avctx, AV_LOG_WARNING, "A decode call did not consume any data\n"); bs.DataOffset = avpkt->size; } if (*sync) { QSVFrame *out_frame = find_frame(q, outsurf); if (!out_frame) { av_log(avctx, AV_LOG_ERROR, "The returned surface does not correspond to any frame\n"); av_freep(&sync); return AVERROR_BUG; } out_frame->queued = 1; av_fifo_generic_write(q->async_fifo, &out_frame, sizeof(out_frame), NULL); av_fifo_generic_write(q->async_fifo, &sync, sizeof(sync), NULL); } else { av_freep(&sync); } if (!av_fifo_space(q->async_fifo) || (!avpkt->size && av_fifo_size(q->async_fifo))) { AVFrame *src_frame; av_fifo_generic_read(q->async_fifo, &out_frame, sizeof(out_frame), NULL); av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL); out_frame->queued = 0; do { ret = MFXVideoCORE_SyncOperation(q->session, *sync, 1000); } while (ret == MFX_WRN_IN_EXECUTION); av_freep(&sync); src_frame = out_frame->frame; ret = av_frame_ref(frame, src_frame); if (ret < 0) return ret; outsurf = out_frame->surface; #if FF_API_PKT_PTS FF_DISABLE_DEPRECATION_WARNINGS frame->pkt_pts = outsurf->Data.TimeStamp; FF_ENABLE_DEPRECATION_WARNINGS #endif frame->pts = outsurf->Data.TimeStamp; frame->repeat_pict = outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_TRIPLING ? 4 : outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_DOUBLING ? 2 : outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_REPEATED ? 1 : 0; frame->top_field_first = outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_TFF; frame->interlaced_frame = !(outsurf->Info.PicStruct & MFX_PICSTRUCT_PROGRESSIVE); *got_frame = 1; } return bs.DataOffset; }
1threat
Notice: Array to string conversion in C:\xampp\htdocs\Employ\index.php on line 36 : I want to insert data into the database using form but I'm getting error. What can I do to solve this? My code is follows I've tried several way to bug it but not working $country = mysqli_real_escape_string($conn, $_POST['country']); $zip = mysqli_real_escape_string($conn, $_POST['zip']); $identity =($_FILES['identity']); $fileName = $_FILES['identity']['name']; $fileTmpName = $_FILES['identity']['tmp_name']; $fileSize = $_FILES['identity']['size']; $fileError = $_FILES['identity']['error']; $fileType = $_FILES['identity']['type']; $fileExt = explode('.', $fileName); $fileActualExt = strtolower(end($fileExt)); $allow = array('jpg', 'jpeg', 'png',); if (in_array($fileActualExt, $allow)) { if ($fileError === 0) { if ($fileSize < 1000000) { $fileNameNew = uniqid('', true).".".$fileActualExt; $fileDestination = 'uploads/'.$fileNameNew; move_uploaded_file($fileTmpName, $fileDestination); $sql = "INSERT INTO applicants (name, email, gender, dob, mobile, accounts, occupation, ssn, m_status, address1, address2, city, country, zip, identity) VALUES ('$name', '$email', '$gender', '$dob', '$mobile', '$accounts', '$occupation', '$ssn', '$m_status', '$address1', '$address2', '$city', '$country', '$zip', '$identity')"; $insert = mysqli_query($conn, $sql);
0debug
Regex to get text between two Special Characters : <p>&lt;%=NAME=%> Your Payment is &lt;%=Payment=%> Regards Rakesh Patel</p>
0debug
how to return Javascript variable in JSON format PHP? : <p>I want to <strong>return</strong> Javascript variable in JSON format in PHP.</p> <p>Below is my Javascript code which returns Longitude and Latitude.</p> <pre><code>function showPosition(){ if(navigator.geolocation){ navigator.geolocation.getCurrentPosition(function(position){ var positionInfo = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")"; //document.getElementById("result").innerHTML = positionInfo; }); } else{ alert("Sorry, your browser does not support HTML5 geolocation."); } } showPosition(); //document.write(positionInfo); </code></pre> <blockquote> <p>How can i get the values of variable <code>position.coords.latitude</code> and <code>position.coords.longitude</code> as response in json format using php</p> </blockquote> <p><strong>Please note:</strong> We are calling this php script in background, so solution of fetching the variables on html input fields is not a viable solution for us.</p>
0debug
static int set_string_fmt(void *obj, const AVOption *o, const char *val, uint8_t *dst, int fmt_nb, int ((*get_fmt)(const char *)), const char *desc) { int fmt; if (!val || !strcmp(val, "none")) { fmt = -1; } else { fmt = get_fmt(val); if (fmt == -1) { char *tail; fmt = strtol(val, &tail, 0); if (*tail || (unsigned)fmt >= fmt_nb) { av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as %s\n", val, desc); return AVERROR(EINVAL); } } } *(int *)dst = fmt; return 0; }
1threat
how to generate automatic Rows : I have Below Sample Table month year budget_Amt Actual_Amt feb 2017 25 30 mar 2016 10 5 apr 2016 50 15 i'am executing following query select month,year,budget_amt,Actual_Amt from Table where month in('Feb','Mar','apr') i need following output month year budget_Amt Actual_Amt feb 2017 25 30 mar 2016 10 5 apr 2016 50 15 QuarterYTD 2016 85 50 4th record will generate automatically when i execute query please help Thank u
0debug
static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1, int letter, const char *buf) { RTSPState *rt = s->priv_data; char buf1[64], st_type[64]; const char *p; int codec_type, payload_type, i; AVStream *st; RTSPStream *rtsp_st; struct in_addr sdp_ip; int ttl; #ifdef DEBUG printf("sdp: %c='%s'\n", letter, buf); #endif p = buf; switch(letter) { case 'c': get_word(buf1, sizeof(buf1), &p); if (strcmp(buf1, "IN") != 0) return; get_word(buf1, sizeof(buf1), &p); if (strcmp(buf1, "IP4") != 0) return; get_word_sep(buf1, sizeof(buf1), "/", &p); if (inet_aton(buf1, &sdp_ip) == 0) return; ttl = 16; if (*p == '/') { p++; get_word_sep(buf1, sizeof(buf1), "/", &p); ttl = atoi(buf1); } if (s->nb_streams == 0) { s1->default_ip = sdp_ip; s1->default_ttl = ttl; } else { st = s->streams[s->nb_streams - 1]; rtsp_st = st->priv_data; rtsp_st->sdp_ip = sdp_ip; rtsp_st->sdp_ttl = ttl; } break; case 's': pstrcpy(s->title, sizeof(s->title), p); break; case 'i': if (s->nb_streams == 0) { pstrcpy(s->comment, sizeof(s->comment), p); break; } break; case 'm': get_word(st_type, sizeof(st_type), &p); if (!strcmp(st_type, "audio")) { codec_type = CODEC_TYPE_AUDIO; } else if (!strcmp(st_type, "video")) { codec_type = CODEC_TYPE_VIDEO; } else { return; } rtsp_st = av_mallocz(sizeof(RTSPStream)); if (!rtsp_st) return; rtsp_st->stream_index = -1; dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st); rtsp_st->sdp_ip = s1->default_ip; rtsp_st->sdp_ttl = s1->default_ttl; get_word(buf1, sizeof(buf1), &p); rtsp_st->sdp_port = atoi(buf1); get_word(buf1, sizeof(buf1), &p); get_word(buf1, sizeof(buf1), &p); rtsp_st->sdp_payload_type = atoi(buf1); if (rtsp_st->sdp_payload_type == RTP_PT_MPEG2TS) { } else { st = av_new_stream(s, 0); if (!st) return; st->priv_data = rtsp_st; rtsp_st->stream_index = st->index; st->codec.codec_type = codec_type; if (rtsp_st->sdp_payload_type < 96) { rtp_get_codec_info(&st->codec, rtsp_st->sdp_payload_type); } } pstrcpy(rtsp_st->control_url, sizeof(rtsp_st->control_url), s->filename); break; case 'a': if (strstart(p, "control:", &p) && s->nb_streams > 0) { char proto[32]; st = s->streams[s->nb_streams - 1]; rtsp_st = st->priv_data; url_split(proto, sizeof(proto), NULL, 0, NULL, NULL, 0, p); if (proto[0] == '\0') { pstrcat(rtsp_st->control_url, sizeof(rtsp_st->control_url), "/"); pstrcat(rtsp_st->control_url, sizeof(rtsp_st->control_url), p); } else { pstrcpy(rtsp_st->control_url, sizeof(rtsp_st->control_url), p); } } else if (strstart(p, "rtpmap:", &p)) { get_word(buf1, sizeof(buf1), &p); payload_type = atoi(buf1); for(i = 0; i < s->nb_streams;i++) { st = s->streams[i]; rtsp_st = st->priv_data; if (rtsp_st->sdp_payload_type == payload_type) { sdp_parse_rtpmap(&st->codec, p); } } } else if (strstart(p, "fmtp:", &p)) { get_word(buf1, sizeof(buf1), &p); payload_type = atoi(buf1); for(i = 0; i < s->nb_streams;i++) { st = s->streams[i]; rtsp_st = st->priv_data; if (rtsp_st->sdp_payload_type == payload_type) { sdp_parse_fmtp(&st->codec, p); } } } break; } }
1threat
int qxl_render_cursor(PCIQXLDevice *qxl, QXLCommandExt *ext) { QXLCursorCmd *cmd = qxl_phys2virt(qxl, ext->cmd.data, ext->group_id); QXLCursor *cursor; QEMUCursor *c; if (!cmd) { return 1; } if (!dpy_cursor_define_supported(qxl->vga.con)) { return 0; } if (qxl->debug > 1 && cmd->type != QXL_CURSOR_MOVE) { fprintf(stderr, "%s", __FUNCTION__); qxl_log_cmd_cursor(qxl, cmd, ext->group_id); fprintf(stderr, "\n"); } switch (cmd->type) { case QXL_CURSOR_SET: cursor = qxl_phys2virt(qxl, cmd->u.set.shape, ext->group_id); if (!cursor) { return 1; } c = qxl_cursor(qxl, cursor, ext->group_id); if (c == NULL) { c = cursor_builtin_left_ptr(); } qemu_mutex_lock(&qxl->ssd.lock); if (qxl->ssd.cursor) { cursor_put(qxl->ssd.cursor); } qxl->ssd.cursor = c; qxl->ssd.mouse_x = cmd->u.set.position.x; qxl->ssd.mouse_y = cmd->u.set.position.y; qemu_mutex_unlock(&qxl->ssd.lock); qemu_bh_schedule(qxl->ssd.cursor_bh); break; case QXL_CURSOR_MOVE: qemu_mutex_lock(&qxl->ssd.lock); qxl->ssd.mouse_x = cmd->u.position.x; qxl->ssd.mouse_y = cmd->u.position.y; qemu_mutex_unlock(&qxl->ssd.lock); qemu_bh_schedule(qxl->ssd.cursor_bh); break; } return 0; }
1threat
Dropdown box like google search box designed in css : <p>Currently I am using normal CSS dropdown list and calling data from database through PHP. <br><br> But I want to create a search box like google.com has, wherein when you type, it will show suggestions from my database. I have its code in JQuery but I don’t know how to use it properly. Is it possible to create it using CSS and PHP?</p>
0debug
spring mvc errors - Request processing failed; nested exception is java.lang.IllegalStateException : i procceding android studio - spring by xml parsing, Error is >>> HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalStateException: An Errors/BindingResult argument is expected to be declared immediately after the model attribute, the @RequestBody or the @RequestPart arguments to which they apply: ..... . . . Spring is >> @RequestMapping(value = "/boardToMyXml") @ResponseBody public XmlDataList MyXml( Errors errors,HttpSession session, HttpServletRequest request, Model model, HttpServletResponse response) { String id = request.getParameter("id"); String pw = request.getParameter("pw"); AuthInfo authInfo = authService.authenticate(id, pw); int userNum =authInfo.getUserNum(); model.addAttribute("id", id); model.addAttribute("pw", pw); model.addAttribute("userNum", userNum); List<Data> listm = boardDao.xmlMyBoardList(userNum); System.out.println(listm); return new XmlDataList(listm); }
0debug
Converting httpClient answer to model objects [Angular 6] : <p>I have a question about the Angular 5 httpClient.</p> <p><strong>This is a model class with a method foo() I'd like to receive from the server</strong></p> <pre><code>export class MyClass implements Deserializable{ id: number; title: string; deserialize(input: any) { Object.assign(this, input); return this; } foo(): string { // return "some string conversion" with this.title } } </code></pre> <p>This is my service requesting it:</p> <pre><code>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { MyClass } from './MyClass'; @Injectable({ providedIn: 'root', }) export class MyClassService { constructor(private http: HttpClient) { } getMyStuff(): Observable&lt;MyClass[]&gt; { // this is where I hope to convert the json to instances of MyClass return this.http.get&lt;MyClass[]&gt;('api/stuff') } } </code></pre> <h1>My Problem</h1> <p>When I ask the service for instances of <code>MyClass</code> I get the data, but I cannot run <code>{{ item.foo() }}</code> in the template. Also, when I <code>console.log()</code> the <code>typeof</code> of an item where it is received in the service, I <strong>do no see</strong> instances of an object of <code>MyClass</code>.</p> <p><strong>What am I doing wrong?</strong> I thought that writing <code>this.http.get&lt;MyClass[]&gt;('api/stuff')</code> would do the conversion.</p> <p>Any hints? Thank you in advance!</p>
0debug
I can not figure out why am i getting the result 2 : <p>Maybe I'm missing out but I can't figure out why I am getting the result 2 in this code:</p> <pre><code>i = 1; i = i-- - --i; System.out.println(i); </code></pre>
0debug
Change Guideline percentage in constraint layout programmatically : <p>I have a guideline in constraint layout like this </p> <pre><code>&lt;android.support.constraint.Guideline android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/guideline8" app:layout_constraintGuide_percent="0.5" android:orientation="vertical"/&gt; </code></pre> <p>Later I want to change the <code>app:layout_constraintGuide_percent</code> value to something else conditionally. How can I achieve this.</p>
0debug
PHP: search bar and insert email : <p>I'm running tests on php and MySql for a single page wich contains an input search bar and a newsletter subscrtion. Both of them work, but not at the same time: if i have the search bar and subscription input and I try to get results from the search, i get the php message from the subscrition (email required...). If eliminate the subscrition form, the query search works...</p> <p>The code: </p> <pre><code> &lt;?php require('MGconfig.php'); if (isset($_GET["game"]) &amp;&amp; $_GET["game"]!="") { $mysearch = htmlspecialchars($_GET["game"]); $result = $connection-&gt;query("select title, genre from games wher title like '%" . $mysearch ."%' or genre like '%" . $mysearch ."%'"); } ?&gt; &lt;h2&gt;Search game&lt;/h2&gt; &lt;form&gt; &lt;input name="game" id="game" class="form-control" type="text" /&gt; &lt;/form&gt; &lt;table class="table table-hover"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Title&lt;/th&gt; &lt;th&gt;Genre&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;?php //while($row = mysqli_fetch_assoc($result)){ foreach ($result as $row) { echo "&lt;tr&gt;"; echo "&lt;td&gt;".$row["title"]. "&lt;/td&gt;&lt;td&gt;".$row["genre"]."&lt;/td&gt;"; echo "&lt;/tr&gt;"; } ?&gt; &lt;/table&gt; &lt;/div&gt; &lt;?php $error=""; $sucessMessage=""; if (($_POST)){ if( $_POST["email"]===""){ $error = "An email is required!"; } if ($error!=""){ $error = '&lt;div class="error"&gt;'.$error.'&lt;/div&gt;'; } else{ require("MGconfig.php"); $email = mysqli_real_escape_string($connection, $_POST["email"]); // check if user mail is already on DB $result=mysqli_query($connection, "select email from newsletter where email = '".$email."'"); //if there is a result, inform user that email is already regis if (mysqli_num_rows($result)&gt;0){ $error = '&lt;div class="error"&gt;Email already registred&lt;/div&gt;'; }else{ //check id for new registration $result=mysqli_query($connection, "select max(id) from newsletter"); $row=mysqli_fetch_row($result); $id = $row[0]+1; $insert ="insert into newsletter(id, email) values (".$id.",'".$email."')"; //Execute insert on the DB mysqli_query($connection, $insert); // Check if there was an error executing the insert if (!$result){ $error ='&lt;div class="error"&gt;Fail to register&lt;/div&gt;'.mysqli_error($connection); }else{ $sucessMessage ='&lt;div class="error"&gt;Thank you for registring!&lt;/div&gt;'; } } } } ?&gt; &lt;div class="subscribe"&gt; &lt;form method="post"&gt; &lt;label style="font-size:20px"&gt;Subscribe our Newsletter!&lt;/label&gt; &lt;input type="email" id="email" name="email" class="newsletter" placeholder=" enter your email here "&gt; &lt;div class="error"&gt; &lt;?php echo $error;?&gt; &lt;/div&gt; &lt;div class="error"&gt; &lt;?php echo $sucessMessage;?&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; </code></pre>
0debug
For inside a while condition to check multiple values : What I want to do is to check if an input value is a member, or not, of a struct that is a part of an array. Since I have multiple elements created, based on that struct, I have to search in each one the value of the member I want. If the value is there, the program should countinue, if not, the program must ask the input to search again. I have the do while loop so ask the input once but I dont know "what" to do whith the while condition in order for it to check all values. if (numAlunos == 0) printf("No data inserted yet!\n"); else { do { printf("Insert the number you want to search:\n"); number= validar_insert (2150001, 2169999);//check if the input is between this values printf("That number doeste exist.\n"); printf("Enter another number.\n"); }while (for (i = 0; i < numAlunos; i++)//I tried something here numero != vAlunos[i].numero)//didnt work for (i = 0; i < numAlunos; i++) { if (number == vAlunos[i].numero) { printf("\nInsert the new grade you want to assign to %s:\n", vAlunos[i].name); scanf("%i", &newGrade); vAlunos[i].finalGrade= newGrade; printf("%i %i %s \n", vAlunos[i].number, vAlunos[i].finalGrade, vAlunos[i].name); } } }
0debug
parsing specific strings from xml to a sql db in javascript : i am looking for the best way to parse a specific string from a xml page. the page in question will have lots of links all with a prefix video and i want to save the number after video/ also has to be a specific line where the video is located. eg. <vidloc>http://example.com/video/12345/myvid.mp4 so i want to be able to search for video in <vidloc> and take only the number 12345 also the url page number and save these both into a db under vidId, pageNum. thanks.
0debug
angular-cli how to add global styles? : <p>I created a global style sheet using sass and put it in the <code>public/style/styles.scss</code>. I only specify a background color.</p> <p>In the index, I added a link to it: <code>&lt;link rel="stylesheet" href="style/styles.css"&gt;</code></p> <p>The background color does not work on the body tag. Upon inspecting the body tag I can see that the background-color was applied but overruled by <code>scaffolding.less:31</code></p> <p>What I am doing wrong?</p> <p>Thanks in advance </p>
0debug
static void scsi_unrealize(SCSIDevice *dev, Error **errp) { SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev); scsi_device_purge_requests(&s->qdev, SENSE_CODE(NO_SENSE)); blockdev_mark_auto_del(s->qdev.conf.blk); }
1threat
how can add toggle button using javascript or jquery to show and hide elements in nav bare : I'm a beginner in javascript I want to add hide and show button using toggle methods <body> <header> <li><a href="#">Mécanique</a> <ul class="sub-menu"> <li><a href="#">Mécanique du point</a></li> <li><a href="#">Mécanique du solide</a></li> </ul> </li> </header> </body>
0debug
remove duplicated rows based on two columns : <p>I have got the following data.frame:</p> <pre><code>df = read.table(text = 'a b c d 1 12 2 1 1 13 2 1 1 3 3 1 2 12 6 2 2 11 2 2 2 14 2 2 1 12 1 2 1 13 2 2 2 11 4 3, header = TRUE') </code></pre> <p>I need to remove the rows which have the same observations based on columns <code>a</code> and <code>b</code>, so that the results would be:</p> <pre><code> a b c d 1 12 2 1 1 13 2 1 1 3 3 1 2 12 6 2 2 11 2 2 2 13 2 2 </code></pre> <p>Thank you for any help</p>
0debug
int nbd_client_session_co_discard(NbdClientSession *client, int64_t sector_num, int nb_sectors) { struct nbd_request request = { .type = NBD_CMD_TRIM }; struct nbd_reply reply; ssize_t ret; if (!(client->nbdflags & NBD_FLAG_SEND_TRIM)) { return 0; } request.from = sector_num * 512; request.len = nb_sectors * 512; nbd_coroutine_start(client, &request); ret = nbd_co_send_request(client, &request, NULL, 0); if (ret < 0) { reply.error = -ret; } else { nbd_co_receive_reply(client, &request, &reply, NULL, 0); } nbd_coroutine_end(client, &request); return -reply.error; }
1threat
What would be the query for Employee who work for all the depertment : What would be the query for the employee who worked for all the department. here department and employee have many to many cardinality.
0debug
Word Press Contact Form 7 Validation Not Working : I am using class:required on my form fields but the validation is not working. I would appreciate for help and guidance. Thank you! <div class="request-form animation" data-animation="fadeInRight"> <h4>REQUEST AN ESTIMATE</h4> <div style="margin-bottom: 18px">Our estimates are free, professional and fair. Most estimates require a site visit. </div> [text Full Name class:input-custom class:input-full placeholder class:required "Name:"] [text Phone class:input-custom class:input-full placeholder class:required "Phone:"] [text E-mail class:input-custom class:input-full placeholder class:required "Email:"] [textarea Message class:input-custom class:input-full placeholder class:required "Message:"] [submit class:btn class:btn-light "SEND MESSAGE"] </div>
0debug
static ssize_t v9fs_synth_llistxattr(FsContext *ctx, V9fsPath *path, void *value, size_t size) { errno = ENOTSUP; return -1; }
1threat
static inline void tcg_out_goto_label(TCGContext *s, int cond, int label_index) { TCGLabel *l = &s->labels[label_index]; if (l->has_value) { tcg_out_goto(s, cond, l->u.value_ptr); } else { tcg_out_reloc(s, s->code_ptr, R_ARM_PC24, label_index, 0); tcg_out_b_noaddr(s, cond); } }
1threat
creating array that compare arrays and state if they are true or false : how i can i improve this array so they compare in the same order. I'm comparing two arrays enter code here static bool CompareArray(int[] a, int[] b) { bool areLenghtsEqual = a.Length == b.Length; if (!areLenghtsEqual) { return false; } return true; }
0debug
R: How to make a for loop for each vector in list : I have a list l, contains four vectors, each vector contains a number of elements, the vectors are not the same length. l<- list(2:4,3:5,4:7,5:7) for ( i in length(l)){ print(l) } [[1]] [1] 2 3 4 [[2]] [1] 3 4 5 [[3]] [1] 4 5 6 7 [[4]] [1] 5 6 7 I would like to add value 2 to all the elements of each vector in the list using for loop. Maybe we need (**two for loops**) The external will be for the list and the internal will be for each vector of the list, I would like to obtain the following result : [[1]] [1] 4 5 6 [[2]] [1] 5 6 7 [[3]] [1] 6 7 8 9 [[4]] [1] 7 8 9 **Please note that:** the original list contains 389 vectors, each vector contains not less than 45 elements.
0debug
My Application keeps stopping, help me find the problem please : I'm having a problem with my application, the thing that it is supposed to do is send a message using volume key buttons on the phone. The problem now is that it keeps stopping and I do not know if it works. Here is the code guys, I also added some wake lock in order for my app to stay active even when phone is locked public class MainActivity extends Activity { private final static int SEND_SMS_PERMISSION_REQUEST_CODE = 111; private Button sendMessage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag"); wl.acquire(); setContentView(R.layout.activity_main); sendMessage = findViewById(R.id.send_message); final EditText phone = findViewById(R.id.phone_no); final EditText message = findViewById(R.id.message); sendMessage.setEnabled(false); if (checkPermission(Manifest.permission.SEND_SMS)) { sendMessage.setEnabled(true); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION_REQUEST_CODE); } sendMessage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String msg = message.getText().toString(); String phonenumber = phone.getText().toString(); if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(phonenumber)) { if (checkPermission(Manifest.permission.SEND_SMS)) { SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(String.valueOf(phone), null, msg, null, null); } else { Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(MainActivity.this, "Enter a message and a phone number", Toast.LENGTH_SHORT).show(); } } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) { sendMessage.setEnabled(true); return true; } else if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP)) { sendMessage.setEnabled(true); return true; } else return super.onKeyDown(keyCode, event); } private boolean checkPermission(String permission) { int checkPermission = ContextCompat.checkSelfPermission(this, permission); return checkPermission == PackageManager.PERMISSION_GRANTED; } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case SEND_SMS_PERMISSION_REQUEST_CODE: if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) { sendMessage.setEnabled(true); } break; } } }
0debug
Flutter Image object to ImageProvider : <p>I had to read my image source from base64 to flutter <a href="https://api.flutter.dev/flutter/widgets/Image-class.html" rel="noreferrer">Image</a> object.</p> <pre class="lang-dart prettyprint-override"><code>Image img = Image.memory(base64Decode(BASE64_STRING)); </code></pre> <p>and then i wanted to put the image as a Container background. But DecorationImage is only accepting <a href="https://api.flutter.dev/flutter/painting/ImageProvider-class.html" rel="noreferrer">ImageProvider</a>. </p> <p>How to convert Image to ImageProvider? or is ther any other way to deliver base64 image to ImageProvider?</p> <pre class="lang-dart prettyprint-override"><code>Container( decoration: BoxDecoration( color: Colors.green, image: DecorationImage( image: img // &lt;-- Expecting ImageProvider ) ) </code></pre>
0debug
static int v410_decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt) { AVFrame *pic = avctx->coded_frame; uint8_t *src = avpkt->data; uint16_t *y, *u, *v; uint32_t val; int i, j; if (pic->data[0]) avctx->release_buffer(avctx, pic); pic->reference = 0; if (avctx->get_buffer(avctx, pic) < 0) { av_log(avctx, AV_LOG_ERROR, "Could not allocate buffer.\n"); return AVERROR(ENOMEM); pic->key_frame = 1; pic->pict_type = FF_I_TYPE; y = (uint16_t *)pic->data[0]; u = (uint16_t *)pic->data[1]; v = (uint16_t *)pic->data[2]; for (i = 0; i < avctx->height; i++) { for (j = 0; j < avctx->width; j++) { val = AV_RL32(src); u[j] = (val >> 2) & 0x3FF; y[j] = (val >> 12) & 0x3FF; v[j] = (val >> 22); src += 4; y += pic->linesize[0] >> 1; u += pic->linesize[1] >> 1; v += pic->linesize[2] >> 1; *data_size = sizeof(AVFrame); *(AVFrame *)data = *pic; return avpkt->size;
1threat
How could I change string in a 2d list?(python) : In python.. How could I change a string in a 2d list to 'X'? this is the sample code. I want to change '9' to 'X' example : cavityMap(['1112', '1912', '1892', '1234']) result : 1112, 1X12, 18X2, 1234 this is my incomplete code. def cavityMap(grid): t = '9' for i, j in enumerate(grid): if i == 0: continue if i == len(grid)-1: break j = list(j) for a, b in enumerate(j): if b == t: pass return grid
0debug
ReactiveSwift Simple Example : <p>I've read the <a href="https://github.com/ReactiveCocoa/ReactiveSwift" rel="noreferrer">documentation</a>, gone through their wonderful Playground example, searched S.O., and reached the extent of my <a href="http://www.urbandictionary.com/define.php?term=google-fu" rel="noreferrer">google-fu</a>, but I cannot for the life of me wrap my head around how to use ReactiveSwift.</p> <p>Given the following....</p> <pre><code>class SomeModel { var mapType: MKMapType = .standard var selectedAnnotation: MKAnnotation? var annotations = [MKAnnotation]() var enableRouteButton = false // The rest of the implementation... } class SomeViewController: UIViewController { let model: SomeModel let mapView = MKMapView(frame: .zero) // It's position is set elsewhere @IBOutlet var routeButton: UIBarButtonItem? init(model: SomeModel) { self.model = model super.init(nibName: nil, bundle: nil) } // The rest of the implementation... } </code></pre> <p>....how can I use ReactiveSwift to initialize <code>SomeViewController</code> with the values from <code>SomeModel</code>, then update <code>SomeViewController</code> whenever the values in <code>SomeModel</code> change?</p> <p>I've never used reactive anything before, but everything I read leads me to believe this should be possible. <em>It is making me crazy.</em> </p> <p>I realize there is much more to ReactiveSwift than what I'm trying to achieve in this example, but if someone could please use it to help me get started, I would greatly appreciate it. I'm hoping once I get this part, the rest will just "click".</p>
0debug
document.getElementById('input').innerHTML = user_input;
1threat
int avcodec_decode_audio(AVCodecContext *avctx, int16_t *samples, int *frame_size_ptr, uint8_t *buf, int buf_size) { int ret; *frame_size_ptr= 0; ret = avctx->codec->decode(avctx, samples, frame_size_ptr, buf, buf_size); avctx->frame_number++; return ret; }
1threat
How to build a powerful crawler like google's? : <p>I want to build a crawler which can update hundreds of thousands of links in several minutes. Is there any mature ways to do the scheduling? Is distributed system needed? What is the greatest barrier that limits the performance? Thx.</p>
0debug
I do have missing script: start : { "name": "ionic-hello-world", "author": "Ionic Framework", "homepage": "http://ionicframework.com/", "private": true, "scripts": { "build": "ionic-app-scripts build", "watch": "ionic-app-scripts watch", "serve:before": "watch", "emulate:before": "build", "deploy:before": "build", "build:before": "build", "run:before": "build" }, "dependencies": { "@angular/common": "2.2.1", "@angular/compiler": "2.2.1", "@angular/compiler-cli": "2.2.1", "@angular/core": "2.2.1", "@angular/forms": "2.2.1", "@angular/http": "2.2.1", "@angular/platform-browser": "2.2.1", "@angular/platform-browser-dynamic": "2.2.1", "@angular/platform-server": "2.2.1", "@ionic/storage": "1.1.7", "@agm/core": "1.0.0-beta.0", "es6-promise": "3.0.2", "es6-shim": "^0.35.0", "ionic-angular": "2.0.0", "ionic-native": "^2.2.14", "ionicons": "3.0.0", "ng2-cordova-oauth": "0.0.6", "rxjs": "5.0.0-beta.12", "sw-toolbox": "3.4.0", "zone.js": "0.6.26" }, "devDependencies": { "@ionic/app-scripts": "1.0.0", "typescript": "2.1.5" }, "cordovaPlugins": [ "cordova-plugin-device", "cordova-plugin-console", "cordova-plugin-whitelist", "cordova-plugin-splashscreen", "cordova-plugin-statusbar", "ionic-plugin-keyboard", "cordova-plugin-inappbrowser" ], "cordovaPlatforms": [ "ios", { "platform": "ios", "version": "", "locator": "ios" } ], "description": "third-party-auth-ionic2-tutorial: An Ionic project" }
0debug
Expression must have class type (vector of ponters) : I have an error that says that "column" must have class type. vector<Column*> is a vector of pointers where Column is an abstract class because my columns can be of type int, double or string class Table { vector<Column*> _columns; Column* value; char* name; public: Table() {...} Table(char* name) {...} ~Table() {...} template <typename T> void addColumn(vector<T> v) { auto column = DataColumnFactory::getColumn(); column.get()->addValuesToVector(v); _columns.push_back(move(column)); } int findLongestColumn() { int length = 0; for (auto &column : _columns) { if (length < column.get()->lengthOfColumn()) //ERROR length = column.get()->lengthOfColumn(); } } };
0debug
static void vmsvga_reset(struct vmsvga_state_s *s) { s->index = 0; s->enable = 0; s->config = 0; s->width = -1; s->height = -1; s->svgaid = SVGA_ID; s->depth = 24; s->bypp = (s->depth + 7) >> 3; s->cursor.on = 0; s->redraw_fifo_first = 0; s->redraw_fifo_last = 0; switch (s->depth) { case 8: s->wred = 0x00000007; s->wgreen = 0x00000038; s->wblue = 0x000000c0; break; case 15: s->wred = 0x0000001f; s->wgreen = 0x000003e0; s->wblue = 0x00007c00; break; case 16: s->wred = 0x0000001f; s->wgreen = 0x000007e0; s->wblue = 0x0000f800; break; case 24: s->wred = 0x00ff0000; s->wgreen = 0x0000ff00; s->wblue = 0x000000ff; break; case 32: s->wred = 0x00ff0000; s->wgreen = 0x0000ff00; s->wblue = 0x000000ff; break; } s->syncing = 0; }
1threat
Is it possible to instantiate objects without constructor in Java : <p>When learning about String literals vs String objects, I came across the fact that there are 2 possible ways to instantiate a variable of type String</p> <pre><code>//Using literals String s1 = "text"; //Using constructor String s2 = new String("text"); </code></pre> <p>I was wondering if it is possible to somehow create an class and instead of instantiating it with a constructor, one could instantiate it using a literal</p> <p>This is what I mean</p> <pre><code>class Value { int value; //Some methods } Value val = 10; //Program automatically sets val.value = 10 </code></pre>
0debug
db.execute('SELECT * FROM products WHERE product_id = ' + product_input)
1threat
static int decode_dsw1(uint8_t *frame, int width, int height, const uint8_t *src, const uint8_t *src_end) { const uint8_t *frame_start = frame; const uint8_t *frame_end = frame + width * height; int mask = 0x10000, bitbuf = 0; int v, offset, count, segments; segments = bytestream_get_le16(&src); while (segments--) { if (mask == 0x10000) { if (src >= src_end) return -1; bitbuf = bytestream_get_le16(&src); mask = 1; } if (src_end - src < 2 || frame_end - frame < 2) return -1; if (bitbuf & mask) { v = bytestream_get_le16(&src); offset = (v & 0x1FFF) << 1; count = ((v >> 13) + 2) << 1; if (frame - offset < frame_start || frame_end - frame < count) return -1; for (v = 0; v < count; v++) frame[v] = frame[v - offset]; frame += count; } else if (bitbuf & (mask << 1)) { frame += bytestream_get_le16(&src); } else { *frame++ = *src++; *frame++ = *src++; } mask <<= 2; } return 0; }
1threat
Go Lang Error Handling Issue / Misunderstanding? : <p>Ok so I am using the following code, </p> <pre><code>err := r.ParseForm() if err != nil { log.Panic(err) } var user User err := decoder.Decode(&amp;user, r.PostForm) if err != nil { log.Panic(err) } </code></pre> <p>Now when I try to run this code, I get the following error, </p> <pre><code>no new variables on left side of := </code></pre> <p>Now I know that this is due to using the same variable, in this case <code>err</code> but I have seen lots of examples where this is how other developers deal with error handling?</p> <p>The way that I have been using is just to use <code>err1</code> and <code>err2</code> so I can build the code.</p> <p>I have been over the docs but there is a lot to take in and must have missed how the <code>err</code> variable is being able to be re-used, or have I completely misunderstood something? </p> <p>Thanks, </p>
0debug
Method can only be called again if 5 seconds is passed : <p>I have an aplication running and i kinda want to create a timeout, my method is called too many times in a small amount of time. i want to determine that the method can only be called again if 5 seconds is passed. How do i do that ?</p>
0debug
How to see files and file structure on a deployed Heroku app : <p>My client app that is deployed on Heroku allows the user to upload images onto Heroku. I wanted to test out a change I made to delete images, so I need a way to see the state of the folder structure on Heroku to ensure the images are being deleted successfully of the file system.</p> <p>I tried - </p> <pre><code>$ heroku run bash --app &lt;appName&gt; ~$ pwd ~$ cd &lt;path to images folder&gt; </code></pre> <p>but I only see images here that I uploaded along with the app, not what was uploaded through the client app.</p> <p>What am I doing wrong?</p>
0debug
Format java.sql.Timestamp into a String : <p>Is it possible to convert/format <code>java.sql.Timestmap</code> into a String that has the following format:</p> <blockquote> <p>yyyyMMdd</p> </blockquote> <p>I know that doing it with a <code>String</code> is fairly simple e.g:</p> <pre><code>String dateString = "2016-02-03 00:00:00.0"; Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(dateString); String formattedDate = new SimpleDateFormat("yyyyMMdd").format(date); </code></pre> <p>But, I have to work with the <code>Timestamp</code> object.</p>
0debug
Store Two Integer Multiplication Result not using int,Long,Double,String,BigDecimal in Java : <p>So Question was like there is an method that is taking two int values as an parameters and we have to store the multiplication of those two integers but not in int,Long,Double,BigDecimal,String. The range of the result(multiplication) would be beyond from Integer range.</p> <pre><code>---- method(int a,int b){ return a*b; } </code></pre> <p>So dashes in method signature denotes the desired return type that interviewer was exactly looking for.</p>
0debug
Which approach is preferable for creating a grid - flexbox, css-table or inline-block? : <p>Which approach is preferable for creating a grid - flexbox, css-table or inline-block?</p> <p>Or may be each of this technics should be used in specified cases?<br> If so, in what cases should be they used?</p>
0debug
static char *get_geokey_val(int key, int val) { char *ap; if (val == TIFF_GEO_KEY_UNDEFINED) return av_strdup("undefined"); if (val == TIFF_GEO_KEY_USER_DEFINED) return av_strdup("User-Defined"); #define RET_GEOKEY_VAL(TYPE, array)\ if (val >= TIFF_##TYPE##_OFFSET &&\ val - TIFF_##TYPE##_OFFSET < FF_ARRAY_ELEMS(ff_tiff_##array##_codes))\ return av_strdup(ff_tiff_##array##_codes[val - TIFF_##TYPE##_OFFSET]); switch (key) { case TIFF_GT_MODEL_TYPE_GEOKEY: RET_GEOKEY_VAL(GT_MODEL_TYPE, gt_model_type); break; case TIFF_GT_RASTER_TYPE_GEOKEY: RET_GEOKEY_VAL(GT_RASTER_TYPE, gt_raster_type); break; case TIFF_GEOG_LINEAR_UNITS_GEOKEY: case TIFF_PROJ_LINEAR_UNITS_GEOKEY: case TIFF_VERTICAL_UNITS_GEOKEY: RET_GEOKEY_VAL(LINEAR_UNIT, linear_unit); break; case TIFF_GEOG_ANGULAR_UNITS_GEOKEY: case TIFF_GEOG_AZIMUTH_UNITS_GEOKEY: RET_GEOKEY_VAL(ANGULAR_UNIT, angular_unit); break; case TIFF_GEOGRAPHIC_TYPE_GEOKEY: RET_GEOKEY_VAL(GCS_TYPE, gcs_type); RET_GEOKEY_VAL(GCSE_TYPE, gcse_type); break; case TIFF_GEOG_GEODETIC_DATUM_GEOKEY: RET_GEOKEY_VAL(GEODETIC_DATUM, geodetic_datum); RET_GEOKEY_VAL(GEODETIC_DATUM_E, geodetic_datum_e); break; case TIFF_GEOG_ELLIPSOID_GEOKEY: RET_GEOKEY_VAL(ELLIPSOID, ellipsoid); break; case TIFF_GEOG_PRIME_MERIDIAN_GEOKEY: RET_GEOKEY_VAL(PRIME_MERIDIAN, prime_meridian); break; case TIFF_PROJECTED_CS_TYPE_GEOKEY: return av_strdup(search_keyval(ff_tiff_proj_cs_type_codes, FF_ARRAY_ELEMS(ff_tiff_proj_cs_type_codes), val)); break; case TIFF_PROJECTION_GEOKEY: return av_strdup(search_keyval(ff_tiff_projection_codes, FF_ARRAY_ELEMS(ff_tiff_projection_codes), val)); break; case TIFF_PROJ_COORD_TRANS_GEOKEY: RET_GEOKEY_VAL(COORD_TRANS, coord_trans); break; case TIFF_VERTICAL_CS_TYPE_GEOKEY: RET_GEOKEY_VAL(VERT_CS, vert_cs); RET_GEOKEY_VAL(ORTHO_VERT_CS, ortho_vert_cs); break; } ap = av_malloc(14); if (ap) snprintf(ap, 14, "Unknown-%d", val); return ap; }
1threat
Markdown doesn't work in attachments : <p>I'm creating a Slack integration with the Slack API. I followed <a href="https://api.slack.com/docs/formatting">the documentation</a> but the markdown formatting doesn't work on my attachments...</p> <p>Here is my response object:</p> <pre><code>{ response_type: "in_channel", text: "List:", attachments: [ { text: "*pseudo*:\nbla bla bla", mrkdwn: true } ] } </code></pre> <p>The "*" are displayed and not evaluated. Did I make a mistake? </p>
0debug
static void test_blk_read(BlockBackend *blk, long pattern, int64_t pattern_offset, int64_t pattern_count, int64_t offset, int64_t count, bool expect_failed) { void *pattern_buf = NULL; QEMUIOVector qiov; void *cmp_buf = NULL; int async_ret = NOT_DONE; if (pattern) { cmp_buf = g_malloc(pattern_count); memset(cmp_buf, pattern, pattern_count); } pattern_buf = g_malloc(count); if (pattern) { memset(pattern_buf, pattern, count); } else { memset(pattern_buf, 0x00, count); } qemu_iovec_init(&qiov, 1); qemu_iovec_add(&qiov, pattern_buf, count); blk_aio_preadv(blk, offset, &qiov, 0, blk_rw_done, &async_ret); while (async_ret == NOT_DONE) { main_loop_wait(false); } if (expect_failed) { g_assert(async_ret != 0); } else { g_assert(async_ret == 0); if (pattern) { g_assert(memcmp(pattern_buf + pattern_offset, cmp_buf, pattern_count) <= 0); } } g_free(pattern_buf); }
1threat
how to spread an object to a function as arguments? : <p>I have an object an a function which accept arguments, I would like to spread the objects so each property is an argument in that function.</p> <p>What am I doing wrong in my code?</p> <pre><code>const args = { a: 1 b: 2 } const fn = (a, b) =&gt; a + b // i am trying with no success console.log(fn(...args)) </code></pre>
0debug