problem
stringlengths
26
131k
labels
class label
2 classes
static int vp5_parse_header(VP56Context *s, const uint8_t *buf, int buf_size) { VP56RangeCoder *c = &s->c; int rows, cols; ff_vp56_init_range_decoder(&s->c, buf, buf_size); s->frames[VP56_FRAME_CURRENT]->key_frame = !vp56_rac_get(c); vp56_rac_get(c); ff_vp56_init_dequant(s, vp56_rac_gets(c, 6)); if (s->frames[VP56_FRAME_CURRENT]->key_frame) { vp56_rac_gets(c, 8); if(vp56_rac_gets(c, 5) > 5) return AVERROR_INVALIDDATA; vp56_rac_gets(c, 2); if (vp56_rac_get(c)) { av_log(s->avctx, AV_LOG_ERROR, "interlacing not supported\n"); return AVERROR_PATCHWELCOME; } rows = vp56_rac_gets(c, 8); cols = vp56_rac_gets(c, 8); if (!rows || !cols) { av_log(s->avctx, AV_LOG_ERROR, "Invalid size %dx%d\n", cols << 4, rows << 4); return AVERROR_INVALIDDATA; } vp56_rac_gets(c, 8); vp56_rac_gets(c, 8); vp56_rac_gets(c, 2); if (!s->macroblocks || 16*cols != s->avctx->coded_width || 16*rows != s->avctx->coded_height) { int ret = ff_set_dimensions(s->avctx, 16 * cols, 16 * rows); if (ret < 0) return ret; return VP56_SIZE_CHANGE; } } else if (!s->macroblocks) return AVERROR_INVALIDDATA; return 0; }
1threat
Randomize Function to create a length range in Delphi : <p>I was wondering how I would create a randomized string that has a set length range, that range being 8 to 24 characters, instead of it it being a fixed length such as 10. </p>
0debug
is it posible to use back button item and left bar button items at same time in swift 3 : I want use back button item to go the stack back and a left bar button to call also the slide menu. for this a use a navigation bar , is this possible and how? [menu button][1] [back item][2] [1]: https://i.stack.imgur.com/U4vfP.png [2]: https://i.stack.imgur.com/dLwmo.png
0debug
def even_Power_Sum(n): sum = 0; for i in range(1,n+1): j = 2*i; sum = sum + (j*j*j*j*j); return sum;
0debug
NullPointerException error Array : <p>Trying to create a basic program, in which an object Swimmer and its data are created and stored to a file (simple database for swimmers). However, I am experiencing numerous run time errors, many of which are classified as NullPointerExceptions. I have a Swimmer class w/o a Constructor with methods that get names, ages, genders, etc. This class also has methods to return all this information. In my Tester class, I have created a switch that prompts the user to either Show Swimmers, Add Swimmer, Edit Swimmer, Delete Swimmer, and Exit the Program. My current error appears when adding a swimmer, specifically when setting a name. There is a Null Pointer Exception at myList[maxIndex].setName(a). </p> <p>This is my code for my Swimmer class: import java.io.<em>; import java.util.</em>;</p> <pre><code>public class Swimmer { private String name; private int age; private int gradeLevel; private String gender; private int grade; private double fiftyFree; private double hundredFree; private double twoFree; private double fiveFree; private double hundredBack; private double hundredBreast; private double hundredFly; private double twoIM; Scanner kbReader = new Scanner(System.in); public void setName(String a) { name = a; } public String getName() { return name; } public void setAge(int a) { age = a; } public int getAge() { return age; } public void setGender(String a) { gender = a; } public String getGender() { return gender; } public void setGrade(int a) { grade = a; } public int getGrade() { return grade; } public void setFiftyFree(double a) { fiftyFree = a; } public double getFiftyFree() { return fiftyFree; } public void setHundredFree(double a) { hundredFree = a; } public double getHundredFree() { return hundredFree; } public void setTwoFree(double a) { twoFree = a; } public double getTwoFree() { return twoFree; } public void setFiveFree(double a) { fiveFree = a; } public double getFiveFree() { return fiveFree; } public void setHundredBack(double a) { hundredBack = a; } public double getHundredBack() { return hundredBack; } public void setHundredBreast(double a) { hundredBreast = a; } public double getHundredBreast() { return hundredBreast; } public void setTwoIM(double a) { twoIM = a; } public double getTwoIM() { return twoIM; } public void setHundredFly(double a) { hundredFly = a; } public double getHundredFly() { return hundredFly; } public void getInfo() { System.out.println("Name: " + name + "\n" + "Age: " + age + "/n" + "Grade enter code here`Level: " + gradeLevel + "\n" + "Gender: " + gender); } } </code></pre> <p>And this is the code for my Main class: import java.io.<em>; import java.util.</em>; import java.util.Arrays;</p> <pre><code>public class Tester { public static Swimmer[] myList = new Swimmer[1000]; public static int maxIndex = 0; public static void main(String args[]) throws IOException { Scanner kbReader = new Scanner(System.in); int choice; String swimmerName = "Default"; boolean condition = true; while(condition) { System.out.println("Which of the following would you like to do?"); System.out.println("1. Show Swimmers" + "\n" + "2. Add Swimmer" + "\n" + "3. Edit Swimmer" + "\n" + "4. Delete Swimmer" + "\n" + "5. Exit"); choice = kbReader.nextInt(); switch (choice) { case 1: showSwimmer(); break; case 2: addSwimmer(); break; case 3: editSwimmer(); break; case 4: deleteSwimmer(); break; case 5: condition = false; break; } } FileWriter(); } public static void FileWriter() throws IOException { FileWriter fw = new FileWriter("database.txt"); PrintWriter output = new PrintWriter(fw); for(int j = 0; j&lt;=maxIndex; j++) { output.println(myList[j].getName() + " ~ " + myList[j].getAge() + " ~ " + myList[j].getGender() + " ~ " + myList[j].getGrade() + " ~ " + myList[j].getFiftyFree() + " ~ " + myList[j].getHundredFree() + " ~ " + myList[j].getTwoFree() + " ~ " + myList[j].getFiveFree() + " ~ " + myList[j].getHundredBack() + " ~ " + myList[j].getHundredBreast() + " ~ " + myList[j].getHundredFly() + myList[j].getTwoIM()); } output.close(); fw.close(); } public static void FileReader() throws IOException { Scanner sf = new Scanner(new File("database.txt")); String s, sp[]; while(sf.hasNext()) { maxIndex++; s = sf.nextLine(); sp = s.split("~"); myList[maxIndex] = new Swimmer(); } sf.close(); } public static void swap(int a, int b) { Swimmer temp = myList[a]; myList[a] = myList[maxIndex]; myList[maxIndex] = temp; } public static void showSwimmer() { for(int j = 1; j &lt; maxIndex; j++) { System.out.println( (j) + ". " + myList[j].getName()); } } public static void addSwimmer() { Scanner kbReader = new Scanner (System.in); System.out.println("What is the swimmer's name? "); String a = kbReader.nextLine(); myList[maxIndex].setName(a); System.out.println("Is the swimmer male or female? Please enter \"m\" for male and \"f\" for female. "); String b = kbReader.nextLine(); System.out.println("How old is he/she? "); int c = kbReader.nextInt(); myList[maxIndex].setAge(c); System.out.println("What is the numerical value of the swimmer's grade?"); int d = kbReader.nextInt(); myList[maxIndex].setGrade(d); System.out.println("How many minutes does it take for this swimmer to complete the 50 Freestyle?"); double e = kbReader.nextDouble(); System.out.println("How many additional seconds does it take for this swimmer to complete the 50 freestyle?"); double f = kbReader.nextDouble(); double g = (e*60.0) + f; myList[maxIndex].setFiftyFree(g); System.out.println("How many minutes does it take for this swimmer to complete the 100 Freestyle?"); double h = kbReader.nextDouble(); System.out.println("How many additional seconds does it take for this swimmer to complete the 100 Freestyle?"); double i = kbReader.nextDouble(); double j = (h*60.0) + i; myList[maxIndex].setHundredFree(j); System.out.println("How many minutes does it take for this swimmer to complete the 200 Freestyle?"); double k = kbReader.nextDouble(); System.out.println("How many additional seconds does it take for this swimmer to complete the 200 Freestyle?"); double l = kbReader.nextDouble(); double m = (k*60.0) + l; myList[maxIndex].setTwoFree(k); System.out.println("How many minutes does it take for this swimmer to complete the 500 Freestyle?"); double n = kbReader.nextDouble(); System.out.println("How many additional seconds does it take for this swimmer to complete the 200 Freestyle?"); double o = kbReader.nextDouble(); double p = (n*60.0) + o; myList[maxIndex].setFiveFree(p); System.out.println("How many minutes does it take for this swimmer to complete the 100 Backstroke?"); double q = kbReader.nextDouble(); System.out.println("How many additional seconds does it take for this swimmer to complete the 100 Backstroke?"); double r = kbReader.nextDouble(); double s = (q*60.0) + r; myList[maxIndex].setHundredBack(s); System.out.println("How many minutes does it take for this swimmer to complete the 100 Breastroke?"); double t = kbReader.nextDouble(); System.out.println("How many additional seconds does it take for this swimmer to complete the 100 Breastroke?"); double u = kbReader.nextDouble(); double v = (t*60.0) + u; myList[maxIndex].setHundredBreast(v); System.out.println("How many minutes does it take for this swimmer to complete the 100 Butterfly?"); double w = kbReader.nextDouble(); System.out.println("How many additional seconds does it take for this swimmer to complete the 100 Butterfly?"); double x = kbReader.nextDouble(); double y = (w*60.0) + x; myList[maxIndex].setHundredFly(y); System.out.println("How many minutes does it take for this swimmer to complete the 200 IM?"); double z = kbReader.nextDouble(); System.out.println("How many additional seconds does it take for this swimmer to complete the 200 IM?"); double aa = kbReader.nextDouble(); double bb = (z*60.0) + aa; myList[maxIndex].setTwoIM(bb); maxIndex++; } public static void editSwimmer() { Scanner kbReader = new Scanner(System.in); System.out.println("Which swimmer would you like to edit? Please enter the corresponding number."); System.out.println(Arrays.toString(myList)); int choice = kbReader.nextInt(); } public static void deleteSwimmer() { int a; Scanner kbReader = new Scanner(System.in); System.out.println("Which swimmer would you like to delete? Please enter the corresponding number."); System.out.println(Arrays.toString(myList)); a = kbReader.nextInt(); swap(a-1, maxIndex); maxIndex--; } } </code></pre> <p>I just need help with the Null Pointer Exception. Any help with backing up to a file would also be great. I have a Mac, I don't think this should alter the code too much. (Maybe just the file extension)</p>
0debug
pixman_format_code_t qemu_default_pixman_format(int bpp, bool native_endian) { if (native_endian) { switch (bpp) { case 15: return PIXMAN_x1r5g5b5; case 16: return PIXMAN_r5g6b5; case 24: return PIXMAN_r8g8b8; case 32: return PIXMAN_x8r8g8b8; } } else { switch (bpp) { case 24: return PIXMAN_b8g8r8; case 32: return PIXMAN_b8g8r8x8; break; } } g_assert_not_reached(); }
1threat
Software to block internet for applications : <p>I am using mobile internet on my desktop computer. All the sudden I have found out there was like one giga mb lost for nothing and I assume it must be because of some other background applications. Is there any software where I could limit internet only for specific applications? Including blocking windows 10 for updates etc. Would appreciate your reply</p>
0debug
What does the 24 mean in 192.168.1.0/24 in route table? : <p>What does the 24 mean in 192.168.1.0/24 in route table? Sorry for my noob question ;(</p>
0debug
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags) { MOVContext* mov = (MOVContext *) s->priv_data; MOVStreamContext* sc; int32_t i, a, b, m; int64_t start_time; int32_t seek_sample, sample; int32_t duration; int32_t count; int32_t chunk; int32_t left_in_chunk; int64_t chunk_file_offset; int64_t sample_file_offset; int32_t first_chunk_sample; int32_t sample_to_chunk_idx; int sample_to_time_index; long sample_to_time_sample = 0; uint64_t sample_to_time_time = 0; int mov_idx; for (mov_idx = 0; mov_idx < mov->total_streams; mov_idx++) if (mov->streams[mov_idx]->ffindex == stream_index) break; if (mov_idx == mov->total_streams) { av_log(s, AV_LOG_ERROR, "mov: requested stream was not found in mov streams (idx=%i)\n", stream_index); return -1; } sc = mov->streams[mov_idx]; sample_time *= s->streams[stream_index]->time_base.num; if (sc->edit_count && 0) { av_log(s, AV_LOG_ERROR, "mov: does not handle seeking in files that contain edit list (c:%d)\n", sc->edit_count); return -1; } dprintf("Searching for time %li in stream #%i (time_scale=%i)\n", (long)sample_time, mov_idx, sc->time_scale); start_time = 0; sample = 1; for (i = 0; i < sc->stts_count; i++) { count = sc->stts_data[i].count; duration = sc->stts_data[i].duration; if ((start_time + count*duration) > sample_time) { sample_to_time_time = start_time; sample_to_time_index = i; sample_to_time_sample = sample; sample += (sample_time - start_time) / duration; break; } sample += count; start_time += count * duration; } sample_to_time_time = start_time; sample_to_time_index = i; dprintf("Found time %li at sample #%u\n", (long)sample_time, sample); if (sample > sc->sample_count) { av_log(s, AV_LOG_ERROR, "mov: sample pos is too high, unable to seek (req. sample=%i, sample count=%ld)\n", sample, sc->sample_count); return -1; } if (sc->keyframes) { a = 0; b = sc->keyframe_count - 1; while (a < b) { m = (a + b + 1) >> 1; if (sc->keyframes[m] > sample) { b = m - 1; } else { a = m; } } seek_sample = sc->keyframes[a]; } else seek_sample = sample; dprintf("Found nearest keyframe at sample #%i \n", seek_sample); for (first_chunk_sample = 1, i = 0; i < (sc->sample_to_chunk_sz - 1); i++) { b = (sc->sample_to_chunk[i + 1].first - sc->sample_to_chunk[i].first) * sc->sample_to_chunk[i].count; if (seek_sample >= first_chunk_sample && seek_sample < (first_chunk_sample + b)) break; first_chunk_sample += b; } chunk = sc->sample_to_chunk[i].first + (seek_sample - first_chunk_sample) / sc->sample_to_chunk[i].count; left_in_chunk = sc->sample_to_chunk[i].count - (seek_sample - first_chunk_sample) % sc->sample_to_chunk[i].count; first_chunk_sample += ((seek_sample - first_chunk_sample) / sc->sample_to_chunk[i].count) * sc->sample_to_chunk[i].count; sample_to_chunk_idx = i; dprintf("Sample was found in chunk #%i at sample offset %i (idx %i)\n", chunk, seek_sample - first_chunk_sample, sample_to_chunk_idx); if (!sc->chunk_offsets) { av_log(s, AV_LOG_ERROR, "mov: no chunk offset atom, unable to seek\n"); return -1; } if (chunk > sc->chunk_count) { av_log(s, AV_LOG_ERROR, "mov: chunk offset atom too short, unable to seek (req. chunk=%i, chunk count=%li)\n", chunk, sc->chunk_count); return -1; } chunk_file_offset = sc->chunk_offsets[chunk - 1]; dprintf("Chunk file offset is #%"PRIu64"\n", chunk_file_offset); sample_file_offset = chunk_file_offset; if (sc->sample_size) sample_file_offset += (seek_sample - first_chunk_sample) * sc->sample_size; else { for (i = 0; i < (seek_sample - first_chunk_sample); i++) { sample_file_offset += sc->sample_sizes[first_chunk_sample + i - 1]; } } dprintf("Sample file offset is #%"PRIu64"\n", sample_file_offset); mov->partial = sc; mov->next_chunk_offset = sample_file_offset; sc->current_sample = seek_sample - 1; sc->left_in_chunk = left_in_chunk; sc->next_chunk = chunk; sc->sample_to_chunk_index = sample_to_chunk_idx; for (i = 0; i<mov->total_streams; i++) { MOVStreamContext *msc; if (i == mov_idx) continue; msc = mov->streams[i]; a = 0; b = msc->chunk_count - 1; while (a < b) { m = (a + b + 1) >> 1; if (msc->chunk_offsets[m] > chunk_file_offset) { b = m - 1; } else { a = m; } } msc->next_chunk = a; if (msc->chunk_offsets[a] < chunk_file_offset && a < (msc->chunk_count-1)) msc->next_chunk ++; dprintf("Nearest next chunk for stream #%i is #%li @%"PRId64"\n", i, msc->next_chunk+1, msc->chunk_offsets[msc->next_chunk]); msc->sample_to_chunk_index = 0; msc->current_sample = 0; for(; msc->sample_to_chunk_index < (msc->sample_to_chunk_sz - 1) && msc->sample_to_chunk[msc->sample_to_chunk_index + 1].first <= (1 + msc->next_chunk); msc->sample_to_chunk_index++) { msc->current_sample += (msc->sample_to_chunk[msc->sample_to_chunk_index + 1].first - msc->sample_to_chunk[msc->sample_to_chunk_index].first) \ * msc->sample_to_chunk[msc->sample_to_chunk_index].count; } msc->current_sample += (msc->next_chunk - (msc->sample_to_chunk[msc->sample_to_chunk_index].first - 1)) * sc->sample_to_chunk[msc->sample_to_chunk_index].count; msc->left_in_chunk = msc->sample_to_chunk[msc->sample_to_chunk_index].count - 1; sample = 0; start_time = 0; for (msc->sample_to_time_index = 0; msc->sample_to_time_index < msc->stts_count; msc->sample_to_time_index++) { count = msc->stts_data[msc->sample_to_time_index].count; duration = msc->stts_data[msc->sample_to_time_index].duration; if ((sample + count - 1) > msc->current_sample) { msc->sample_to_time_time = start_time; msc->sample_to_time_sample = sample; break; } sample += count; start_time += count * duration; } sample = 0; for (msc->sample_to_ctime_index = 0; msc->sample_to_ctime_index < msc->ctts_count; msc->sample_to_ctime_index++) { count = msc->ctts_data[msc->sample_to_ctime_index].count; duration = msc->ctts_data[msc->sample_to_ctime_index].duration; if ((sample + count - 1) > msc->current_sample) { msc->sample_to_ctime_sample = sample; break; } sample += count; } dprintf("Next Sample for stream #%i is #%li @%li\n", i, msc->current_sample + 1, msc->sample_to_chunk_index + 1); } return 0; }
1threat
Cannot read property 'setState' of undefined (with fetch api) : <p>When I'm trying to set my "users" state's variable, I've got the following message : <br/><em>Cannot read property 'setState' of undefined</em> <br/> It's on the following code line :<br/><br/> <code>this.setState({users: data.users});</code></p> <p>Here is my class </p> <p>` import React, { Component } from 'react';</p> <p>class Users extends Component {</p> <pre><code>constructor(props) { super(props); this.state = { users: [] }; } componentWillMount() { this.getUsers(); } getUsers = () =&gt; { let myHeaders = new Headers({ 'Authorization': 'Basic '+btoa('john@doe.com:password'), 'Accept': 'application/json', 'Content-Type': 'application/json' }); fetch('https://dev-api/v1/user/', { method: 'GET', headers: myHeaders }).then(function(response) { if (!response.ok) { throw Error(response.statusText); } return response; }).then(function(response) { response.json().then(function(data) { this.setState({users: data.users}); }); }).catch(function(error) { console.log(error); }); } render() { return ( &lt;table className="striped bordered"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;email&lt;/th&gt; &lt;th&gt;Firstname&lt;/th&gt; &lt;th&gt;Lastname&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; {this.state &amp;&amp; this.state.users &amp;&amp; this.state.users.map(user =&gt; &lt;tr&gt; &lt;td&gt;{user.username}&lt;/td&gt; &lt;td&gt;{user.firstname}&lt;/td&gt; &lt;td&gt;{user.lastname}&lt;/td&gt; &lt;/tr&gt; )} &lt;/tbody&gt; &lt;/table&gt; ); } </code></pre> <p>}</p> <p>export default Users;`</p> <p>Thanks a lot !</p>
0debug
Java exit while loop from called method : <p>How do I make this code exit after the s variable updates to 0? As of now, its executing the whole block outputting the last print statement before stopping. Is this the normal behaviour of while loop?</p> <pre><code>public class test { private static int i = 0; private static int s = 1; public static void main(String[] args) { // TODO Auto-generated method stub s: while(s&gt;0 &amp;&amp; i==0) { s(); } } public static void s() { System.out.println(s); s--; //I want the program to stop here since s is already 0. System.out.println(s); } } </code></pre>
0debug
Membership site with PHP and MySQL : <p>I have a html site, and I have a page that acts as a bio for users (which I currently have to update by hand with html).</p> <p>I want to create a membership login page, and I want users to be able to input their own data, that in turn updates their bio page automatically. With an option to upload images.</p> <p>I read up and looks like php and mysql is the way to go, which I know nothing about. Is that the right route? Or is there an easier way?</p> <p>Kick me in the right direction to get that setup please? I'm lazy and don't want to spend months figuring out how everything works just to setup one page...</p>
0debug
how to use colored google maps in website without any JavaScript? : can we use google maps in webpage or website without any javascript? just using HTML and CSS. previously I used google map with `<iframe>` tag `<iframe id="map-canvas" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3784.7722058335007!2d73.82234131437744!3d18.44864907618605!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3bc2953b7cc05b01%3A0x4f3556fac1a61485!2sAVIG+PVT.LTD.!5e0!3m2!1sen!2sin!4v1508922847004" width="80%" height="320" frameborder="0" style="border:solid 1px black;" allowfullscreen></iframe>` but I want to use colored dark map now but the procedure of a colored map is very big and includes lots of JavaScript I don't want to include that javascript is there any solution to include colored google maps without any Javascript or jQuery.
0debug
format a string like a date : <p>I'm receiving a "<em>date</em>" represented by a string in the form <strong>yyyymmdd</strong> from a database table over which I have no control. (I cannot modify the type/format of the date field)</p> <p>I would like to insert the character '<strong>/</strong>' at the right place. (<em>20150113 = 2015/01/13</em>)</p> <p>As I haven't been able to use <code>new Date('20150113')</code> I am using a regex to insert the slash like so:</p> <pre><code>string = string.toString().replace(/(^[0-9]{4})/g , "$1\/"); string = string.replace(/(^[0-9\/]{7})/g , "$1\/"); </code></pre> <p>Is it possible to merge both regexes into one or is there an existing function (angular, javascript) that can understand that date format (<em>20150113</em>)?</p>
0debug
Git rebase and push instead of pull : <p>Alternative for 1. git pull origin master 2. git add -a 3. git commit -m 'message' 4. git push</p> <p>How can I do the above without using a pull and using a rebase 1. git rebase master 2. git add -a 3. git commit -m 'message' 4. git push</p> <p>Is that all I need to do or am I missing anything. I want to use rebase to have a linear history.</p>
0debug
Reasons to use generic array over array of Object : I know two reason to use generic array over array of objects. 1. To restrict what type of objects can be inserted into the array List<Object> stringObjects = Arrays.asList("a",new Integer(5)); List<String> genericStrings = Arrays.asList("a",new Integer(5));//compile error 2. To have access to the correct method in your IDE List<Object> stringObjects = Arrays.asList("a",new Integer(5)); List<String> genericStrings = Arrays.asList("a"); stringObjects.get(0).length();//compile error genericStrings.get(0).length(); When I gave this answer to an interview, but they didn't seem very happy with my answer. So are there any other reason to user Generics over Abstract Class in arrays?
0debug
Difference between Number and Integer in SQL Datatypes? : <p>i want to know the basic difference between sql datatype Number and Integer. </p>
0debug
ESLint's "no-undef" rule is calling my use of Underscore an undefined variable : <p>I am using Grunt as my Build Tool and ESLint as my linting tool for an app I am working on. I am also using the Underscore Node package, and have made use of it in my app. Unfortunately, when I run ESLint on my code, it thinks that _ is an undefined variable in the following line:</p> <p><code>return _.pluck(objects, nameColumn);</code></p> <p>This is the error it is giving me:</p> <p><code>78:21 error "_" is not defined no-undef</code></p> <p>I would prefer not to disable the no-undef rule for ESLint, and I have tried installing the Underscore plugin, but I am still receiving this error. If anyone else has any ideas for what to try with this, I would be very appreciative!</p> <p>If there is any further information I can give that would help anyone with helping me get this figured out, just let me know!</p>
0debug
How to Resize Center and Crop an image with ImageSharp : <p>I need to convert some System.Drawing based code to use this .NET Core compatible library:</p> <p><a href="https://github.com/SixLabors/ImageSharp" rel="noreferrer">https://github.com/SixLabors/ImageSharp</a></p> <p>The System.Drawing based code below resizes an image and crops of the edges, returning the memory stream to then be saved. Is this possible with the ImageSharp library?</p> <pre><code>private static Stream Resize(Stream inStream, int newWidth, int newHeight) { var img = Image.Load(inStream); if (newWidth != img.Width || newHeight != img.Height) { var ratioX = (double)newWidth / img.Width; var ratioY = (double)newHeight / img.Height; var ratio = Math.Max(ratioX, ratioY); var width = (int)(img.Width * ratio); var height = (int)(img.Height * ratio); var newImage = new Bitmap(width, height); Graphics.FromImage(newImage).DrawImage(img, 0, 0, width, height); img = newImage; if (img.Width != newWidth || img.Height != newHeight) { var startX = (Math.Max(img.Width, newWidth) - Math.Min(img.Width, newWidth)) / 2; var startY = (Math.Max(img.Height, newHeight) - Math.Min(img.Height, newHeight)) / 2; img = Crop(img, newWidth, newHeight, startX, startY); } } var ms = new MemoryStream(); img.Save(ms, ImageFormat.Jpeg); ms.Position = 0; return ms; } private static Image Crop(Image image, int newWidth, int newHeight, int startX = 0, int startY = 0) { if (image.Height &lt; newHeight) newHeight = image.Height; if (image.Width &lt; newWidth) newWidth = image.Width; using (var bmp = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb)) { bmp.SetResolution(72, 72); using (var g = Graphics.FromImage(bmp)) { g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.DrawImage(image, new Rectangle(0, 0, newWidth, newHeight), startX, startY, newWidth, newHeight, GraphicsUnit.Pixel); var ms = new MemoryStream(); bmp.Save(ms, ImageFormat.Jpeg); image.Dispose(); var outimage = Image.FromStream(ms); return outimage; } } } </code></pre>
0debug
is this a correct way to analyze a graph ? : Hi guys I need help with analyzing a graph , I have implemented Dijkstra algorithm but i'm not sure about my analysis. is this a correct way to analyze a graph ? my analysis are in the comments. public class Dijkstra { for (int i = 0; i < distance.length; i++)//O(v^2) { visited[i] = 0; preD[i] = 0; for (int j = 0; j < distance.length; j++) { matrix[i][j] = scan.nextInt(); if (matrix[i][j]==0) matrix[i][j] = 999; } } for (int counter = 0; counter < n; counter++)//O(V^2) { min = 999; for (int i = 0; i < 3; i++) { if (min > distance[i] && visited[i]!=1) { min = distance[i]; nextNode = i; } } for (int i = 0; i < n; i++)//O(E) { if (visited[i]!=1) { if (min+matrix[nextNode][i] < distance[i]) { distance[i] = min+matrix[nextNode][i]; preD[i] = nextNode; } } } }//finally Dijkstra takes O(v^2) }
0debug
static abi_long do_socketcall(int num, abi_ulong vptr) { abi_long ret; const int n = sizeof(abi_ulong); switch(num) { case SOCKOP_socket: { abi_ulong domain, type, protocol; if (get_user_ual(domain, vptr) || get_user_ual(type, vptr + n) || get_user_ual(protocol, vptr + 2 * n)) return -TARGET_EFAULT; ret = do_socket(domain, type, protocol); } break; case SOCKOP_bind: { abi_ulong sockfd; abi_ulong target_addr; socklen_t addrlen; if (get_user_ual(sockfd, vptr) || get_user_ual(target_addr, vptr + n) || get_user_ual(addrlen, vptr + 2 * n)) return -TARGET_EFAULT; ret = do_bind(sockfd, target_addr, addrlen); } break; case SOCKOP_connect: { abi_ulong sockfd; abi_ulong target_addr; socklen_t addrlen; if (get_user_ual(sockfd, vptr) || get_user_ual(target_addr, vptr + n) || get_user_ual(addrlen, vptr + 2 * n)) return -TARGET_EFAULT; ret = do_connect(sockfd, target_addr, addrlen); } break; case SOCKOP_listen: { abi_ulong sockfd, backlog; if (get_user_ual(sockfd, vptr) || get_user_ual(backlog, vptr + n)) return -TARGET_EFAULT; ret = get_errno(listen(sockfd, backlog)); } break; case SOCKOP_accept: { abi_ulong sockfd; abi_ulong target_addr, target_addrlen; if (get_user_ual(sockfd, vptr) || get_user_ual(target_addr, vptr + n) || get_user_ual(target_addrlen, vptr + 2 * n)) return -TARGET_EFAULT; ret = do_accept4(sockfd, target_addr, target_addrlen, 0); } break; case SOCKOP_accept4: { abi_ulong sockfd; abi_ulong target_addr, target_addrlen; abi_ulong flags; if (get_user_ual(sockfd, vptr) || get_user_ual(target_addr, vptr + n) || get_user_ual(target_addrlen, vptr + 2 * n) || get_user_ual(flags, vptr + 3 * n)) { return -TARGET_EFAULT; } ret = do_accept4(sockfd, target_addr, target_addrlen, flags); } break; case SOCKOP_getsockname: { abi_ulong sockfd; abi_ulong target_addr, target_addrlen; if (get_user_ual(sockfd, vptr) || get_user_ual(target_addr, vptr + n) || get_user_ual(target_addrlen, vptr + 2 * n)) return -TARGET_EFAULT; ret = do_getsockname(sockfd, target_addr, target_addrlen); } break; case SOCKOP_getpeername: { abi_ulong sockfd; abi_ulong target_addr, target_addrlen; if (get_user_ual(sockfd, vptr) || get_user_ual(target_addr, vptr + n) || get_user_ual(target_addrlen, vptr + 2 * n)) return -TARGET_EFAULT; ret = do_getpeername(sockfd, target_addr, target_addrlen); } break; case SOCKOP_socketpair: { abi_ulong domain, type, protocol; abi_ulong tab; if (get_user_ual(domain, vptr) || get_user_ual(type, vptr + n) || get_user_ual(protocol, vptr + 2 * n) || get_user_ual(tab, vptr + 3 * n)) return -TARGET_EFAULT; ret = do_socketpair(domain, type, protocol, tab); } break; case SOCKOP_send: { abi_ulong sockfd; abi_ulong msg; size_t len; abi_ulong flags; if (get_user_ual(sockfd, vptr) || get_user_ual(msg, vptr + n) || get_user_ual(len, vptr + 2 * n) || get_user_ual(flags, vptr + 3 * n)) return -TARGET_EFAULT; ret = do_sendto(sockfd, msg, len, flags, 0, 0); } break; case SOCKOP_recv: { abi_ulong sockfd; abi_ulong msg; size_t len; abi_ulong flags; if (get_user_ual(sockfd, vptr) || get_user_ual(msg, vptr + n) || get_user_ual(len, vptr + 2 * n) || get_user_ual(flags, vptr + 3 * n)) return -TARGET_EFAULT; ret = do_recvfrom(sockfd, msg, len, flags, 0, 0); } break; case SOCKOP_sendto: { abi_ulong sockfd; abi_ulong msg; size_t len; abi_ulong flags; abi_ulong addr; abi_ulong addrlen; if (get_user_ual(sockfd, vptr) || get_user_ual(msg, vptr + n) || get_user_ual(len, vptr + 2 * n) || get_user_ual(flags, vptr + 3 * n) || get_user_ual(addr, vptr + 4 * n) || get_user_ual(addrlen, vptr + 5 * n)) return -TARGET_EFAULT; ret = do_sendto(sockfd, msg, len, flags, addr, addrlen); } break; case SOCKOP_recvfrom: { abi_ulong sockfd; abi_ulong msg; size_t len; abi_ulong flags; abi_ulong addr; socklen_t addrlen; if (get_user_ual(sockfd, vptr) || get_user_ual(msg, vptr + n) || get_user_ual(len, vptr + 2 * n) || get_user_ual(flags, vptr + 3 * n) || get_user_ual(addr, vptr + 4 * n) || get_user_ual(addrlen, vptr + 5 * n)) return -TARGET_EFAULT; ret = do_recvfrom(sockfd, msg, len, flags, addr, addrlen); } break; case SOCKOP_shutdown: { abi_ulong sockfd, how; if (get_user_ual(sockfd, vptr) || get_user_ual(how, vptr + n)) return -TARGET_EFAULT; ret = get_errno(shutdown(sockfd, how)); } break; case SOCKOP_sendmsg: case SOCKOP_recvmsg: { abi_ulong fd; abi_ulong target_msg; abi_ulong flags; if (get_user_ual(fd, vptr) || get_user_ual(target_msg, vptr + n) || get_user_ual(flags, vptr + 2 * n)) return -TARGET_EFAULT; ret = do_sendrecvmsg(fd, target_msg, flags, (num == SOCKOP_sendmsg)); } break; case SOCKOP_setsockopt: { abi_ulong sockfd; abi_ulong level; abi_ulong optname; abi_ulong optval; abi_ulong optlen; if (get_user_ual(sockfd, vptr) || get_user_ual(level, vptr + n) || get_user_ual(optname, vptr + 2 * n) || get_user_ual(optval, vptr + 3 * n) || get_user_ual(optlen, vptr + 4 * n)) return -TARGET_EFAULT; ret = do_setsockopt(sockfd, level, optname, optval, optlen); } break; case SOCKOP_getsockopt: { abi_ulong sockfd; abi_ulong level; abi_ulong optname; abi_ulong optval; socklen_t optlen; if (get_user_ual(sockfd, vptr) || get_user_ual(level, vptr + n) || get_user_ual(optname, vptr + 2 * n) || get_user_ual(optval, vptr + 3 * n) || get_user_ual(optlen, vptr + 4 * n)) return -TARGET_EFAULT; ret = do_getsockopt(sockfd, level, optname, optval, optlen); } break; default: gemu_log("Unsupported socketcall: %d\n", num); ret = -TARGET_ENOSYS; break; } return ret; }
1threat
How to set the path of the folder to be created in uwp in C# : <p>For example: C:\Users\gabriel\Desktop\</p> <p>There it creates the folder on the desktop</p> <p>I do not have code, and I have no idea how to do it. And I do not want to use FolderPicker, I want to define in the folder path code</p>
0debug
User control with if/else statment? : So.. I want to include an ascx file with navigator bar. There are two versions, one shows up when user is not logged in and one is for logged user. <div class="navigator"> <uc1:nav runat="server" ID="nav" /> </div> This is how I can link one of the nav... but I have no idea how to make this path into if/else statment Tried to do some things inside of <% %> but.... without any success. Could anyone help me?
0debug
static int integrate(hdcd_state_t *state, int *flag, const int32_t *samples, int count, int stride) { uint32_t bits = 0; int result = FFMIN(state->readahead, count); int i; *flag = 0; for (i = result - 1; i >= 0; i--) { bits |= (*samples & 1) << i; samples += stride; } state->window = (state->window << result) | bits; state->readahead -= result; if (state->readahead > 0) return result; bits = (state->window ^ state->window >> 5 ^ state->window >> 23); if (state->arg) { if ((bits & 0xffffffc8) == 0x0fa00500) { state->control = (bits & 255) + (bits & 7); *flag = 1; state->code_counterA++; } if (((bits ^ (~bits >> 8 & 255)) & 0xffff00ff) == 0xa0060000) { state->control = bits >> 8 & 255; *flag = 1; state->code_counterB++; } state->arg = 0; } if (bits == 0x7e0fa005 || bits == 0x7e0fa006) { state->readahead = (bits & 3) * 8; state->arg = 1; state->code_counterC++; } else { if (bits) state->readahead = readaheadtab[bits & ~(-1 << 8)]; else state->readahead = 31; } return result; }
1threat
Git revert just some files in commit : <p>I have few commits on github that I want to change. So in my previous commit I've changed some file/folders and I need to revert changes only for some of them. What is the best solution to make it.</p>
0debug
Use AngularJS directive in Angular Component : <p>I'm trying to upgrade an angularjs directive to use it my angular component. I've gotten the hybrid (ng1 + ng2) environment to work. I can also inject angularjs services in angular and use them in angular components (I actually got this working even with angularjs 1.4.x).</p> <p>Now I'm trying to use an existing angularjs directive in angular, but not working.</p> <p>For reference, are some snippets of my codes.</p> <p><strong>[index.html] (my-app is the Angular 4 root component)</strong></p> <pre><code>... &lt;body&gt; &lt;div class="banner"&gt;Angular Migration&lt;/div&gt; &lt;my-app&gt;Loading...&lt;/my-app&gt; ... &lt;/body&gt; ... </code></pre> <p><strong>[main.ts] (bootstrapping code)</strong></p> <pre><code>import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { UpgradeModule } from '@angular/upgrade/static'; import { Router } from '@angular/router'; import { AppModule } from './app.module'; platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef =&gt; { let upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule; upgrade.bootstrap(document.documentElement, ['sampleApp']); platformRef.injector.get(Router).initialNavigation(); }); </code></pre> <p><strong>[app.module.ts] (Angular 4 module)</strong></p> <pre><code>import { NgModule, Component } from '@angular/core'; import { HashLocationStrategy, LocationStrategy, CommonModule } from '@angular/common'; import { BrowserModule } from '@angular/platform-browser'; import { UpgradeModule } from '@angular/upgrade/static'; import { RouterModule, Routes, UrlHandlingStrategy } from '@angular/router'; import { HybridUrlHandlingStrategy } from './hybridUrlHandlingStrategy'; import { AppComponent } from './app.component'; export const routes: Routes = [ ... ]; @NgModule({ imports: [ CommonModule, BrowserModule, UpgradeModule, RouterModule.forRoot([], { useHash: true, initialNavigation: false }) ], providers: [ { provide: LocationStrategy, useClass: HashLocationStrategy }, { provide: UrlHandlingStrategy, useClass: HybridUrlHandlingStrategy }, { provide: 'appService', useFactory: (i: any) =&gt; i.get('appService'), deps: ['$injector'] }, { provide: 'mdToHtml', useFactory: (i: any) =&gt; i.get('mdToHtml'), deps: ['$injector'] } ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { ngDoBootstrap() { } } </code></pre> <p><strong>[app.component.ts] (Angular 4 component)</strong></p> <pre><code>import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` &lt;router-outlet&gt;&lt;/router-outlet&gt; &lt;div ng-view&gt;&lt;/div&gt; `, }) export class AppComponent { } </code></pre> <p><strong>[app.js] (AngularJs app)</strong></p> <pre><code>'use strict'; angular.module('sampleApp', [ 'ngRoute', 'app.components.services.appService' ]) .config(function ($routeProvider) { $routeProvider .otherwise({ template: '' }); }); </code></pre> <p><strong>[myStars.js] (AngularJs directive)</strong></p> <pre><code>'use strict'; angular.module('app.components.directives.myStars', []) .controller('MyStarsCtrl', function() { console.log("**** in MyStarsCtrl ") }) .component('myStars', { restrict: 'E', bindings: { count: '=count' }, template: '&lt;div&gt;***** M Y S T A R S *****&lt;/div&gt;' }); </code></pre> <p><strong>[myStars.ts] (an attempt to migrate myStars directive to Angular 4)</strong></p> <pre><code>import { Directive, ElementRef, Injector, Input, Output, EventEmitter } from '@angular/core'; import { UpgradeComponent } from '@angular/upgrade/static'; @Directive({ selector: 'my-stars' }) export class MyStarsDirective extends UpgradeComponent { @Input() count: number; @Output() clicked: EventEmitter&lt;number&gt;; constructor(elementRef: ElementRef, injector: Injector) { super('myStars', elementRef, injector); } } </code></pre> <p><strong>[test.module.ts] (Angular 4 test module)</strong></p> <pre><code>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes} from '@angular/router'; import { TestComponent } from './test.component'; // importing the new MyStarsDirective) import { MyStarsDirective } from '../../../components/directives/myStars/myStars'; const thisRoute: Routes = [ { path: 'test/:id', component: TestComponent } ]; @NgModule({ declarations: [ TestComponent, MyStarsDirective, // &lt;&lt;&lt;&lt; adding directive here ], providers: [], imports: [ CommonModule, RouterModule.forChild(thisRoute) ], exports: [ RouterModule ] }) export class TestModule {} </code></pre> <p><strong>[test.component.ts] (Angular 4 test component)</strong></p> <pre><code>import { Component, Inject, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { FormsModule } from '@angular/forms'; import { HybridUrlHandlingStrategy } from '../../../hybridUrlHandlingStrategy'; import { MyStarsDirective } from '../../../components/directives/myStars/myStars'; @Component({ templateUrl: './test.component.html' }) export class TestComponent implements OnInit { routeParams: any myService: any mdToHtml: any constructor( @Inject('myService') myService: any, @Inject('mdToHtml') mdToHtml: (str: string) =&gt; string, private activatedRoute: ActivatedRoute ) { this.myService = myService; this.mdToHtml = mdToHtml; } ngOnInit() { this.routeParams = this.activatedRoute.params.subscribe(params =&gt; { console.log("params", params['groupId']) ... } ngOnDestroy() { this.routeParams.unsubscribe(); } } </code></pre> <p><strong>[test.component.html] (Angular 4 html)</strong></p> <pre><code>... &lt;my-stars&gt;&lt;/my-stars&gt; &lt;!-- &lt;&lt;&lt;&lt; using directive here --&gt; ... </code></pre> <p>Note: I've also upgrade angularjs version to 1.5 just to make this hybrid app works.</p> <p>Here's the error when I browser the test component page:</p> <p><a href="https://i.stack.imgur.com/FLY1H.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FLY1H.png" alt="enter image description here"></a></p> <p>Any help would be greatly appreciated.</p> <p>Thanks.</p>
0debug
Some example of Junit of Rest Api : I wanna to try some example of junit with rest api, i m a beginner of j unit and i don t know how to start nothing to test My Repository: @Repository public interface ClienteRepository extends JpaRepository<ClienteEntity, Integer>{ ClienteEntity findByEmail(@Param("email") String email); @Query(value = "SELECT u FROM ClienteEntity u where u.email = ?1 and u.password = ?2 ") Optional<ClienteEntity> login(String email,String password); Optional<ClienteEntity> findByToken(String token); @Query(value = "SELECT c " + "FROM ClienteEntity c " + "WHERE c.id = :id ") ClienteEntity getClienteById(@Param("id")Integer id); } Had an entity "cliente" with these fields: @Id @GeneratedValue(strategy=GenerationType.AUTO) //Vedere UUID bene private Integer id; private String nome; private String cognome; @Column(name = "email", unique = true) private String email ; private String password; private String citta; private String cap; private String indirizzo; private String token; public String getToken() { return token; } with their set and get methods i wanna for example test a "cliente" means "user" by email and wanna test on fields instead my db
0debug
How do I add an intermediate SSL certificate to Kubernetes ingress TLS configuration? : <p>The documentation does not specify how to add an intermediate SSL certificate: <a href="https://kubernetes.io/docs/concepts/services-networking/ingress/#tls" rel="noreferrer">https://kubernetes.io/docs/concepts/services-networking/ingress/#tls</a></p> <p>I suppose the next step would be to read the Kubernetes source code.</p>
0debug
A Python implementation of GitHub flavored markdown : <p>I've been searching for a while now but still can't find anything. I basically need a Python converter for Github flavored markdown, that supports syntax highlighting. I currently use <a href="https://github.com/stewart/gfm" rel="nofollow">gfm</a>, however, that doesn't seem to support syntax highlighting. Not only it doesn't color it, it also does weird things with the code and puts it all on one line.</p>
0debug
Algorithm to remove and shift elements in an array : <p>I am struggling to come up with a technique to achieve following:</p> <p>Example: Input:</p> <pre><code>a[] = [0 1 0 1 0 1 1 0] Array a has 8 entries. Each entry will have either 0 or 1. </code></pre> <p>Output:</p> <pre><code>output = [1 3 5 6 0 2 4 7] Output will have the indices of all the 1s first and then all the zeros. </code></pre> <p>Any recommendation? I am not an algo expert. I have tried solving it using heap/tree but struggling to come up with something with time complexity O(log2(N)).</p>
0debug
How to get Database Messages while executing any query from JAVA : Is it possible to get Database console messages using JDBC after a query is being executed? select * from staff [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/pw5hy.png
0debug
Can't create project on Netbeans 8.2 : <p>I have windows 10 OS, I just downloaded JDK 9, and Netbeans 8.2 version with All features. When I want to create (Java) project, it just can't do it. Doesn't give me an error or something, just this blank screen.</p> <p><a href="https://i.stack.imgur.com/FokIp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FokIp.png" alt="enter image description here"></a></p> <p>What could be problem here, so I can't create any project ?</p>
0debug
Iframe not loading in IE after installing update KB3154070 : <p>We have an application that mostly deals with iframes (loads the different pages within the application on demand)</p> <p>Recently, the IE browser got updated with <a href="https://support.microsoft.com/en-gb/kb/3154070">KB3154070</a>(Current IE Version: 11.0.9600.18314) as part of the system updates. After that update, majority of the functionality is breaking completely. It effected all the pages that use iframes. The content is not loading and resulting in a blank page. The request appears to be aborted when inspected in the network panel as shown in the below screen capture. <a href="http://i.stack.imgur.com/uKfgp.png">Network Traffic Capture</a></p> <p>We have performed the following troubleshooting</p> <p>We made sure that all iframe tags are close properly. The src of the iframe is not empty. If we access the same page outside (without loading into iframe), it works fine. But, the problem is with only within iframe. As a quick workaround to this problem, we have asked our users to roll back the update. But, this is not the expected solution.</p> <p>Your help is really appreciated.</p> <p>Regards, Swajay.</p>
0debug
void tcg_dump_ops(TCGContext *s) { char buf[128]; TCGOp *op; int oi; for (oi = s->gen_first_op_idx; oi >= 0; oi = op->next) { int i, k, nb_oargs, nb_iargs, nb_cargs; const TCGOpDef *def; const TCGArg *args; TCGOpcode c; op = &s->gen_op_buf[oi]; c = op->opc; def = &tcg_op_defs[c]; args = &s->gen_opparam_buf[op->args]; if (c == INDEX_op_insn_start) { qemu_log("%s ----", oi != s->gen_first_op_idx ? "\n" : ""); for (i = 0; i < TARGET_INSN_START_WORDS; ++i) { target_ulong a; #if TARGET_LONG_BITS > TCG_TARGET_REG_BITS a = ((target_ulong)args[i * 2 + 1] << 32) | args[i * 2]; #else a = args[i]; #endif qemu_log(" " TARGET_FMT_lx, a); } } else if (c == INDEX_op_call) { nb_oargs = op->callo; nb_iargs = op->calli; nb_cargs = def->nb_cargs; qemu_log(" %s %s,$0x%" TCG_PRIlx ",$%d", def->name, tcg_find_helper(s, args[nb_oargs + nb_iargs]), args[nb_oargs + nb_iargs + 1], nb_oargs); for (i = 0; i < nb_oargs; i++) { qemu_log(",%s", tcg_get_arg_str_idx(s, buf, sizeof(buf), args[i])); } for (i = 0; i < nb_iargs; i++) { TCGArg arg = args[nb_oargs + i]; const char *t = "<dummy>"; if (arg != TCG_CALL_DUMMY_ARG) { t = tcg_get_arg_str_idx(s, buf, sizeof(buf), arg); } qemu_log(",%s", t); } } else { qemu_log(" %s ", def->name); nb_oargs = def->nb_oargs; nb_iargs = def->nb_iargs; nb_cargs = def->nb_cargs; k = 0; for (i = 0; i < nb_oargs; i++) { if (k != 0) { qemu_log(","); } qemu_log("%s", tcg_get_arg_str_idx(s, buf, sizeof(buf), args[k++])); } for (i = 0; i < nb_iargs; i++) { if (k != 0) { qemu_log(","); } qemu_log("%s", tcg_get_arg_str_idx(s, buf, sizeof(buf), args[k++])); } switch (c) { case INDEX_op_brcond_i32: case INDEX_op_setcond_i32: case INDEX_op_movcond_i32: case INDEX_op_brcond2_i32: case INDEX_op_setcond2_i32: case INDEX_op_brcond_i64: case INDEX_op_setcond_i64: case INDEX_op_movcond_i64: if (args[k] < ARRAY_SIZE(cond_name) && cond_name[args[k]]) { qemu_log(",%s", cond_name[args[k++]]); } else { qemu_log(",$0x%" TCG_PRIlx, args[k++]); } i = 1; break; case INDEX_op_qemu_ld_i32: case INDEX_op_qemu_st_i32: case INDEX_op_qemu_ld_i64: case INDEX_op_qemu_st_i64: { TCGMemOpIdx oi = args[k++]; TCGMemOp op = get_memop(oi); unsigned ix = get_mmuidx(oi); if (op & ~(MO_AMASK | MO_BSWAP | MO_SSIZE)) { qemu_log(",$0x%x,%u", op, ix); } else { const char *s_al = "", *s_op; if (op & MO_AMASK) { if ((op & MO_AMASK) == MO_ALIGN) { s_al = "al+"; } else { s_al = "un+"; } } s_op = ldst_name[op & (MO_BSWAP | MO_SSIZE)]; qemu_log(",%s%s,%u", s_al, s_op, ix); } i = 1; } break; default: i = 0; break; } switch (c) { case INDEX_op_set_label: case INDEX_op_br: case INDEX_op_brcond_i32: case INDEX_op_brcond_i64: case INDEX_op_brcond2_i32: qemu_log("%s$L%d", k ? "," : "", arg_label(args[k])->id); i++, k++; break; default: break; } for (; i < nb_cargs; i++, k++) { qemu_log("%s$0x%" TCG_PRIlx, k ? "," : "", args[k]); } } qemu_log("\n"); } }
1threat
Extending Angular 4 universal renderer : <p>I hope someone can help with the logic on this one. I would like to modify the way angular universal injects the style for each component. Does anyone know how to extend the renderer an get the stylesheet from other place by doing an api request. I would just need an example on the renderer example and the api request I think I may figure out myself.</p> <p>I am looking at this old one. <a href="https://github.com/ralfstx/angular2-renderer-example/blob/master/src/custom-renderer.ts" rel="noreferrer">https://github.com/ralfstx/angular2-renderer-example/blob/master/src/custom-renderer.ts</a></p> <pre><code>import { Injectable, Renderer, RootRenderer, RenderComponentType } from '@angular/core'; export class Element { constructor(private nodeName: string, private parent?: Element) { } toString() { return '&lt;' + this.nodeName + '&gt;'; } }; @Injectable() export class CustomRootRenderer extends RootRenderer { private _registeredComponents: Map&lt;string, CustomRenderer&gt; = new Map&lt;string, CustomRenderer&gt;(); renderComponent(componentProto: RenderComponentType): Renderer { var renderer = this._registeredComponents.get(componentProto.id); if (!renderer) { renderer = new CustomRenderer(this); this._registeredComponents.set(componentProto.id, renderer); } return renderer; } } @Injectable() export class CustomRenderer extends Renderer { constructor(private _rootRenderer: CustomRootRenderer) { super(); console.log('CustomRenderer created'); } renderComponent(componentType: RenderComponentType): Renderer { return this._rootRenderer.renderComponent(componentType); } selectRootElement(selector: string): Element { console.log('selectRootElement', selector); return new Element('Root'); } createElement(parentElement: Element, name: string): Element { console.log('createElement', 'parent: ' + parentElement, 'name: ' + name); return new Element(name, parentElement); } createViewRoot(hostElement: Element): Element { console.log('createViewRoot', 'host: ' + hostElement); return hostElement; } createTemplateAnchor(parentElement: Element): Element { console.log('createTemplateAnchor', 'parent: ' + parentElement); return new Element('?'); } createText(parentElement: Element, value: string): Element { console.log('createText', 'parent: ' + parentElement, 'value: ' + value); return new Element('text'); } projectNodes(parentElement: Element, nodes: Element[]) { console.log('projectNodes', 'parent: ' + parentElement, 'nodes: ' + nodes.map(node =&gt; node.toString())); } attachViewAfter(node: Element, viewRootNodes: Element[]) { console.log('attachViewAfter', 'node: ' + node, 'viewRootNodes: ' + viewRootNodes.map(node =&gt; node.toString())); } detachView(viewRootNodes: Element[]) { console.log('detachView', 'viewRootNodes: ' + viewRootNodes.map(node =&gt; node.toString())); } destroyView(hostElement: Element, viewAllNodes: Element[]) { console.log('destroyView', 'host: ' + hostElement, 'viewAllNodes: ' + viewAllNodes.map(node =&gt; node.toString())); } setElementProperty(renderElement: Element, propertyName: string, propertyValue: any): void { console.log('setElementProperty', 'element: ' + renderElement, 'name: ' + propertyName, 'value: ' + propertyValue); } setElementAttribute(renderElement: Element, attributeName: string, attributeValue: string): void { console.log('setElementAttribute', 'element: ' + renderElement, 'name: ' + attributeName, 'value: ' + attributeValue); return this.setElementProperty(renderElement, attributeName, attributeValue); } listen(renderElement: Element, eventName: string, callback: Function): Function { console.log('listen', 'element: ' + renderElement, 'eventName: ' + eventName); return function () { }; } listenGlobal(target: string, eventName: string, callback: Function): Function { console.log('listen', 'target: ' + target, 'eventName: ' + eventName); return function () { }; } // Used only in debug mode to serialize property changes to comment nodes, // such as &lt;template&gt; placeholders. setBindingDebugInfo(renderElement: Element, propertyName: string, propertyValue: string): void { console.log('setBindingDebugInfo', 'element: ' + renderElement, 'name: ' + propertyName, 'value: ' + propertyValue); } setElementClass(renderElement: Element, className: string, isAdd: boolean): void { console.log('setElementClass', 'className' + className, 'isAdd: ' + isAdd); } setElementStyle(renderElement: Element, styleName: string, styleValue: string): void { console.log('setElementStyle', 'name: ' + styleName, 'value: ' + styleValue); } invokeElementMethod(renderElement: Element, methodName: string, args: Array&lt;any&gt;) { console.log('invokeElementMethod', 'name: ' + methodName, 'args: ' + args); } setText(renderNode: Element, text: string): void { console.log('setText', 'node: ' + renderNode, 'text: ' + text); } } </code></pre>
0debug
Android Developer Console - wrong fingerprint after release build with Android Studio : <p>I started building an Android app with Adobe Air so I needed a .p12 key for building the release version .apk Next I ported the app to Unity3d so I converted the .p12 to .keystore. Up to this point there was no problem uploading new versions to the Developer Console. </p> <p>Now I rewrote and redesigned the app with Android Studio. When I upload the release version build with Android Studio I'm not able to publish it because of different fingerprints. I tried to sign the release build in Android Studio with v1, v2 and both.</p> <p>Any idea on how to solve the issue?</p>
0debug
How to capitalized only first letter of sentence in input fields with javascript? : <p>I want to have only first letter of the sentence to be capitalized in input fields with javascript when i type something. </p> <p>This is my website <a href="http://web.quick-truck.com/signup" rel="nofollow">link</a> where i want to use it.</p> <p>Is there any solution for it?</p> <p>Here is my HTML code:</p> <pre><code>&lt;div class="form-group"&gt; &lt;label for="name" class="label-head"&gt;Company Name &lt;sup&gt;&lt;span class="glyphicon glyphicon-asterisk red" aria-hidden="true"&gt;&lt;/span&gt;&lt;/sup&gt;&lt;/label&gt; &lt;input type="text" class="form-control text-box-length input-lg" id="companyname" placeholder="Enter Your Company Name" data-validation="required" maxlength="50"&gt; &lt;/div&gt; </code></pre>
0debug
PPC_OP(setcrfbit) { T1 = (T1 & PARAM(1)) | (T0 << PARAM(2)); RETURN(); }
1threat
How to return the last element in a byte array of integers in golang : In Golang, I want to find the last element in an array of integers. But it seems like this needs to be done manually or in such a complex way. So if I have a list of 0.0.1, 0.0.2, 0.0.3 I just want 0.0.3 to be returned. Every time I try to return the last element the console returns ``` %!(EXTRA uint8=10) ``` Which I assume means I need to convert a byte array to a slice? WHY DOES THIS GOT TO BE SO COMPLEX? IN JAVASCRIPT I CAN JUST DO `pop()` Here's my code: ``` cmd := exec.Command("git", "tag") out, err := cmd.CombinedOutput() if err != nil { log.Fatalf("cmd.Run() failed with %s\n", err) } fmt.Printf("Variable Type:\n%s\n", reflect.TypeOf(out)) fmt.Printf("Variable:\n%s\n", (out)) slice := out[0:len(out)] releaseVersion := slice[len(slice)-1] fmt.Printf("release version:", releaseVersion) ``` Here's the output: ``` Variable Type: []uint8 Variable: 0.0.1 0.0.2 0.0.3 release version:%!(EXTRA uint8=10) ```
0debug
XCode, Swift, Adapt to all devices : I am a newbie in Swift world. I am trying to design a screen like below. I can do this design for several devices for example IPhone 5 and 5S. This means that my application runs properly on IPhone 5 and 5S. But when I try to run it on IPhone 6 or 6S, my design is broken and disrupted. How can I do a common design for all devices. I am sorry for this question but I need this. Thanks for help. [![enter image description here][1]][1] [1]: http://i.stack.imgur.com/1Wp5Q.jpg
0debug
Can someone explain to me how this if else loop works? : studying some linked lists and not sure how this loop works with the assignment. The question where the code is from is to find the intersection of two linked lists. `ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode *cur1 = headA, *cur2 = headB; while(cur1 != cur2){ cur1 = cur1?cur1->next:headB; cur2 = cur2?cur2->next:headA; } return cur1; }` not sure how the cur1 = cur1 is evaluated with assignments rather than a boolean condition. I understand how the iteration works but unsure of why I can't just do `while(cur1!=cur2){ cur1=cur1->next; cur2=cur2->next; } return cur1;` with this i'm pretty sure I will end up with a runtime error though.
0debug
WPF Window Closing does not work after Cancel : <p>I have an issue that I can't seem to resolve via Google (likely because I'm not searching the right criteria). I have a Closing Event that checks if a button is enabled and pops a messagebox with a result (Yes/No). If the user says NO, I get the desired results in the app; however, the X in the top right corner stops working. How to I "reinstate" the close button ("X" in the top right hand corner) so it works again if pressed (and also evaluates the logic again). </p> <p>I tried this: <a href="https://stackoverflow.com/questions/3001525/how-to-override-default-window-close-operation">Stackoverflow Question</a></p> <p>i don't think I want to play with Visibility of the window. The window doesnt go anywhere. They have dirty data and they need to fix it or have it auto saved. </p> <p>What I have in the application is:</p> <pre><code> private void DXWindow_Closing(object sender, CancelEventArgs e) { if (BtnPatSave.IsEnabled == false) return; if (MessageBox.Show(Properties.Resources.PatAcctMsgBox3, Properties.Resources.PatAcctMsgBox1, MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.No) { e.Cancel = true; } else { var patId = TbPatId.Text; var usl = new UnSetLockValue(); usl.UnSetVal(patId); Log.Info("Patient Account is now unlocked by user: " + Environment.UserName); } } </code></pre>
0debug
How do I set array to a new array? : I need to a implement a function that modifies array. New array maybe different size. `cout` prints 1. I understand what's wrong with this code but I just cannot figure out what the syntax is. //tried this.. int reduce(int *array[]) { *array = new int[1]; (*array)[0] = 6; return 0; } //also tried this.. int reduce(int array[]) { array = new int [1]; array[0] = 6; return 0; } int main() { int a[1] = {1}; int *p = a; reduce(&p); cout << a[0]; return 0; }
0debug
Avoiding Android navigation IllegalArgumentException in NavController : <p>I recently switched over to Android Navigation, but have encountered a fair amount of situations (in different parts of the code), where I get:</p> <pre><code>Fatal Exception: java.lang.IllegalArgumentException navigation destination com.xxx.yyy:id/action_aFragment_to_bFragment is unknown to this NavController </code></pre> <p>In every case, the code are simple calls like:</p> <pre><code>findNavController(this, R.id.navigation_host_fragment).navigate(R.id.action_aFragment_to_bFragment) </code></pre> <p>Usually in response to a button press.</p> <p>It's unclear why this error is getting thrown. My current suspicion is that the onClickListener is somehow getting called twice on some devices, causing the navigate to be called a second time (causing it to be in the wrong state at the time). The reason for this suspicion is that this most often seems to happen in cases where one might have a "long" running operation before the navigate call. I can't recreate this on my own device, though.</p> <p>Ideas on how to avoid this issue (or indeed, what the actual root cause of the issue is)?</p> <p>I don't want to use Global Actions; I'm wary of introducing even more unexpected states to the backstack. And I'd really prefer not to have to try and test for the currentstate every time a navigate call is made.</p>
0debug
Are there any alternatives to T4 templates and EnvDTE for cross platform asp.net 5 development? : <p>We currently use T4 templates to generate C# code files based on C# Code (Entity POCO's) and the EDMX (in older applications) </p> <p>Moving to ASP.NET 5 with a view to support cross platform development, are there any code generation tools available that can read a projects class &amp; meta data structures, and to generate C# files at design time, similar to T4 templates?</p>
0debug
static int img_bench(int argc, char **argv) { int c, ret = 0; const char *fmt = NULL, *filename; bool quiet = false; bool image_opts = false; bool is_write = false; int count = 75000; int depth = 64; int64_t offset = 0; size_t bufsize = 4096; int pattern = 0; size_t step = 0; int flush_interval = 0; bool drain_on_flush = true; int64_t image_size; BlockBackend *blk = NULL; BenchData data = {}; int flags = 0; bool writethrough = false; struct timeval t1, t2; int i; for (;;) { static const struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL}, {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS}, {"pattern", required_argument, 0, OPTION_PATTERN}, {"no-drain", no_argument, 0, OPTION_NO_DRAIN}, {0, 0, 0, 0} }; c = getopt_long(argc, argv, "hc:d:f:no:qs:S:t:w", long_options, NULL); if (c == -1) { break; } switch (c) { case 'h': case '?': help(); break; case 'c': { unsigned long res; if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) { error_report("Invalid request count specified"); return 1; } count = res; break; } case 'd': { unsigned long res; if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) { error_report("Invalid queue depth specified"); return 1; } depth = res; break; } case 'f': fmt = optarg; break; case 'n': flags |= BDRV_O_NATIVE_AIO; break; case 'o': { offset = cvtnum(optarg); if (offset < 0) { error_report("Invalid offset specified"); return 1; } break; } break; case 'q': quiet = true; break; case 's': { int64_t sval; sval = cvtnum(optarg); if (sval < 0 || sval > INT_MAX) { error_report("Invalid buffer size specified"); return 1; } bufsize = sval; break; } case 'S': { int64_t sval; sval = cvtnum(optarg); if (sval < 0 || sval > INT_MAX) { error_report("Invalid step size specified"); return 1; } step = sval; break; } case 't': ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough); if (ret < 0) { error_report("Invalid cache mode"); ret = -1; goto out; } break; case 'w': flags |= BDRV_O_RDWR; is_write = true; break; case OPTION_PATTERN: { unsigned long res; if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) { error_report("Invalid pattern byte specified"); return 1; } pattern = res; break; } case OPTION_FLUSH_INTERVAL: { unsigned long res; if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) { error_report("Invalid flush interval specified"); return 1; } flush_interval = res; break; } case OPTION_NO_DRAIN: drain_on_flush = false; break; case OPTION_IMAGE_OPTS: image_opts = true; break; } } if (optind != argc - 1) { error_exit("Expecting one image file name"); } filename = argv[argc - 1]; if (!is_write && flush_interval) { error_report("--flush-interval is only available in write tests"); ret = -1; goto out; } if (flush_interval && flush_interval < depth) { error_report("Flush interval can't be smaller than depth"); ret = -1; goto out; } blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet); if (!blk) { ret = -1; goto out; } image_size = blk_getlength(blk); if (image_size < 0) { ret = image_size; goto out; } data = (BenchData) { .blk = blk, .image_size = image_size, .bufsize = bufsize, .step = step ?: bufsize, .nrreq = depth, .n = count, .offset = offset, .write = is_write, .flush_interval = flush_interval, .drain_on_flush = drain_on_flush, }; printf("Sending %d %s requests, %d bytes each, %d in parallel " "(starting at offset %" PRId64 ", step size %d)\n", data.n, data.write ? "write" : "read", data.bufsize, data.nrreq, data.offset, data.step); if (flush_interval) { printf("Sending flush every %d requests\n", flush_interval); } data.buf = blk_blockalign(blk, data.nrreq * data.bufsize); memset(data.buf, pattern, data.nrreq * data.bufsize); data.qiov = g_new(QEMUIOVector, data.nrreq); for (i = 0; i < data.nrreq; i++) { qemu_iovec_init(&data.qiov[i], 1); qemu_iovec_add(&data.qiov[i], data.buf + i * data.bufsize, data.bufsize); } gettimeofday(&t1, NULL); bench_cb(&data, 0); while (data.n > 0) { main_loop_wait(false); } gettimeofday(&t2, NULL); printf("Run completed in %3.3f seconds.\n", (t2.tv_sec - t1.tv_sec) + ((double)(t2.tv_usec - t1.tv_usec) / 1000000)); out: qemu_vfree(data.buf); blk_unref(blk); if (ret) { return 1; } return 0; }
1threat
Android WebView err_unknown_url_scheme : <p>With the simple below code I can get my url loaded correctly, but, I get "ERR_UNKNOWN_URL_SCHEME" when trying to tap on html links that starts with <em>mailto:</em> <em>whatsapp:</em> and <em>tg:</em> (Telegram).</p> <p>Anyone can help me to fix this please? Unfortunately I do not know Java at all :(</p> <p>Thanks.</p> <pre><code>import android.app.Activity; import android.os.Bundle; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; public class MainActivity extends Activity { private WebView mWebView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mWebView = (WebView) findViewById(R.id.activity_main_webview); // Force links and redirects to open in the WebView instead of in a browser mWebView.setWebViewClient(new WebViewClient()); // Enable Javascript WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); // Use remote resource mWebView.loadUrl("http://myexample.com"); } } </code></pre>
0debug
Javascript Copy To Clipboard on safari? : <p>It may be duplicate question but i didnt find the solution for this.</p> <p>I am trying to copy text on button click. Its working on chrome, mozilla(working on on windows and mac but not on linux). And its not working on safari.</p> <p>I am using <code>document.execCommand("copy")</code> command for copy. </p> <p><strong>Is safari support this command?</strong></p> <p><strong>Is there any way which will supports to all browsers?</strong></p>
0debug
Declare a C++ function that has C calling convention but internal linkage : <p>I'm trying to interface with a C library, which expects me to provide a pointer to a callback function.</p> <p>As I understand it, according to the standard the callback must have C <em>language linkage</em>, due to possibly different calling convention. I can accomplish this by declaring my callback function as <code>extern "C"</code>. However this has an undesirable side effect: exposing the function's unqualified and unmangled name to other translation units.</p> <p>Is it possible to declare a function such that its name has <em>internal linkage</em> (not visible to other translation units), but which can be called from C via a pointer (has appropriate calling convention) using only standard C++?</p> <p>If it's impossible to make it have <em>internal linkage</em>, is it at least possible to make it keep its C++ name mangling?</p> <p>I tried:</p> <ul> <li>Declaring it as <code>static extern "C" void f();</code> which caused a compilation error to the effect that <code>static</code> and <code>extern "C"</code> cannot be used together.</li> <li>Declaring it within an anonymous namespace as <code>namespace { extern "C" void f(); }</code> which turned out to have the same effect as regular namespace, exposing the unmangled unqualified name.</li> </ul>
0debug
static int vc9_decode_init(AVCodecContext *avctx) { VC9Context *v = avctx->priv_data; MpegEncContext *s = &v->s; GetBitContext gb; if (!avctx->extradata_size || !avctx->extradata) return -1; avctx->pix_fmt = PIX_FMT_YUV420P; v->s.avctx = avctx; if(ff_h263_decode_init(avctx) < 0) return -1; if (vc9_init_common(v) < 0) return -1; avctx->coded_width = avctx->width; avctx->coded_height = avctx->height; if (avctx->codec_id == CODEC_ID_WMV3) { int count = 0; init_get_bits(&gb, avctx->extradata, avctx->extradata_size); decode_sequence_header(avctx, &gb); count = avctx->extradata_size*8 - get_bits_count(&gb); if (count>0) { av_log(avctx, AV_LOG_INFO, "Extra data: %i bits left, value: %X\n", count, get_bits(&gb, count)); } else { av_log(avctx, AV_LOG_INFO, "Read %i bits in overflow\n", -count); } } avctx->has_b_frames= !!(avctx->max_b_frames); s->mb_width = (avctx->coded_width+15)>>4; s->mb_height = (avctx->coded_height+15)>>4; if (alloc_bitplane(&v->mv_type_mb_plane, s->mb_width, s->mb_height) < 0) return -1; if (alloc_bitplane(&v->mv_type_mb_plane, s->mb_width, s->mb_height) < 0) return -1; if (alloc_bitplane(&v->skip_mb_plane, s->mb_width, s->mb_height) < 0) return -1; if (alloc_bitplane(&v->direct_mb_plane, s->mb_width, s->mb_height) < 0) return -1; v->previous_line_cbpcy = (uint8_t *)av_malloc(s->mb_stride*4); if (!v->previous_line_cbpcy) return -1; #if HAS_ADVANCED_PROFILE if (v->profile > PROFILE_MAIN) { if (alloc_bitplane(&v->over_flags_plane, s->mb_width, s->mb_height) < 0) return -1; if (alloc_bitplane(&v->ac_pred_plane, s->mb_width, s->mb_height) < 0) return -1; } #endif return 0; }
1threat
static int get_uint16_equal(QEMUFile *f, void *pv, size_t size, VMStateField *field) { uint16_t *v = pv; uint16_t v2; qemu_get_be16s(f, &v2); if (*v == v2) { return 0; error_report("%x != %x", *v, v2); return -EINVAL;
1threat
C# - A* algorithm gives wrong results : <p>I am trying to make 4-directional A-star pathfinding algorithm in C# but can't make it work properly. In Main method i have a example 5x5 <em>int</em> array map to set which fields can be accessed and which not (0 - clear field, 1 - obstacle). As example i set <em>START</em> point at (1, 3) and <em>TARGET</em> point at (4, 4), so i would expect path to avoid wall and proceed etc. but it doesn't. I've even made my algorithm display every parent and it's successors (neighbour). In my case it displays (2,4) as one of the nodes despite being marked as obstacle in Fields (Map), how did it happen? There is clear statement in <em>GetSuccessors</em> method to include only the ones marked as 0 but it still includes (2, 4) point. I am not really sure if something is wrong with <em>GetSuccessors</em> or <em>FindPath</em> (main algorithm).</p> <p>Example map:</p> <pre><code>int[,] fields = new int[5, 5] //MAP, 1 - OBSTACLE { { 0, 0, 0, 0, 0 }, { 0, 1, 1, 1, 0 }, { 0, 1, 1, 1, 0 }, { 0, 0, 1, 0, 0 }, { 0, 0, 1, 0, 0 } }; </code></pre> <p>Example points:</p> <pre><code>Node start = new Node(1, 3); //START LOCATION ON MAP Node target = new Node(4, 4); //TARGET LOCATION ON MAP </code></pre> <p>Produced path (from TARGET to START):</p> <pre><code>4, 4 3, 4 2, 4 1, 3 </code></pre> <p>Full code (FindPath and GetSuccessors are the main ones but i still could make something wrong with other methods):</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; namespace FoxLib { public class Node { public Node(int x, int y) { this.x = x; this.y = y; } public int x, y; //POSITION ON MAP public Node parent; //NEEDED TO RETRIEVE PATH LATER public int G, H, F; //G - COST FROM START NODE TO THIS NODE //H - COST FROM THIS NODE TO TARGET (HEURISTIC) //F - G + H; NODE COST } public class Pathfinding { public static void FindPath(int startX, int startY, int targetX, int targetY, int[,] fields) //MAIN ALGORITHM { bool pathFound=false; //IS PATH AVAILABLE? Node start = new Node(startX, startY); //STARTING NODE Node target = new Node(targetX, targetY); //TARGET NODE start.parent = start; start.G = 0; start.H = Math.Abs(target.x - start.x) + Math.Abs(target.y - start.y); start.F = start.G + start.H; Node current = new Node(0, 0); List&lt;Node&gt; openList = new List&lt;Node&gt;(); //NODES WAITING TO BE CHECKED List&lt;Node&gt; closedList = new List&lt;Node&gt;(); //ALREADY CHECKED NODES openList.Add(start); while(openList.Count&gt;0) //DO AS LONG AS THERE ARE STILL NODES TO DISCOVER { current = MinFNode(openList); //FIND NODE WITH LOWEST F COST (LOWER=BETTER PATH) openList.Remove(current); //REMOVE CURRENT NODE FROM QUEUE if ((current.x==target.x)&amp;&amp;(current.y==target.y)) //TARGET FOUND { Console.WriteLine("PATH FOUND"); pathFound = true; //DISPLAY PATH (FROM TARGET TO START) BY CHECKING PARENTS Console.WriteLine("[FULL PATH]"); do { Console.WriteLine(current.x + ", " + current.y); current = current.parent; } while ((current.x != start.x) &amp;&amp; (current.y != start.y)); Console.WriteLine(start.x + ", " + start.y); break; } List&lt;Node&gt; successors = GetSuccessors(current.x, current.y, fields); //GET SUCCESSORS foreach (Node node in successors) { node.parent = current; //SET CURRENT NODE AS PARENT TO RETRIEVE PATH LATER node.G = current.G + 10; //10 - DISTANCE FROM CURRENT TO ITS SUCCESSOR, current.G DISTANCE FROM CURRENT TO START node.H = Math.Abs(target.x - node.x) + Math.Abs(target.y - node.y); //HEURISTIC DISTANCE TO TARGET node.F = node.G + node.H; //NODE FINAL COST Console.WriteLine(current.x + ", " + current.y + " PARENT | SUCCESSOR: " + node.x + ", " + node.y); //TEST DISPLAY TO CHECK SUCCESSORS CURRENT NODE PRODUCED if (closedList.FirstOrDefault(l =&gt; l.x == node.x &amp;&amp; l.y == node.y) != null) //IF SUCCESSOR ALREADY EXISTS ON CLOSED LIST { Node temp = closedList.FirstOrDefault(l =&gt; l.x == node.x &amp;&amp; l.y == node.y); if (node.F &lt; temp.F) //IF NEW PATH TO THIS NODE IS BETTER? (LOWER F = SHORTER PATH) { closedList.Remove(temp); //REMOVE OLD NODE temp.parent = node.parent; temp.F = node.F; closedList.Add(temp); //ADD UPDATED NODE } } else if(openList.FirstOrDefault(l =&gt; l.x == node.x &amp;&amp; l.y == node.y) != null) //IF SUCCESSOR ALREADY EXISTS ON OPEN LIST { Node temp = openList.FirstOrDefault(l =&gt; l.x == node.x &amp;&amp; l.y == node.y); if (node.F &lt; temp.F) //IF NEW PATH TO THIS NODE IS BETTER? (LOWER F = SHORTER PATH) { openList.Remove(temp); //REMOVE OLD NODE temp.parent = node.parent; temp.F = node.F; openList.Add(temp); //ADD UPDATED NODE } } else { openList.Add(node); //ADD SUCCESSOR TO OPEN LIST } } closedList.Add(current); //MARK CURRENT NODE AS CHECKED (NO NEED TO CHECK IT UNTIL BETTER PATH TO THIS NODE IS FOUND) } if(!pathFound) { Console.WriteLine("PATH NOT FOUND"); } } //FIND NODE WITH LOWEST F COST public static Node MinFNode(List&lt;Node&gt; nodes) { Node result = nodes[0]; foreach(Node node in nodes) { if (node.F &lt; result.F) result = node; } return result; } //GET SUCCESSORS OF CURRENT NODE (ONLY THE ONES WITH "0" VALUE) public static List&lt;Node&gt; GetSuccessors(int x, int y, int[,] fields) { List&lt;Node&gt; Successors = new List&lt;Node&gt;(); if ((x - 1 &gt;= 0) &amp;&amp; (fields[x - 1, y]==0)) Successors.Add(new Node(x - 1, y)); //LEFT if ((x + 1 &lt; fields.GetLength(0)) &amp;&amp; (fields[x + 1, y]==0)) Successors.Add(new Node(x + 1, y)); //RIGHT if ((y - 1 &gt;= 0) &amp;&amp; (fields[x, y - 1]==0)) Successors.Add(new Node(x, y - 1)); //UP if ((y + 1 &lt; fields.GetLength(1)) &amp;&amp; (fields[x, y + 1]==0)) Successors.Add(new Node(x, y + 1)); //DOWN return Successors; //RETURN LIST OF AVAILABLE SUCCESSORS } static void Main() { int[,] fields = new int[5, 5] //MAP, 1 - OBSTACLE { { 0, 0, 0, 0, 0 }, { 0, 1, 1, 1, 0 }, { 0, 1, 1, 1, 0 }, { 0, 0, 1, 0, 0 }, { 0, 0, 1, 0, 0 } }; Node start = new Node(1, 3); //START LOCATION ON MAP Node target = new Node(4, 4); //TARGET LOCATION ON MAP FindPath(start.x,start.y,target.x,target.y,fields); //MAIN ALGORITHM Console.WriteLine("END"); Console.ReadLine(); } } } </code></pre>
0debug
static bool lowprot_enabled(const CPUS390XState *env) { if (!(env->cregs[0] & CR0_LOWPROT)) { return false; } if (!(env->psw.mask & PSW_MASK_DAT)) { return true; } switch (env->psw.mask & PSW_MASK_ASC) { case PSW_ASC_PRIMARY: return !(env->cregs[1] & _ASCE_PRIVATE_SPACE); case PSW_ASC_SECONDARY: return !(env->cregs[7] & _ASCE_PRIVATE_SPACE); case PSW_ASC_HOME: return !(env->cregs[13] & _ASCE_PRIVATE_SPACE); default: error_report("unsupported addressing mode"); exit(1); } }
1threat
Limites de uso gratuito no Azure : Olá, me inscrevi agora no teste gratuito do Azure não sei como funciona. Gostaria de saber quais os limites de uso terei depois que o plano gratuito acabar. Eu tenho um site com 400mb e 10mb de banco de dados MySQL, posso hospedar de forma gratuita sem exceder os limites de uso do plano gratuito? Obrigado
0debug
VB.Net MS ACCESS .Object Reference Not Set to an instanceof an object : 'Sql = "Select ItemName,Count(itemID) from tblItem where Item ='" & "A" & "' AND ExpireDate < '" & Now().Date() & "' Group By ItemName" Im FACING Datatype miss match in this querry in DATE Field.... how could i make this ? DB-MS ACCESS
0debug
static int adx_decode_frame(AVCodecContext *avctx, void *data, int *data_size, const uint8_t *buf0, int buf_size) { ADXContext *c = avctx->priv_data; short *samples = data; const uint8_t *buf = buf0; int rest = buf_size; if (!c->header_parsed) { int hdrsize = adx_decode_header(avctx,buf,rest); if (hdrsize==0) return -1; c->header_parsed = 1; buf += hdrsize; rest -= hdrsize; } if (c->in_temp) { int copysize = 18*avctx->channels - c->in_temp; memcpy(c->dec_temp+c->in_temp,buf,copysize); rest -= copysize; buf += copysize; if (avctx->channels==1) { adx_decode(samples,c->dec_temp,c->prev); samples += 32; } else { adx_decode_stereo(samples,c->dec_temp,c->prev); samples += 32*2; } } if (avctx->channels==1) { while(rest>=18) { adx_decode(samples,buf,c->prev); rest-=18; buf+=18; samples+=32; } } else { while(rest>=18*2) { adx_decode_stereo(samples,buf,c->prev); rest-=18*2; buf+=18*2; samples+=32*2; } } c->in_temp = rest; if (rest) { memcpy(c->dec_temp,buf,rest); buf+=rest; } *data_size = (uint8_t*)samples - (uint8_t*)data; printf("%d:%d ",buf-buf0,*data_size); fflush(stdout); return buf-buf0; }
1threat
Python: Extracting every nth m items from a list : Champs, What's the most efficient way of extracting every nth m items from a list. So if I have: [1,2,3,4,5,6,7,8,9,10,...] I would like every 3rd 2 items, starting from the first index: [1,2,7,8,13,14,...] Thanks Kam
0debug
Run some php Code with SAPUI5 on HANA Cloud Platform : I try to write some data with php in an .txt file. Therefore I create in my SAPUI5 App the file "writeData.php" with this content: <?php $inhalt = "123456789"; $handle = fopen ("testWrite.txt", w); fwrite ($handle, $inhalt); fclose ($handle); ?> Then I try to call this file with the following Ajax request: writeStringToWhitelist: function(newContent){ $.ajax({ url: "writeData.php", type: "POST", data: newContent, async: false, success: function(){ console.log("Success"); } }); } I know that there are surely some mistakes, but I hope someone can help me! Thanks in regards
0debug
void *pci_assign_dev_load_option_rom(PCIDevice *dev, struct Object *owner, int *size, unsigned int domain, unsigned int bus, unsigned int slot, unsigned int function) { char name[32], rom_file[64]; FILE *fp; uint8_t val; struct stat st; void *ptr = NULL; if (dev->romfile || !dev->rom_bar) { return NULL; } snprintf(rom_file, sizeof(rom_file), "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/rom", domain, bus, slot, function); if (stat(rom_file, &st)) { return NULL; } if (access(rom_file, F_OK)) { error_report("pci-assign: Insufficient privileges for %s", rom_file); return NULL; } fp = fopen(rom_file, "r+"); if (fp == NULL) { return NULL; } val = 1; if (fwrite(&val, 1, 1, fp) != 1) { goto close_rom; } fseek(fp, 0, SEEK_SET); snprintf(name, sizeof(name), "%s.rom", object_get_typename(owner)); memory_region_init_ram(&dev->rom, owner, name, st.st_size, &error_abort); vmstate_register_ram(&dev->rom, &dev->qdev); ptr = memory_region_get_ram_ptr(&dev->rom); memset(ptr, 0xff, st.st_size); if (!fread(ptr, 1, st.st_size, fp)) { error_report("pci-assign: Cannot read from host %s", rom_file); error_printf("Device option ROM contents are probably invalid " "(check dmesg).\nSkip option ROM probe with rombar=0, " "or load from file with romfile=\n"); goto close_rom; } pci_register_bar(dev, PCI_ROM_SLOT, 0, &dev->rom); dev->has_rom = true; *size = st.st_size; close_rom: fseek(fp, 0, SEEK_SET); val = 0; if (!fwrite(&val, 1, 1, fp)) { DEBUG("%s\n", "Failed to disable pci-sysfs rom file"); } fclose(fp); return ptr; }
1threat
How do i select rows based on specific condition in R : I am trying to select specific rows based on specific condition. Like to get values all below z with respect to 1st column and exclude the ones on top. I tried using filter and group by but it is not working:( https://i.stack.imgur.com/Xfa6j.png
0debug
Is there a wildcard character in Express.js routing? : <p>I want to create a web application structure like the following:</p> <pre><code>rootUrl/shopRecords/shop1 rootUrl/shopRecords/shop2 rootUrl/shopRecords/shop3... </code></pre> <p>where there can be any limit of shops, but all of the shop pages will have the same page layout (same HTML/Pug page, just populated with different data from a database). These URLs will be accessed from a list of buttons/links on a home page. </p> <p>Does Express.js have a wildcard character so that I can specify behavior for all pages with link format <code>rootUrl/shopRecords/*</code> to be the same?</p>
0debug
void apic_enable_vapic(DeviceState *d, target_phys_addr_t paddr) { APICCommonState *s = DO_UPCAST(APICCommonState, busdev.qdev, d); APICCommonClass *info = APIC_COMMON_GET_CLASS(s); s->vapic_paddr = paddr; info->vapic_base_update(s); }
1threat
How to interact with Java Scanner Class (Atom editor) : I am super newb with Java and I am trying simple codes with Atom editor (osx). Please, someone can help me to understand how can I interact with code with Atom? I use Script package (Atom) to run the code (cmd+i). For example if I use the Scanner class: import java.util.Scanner; public class Les { public static void main(String[] args) { String s; Scanner in = new Scanner(System.in); System.out.println("Enter a string"); s = in.nextLine(); System.out.println("You entered string " + s); } } the output will be "enter a string" Where I can insert the Strings? Thank you
0debug
int qcow2_alloc_clusters_at(BlockDriverState *bs, uint64_t offset, int nb_clusters) { BDRVQcowState *s = bs->opaque; uint64_t cluster_index; uint64_t old_free_cluster_index; int i, refcount, ret; cluster_index = offset >> s->cluster_bits; for(i = 0; i < nb_clusters; i++) { refcount = get_refcount(bs, cluster_index++); if (refcount < 0) { return refcount; } else if (refcount != 0) { break; } } ret = update_refcount(bs, offset, i << s->cluster_bits, 1); if (ret < 0) { return ret; } return i; }
1threat
Regarding Contacts Framework in Swift : Having no experience in coding and having an app idea 6 months ago,I am watching swift programmatically rather than using the storyboard. So I have a question hoping some folks here can answer, and based on my limited search ability on what key words to use. I haven't been able to answer this in my research and its regarding the contacts framework. When the app has access to your contacts, and you need those contacts to populate a pickerview, does it pull the contacts to the firebase db(what i am using) and fetch those contacts to populate the pickerview, or does it do it within the phone(maybe coredata?) any advice or guidance would be greatly appreciated. And if does and I can use coredata, I can use it hand in hand with firebase? Or does it even pull and store somewhere? I'd like my users to be able to select which contacts they want to add to the app. Thank you in advance.
0debug
Is DatabaseCleaner still necessary with Rails system specs? : <p>From all that I've read about Rails 5.1 new system specs my understanding was that Rails now handles database transactions internally. </p> <p>From <a href="http://rspec.info/blog/2017/10/rspec-3-7-has-been-released/" rel="noreferrer">Rspec's blog</a>: "[previously] your tests and your code under test cannot share a database transaction, and so you cannot use RSpec's built in mechanism to roll back database changes, instead requiring a gem like database cleaner. With system tests, the Rails team has done the hard work to ensure that this is not the case, and so you can safely use RSpec's mechanism, without needing an extra gem."</p> <p>My experience is different: </p> <ol> <li>My Rspec feature tests were all passing after upgrading to Rails 5.1. </li> <li>I renamed the 'feature' specs to become 'system' specs. All tests passed. </li> <li>I removed the <a href="https://github.com/DatabaseCleaner/database_cleaner" rel="noreferrer">Database Cleaner</a> gem, and removed all references from <code>rails_helper.rb</code>. JS tests now fail due to <code>validates uniqueness</code> errors. Non-JS tests pass.</li> </ol> <p>My tests are very simple. </p> <pre><code>let(:subject) { page } let(:user) { create :user, name: "TestUser" } it "displays the user page", :js do visit user_path(user) it is_expected.to have_content "TestUser" end </code></pre> <p>With Database cleaner disabled and <code>:js =&gt; true</code> I get <code>user named TestUser already exists</code>. With <code>:js =&gt; false</code> the test passes. </p> <p>What is the current situation with system tests and rspec? Does Rails handle database transactions internally, or is Database Cleaner still required? Has anyone encountered this, or can point me towards relevant info? </p>
0debug
static int ipvideo_decode_block_opcode_0x4(IpvideoContext *s) { int x, y; unsigned char B, BL, BH; CHECK_STREAM_PTR(1); B = *s->stream_ptr++; BL = B & 0x0F; BH = (B >> 4) & 0x0F; x = -8 + BL; y = -8 + BH; debug_interplay (" motion byte = %d, (x, y) = (%d, %d)\n", B, x, y); return copy_from(s, &s->last_frame, x, y); }
1threat
static int close_f(int argc, char **argv) { bdrv_close(bs); bs = NULL; return 0; }
1threat
avoid to show anything except English keyboard with javascript : how can do in javascript , when user typewrite anything except numbers , don't show anything in input field type text ,for some reason i can't change input type to number ? and in other input type text when user typewrite any things except English keyboard (characters) , don't show anything. <input type="text" name="nationalityCode" placeholder="please just enter number" > <input type="text" name="name" placeholder="please Enter your name in English" >
0debug
Is this R bug real? : <p>I am quite confused... and thinking is this bug real? How can it be? I just want to make a vector of 0's and 1's.</p> <p>Here's the source and the outcome</p> <pre><code>n.subj=1000 prop.aber = 0.9 n.measure = 3 n.subj.norm = n.subj*(1-prop.aber) n.subj.aber = n.subj*prop.aber labE &lt;- rnorm(n.subj*n.measure, 0, 1) labT_ &lt;- c(rep(0, n.subj.norm), rep(1, n.subj.aber)); length(labT_) sum(labT_ == 0); sum(labT_ == 1) [1] 99 [1] 900 </code></pre> <p>My common sense tells me that it should be 100 and 900!!!!!!?!?!?????</p>
0debug
static void dp8393x_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); set_bit(DEVICE_CATEGORY_NETWORK, dc->categories); dc->realize = dp8393x_realize; dc->reset = dp8393x_reset; dc->vmsd = &vmstate_dp8393x; dc->props = dp8393x_properties; }
1threat
Force browser user to maximize window and set 100% zoom : I know it sound weird but there really is a reason and it is in the users' best intereset. I know that having the browser automatically maximize and set 100% might be problematic but how about making so that if the window is not maximize and the zoom is not 100% all the user's would see is a message "please max your window and set zom to 100%". I need to make this work in Chrome, Firefox and IE ...at least.
0debug
static int mpeg4_unpack_bframes_filter(AVBSFContext *ctx, AVPacket *out) { UnpackBFramesBSFContext *s = ctx->priv_data; int pos_p = -1, nb_vop = 0, pos_vop2 = -1, ret = 0; AVPacket *in; ret = ff_bsf_get_packet(ctx, &in); if (ret < 0) return ret; scan_buffer(in->data, in->size, &pos_p, &nb_vop, &pos_vop2); av_log(ctx, AV_LOG_DEBUG, "Found %d VOP startcode(s) in this packet.\n", nb_vop); if (pos_vop2 >= 0) { if (s->b_frame_buf) { av_log(ctx, AV_LOG_WARNING, "Missing one N-VOP packet, discarding one B-frame.\n"); av_freep(&s->b_frame_buf); s->b_frame_buf_size = 0; } s->b_frame_buf_size = in->size - pos_vop2; s->b_frame_buf = create_new_buffer(in->data + pos_vop2, s->b_frame_buf_size); if (!s->b_frame_buf) { s->b_frame_buf_size = 0; av_packet_free(&in); return AVERROR(ENOMEM); } } if (nb_vop > 2) { av_log(ctx, AV_LOG_WARNING, "Found %d VOP headers in one packet, only unpacking one.\n", nb_vop); } if (nb_vop == 1 && s->b_frame_buf) { ret = av_packet_copy_props(out, in); if (ret < 0) { av_packet_free(&in); return ret; } av_packet_from_data(out, s->b_frame_buf, s->b_frame_buf_size); if (in->size <= MAX_NVOP_SIZE) { av_log(ctx, AV_LOG_DEBUG, "Skipping N-VOP.\n"); s->b_frame_buf = NULL; s->b_frame_buf_size = 0; } else { s->b_frame_buf_size = in->size; s->b_frame_buf = create_new_buffer(in->data, in->size); if (!s->b_frame_buf) { s->b_frame_buf_size = 0; av_packet_unref(out); av_packet_free(&in); return AVERROR(ENOMEM); } } } else if (nb_vop >= 2) { av_packet_move_ref(out, in); out->size = pos_vop2; } else if (pos_p >= 0) { av_log(ctx, AV_LOG_DEBUG, "Updating DivX userdata (remove trailing 'p').\n"); av_packet_move_ref(out, in); out->data[pos_p] = '\0'; } else { av_packet_move_ref(out, in); } av_packet_free(&in); return 0; }
1threat
int ff_hevc_cu_qp_delta_abs(HEVCContext *s) { int prefix_val = 0; int suffix_val = 0; int inc = 0; while (prefix_val < 5 && GET_CABAC(elem_offset[CU_QP_DELTA] + inc)) { prefix_val++; inc = 1; } if (prefix_val >= 5) { int k = 0; while (k < CABAC_MAX_BIN && get_cabac_bypass(&s->HEVClc->cc)) { suffix_val += 1 << k; k++; } if (k == CABAC_MAX_BIN) av_log(s->avctx, AV_LOG_ERROR, "CABAC_MAX_BIN : %d\n", k); while (k--) suffix_val += get_cabac_bypass(&s->HEVClc->cc) << k; } return prefix_val + suffix_val; }
1threat
Can you create objects with length 0 in R? : <p>Is it possible to create objects in R with length 0?</p>
0debug
Unable to trace the error for a function any help as in where i have gone wrong? : I am having trouble in debugging the error in this code, and not understanding where exactly i am going wrong? Can you please help? #include <iostream> using namespace std; class man { int age; int height; int weight; public: int data(void); void initialize(int,int,int); }; int man::data(void) { return (age*height)/weight; }; void man::initialize(initial_age,initial_height,initial_weight) { age = initial_age; height = initial_height; weight = initial_weight; }; int main() { man tim,crook; tim.initialize(19,178,55); crook.initialize(28,171,71); cout << "THE DATA IS AS SHOWN FOR tim" << tim.initialize(19,178,55) << endl; cout <<"THE DATA IS AS SHOWN FOR crook" << crook.initialialize(28,171,69) << endl; }
0debug
How to extract words from the string in python? : <p>I have strings of the form </p> <pre><code> sent="Software Development = 1831". </code></pre> <p>I want to extract only words from the string i.e. "Software Development". How I can extract this in Python. </p>
0debug
def median_trapezium(base1,base2,height): median = 0.5 * (base1+ base2) return median
0debug
PHP print JSON specific value : <p>In my code I want to print a specific value i.e. <code>ticket</code> from JSON data but when I do it I got <code>Notice: Trying to get property of non-object</code> error every time I don't know what I am doing wrong in it</p> <p>Here is my JSON array dump</p> <pre><code>array(3) { ["status"]=&gt; int(200) ["msg"]=&gt; string(2) "OK" ["result"]=&gt; array(6) { ["ticket"]=&gt; string(79) "w-_xdRcVDJQ~55de39b726745a28~1505246565~def~FzuGpPpNoQEus6lK~1~Dhyp8PJM83-pMwAe" ["captcha_url"]=&gt; string(50) "https://myurl.com/images/FzuGpPpNoQEus6lK.png" ["captcha_w"]=&gt; int(160) ["captcha_h"]=&gt; int(70) ["wait_time"]=&gt; int(0) ["valid_until"]=&gt; string(19) "2017-09-12 20:17:46" } } </code></pre> <p>Here is my PHP Code</p> <pre><code>$response = file_get_contents($url); $obj = json_decode($response, TRUE); $printjson = $obj-&gt;result-&gt;ticket; echo $printjson; </code></pre>
0debug
How to create array from string in javascript : <p>I have a string like below</p> <pre><code> Ontario;Northwest Territories;Nunavut;Prince Edward Island </code></pre> <p>from this string I need to create an array of string like</p> <pre><code> territoty:Array&lt;string&gt; = [Ontario,Northwest Territories,Nunavut,Prince Edward Island] </code></pre> <p>in javascript.</p> <p>How can I create the array from the string?</p>
0debug
What are the industry standard breakpoints in Responsive Design based on the most popular devices TODAY 2016? : <p>What are the most popular breakpoints used in responsive design today? My interest is mainly mobile > tablet > desktop.</p> <p>No opinions solicited, just hoping for concrete answers</p>
0debug
Visual studio/GIT : No tracked remote branch : <p>I just configured Visual Studio 2015 with a connection to GitHub. Unfortunately, it doesn't work to track the remote branch. I have 2 projects in the same solution, each has its own repository. For each of them, - I only have one branch (Master) - I checked that the remote branch was set correctly (Push and fetch have the same value). I eventually reset the branches - In Synchronization, only "Fetch" is not greyed out. Clicking on it doesn't synchronize. Under "Incoming Commit" is written "The current branch does not track a remote branch". - When working with Git GUI, it works fine, I can easily fetch and push.</p> <p>Please ask if you need more information.</p> <p>Thanks</p> <p>Niko</p>
0debug
convert how to Convert textbox to integer c# : <p>I'v problem how to Convert textbox to float c#</p> <p>I have in my textbox.text example</p> <p>8.1.1</p> <p>I did this cod but error</p> <p>//</p> <pre><code> int a ; a = val (model.Text); // if (a &gt;= 6) { } </code></pre> <p>Convert textbox to float</p> <p>some one pleas help me</p>
0debug
how to get the largest sum of indexes in array that have a negative numbers in java : <p>hy , i'm a beginner java student and we were asked to take the sequence of indexes with the largest sum , the array have negative and positive numbers and may contain 0 our job is to get the largest sum of indexes that are in a row and it can be one index , with method not with algorithm because we haven't learned that yet thank you for your help </p>
0debug
SQLite provider in VS2017 : <p>I want to connect sqlite using EF6 in VS2017. I installed "System.Data.SQLite" nuget package. I also installed "sqlite-netFx46-setup-bundle-x86-2015-1.0.104.0.exe" from <a href="http://system.data.sqlite.org" rel="noreferrer">http://system.data.sqlite.org</a>, but I cannot see the sqlite provider when adding ADO.NET data entity.</p> <p>Am I missing something? or the above package not supporting VS2017 (it said it is for VS2015)</p>
0debug
def find_substring(str1, sub_str): if any(sub_str in s for s in str1): return True return False
0debug
I can't ever get Regex Right : <p>I have a query string I'm trying to remove a query string parameter. What I currently have is</p> <p><code>date=(.*)&amp;</code></p> <p>But this will remove anything to the last &amp;. I only want to remove to the first occurance of the &amp;.</p> <p>So this is how it should work:</p> <p><code>date=5%2F13%2F16&amp;tab=1&amp;a=b</code> = <code>tab=1&amp;a=b</code></p> <p>But mine is doing this:</p> <p><code>date=5%2F13%2F16&amp;tab=1&amp;a=b</code> = <code>a=b</code></p> <p>I think I probably need something around the &amp; but I read the regex stuff and I just get more confused.</p>
0debug
static void exynos4210_gic_init(Object *obj) { DeviceState *dev = DEVICE(obj); Exynos4210GicState *s = EXYNOS4210_GIC(obj); SysBusDevice *sbd = SYS_BUS_DEVICE(obj); uint32_t i; const char cpu_prefix[] = "exynos4210-gic-alias_cpu"; const char dist_prefix[] = "exynos4210-gic-alias_dist"; char cpu_alias_name[sizeof(cpu_prefix) + 3]; char dist_alias_name[sizeof(cpu_prefix) + 3]; SysBusDevice *busdev; s->gic = qdev_create(NULL, "arm_gic"); qdev_prop_set_uint32(s->gic, "num-cpu", s->num_cpu); qdev_prop_set_uint32(s->gic, "num-irq", EXYNOS4210_GIC_NIRQ); qdev_init_nofail(s->gic); busdev = SYS_BUS_DEVICE(s->gic); sysbus_pass_irq(sbd, busdev); qdev_init_gpio_in(dev, exynos4210_gic_set_irq, EXYNOS4210_GIC_NIRQ - 32); memory_region_init(&s->cpu_container, obj, "exynos4210-cpu-container", EXYNOS4210_EXT_GIC_CPU_REGION_SIZE); memory_region_init(&s->dist_container, obj, "exynos4210-dist-container", EXYNOS4210_EXT_GIC_DIST_REGION_SIZE); for (i = 0; i < s->num_cpu; i++) { sprintf(cpu_alias_name, "%s%x", cpu_prefix, i); memory_region_init_alias(&s->cpu_alias[i], obj, cpu_alias_name, sysbus_mmio_get_region(busdev, 1), 0, EXYNOS4210_GIC_CPU_REGION_SIZE); memory_region_add_subregion(&s->cpu_container, EXYNOS4210_EXT_GIC_CPU_GET_OFFSET(i), &s->cpu_alias[i]); sprintf(dist_alias_name, "%s%x", dist_prefix, i); memory_region_init_alias(&s->dist_alias[i], obj, dist_alias_name, sysbus_mmio_get_region(busdev, 0), 0, EXYNOS4210_GIC_DIST_REGION_SIZE); memory_region_add_subregion(&s->dist_container, EXYNOS4210_EXT_GIC_DIST_GET_OFFSET(i), &s->dist_alias[i]); } sysbus_init_mmio(sbd, &s->cpu_container); sysbus_init_mmio(sbd, &s->dist_container); }
1threat
static void channel_weighting(float *su1, float *su2, int *p3) { int band, nsample; float w[2][2]; if (p3[1] != 7 || p3[3] != 7) { get_channel_weights(p3[1], p3[0], w[0]); get_channel_weights(p3[3], p3[2], w[1]); for (band = 1; band < 4; band++) { for (nsample = 0; nsample < 8; nsample++) { su1[band * 256 + nsample] *= INTERPOLATE(w[0][0], w[0][1], nsample); su2[band * 256 + nsample] *= INTERPOLATE(w[1][0], w[1][1], nsample); } for(; nsample < 256; nsample++) { su1[band * 256 + nsample] *= w[1][0]; su2[band * 256 + nsample] *= w[1][1]; } } } }
1threat
Group by and find top n value_counts pandas : <p>I have a dataframe of taxi data with two columns that looks like this:</p> <pre><code>Neighborhood Borough Time Midtown Manhattan X Melrose Bronx Y Grant City Staten Island Z Midtown Manhattan A Lincoln Square Manhattan B </code></pre> <p>Basically, each row represents a taxi pickup in that neighborhood in that borough. Now, I want to find the top 5 neighborhoods in each borough with the most number of pickups. I tried this:</p> <pre><code>df['Neighborhood'].groupby(df['Borough']).value_counts() </code></pre> <p>Which gives me something like this:</p> <pre><code>borough Bronx High Bridge 3424 Mott Haven 2515 Concourse Village 1443 Port Morris 1153 Melrose 492 North Riverdale 463 Eastchester 434 Concourse 395 Fordham 252 Wakefield 214 Kingsbridge 212 Mount Hope 200 Parkchester 191 ...... Staten Island Castleton Corners 4 Dongan Hills 4 Eltingville 4 Graniteville 4 Great Kills 4 Castleton 3 Woodrow 1 </code></pre> <p>How do I filter it so that I get only the top 5 from each? I know there are a few questions with a similar title but they weren't helpful to my case.</p>
0debug
int float64_le( float64 a, float64 b STATUS_PARAM ) { flag aSign, bSign; if ( ( ( extractFloat64Exp( a ) == 0x7FF ) && extractFloat64Frac( a ) ) || ( ( extractFloat64Exp( b ) == 0x7FF ) && extractFloat64Frac( b ) ) ) { float_raise( float_flag_invalid STATUS_VAR); return 0; } aSign = extractFloat64Sign( a ); bSign = extractFloat64Sign( b ); if ( aSign != bSign ) return aSign || ( (bits64) ( ( a | b )<<1 ) == 0 ); return ( a == b ) || ( aSign ^ ( a < b ) ); }
1threat
void *checkasm_check_func(void *func, const char *name, ...) { char name_buf[256]; void *ref = func; CheckasmFuncVersion *v; int name_length; va_list arg; va_start(arg, name); name_length = vsnprintf(name_buf, sizeof(name_buf), name, arg); va_end(arg); if (!func || name_length <= 0 || name_length >= sizeof(name_buf)) return NULL; state.current_func = get_func(name_buf, name_length); v = &state.current_func->versions; if (v->func) { CheckasmFuncVersion *prev; do { if (v->func == func) return NULL; if (v->ok) ref = v->func; prev = v; } while ((v = v->next)); v = prev->next = checkasm_malloc(sizeof(CheckasmFuncVersion)); } v->func = func; v->ok = 1; v->cpu = state.cpu_flag; state.current_func_ver = v; if (state.cpu_flag) state.num_checked++; return ref; }
1threat
Java homework- what's wrong with my code? : Here's the question: A string contains several X's followed by several O's. Devise a divide-and-conquer algorithm that finds the number of X's in the string in log2n steps, where n is the length of the string. And here's my code: public static int count(String str){ int min = 0; int max = str.length() - 1; while(min < max){ if(str.charAt(min) == 'X') min += (max - min) / 2; else max = min + (max - min) / 2; } return min; } It seems to work most of the time but there are a few cases where it gives unexpected output. For example, when I put give it the string "XXXXOOOO" it should return 4, but it returns 5 instead. Why?
0debug
document.getElementById('input').innerHTML = user_input;
1threat
how can i fetch json array from php code and display it in textview? using webclient : i am using xamarin.android at visual studio 2015 with c# language also i am using Mysql as a server and used `webclient` for connecting xamarin.android to Mysql this is my php code : ` $sql = "SELECT * FROM DoctorMaster WHERE DoctorId = '1'"; $result = $conn->query($sql);} i am pasting 2 images. [php code][1] [1]: http://i.stack.imgur.com/oZpbK.png and my Activity code is ` mClient = new WebClient(); mUrl = new Uri("http://www.olympicfitness.us/home.php"); //Call the PHP file mClient.DownloadDataAsync(mUrl); mClient.DownloadDataCompleted += MClient_DownloadDataCompleted; } private void MClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) { string json = Encoding.UTF8.GetString(e.Result); mtextviwe3 = JsonConvert.DeserializeObject<TextView>(json); }` i am working on android and connected to server using webclient .i just want to know that my php code passes a list of array which i want to display array on textview .i have used "DeserializeObject()" but it give me an error "Newtonsoft.Json.JsonSerializationException: Unable to find a constructor to use for type Android.Widget.TextView. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path '0', line 1, position 5." so my que is if i cant use "DeserializeObject()" for displaying it on textview den what function should i use and also i want to know that if i cant use textview den what can i use to display jsoon array. please guys help me.
0debug
Identify first n characters of regex pattern : I'm trying to mask all the occurences of **AccountNumber** in my XML response code. The AccountNumber has 16 digits and I want to mask first 12 digits and retain last four. XML response: <ns2:PaymentMethod> <CCInfo xmlns=""> <AccountType>sdaj</AccountType> <AccountNumber>1234567890123456</AccountNumber> <AccountName>sdfsad</AccountName> <ExpirationMonth>sdaf</ExpirationMonth> <ExpirationYear>afgds</ExpirationYear> </CCInfo> </ns2:PaymentMethod> <ns2:PaymentMethod> <CCInfo xmlns=""> <AccountType>kyfkuk</AccountType> <AccountNumber>098765432123987</AccountNumber> <AccountName>hjvkv</AccountName> <ExpirationMonth>gfdgh</ExpirationMonth> <ExpirationYear>tdjk</ExpirationYear> </CCInfo> </ns2:PaymentMethod> Below is my java code: String accountNumberPatternString ="<AccountNumber>(^.{12})"; Pattern accountNumberPattern = Pattern.compile(accountNumberPatternString); Matcher matcher = accountNumberPattern.matcher(data); String maskedResult = matcher.replaceAll("<AccountNumber>*******"); I'm expecting the result as: <AccountNumber>************3456</AccountNumber> but I'm getting the result as: <AccountNumber>1234567890123456</AccountNumber>
0debug
Aligning title, subtitle and caption for horizontal ggplot barchart : <p>I would like to left align the <code>plot.title</code>, <code>plot.subtitle</code> and <code>plot.caption</code> in a horizontal ggplot2 barchart.</p> <p><em>Example:</em></p> <pre><code>library("ggplot2") # ggplot2 2.2 df &lt;- data.frame(type=factor(c("Brooklyn", "Manhatten and\n Queens")), value=c(15,30)) # manual hjust for title, subtitle &amp; caption myhjust &lt;- -0.2 ggplot(df, aes(x=type, y=value)) + geom_bar(stat='identity') + coord_flip() + labs( title = "This is a nice title", subtitle = "A subtitle", caption = "We even have a caption. A very long one indeed.") + theme(axis.title=element_blank(), plot.title=element_text(hjust = myhjust), plot.subtitle=element_text(hjust = myhjust ), plot.caption=element_text(hjust = myhjust)) </code></pre> <p>How can I align all 3 <code>labs</code> elements (<code>plot.title</code>, <code>plot.subtitle</code> and <code>plot.caption</code>) to where the <code>axis.text</code> starts (red vertical line, "M" of Manhatten)?</p> <p>Besides: Why does a fixed <code>myhjust</code> result in 3 different horizontal positions for <code>plot.title</code>, <code>plot.subtitle</code> and <code>plot.caption</code>?</p> <p><a href="https://i.stack.imgur.com/Jphoe.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Jphoe.jpg" alt="Problem"></a></p>
0debug
static int aac_encode_frame(AVCodecContext *avctx, uint8_t *frame, int buf_size, void *data) { AACEncContext *s = avctx->priv_data; int16_t *samples = s->samples, *samples2, *la; ChannelElement *cpe; int i, j, chans, tag, start_ch; const uint8_t *chan_map = aac_chan_configs[avctx->channels-1]; int chan_el_counter[4]; FFPsyWindowInfo windows[avctx->channels]; if (s->last_frame) return 0; if (data) { if (!s->psypp) { memcpy(s->samples + 1024 * avctx->channels, data, 1024 * avctx->channels * sizeof(s->samples[0])); } else { start_ch = 0; samples2 = s->samples + 1024 * avctx->channels; for (i = 0; i < chan_map[0]; i++) { tag = chan_map[i+1]; chans = tag == TYPE_CPE ? 2 : 1; ff_psy_preprocess(s->psypp, (uint16_t*)data + start_ch, samples2 + start_ch, start_ch, chans); start_ch += chans; } } } if (!avctx->frame_number) { memcpy(s->samples, s->samples + 1024 * avctx->channels, 1024 * avctx->channels * sizeof(s->samples[0])); return 0; } start_ch = 0; for (i = 0; i < chan_map[0]; i++) { FFPsyWindowInfo* wi = windows + start_ch; tag = chan_map[i+1]; chans = tag == TYPE_CPE ? 2 : 1; cpe = &s->cpe[i]; samples2 = samples + start_ch; la = samples2 + 1024 * avctx->channels + start_ch; if (!data) la = NULL; for (j = 0; j < chans; j++) { IndividualChannelStream *ics = &cpe->ch[j].ics; int k; wi[j] = ff_psy_suggest_window(&s->psy, samples2, la, start_ch + j, ics->window_sequence[0]); ics->window_sequence[1] = ics->window_sequence[0]; ics->window_sequence[0] = wi[j].window_type[0]; ics->use_kb_window[1] = ics->use_kb_window[0]; ics->use_kb_window[0] = wi[j].window_shape; ics->num_windows = wi[j].num_windows; ics->swb_sizes = s->psy.bands [ics->num_windows == 8]; ics->num_swb = s->psy.num_bands[ics->num_windows == 8]; for (k = 0; k < ics->num_windows; k++) ics->group_len[k] = wi[j].grouping[k]; s->cur_channel = start_ch + j; apply_window_and_mdct(avctx, s, &cpe->ch[j], samples2, j); } start_ch += chans; } init_put_bits(&s->pb, frame, buf_size*8); if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & CODEC_FLAG_BITEXACT)) put_bitstream_info(avctx, s, LIBAVCODEC_IDENT); start_ch = 0; memset(chan_el_counter, 0, sizeof(chan_el_counter)); for (i = 0; i < chan_map[0]; i++) { FFPsyWindowInfo* wi = windows + start_ch; tag = chan_map[i+1]; chans = tag == TYPE_CPE ? 2 : 1; cpe = &s->cpe[i]; for (j = 0; j < chans; j++) { s->coder->search_for_quantizers(avctx, s, &cpe->ch[j], s->lambda); } cpe->common_window = 0; if (chans > 1 && wi[0].window_type[0] == wi[1].window_type[0] && wi[0].window_shape == wi[1].window_shape) { cpe->common_window = 1; for (j = 0; j < wi[0].num_windows; j++) { if (wi[0].grouping[j] != wi[1].grouping[j]) { cpe->common_window = 0; break; } } } if (cpe->common_window && s->coder->search_for_ms) s->coder->search_for_ms(s, cpe, s->lambda); adjust_frame_information(s, cpe, chans); put_bits(&s->pb, 3, tag); put_bits(&s->pb, 4, chan_el_counter[tag]++); if (chans == 2) { put_bits(&s->pb, 1, cpe->common_window); if (cpe->common_window) { put_ics_info(s, &cpe->ch[0].ics); encode_ms_info(&s->pb, cpe); } } for (j = 0; j < chans; j++) { s->cur_channel = start_ch + j; ff_psy_set_band_info(&s->psy, s->cur_channel, cpe->ch[j].coeffs, &wi[j]); encode_individual_channel(avctx, s, &cpe->ch[j], cpe->common_window); } start_ch += chans; } put_bits(&s->pb, 3, TYPE_END); flush_put_bits(&s->pb); avctx->frame_bits = put_bits_count(&s->pb); if (!(avctx->flags & CODEC_FLAG_QSCALE)) { float ratio = avctx->bit_rate * 1024.0f / avctx->sample_rate / avctx->frame_bits; s->lambda *= ratio; s->lambda = fminf(s->lambda, 65536.f); } if (avctx->frame_bits > 6144*avctx->channels) av_log(avctx, AV_LOG_ERROR, "input buffer violation %d > %d.\n", avctx->frame_bits, 6144*avctx->channels); if (!data) s->last_frame = 1; memcpy(s->samples, s->samples + 1024 * avctx->channels, 1024 * avctx->channels * sizeof(s->samples[0])); return put_bits_count(&s->pb)>>3; }
1threat
How to use RETURNING for query.update() with sqlalchemy : <p>I want to specify the return values for a specific update in sqlalchemy.</p> <p>The documentation of the underlying <a href="http://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.update" rel="noreferrer">update statement</a> (sqlalchemy.sql.expression.update) says it accepts a "returning" argument and the docs for the <a href="http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query" rel="noreferrer">query object</a> state that query.update() accepts a dictionary "update_args" which will be passed as the arguments to the query statement.</p> <p>Therefore my code looks like this:</p> <pre><code>session.query( ItemClass ).update( {ItemClass.value: value_a}, synchronize_session='fetch', update_args={ 'returning': (ItemClass.id,) } ) </code></pre> <p>However, this does not seem to work. It just returns the regular integer.</p> <p>My question is now: Am I doing something wrong or is this simply not possible with a query object and I need to manually construct statements or write raw sql?</p>
0debug
int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags) { PerThreadContext *p = avctx->internal->thread_ctx; int err; f->owner = avctx; if (!(avctx->active_thread_type & FF_THREAD_FRAME)) return ff_get_buffer(avctx, f->f, flags); if (atomic_load(&p->state) != STATE_SETTING_UP && (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) { av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n"); return -1; } if (avctx->internal->allocate_progress) { atomic_int *progress; f->progress = av_buffer_alloc(2 * sizeof(*progress)); if (!f->progress) { return AVERROR(ENOMEM); } progress = (atomic_int*)f->progress->data; atomic_store(&progress[0], -1); atomic_store(&progress[1], -1); } pthread_mutex_lock(&p->parent->buffer_mutex); if (avctx->thread_safe_callbacks || avctx->get_buffer2 == avcodec_default_get_buffer2) { err = ff_get_buffer(avctx, f->f, flags); } else { p->requested_frame = f->f; p->requested_flags = flags; atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release); pthread_mutex_lock(&p->progress_mutex); pthread_cond_signal(&p->progress_cond); while (atomic_load(&p->state) != STATE_SETTING_UP) pthread_cond_wait(&p->progress_cond, &p->progress_mutex); err = p->result; pthread_mutex_unlock(&p->progress_mutex); } if (!avctx->thread_safe_callbacks && !avctx->codec->update_thread_context) ff_thread_finish_setup(avctx); if (err) av_buffer_unref(&f->progress); pthread_mutex_unlock(&p->parent->buffer_mutex); return err; }
1threat