problem
stringlengths
26
131k
labels
class label
2 classes
JavaScript Intl.DateTimeFormat.format vs Date.toLocaleString : <p>I would like to print a string representing a Date, using a specific timezone, locale, and display options.</p> <p>Which one of these should I use?</p> <ol> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/format" rel="noreferrer">Intl.DateTimeFormat.prototype.format</a></li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString" rel="noreferrer">Date.prototype.toLocaleString()</a></li> </ol> <p>It seems like they return identical results.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const event = new Date(1521065710000); const options = { day: 'numeric', month: 'long', weekday: 'short', hour: 'numeric', minute: 'numeric', timeZoneName: 'short', timeZone: 'America/Los_Angeles', }; console.log(event.toLocaleString('en-US', options)); // "Wed, March 14, 3:15 PM PDT" console.log(new Intl.DateTimeFormat('en-US', options).format(event)); // "Wed, March 14, 3:15 PM PDT"</code></pre> </div> </div> </p>
0debug
static int tap_set_sndbuf(TAPState *s, const char *sndbuf_str) { int sndbuf = TAP_DEFAULT_SNDBUF; if (sndbuf_str) { sndbuf = atoi(sndbuf_str); } if (!sndbuf) { sndbuf = INT_MAX; } if (ioctl(s->fd, TUNSETSNDBUF, &sndbuf) == -1 && sndbuf_str) { qemu_error("TUNSETSNDBUF ioctl failed: %s\n", strerror(errno)); return -1; } return 0; }
1threat
How to put log file in user home directory in portable way in logback? : <p>I would like to put log file into user home directory.</p> <p>How to do that in portable way, i.e. working on Windows, Linux and Mac?</p>
0debug
Can anyone tell the difference between Ubuntu server and lamp stack or server : I know that Ubuntu server is is for server and lamp is software for server which stands for Linux Apache MySQL php....my doubt is to host a site ..is it required to install lamp on Ubuntu server.or does Ubuntu server has all the features of lamp...?
0debug
Anroid Studion 3.4.2 error when compiling : [I am getting errors on the lines compiling message_text][1] [1]: https://i.stack.imgur.com/zVP7j.png
0debug
static int wav_read_packet(AVFormatContext *s, AVPacket *pkt) { int ret, size; int64_t left; AVStream *st; WAVDemuxContext *wav = s->priv_data; if (CONFIG_SPDIF_DEMUXER && wav->spdif == 0 && s->streams[0]->codec->codec_tag == 1) { enum AVCodecID codec; ret = ff_spdif_probe(s->pb->buffer, s->pb->buf_end - s->pb->buffer, &codec); if (ret > AVPROBE_SCORE_EXTENSION) { s->streams[0]->codec->codec_id = codec; wav->spdif = 1; } else { wav->spdif = -1; } } if (CONFIG_SPDIF_DEMUXER && wav->spdif == 1) return ff_spdif_read_packet(s, pkt); if (wav->smv_data_ofs > 0) { int64_t audio_dts, video_dts; smv_retry: audio_dts = s->streams[0]->cur_dts; video_dts = s->streams[1]->cur_dts; if (audio_dts != AV_NOPTS_VALUE && video_dts != AV_NOPTS_VALUE) { wav->smv_last_stream = wav->smv_given_first ? av_compare_ts(video_dts, s->streams[1]->time_base, audio_dts, s->streams[0]->time_base) > 0 : 0; wav->smv_given_first = 1; } wav->smv_last_stream = !wav->smv_last_stream; wav->smv_last_stream |= wav->audio_eof; wav->smv_last_stream &= !wav->smv_eof; if (wav->smv_last_stream) { uint64_t old_pos = avio_tell(s->pb); uint64_t new_pos = wav->smv_data_ofs + wav->smv_block * wav->smv_block_size; if (avio_seek(s->pb, new_pos, SEEK_SET) < 0) { ret = AVERROR_EOF; goto smv_out; } size = avio_rl24(s->pb); ret = av_get_packet(s->pb, pkt, size); if (ret < 0) goto smv_out; pkt->pos -= 3; pkt->pts = wav->smv_block * wav->smv_frames_per_jpeg + wav->smv_cur_pt; wav->smv_cur_pt++; if (wav->smv_frames_per_jpeg > 0) wav->smv_cur_pt %= wav->smv_frames_per_jpeg; if (!wav->smv_cur_pt) wav->smv_block++; pkt->stream_index = 1; smv_out: avio_seek(s->pb, old_pos, SEEK_SET); if (ret == AVERROR_EOF) { wav->smv_eof = 1; goto smv_retry; } return ret; } } st = s->streams[0]; left = wav->data_end - avio_tell(s->pb); if (wav->ignore_length) left = INT_MAX; if (left <= 0) { if (CONFIG_W64_DEMUXER && wav->w64) left = find_guid(s->pb, ff_w64_guid_data) - 24; else left = find_tag(s->pb, MKTAG('d', 'a', 't', 'a')); if (left < 0) { wav->audio_eof = 1; if (wav->smv_data_ofs > 0 && !wav->smv_eof) goto smv_retry; return AVERROR_EOF; } wav->data_end = avio_tell(s->pb) + left; } size = MAX_SIZE; if (st->codec->block_align > 1) { if (size < st->codec->block_align) size = st->codec->block_align; size = (size / st->codec->block_align) * st->codec->block_align; } size = FFMIN(size, left); ret = av_get_packet(s->pb, pkt, size); if (ret < 0) return ret; pkt->stream_index = 0; return ret; }
1threat
i am trying to insert some data in database using this code : i'm using this code to insert image into databse but some error keep popping plz help me out <?php if(isset($_POST ['insert_post'])) { $product_title=$_POST['product_title']; $product_cat=$_POST['product_cat']; $product_brand=$_POST['product_brand']; $product_price=$_POST['product_price']; $product_desc=$_POST['product_desc']; $product_keyword=$_POST['product_keyword']; $product_img=$_FILES['product_image']['name']; $product_img_tmp=$_FILES['product_image']['tmp_name']; } echo $insert_product="insert into products (product_cat,product_brand,product_title,product_price,product_desc,product_imag e,product_keyword) values ('$product_cat','$product_brand','$product_title','$product_price','$product_desc','$product_img','$product_keyword')"; ?>
0debug
write a java method insertNode which takes two integers int a and int b : Two given classes: public class Node { int data; Node next; Node(int d, Node n){ data = d; next = n; } } public class List{ Node header; } write a java method insertNode which takes two integers int a( which is the data of the new node we want to insert) and int b(which is the data of the node that we need to insert a new node before) for the list mylist... Kindly guide me how to solve this
0debug
static int sdl_init_out (HWVoiceOut *hw, audsettings_t *as) { SDLVoiceOut *sdl = (SDLVoiceOut *) hw; SDLAudioState *s = &glob_sdl; SDL_AudioSpec req, obt; int shift; int endianess; int err; audfmt_e effective_fmt; audsettings_t obt_as; shift <<= as->nchannels == 2; req.freq = as->freq; req.format = aud_to_sdlfmt (as->fmt, &shift); req.channels = as->nchannels; req.samples = conf.nb_samples; req.callback = sdl_callback; req.userdata = sdl; if (sdl_open (&req, &obt)) { return -1; } err = sdl_to_audfmt (obt.format, &effective_fmt, &endianess); if (err) { sdl_close (s); return -1; } obt_as.freq = obt.freq; obt_as.nchannels = obt.channels; obt_as.fmt = effective_fmt; obt_as.endianness = endianess; audio_pcm_init_info (&hw->info, &obt_as); hw->samples = obt.samples; s->initialized = 1; s->exit = 0; SDL_PauseAudio (0); return 0; }
1threat
I am completely lost on how to start, let alone accomplish a coding project for school : <p>So, my java class is having this thing called stem challenge Wednesday, and my group decided to tackle the problem of misinformation. We wanted to create a program that will scan an inputted document and cross reference it on online databases, like the library of congress, or wikipedia, or something like that. The only problem is that we have no clue how to use any IDEs or which IDE will allow us to accomplish what we want to do, let alone implement an AI into the program. </p> <p>I come here seeking advice on what to use and a basic how to start, because after that it's a matter of googling around, which I'm fairly good at lol. </p> <p>I've tried using Netbeans, Repl.it, and Eclipse, and once I know what I need to do, it'll be easier to learn how to use these, but I don't know if they are good for what I want to accomplish, or if they even allow for me to do so.</p>
0debug
ROUND Function - Round up to nearest whole number : <p>I want to be able to round up a number to the nearest whole - for example, 4.1 would round to 5, 4 would stay as 4.</p> <p>5.6 would round to 6, 5.01 would round to 6.00. any whole numbers would not round but stay the same.</p>
0debug
Windows Mobile Device center stops working after Windows 10 1703 upgrade : <p>i just installed new Windows 10 version (1703) and now i'm not able to connect any Windows CE device because Windows Mobile Device center 6.1 doesn't run. <a href="https://i.stack.imgur.com/1TRsz.png" rel="noreferrer"></a> I tried to reinstall it but there is no way, the install process stops. Do i have to downgrade to a previous version of Windows? Is there a workaround for this situation?</p> <p>Thanks for your advices regards</p>
0debug
db.execute('SELECT * FROM products WHERE product_id = ' + product_input)
1threat
I wanted to ask about how to prevent audio, video and image files from appearing on other websites and running it only on my own site : <p>I will simply explain I don't want audio, video, and images to work only on my site Whoever has this experience I hope to benefit us</p>
0debug
modify array with specific condition (JS) : Have an array with objects. Look like this: [{id:2},{id:3},{id:4},{id:9},{id:10},{id:11},] in result I want this: [{id:2,id:4},{id:9,id:11}] Have no idea how to delete middle values, and how to separate it when we don't have ids:5,6,7,8
0debug
Android - Refresh An Activity , but it should not clear previous selection areas : This is code of MainActivity languages = (Spinner) findViewById(R.id.spin_lang); languages.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) { // TODO Auto-generated method stub if (pos==1){ Toast.makeText(getApplicationContext(), "You Selected :" +languages.getSelectedItem().toString(),Toast.LENGTH_SHORT).show(); setLocale("en"); } else if(pos ==2){ Toast.makeText(getApplicationContext(), "You Selected :" +languages.getSelectedItem().toString(),Toast.LENGTH_SHORT).show(); setLocale("de"); } } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); the method created for change language. public void setLocale(String lang){ mylocal = new Locale(lang); Locale.setDefault(mylocal); Resources res = getResources(); Configuration conf = res.getConfiguration(); conf.locale = mylocal; DisplayMetrics dm = res.getDisplayMetrics(); res.updateConfiguration(conf, dm); }
0debug
Microservices: REST vs Messaging : <p>I heard Amazon uses HTTP for its microservice based architecture. An alternative is to use a messaging system like RabbitMQ or Solace systems. I personally have experience with Solace based microservice architecture, but never with REST. <br> Any idea what do various big league implementations like Amazon, Netflix, UK Gov etc use?<br> Other aspect is, in microservices, following things are required (besides others):<br> * Pattern matching<br> * Async messaging.. receiving system may be down<br> * Publish subscribe<br> * Cache load event.. i.e. on start up, a service may need to load all data from a couple of other services, and should be notified when data is completely loaded, so that it can 'know' that it is now ready to service requests <br> These aspects are naturally done with messaging rather than REST. Why should anyone use REST (except for public API). Thanks.</p>
0debug
how to wrap a binary operator using modern C++ instead of macros : <p>I saw a macro wrapper for binary operator on <a href="http://craftinginterpreters.com/a-virtual-machine.html" rel="nofollow noreferrer">this site</a> like this:</p> <pre><code>#define BINARY_OP(op) \ do { \ double b = pop(); \ double a = pop(); \ push(a op b); \ } while (false) </code></pre> <p>and it's used like this:</p> <pre><code>switch(op){ case OP_ADD: BINARY_OP(+); break; case OP_SUBTRACT: BINARY_OP(-); break; case OP_MULTIPLY: BINARY_OP(*); break; case OP_DIVIDE: BINARY_OP(/); break; // other ops... } </code></pre> <p>but can I use a modern C++ way to implement such a wrapper instead of a macro?</p>
0debug
Is there a way to log in to discord using a python script? : <p>My goal is to be able to loging to Discord using a script and then be able to send messages to channels. I need it to communicate with a music bot automatically but if I write a bot for discord other bot's will ignore it so thats not an option. Does anyone know how to do it?</p> <p>Thanks!</p>
0debug
What are best resources to understand concurrency in golang? : <p>I am new to go? Can someone specify resources for understanding concurrency using go? </p>
0debug
how to remove ads url / ads search url from search engine : <p>I am facing one issue on chrome search engine. Whenever I searched something it shows ads urls why? Please check below the image. Can I add an ad blocker extension? </p> <p><a href="https://i.stack.imgur.com/pnwBv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pnwBv.png" alt="enter image description here"></a></p>
0debug
IIS Rewrite rule - ignore for localhost : <p>I have the following rule which is working well for redirecting my www requests to the root.</p> <p>However I can't seem to turn it off for localhost. Here is what I have now:</p> <pre><code> &lt;rule name="CanonicalHostNameRule1"&gt; &lt;match url="(.*)" /&gt; &lt;conditions&gt; &lt;add input="{HTTP_HOST}" pattern="^example\.com$" negate="true" /&gt; &lt;/conditions&gt; &lt;action type="Redirect" url="https://example.com/{R:1}" /&gt; &lt;/rule&gt; </code></pre> <p>I've tried many things including things like:</p> <pre><code> &lt;rule name="CanonicalHostNameRule1"&gt; &lt;match url="(.*)" /&gt; &lt;conditions&gt; &lt;add input="{HTTP_HOST}" pattern="^localhost$" negate="true" /&gt; &lt;add input="{HTTP_HOST}" pattern="^example\.com$" negate="true" /&gt; &lt;/conditions&gt; &lt;action type="Redirect" url="https://example.com/{R:1}" /&gt; &lt;/rule&gt; </code></pre> <p>Could you help? Regexes are my weakness alas</p>
0debug
ReadLineState *readline_init(Monitor *mon, ReadLineCompletionFunc *completion_finder) { ReadLineState *rs = g_malloc0(sizeof(*rs)); rs->hist_entry = -1; rs->mon = mon; rs->completion_finder = completion_finder; return rs; }
1threat
Should I prevent from using position relative and absolute? : <p>I have a friend that deals with web a pretty much time, and he is saying that the standard is almost not using absolute/relative position, especially when you doing responsive design.</p> <p>I am totally beginner, and until now I use for positioning position:absolute or relative. is he right? How do you build a website usually?</p> <p>Thank for response.</p>
0debug
static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){ AVIContext *avi = s->priv_data; AVIOContext *pb = s->pb; int longs_pre_entry= avio_rl16(pb); int index_sub_type = avio_r8(pb); int index_type = avio_r8(pb); int entries_in_use = avio_rl32(pb); int chunk_id = avio_rl32(pb); int64_t base = avio_rl64(pb); int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0'); AVStream *st; AVIStream *ast; int i; int64_t last_pos= -1; int64_t filesize= avio_size(s->pb); av_dlog(s, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n", longs_pre_entry,index_type, entries_in_use, chunk_id, base); if(stream_id >= s->nb_streams || stream_id < 0) return -1; st= s->streams[stream_id]; ast = st->priv_data; if(index_sub_type) return -1; avio_rl32(pb); if(index_type && longs_pre_entry != 2) return -1; if(index_type>1) return -1; if(filesize > 0 && base >= filesize){ av_log(s, AV_LOG_ERROR, "ODML index invalid\n"); if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF) base &= 0xFFFFFFFF; else return -1; } for(i=0; i<entries_in_use; i++){ if(index_type){ int64_t pos= avio_rl32(pb) + base - 8; int len = avio_rl32(pb); int key= len >= 0; len &= 0x7FFFFFFF; av_dlog(s, "pos:%"PRId64", len:%X\n", pos, len); if(pb->eof_reached) return -1; if(last_pos == pos || pos == base - 8) avi->non_interleaved= 1; if(last_pos != pos && (len || !ast->sample_size)) av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0); ast->cum_len += get_duration(ast, len); last_pos= pos; }else{ int64_t offset, pos; int duration; offset = avio_rl64(pb); avio_rl32(pb); duration = avio_rl32(pb); if(pb->eof_reached) return -1; pos = avio_tell(pb); if(avi->odml_depth > MAX_ODML_DEPTH){ av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n"); return -1; } avio_seek(pb, offset+8, SEEK_SET); avi->odml_depth++; read_braindead_odml_indx(s, frame_num); avi->odml_depth--; frame_num += duration; avio_seek(pb, pos, SEEK_SET); } } avi->index_loaded=1; return 0; }
1threat
static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs, int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file) { int64_t total_sectors; int64_t n; int64_t ret, ret2; *file = NULL; total_sectors = bdrv_nb_sectors(bs); if (total_sectors < 0) { return total_sectors; } if (sector_num >= total_sectors) { *pnum = 0; return BDRV_BLOCK_EOF; } if (!nb_sectors) { *pnum = 0; return 0; } n = total_sectors - sector_num; if (n < nb_sectors) { nb_sectors = n; } if (!bs->drv->bdrv_co_get_block_status) { *pnum = nb_sectors; ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED; if (sector_num + nb_sectors == total_sectors) { ret |= BDRV_BLOCK_EOF; } if (bs->drv->protocol_name) { ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE); *file = bs; } return ret; } bdrv_inc_in_flight(bs); ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum, file); if (ret < 0) { *pnum = 0; goto out; } if (ret & BDRV_BLOCK_RAW) { assert(ret & BDRV_BLOCK_OFFSET_VALID && *file); ret = bdrv_co_get_block_status(*file, ret >> BDRV_SECTOR_BITS, *pnum, pnum, file); goto out; } if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) { ret |= BDRV_BLOCK_ALLOCATED; } else { if (bdrv_unallocated_blocks_are_zero(bs)) { ret |= BDRV_BLOCK_ZERO; } else if (bs->backing) { BlockDriverState *bs2 = bs->backing->bs; int64_t nb_sectors2 = bdrv_nb_sectors(bs2); if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) { ret |= BDRV_BLOCK_ZERO; } } } if (*file && *file != bs && (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) && (ret & BDRV_BLOCK_OFFSET_VALID)) { BlockDriverState *file2; int file_pnum; ret2 = bdrv_co_get_block_status(*file, ret >> BDRV_SECTOR_BITS, *pnum, &file_pnum, &file2); if (ret2 >= 0) { if (ret2 & BDRV_BLOCK_EOF && (!file_pnum || ret2 & BDRV_BLOCK_ZERO)) { ret |= BDRV_BLOCK_ZERO; } else { *pnum = file_pnum; ret |= (ret2 & BDRV_BLOCK_ZERO); } } } out: bdrv_dec_in_flight(bs); if (ret >= 0 && sector_num + *pnum == total_sectors) { ret |= BDRV_BLOCK_EOF; } return ret; }
1threat
def is_Monotonic(A): return (all(A[i] <= A[i + 1] for i in range(len(A) - 1)) or all(A[i] >= A[i + 1] for i in range(len(A) - 1)))
0debug
Java - code always throw NullPointerException : <p>This code throws a NullPointerException. </p> <pre><code>protected static Integer cost; public static int incCost(int value) { cost += value; }; </code></pre>
0debug
Android Chat Application using Openfire server and XMPP (SMACK) client : <p>So far, I have learnt that I need a Chat Server(Openfire) and a XMPP client with Smack Libraries to communicate with the server.So,</p> <ol> <li>Installed and configured Openfire.</li> <li>Now for the client part, I am really confused how to get start with.</li> </ol> <p>I need a simple chat application with limited users and few features like file sharing, message sent and seen, users online etc. </p> <p>P.S: Yes, I am new to android and have built few applications, but good at UI.</p>
0debug
JQuery - Is it possible to fire more effects after a callback has been used? : I would like to be able to use a callback in a stack of events, but not at the end. I tried to do it, but it seems the code escapes any effects after the callback has been called. $(this).animate({//animate image top:0 }, aniTime) .delay(1000, function(){ //some code }) .animate({//animate image top:250 }, aniTime) Is there a way to do this or is it not possible/best practise ? Thanks Rog
0debug
How to skip files that have no data in them in folder? : <p>I have a folder, with 1000s of txt files. My code is working perfectly fine if there is data in the file. </p> <p>Is there anyway to build logic in my code to check if the file is empty, and if empty to skip to the next one? </p> <pre><code>import glob import os path = 'path/to/file' for filename in glob.glob(os.path.join(path, '*.txt')): with open(filename, 'r',encoding='ISO-8859-1') as f: print(filename) text = f.read() do other stuff </code></pre>
0debug
static inline void decode(DisasContext *dc, uint32_t ir) { if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP | CPU_LOG_TB_OP_OPT))) { tcg_gen_debug_insn_start(dc->pc); } dc->ir = ir; LOG_DIS("%8.8x\t", dc->ir); if (dc->ir) { dc->nr_nops = 0; } else { LOG_DIS("nr_nops=%d\t", dc->nr_nops); dc->nr_nops++; if (dc->nr_nops > 4) { cpu_abort(dc->env, "fetching nop sequence\n"); } } dc->opcode = EXTRACT_FIELD(ir, 26, 31); dc->imm5 = EXTRACT_FIELD(ir, 0, 4); dc->imm16 = EXTRACT_FIELD(ir, 0, 15); dc->imm26 = EXTRACT_FIELD(ir, 0, 25); dc->csr = EXTRACT_FIELD(ir, 21, 25); dc->r0 = EXTRACT_FIELD(ir, 21, 25); dc->r1 = EXTRACT_FIELD(ir, 16, 20); dc->r2 = EXTRACT_FIELD(ir, 11, 15); if (ir & (1 << 31)) { dc->format = OP_FMT_RR; } else { dc->format = OP_FMT_RI; } assert(ARRAY_SIZE(decinfo) == 64); assert(dc->opcode < 64); decinfo[dc->opcode](dc); }
1threat
How to convert varchar to number : <p>I have character string as '00000625710' I want it as number 6257.10 how can I do that . I tried as follow <code>select to_number('00000002511','999999999.99')from dual;</code></p> <p>But didn't work . can any one help me in this . Thank you.</p>
0debug
Rspec 3.6, Rails 5 error: wrong number of arguments (given 2, expected 1) for `post` request : <p>I just started a new project in Rails 5, (my first, though I have several projects in Rails 4.x.) and am having trouble with controller specs. </p> <pre><code>describe RequestsController, :type =&gt; :controller do it "receives new request" do post :accept_request, my_params end end </code></pre> <p>Returns the error: </p> <pre><code> Failure/Error: post :accept_request, my_params ArgumentError: wrong number of arguments (given 2, expected 1) </code></pre> <p>I understand there has been a shift in the preferred testing strategy for controllers with Rails 5 as noted on <a href="https://everydayrails.com/2016/08/29/replace-rspec-controller-tests.html" rel="noreferrer">Everyday Rails</a>, specifically, shifting controller tests into request specs, but no word on changes to this basic method of controller testing. </p>
0debug
Vector with 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9 with the commands rep() and seq()? : I'm having problem to create the vector `1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9` with the commands `rep()` and `seq()`. Could anyone be able to give me a hint?
0debug
MOOC Week 2, Exercise 36.1 : import java.util.Scanner; public class Pollo { public static void main(String[] args) { Scanner carne = new Scanner(System.in); System.out.println("Type numbers:"); int Numero = Integer.parseInt(carne.nextLine()); while (Numero != -1) { if (Numero == -1) { System.out.println("Thank you and see you later!"); break; } } } } My problem here is that if I type a number (or more), and then type -1, nothing happens. If the first number is -1, then no message is displayed, and the process finishes with exit code 0. What could possibly be wrong?
0debug
static int oss_init_in (HWVoiceIn *hw, struct audsettings *as) { OSSVoiceIn *oss = (OSSVoiceIn *) hw; struct oss_params req, obt; int endianness; int err; int fd; audfmt_e effective_fmt; struct audsettings obt_as; oss->fd = -1; req.fmt = aud_to_ossfmt (as->fmt, as->endianness); req.freq = as->freq; req.nchannels = as->nchannels; req.fragsize = conf.fragsize; req.nfrags = conf.nfrags; if (oss_open (1, &req, &obt, &fd)) { return -1; } err = oss_to_audfmt (obt.fmt, &effective_fmt, &endianness); if (err) { oss_anal_close (&fd); return -1; } obt_as.freq = obt.freq; obt_as.nchannels = obt.nchannels; obt_as.fmt = effective_fmt; obt_as.endianness = endianness; audio_pcm_init_info (&hw->info, &obt_as); oss->nfrags = obt.nfrags; oss->fragsize = obt.fragsize; if (obt.nfrags * obt.fragsize & hw->info.align) { dolog ("warning: Misaligned ADC buffer, size %d, alignment %d\n", obt.nfrags * obt.fragsize, hw->info.align + 1); } hw->samples = (obt.nfrags * obt.fragsize) >> hw->info.shift; oss->pcm_buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift); if (!oss->pcm_buf) { dolog ("Could not allocate ADC buffer (%d samples, each %d bytes)\n", hw->samples, 1 << hw->info.shift); oss_anal_close (&fd); return -1; } oss->fd = fd; return 0; }
1threat
TypeError: search.valueChanges.debounceTime is not a function : <p>I am just learning angular2. At the time of applying something at input changes, I am getting the error.</p> <p>app.ts:</p> <pre><code>export class AppComponent { form: ControlGroup; constructor(fb: FormBuilder) { this.form = fb.group({ search: [] }); var search = this.form.find('search'); search.valueChanges .debounceTime(400) .map(str =&gt; (&lt;string&gt;str).replace(' ','‐')) .subscribe(x =&gt; console.log(x)); }; } </code></pre> <p>Error:</p> <p><a href="https://i.stack.imgur.com/N5Enw.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/N5Enw.jpg" alt="enter image description here"></a></p> <p>How to solve this? Am I missing something?</p> <p><a href="http://plnkr.co/edit/MQIQvFYAvsPv9Pu8xZap?p=preview" rel="noreferrer">Plunker Demo</a></p> <p><strong>N.B.</strong> I cannot produce anything at plunker as I am writing angular2 first time at plunker now. I have written only my app.ts code at plunker. I have showed the screenshot of error from my local pc. I will be grateful too if you tell me the way of running angular2 project at plunker.</p>
0debug
Partialy reload my website Nginx? : I am currently working on the development of a platform and I was wondering how sites like Behance, Artsation and upwork do to partially reload their page. (When you click on a link, the page loads well but the menu does not move just like the footer). I first thought of Nginx but Artsation does not seem to be used Nginx. I would like to know the things to reproduce this kind of loading page if someone could enlighten me on the subject. Thanks
0debug
static int tls_open(URLContext *h, const char *uri, int flags) { TLSContext *c = h->priv_data; int ret; int port; char buf[200], host[200]; int numerichost = 0; struct addrinfo hints = { 0 }, *ai = NULL; const char *proxy_path; int use_proxy; ff_tls_init(); av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0, uri); ff_url_join(buf, sizeof(buf), "tcp", NULL, host, port, NULL); hints.ai_flags = AI_NUMERICHOST; if (!getaddrinfo(host, NULL, &hints, &ai)) { numerichost = 1; freeaddrinfo(ai); } proxy_path = getenv("http_proxy"); use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), host) && proxy_path != NULL && av_strstart(proxy_path, "http: if (use_proxy) { char proxy_host[200], proxy_auth[200], dest[200]; int proxy_port; av_url_split(NULL, 0, proxy_auth, sizeof(proxy_auth), proxy_host, sizeof(proxy_host), &proxy_port, NULL, 0, proxy_path); ff_url_join(dest, sizeof(dest), NULL, NULL, host, port, NULL); ff_url_join(buf, sizeof(buf), "httpproxy", proxy_auth, proxy_host, proxy_port, "/%s", dest); } ret = ffurl_open(&c->tcp, buf, AVIO_FLAG_READ_WRITE, &h->interrupt_callback, NULL); if (ret) goto fail; c->fd = ffurl_get_file_handle(c->tcp); #if CONFIG_GNUTLS gnutls_init(&c->session, GNUTLS_CLIENT); if (!numerichost) gnutls_server_name_set(c->session, GNUTLS_NAME_DNS, host, strlen(host)); gnutls_certificate_allocate_credentials(&c->cred); gnutls_certificate_set_verify_flags(c->cred, 0); gnutls_credentials_set(c->session, GNUTLS_CRD_CERTIFICATE, c->cred); gnutls_transport_set_ptr(c->session, (gnutls_transport_ptr_t) (intptr_t) c->fd); gnutls_priority_set_direct(c->session, "NORMAL", NULL); while (1) { ret = gnutls_handshake(c->session); if (ret == 0) break; if ((ret = do_tls_poll(h, ret)) < 0) goto fail; } #elif CONFIG_OPENSSL c->ctx = SSL_CTX_new(TLSv1_client_method()); if (!c->ctx) { av_log(h, AV_LOG_ERROR, "%s\n", ERR_error_string(ERR_get_error(), NULL)); ret = AVERROR(EIO); goto fail; } c->ssl = SSL_new(c->ctx); if (!c->ssl) { av_log(h, AV_LOG_ERROR, "%s\n", ERR_error_string(ERR_get_error(), NULL)); ret = AVERROR(EIO); goto fail; } SSL_set_fd(c->ssl, c->fd); if (!numerichost) SSL_set_tlsext_host_name(c->ssl, host); while (1) { ret = SSL_connect(c->ssl); if (ret > 0) break; if (ret == 0) { av_log(h, AV_LOG_ERROR, "Unable to negotiate TLS/SSL session\n"); ret = AVERROR(EIO); goto fail; } if ((ret = do_tls_poll(h, ret)) < 0) goto fail; } #endif return 0; fail: TLS_free(c); if (c->tcp) ffurl_close(c->tcp); ff_tls_deinit(); return ret; }
1threat
How to icon them at the same level , help me please : How to icon them at the same level , help me please [view page ][1] [code source][2] [1]: https://i.stack.imgur.com/PoU96.png [2]: https://i.stack.imgur.com/0duVy.png
0debug
Why is my python script crashing on my server? : <p>Hey I currently run a python script on my windows server. After 10-24h the script crashes and I don't know why. Is there an easy opportunity to get to know where its coming from? I thought about using an IDE, but my server is probably to small and its kind of an overkill. Is there an opportunity to write the error in a txt file or so when the code crashes? Thanks for your help!</p>
0debug
static void do_video_out(AVFormatContext *s, AVOutputStream *ost, AVInputStream *ist, AVPicture *in_picture, int *frame_size, AVOutputStream *audio_sync) { int nb_frames, i, ret; AVPicture *final_picture, *formatted_picture; AVPicture picture_format_temp, picture_crop_temp; static uint8_t *video_buffer; uint8_t *buf = NULL, *buf1 = NULL; AVCodecContext *enc, *dec; #define VIDEO_BUFFER_SIZE (1024*1024) enc = &ost->st->codec; dec = &ist->st->codec; nb_frames = 1; *frame_size = 0; if (audio_sync) { double adelta, vdelta, av_delay; adelta = audio_sync->sync_ipts - ((double)audio_sync->sync_opts * s->pts_num / s->pts_den); vdelta = ost->sync_ipts - ((double)ost->sync_opts * s->pts_num / s->pts_den); av_delay = adelta - vdelta; if (av_delay < -AV_DELAY_MAX) nb_frames = 2; else if (av_delay > AV_DELAY_MAX) nb_frames = 0; } else { double vdelta; vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset); if (vdelta < 100 && vdelta > -100 && ost->sync_ipts_offset) { if (vdelta < -AV_DELAY_MAX) nb_frames = 2; else if (vdelta > AV_DELAY_MAX) nb_frames = 0; } else { ost->sync_ipts_offset -= vdelta; if (!ost->sync_ipts_offset) ost->sync_ipts_offset = 0.000001; } } #if defined(AVSYNC_DEBUG) static char *action[] = { "drop frame", "copy frame", "dup frame" }; if (audio_sync) fprintf(stderr, "Input APTS %12.6f, output APTS %12.6f, ", (double) audio_sync->sync_ipts, (double) audio_sync->st->pts.val * s->pts_num / s->pts_den); fprintf(stderr, "Input VPTS %12.6f, output VPTS %12.6f: %s\n", (double) ost->sync_ipts, (double) ost->st->pts.val * s->pts_num / s->pts_den, action[nb_frames]); #endif if (nb_frames <= 0) return; if (!video_buffer) video_buffer = av_malloc(VIDEO_BUFFER_SIZE); if (!video_buffer) return; if (enc->pix_fmt != dec->pix_fmt) { int size; size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height); buf = av_malloc(size); if (!buf) return; formatted_picture = &picture_format_temp; avpicture_fill(formatted_picture, buf, enc->pix_fmt, dec->width, dec->height); if (img_convert(formatted_picture, enc->pix_fmt, in_picture, dec->pix_fmt, dec->width, dec->height) < 0) { fprintf(stderr, "pixel format conversion not handled\n"); goto the_end; } } else { formatted_picture = in_picture; } if (ost->video_resample) { final_picture = &ost->pict_tmp; img_resample(ost->img_resample_ctx, final_picture, formatted_picture); } else if (ost->video_crop) { picture_crop_temp.data[0] = formatted_picture->data[0] + (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand; picture_crop_temp.data[1] = formatted_picture->data[1] + ((ost->topBand >> 1) * formatted_picture->linesize[1]) + (ost->leftBand >> 1); picture_crop_temp.data[2] = formatted_picture->data[2] + ((ost->topBand >> 1) * formatted_picture->linesize[2]) + (ost->leftBand >> 1); picture_crop_temp.linesize[0] = formatted_picture->linesize[0]; picture_crop_temp.linesize[1] = formatted_picture->linesize[1]; picture_crop_temp.linesize[2] = formatted_picture->linesize[2]; final_picture = &picture_crop_temp; } else { final_picture = formatted_picture; } for(i=0;i<nb_frames;i++) { if (s->oformat->flags & AVFMT_RAWPICTURE) { av_write_frame(s, ost->index, (uint8_t *)final_picture, sizeof(AVPicture)); } else { AVFrame big_picture; memset(&big_picture, 0, sizeof(AVFrame)); *(AVPicture*)&big_picture= *final_picture; if (same_quality) { big_picture.quality = ist->st->quality; }else big_picture.quality = ost->st->quality; ret = avcodec_encode_video(enc, video_buffer, VIDEO_BUFFER_SIZE, &big_picture); av_write_frame(s, ost->index, video_buffer, ret); *frame_size = ret; if (ost->logfile && enc->stats_out) { fprintf(ost->logfile, "%s", enc->stats_out); } } ost->frame_number++; } the_end: av_free(buf); av_free(buf1); }
1threat
ADD README.TXT FILE TO ALL COMPRESSIONS WINRAR CMD PROGRAM : Example : @ECHO OFF for /D %%f in ("C:\directory_with_files_you_want_to_compress\ *") do copy "C:\directory_with_readme.txt\readme.txt" "%%f\" cd C:\directory_with_files_you_want_to_compress SET PATH=C:;C:\Program Files (x86)\WinRAR;C:\Windows\system32;C:\Windows;C:\Win dows\System32\Wbem;%PATH% FOR /f "delims=" %%d IN ('DIR /B') DO WinRAR a -m0 -ep -df -v100m -x*.rar "C:\where_you_want_to_save_new_rar_files\%%~nxd.ra r" "%%~fd" EXIT But It don't add readme.txt to rar file.
0debug
Python/Kivy : can i move from one TextBox to another TextBox by press enter button of keyboard : I have two file test.py and test.kv.<br/> I want to move from one TextBox to another TextBox by press enter key.I am new to python and kivy.Anyone can tell me It is possible or not? #test.py from kivy.uix.screenmanager import Screen from kivy.app import App from kivy.lang import Builder from kivy.core.window import Window from kivy.properties import ObjectProperty Window.size = (500, 330) class TestScreen(Screen): popup = ObjectProperty(None) class Test(App): def build(self): self.root = Builder.load_file('test.kv') return self.root if __name__ == '__main__': Test().run() #test.kv #:kivy 1.10.0 TestScreen: GridLayout: cols: 2 padding : 30,30 spacing: 10, 10 row_default_height: '40dp' Label: text: 'Name' TextInput: id: name Label: text: 'Class' TextInput: id: clas Button: text: 'Ok' Button: text: 'Cancel' Can anyone help me?
0debug
How to remove specific substrings from a set of strings in Python? : <p>I have a set of strings <code>set1</code>, and all the strings in <code>set1</code> have a two specific substrings which I don't need and want to remove. <br/> Sample Input: <code>set1={'Apple.good','Orange.good','Pear.bad','Pear.good','Banana.bad','Potato.bad'}</code><br/> So basically I want the <code>.good</code> and <code>.bad</code> substrings removed from all the strings. <br/>What I tried:</p> <pre><code>for x in set1: x.replace('.good','') x.replace('.bad','') </code></pre> <p>But this doesn't seem to work at all. There is absolutely no change in the output and it is the same as the input. I tried using <code>for x in list(set1)</code> instead of the original one but that doesn't change anything. </p>
0debug
static target_ulong h_protect(PowerPCCPU *cpu, sPAPREnvironment *spapr, target_ulong opcode, target_ulong *args) { CPUPPCState *env = &cpu->env; target_ulong flags = args[0]; target_ulong pte_index = args[1]; target_ulong avpn = args[2]; hwaddr hpte; target_ulong v, r, rb; if ((pte_index * HASH_PTE_SIZE_64) & ~env->htab_mask) { return H_PARAMETER; } hpte = pte_index * HASH_PTE_SIZE_64; v = ppc_hash64_load_hpte0(env, hpte); r = ppc_hash64_load_hpte1(env, hpte); if ((v & HPTE64_V_VALID) == 0 || ((flags & H_AVPN) && (v & ~0x7fULL) != avpn)) { return H_NOT_FOUND; } r &= ~(HPTE64_R_PP0 | HPTE64_R_PP | HPTE64_R_N | HPTE64_R_KEY_HI | HPTE64_R_KEY_LO); r |= (flags << 55) & HPTE64_R_PP0; r |= (flags << 48) & HPTE64_R_KEY_HI; r |= flags & (HPTE64_R_PP | HPTE64_R_N | HPTE64_R_KEY_LO); rb = compute_tlbie_rb(v, r, pte_index); ppc_hash64_store_hpte0(env, hpte, (v & ~HPTE64_V_VALID) | HPTE64_V_HPTE_DIRTY); ppc_tlb_invalidate_one(env, rb); ppc_hash64_store_hpte1(env, hpte, r); ppc_hash64_store_hpte0(env, hpte, v | HPTE64_V_HPTE_DIRTY); return H_SUCCESS; }
1threat
static inline uint64_t fload_invalid_op_excp(CPUPPCState *env, int op) { uint64_t ret = 0; int ve; ve = fpscr_ve; switch (op) { case POWERPC_EXCP_FP_VXSNAN: env->fpscr |= 1 << FPSCR_VXSNAN; break; case POWERPC_EXCP_FP_VXSOFT: env->fpscr |= 1 << FPSCR_VXSOFT; break; case POWERPC_EXCP_FP_VXISI: env->fpscr |= 1 << FPSCR_VXISI; goto update_arith; case POWERPC_EXCP_FP_VXIDI: env->fpscr |= 1 << FPSCR_VXIDI; goto update_arith; case POWERPC_EXCP_FP_VXZDZ: env->fpscr |= 1 << FPSCR_VXZDZ; goto update_arith; case POWERPC_EXCP_FP_VXIMZ: env->fpscr |= 1 << FPSCR_VXIMZ; goto update_arith; case POWERPC_EXCP_FP_VXVC: env->fpscr |= 1 << FPSCR_VXVC; env->fpscr &= ~(0xF << FPSCR_FPCC); env->fpscr |= 0x11 << FPSCR_FPCC; if (ve != 0) { env->exception_index = POWERPC_EXCP_PROGRAM; env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_VXVC; env->fpscr |= 1 << FPSCR_FEX; ve = 0; } break; case POWERPC_EXCP_FP_VXSQRT: env->fpscr |= 1 << FPSCR_VXSQRT; update_arith: env->fpscr &= ~((1 << FPSCR_FR) | (1 << FPSCR_FI)); if (ve == 0) { ret = 0x7FF8000000000000ULL; env->fpscr &= ~(0xF << FPSCR_FPCC); env->fpscr |= 0x11 << FPSCR_FPCC; } break; case POWERPC_EXCP_FP_VXCVI: env->fpscr |= 1 << FPSCR_VXCVI; env->fpscr &= ~((1 << FPSCR_FR) | (1 << FPSCR_FI)); if (ve == 0) { ret = 0x7FF8000000000000ULL; env->fpscr &= ~(0xF << FPSCR_FPCC); env->fpscr |= 0x11 << FPSCR_FPCC; } break; } env->fpscr |= 1 << FPSCR_VX; env->fpscr |= 1 << FPSCR_FX; if (ve != 0) { env->fpscr |= 1 << FPSCR_FEX; if (msr_fe0 != 0 || msr_fe1 != 0) { helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM, POWERPC_EXCP_FP | op); } } return ret; }
1threat
Can we integrate JSF 2.0 + Spring 4.2.X + Spring Security 4.2.X : <p>I would like to know can we integrate Spring security 4.2.X with JSF 2.0. I am facing issue with JSP pring security tags for role wise access. If yes please suggest.</p>
0debug
static void gen_mfsri(DisasContext *ctx) { #if defined(CONFIG_USER_ONLY) gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC); #else int ra = rA(ctx->opcode); int rd = rD(ctx->opcode); TCGv t0; if (unlikely(ctx->pr)) { gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC); return; } t0 = tcg_temp_new(); gen_addr_reg_index(ctx, t0); tcg_gen_shri_tl(t0, t0, 28); tcg_gen_andi_tl(t0, t0, 0xF); gen_helper_load_sr(cpu_gpr[rd], cpu_env, t0); tcg_temp_free(t0); if (ra != 0 && ra != rd) tcg_gen_mov_tl(cpu_gpr[ra], cpu_gpr[rd]); #endif }
1threat
Can I somehow build webassembly code *without* the emscripten "glue"? : <p>Can I somehow create a wasm file, that will work on its own as described <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance/exports" rel="noreferrer">in MDN here</a> (by instatiating the objects and calling functions on them)?</p> <p>All the guides I can find (<a href="https://developer.mozilla.org/en-US/docs/WebAssembly/C_to_wasm" rel="noreferrer">such as this one on MDN</a>) recommend using emscripten; that will, however, also include ~70kB "glue code" (with ~50 kB optional filesystem emulation), that has additional logic (like detection node/browser environment and automatic fetching etc), and probably some other emulation.</p> <p>What if I don't want that "glue code" and want to just create WASM directly (probably from C code, but maybe something else)? Is that possible right now?</p>
0debug
Gensim word2vec in python3 missing vocab : <p>I'm using gensim implementation of Word2Vec. I have the following code snippet:</p> <pre><code>print('training model') model = Word2Vec(Sentences(start, end)) print('trained model:', model) print('vocab:', model.vocab.keys()) </code></pre> <p>When I run this in python2, it runs as expected. The final print is all the words in the vocabulary.</p> <p>However, if I run it in python3, I get an error:</p> <pre><code>trained model: Word2Vec(vocab=102, size=100, alpha=0.025) Traceback (most recent call last): File "learn.py", line 58, in &lt;module&gt; train(to_datetime('-4h'), to_datetime('now'), 'model.out') File "learn.py", line 23, in train print('vocab:', model.vocab.keys()) AttributeError: 'Word2Vec' object has no attribute 'vocab' </code></pre> <p>What is going on? Is gensim word2vec not compatible with python3?</p>
0debug
Dockerfile and dpkg command : <p>I'm trying to create a Dockerfile to install VuFind.</p> <p>This is my Dockerfile:</p> <pre><code>#Name of container: docker-vufind:3 # Pull base image FROM ubuntu:16.04 MAINTAINER xxx "xxx@mail.com" #Install latest patches RUN apt-get update &amp;&amp; apt-get install -y \ &amp;&amp; apt-get install -y wget #Obtain the package RUN wget http://downloads.sourceforge.net/vufind/vufind_3.1.1.deb?use_mirror=osdn -O vufind_3.1.1.deb #Install it RUN dpkg -i vufind_3.1.1.deb #Install VuFind's dependecies RUN apt-get install -y -f </code></pre> <p>I launched these commands on my Ubuntu's bash and the software worked fine, but it seems that I can't obtain the same result with the Dockerfile because the dpkg command failed for the lack of the dependencies.</p> <pre><code>The command '/bin/sh -c dpkg -i vufind_3.1.1.deb' returned a non-zero code: 1 </code></pre> <p>Is installing the dependecies (Apache, jdk, php...) before the dpkg command line the only way to create a working Dockerfile or is there a shorter way ?</p>
0debug
static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOVAtom atom) { AVStream *st = c->fc->streams[c->fc->nb_streams-1]; if((uint64_t)atom.size > (1<<30)) return -1; av_free(st->codec->extradata); st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE); if (!st->codec->extradata) return AVERROR(ENOMEM); st->codec->extradata_size = 0x5a + atom.size; memcpy(st->codec->extradata, "SVQ3", 4); get_buffer(pb, st->codec->extradata + 0x5a, atom.size); dprintf(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a); return 0; }
1threat
Why does Go panic on writing to a closed channel? : <p>Why does Go panic on writing to a closed channel?</p> <p>While one can use the <code>value, ok := &lt;-channel</code> idiom for reading from channels, and thus the ok result can be tested for hitting a closed channel:</p> <pre><code>// reading from closed channel package main import "fmt" func main() { ch := make(chan int, 1) ch &lt;- 2 close(ch) read(ch) read(ch) read(ch) } func read(ch &lt;-chan int) { i,ok := &lt;- ch if !ok { fmt.Printf("channel is closed\n") return } fmt.Printf("read %d from channel\n", i) } </code></pre> <p>Output:</p> <pre><code>read 2 from channel channel is closed channel is closed </code></pre> <p>Run "reading from closed channel" on <a href="http://play.golang.org/p/oJoLGeRI4S" rel="noreferrer">Playground</a></p> <p>Writing to a possibly closed channel is more convoluted, because Go will panic if you simply try to write when the channel is closed:</p> <pre><code>//writing to closed channel package main import ( "fmt" ) func main() { output := make(chan int, 1) // create channel write(output, 2) close(output) // close channel write(output, 3) write(output, 4) } // how to write on possibly closed channel func write(out chan int, i int) (err error) { defer func() { // recover from panic caused by writing to a closed channel if r := recover(); r != nil { err = fmt.Errorf("%v", r) fmt.Printf("write: error writing %d on channel: %v\n", i, err) return } fmt.Printf("write: wrote %d on channel\n", i) }() out &lt;- i // write on possibly closed channel return err } </code></pre> <p>Output:</p> <pre><code>write: wrote 2 on channel write: error writing 3 on channel: send on closed channel write: error writing 4 on channel: send on closed channel </code></pre> <p>Run "writing to closed channel" on <a href="http://play.golang.org/p/qL7z3SVeqX" rel="noreferrer">Playground</a></p> <p>As far as I know, there is not a simpler idiom for writing into a possibly closed channel without panicking. Why not? What is the reasoning behind such an asymmetric behavior between read and write?</p>
0debug
Determine if a list composed of anagram elements in Java 8 : <p>I want to determine if a list is anagram or not using Java 8.</p> <p>Example input:</p> <pre><code>"cat", "cta", "act", "atc", "tac", "tca" </code></pre> <p>I have written the following function that does the job but I am wondering if there is a better and elegant way to do this.</p> <pre><code>boolean isAnagram(String[] list) { long count = Stream.of(list) .map(String::toCharArray) .map(arr -&gt; { Arrays.sort(arr); return arr; }) .map(String::valueOf) .distinct() .count(); return count == 1; } </code></pre> <p>It seems I can't sort char array with <code>Stream.sorted()</code> method so that's why I used a second map operator. If there is some way that I can operate directly on char stream instead of Stream of char array, that would also help.</p>
0debug
How to create own database in redis? : <pre><code>There are 0 to 15 databases in redis. </code></pre> <p>I want to create my own database using redis-cli. Is there any command for it?</p>
0debug
A Python Program that picks something from a list : <p>Sorry If there is already a question of this but I didn't find it. So is there function that picks something from a list but with percents like we have a list with a soda, a soup and a water bottle so the program must pick one of these but the chance it would pick the soup is 2% for the soda is 30% and for the water bottle is 68%?</p>
0debug
static int foreach_device_config(int type, int (*func)(const char *cmdline)) { struct device_config *conf; int rc; TAILQ_FOREACH(conf, &device_configs, next) { if (conf->type != type) continue; rc = func(conf->cmdline); if (0 != rc) return rc; } return 0; }
1threat
how remove error while using variable "la" in scatter chart? : \\GPS coordinates obtain @Override public void onLocationChanged(Location location) { location.getLatitude(); location.getLongitude(); location.getAltitude(); location.getAccuracy(); double la,lo,al,aq; location.setLatitude(la= location.getLatitude()); location.setLatitude(lo=location.getLongitude()); location.setLatitude(al=location.getAltitude()); location.setLatitude(aq = location.getAccuracy()); textView.append("\n"+la); \\plotting "la" value in scatter chart ScatterChart scatterChart =(ScatterChart) findViewById(R.id.chart); List<ChartData> values = new ArrayList<>(); float longi = (float) la; values.add(new ChartData(4f, 6f)); values.add(new ChartData(10f, 10f)); scatterChart.setData(values); scatterChart.setGesture(true); scatterChart.setDescription("Location");
0debug
Change array elements to objects with key, value : <p>Can anyone tell me how to change this array in javaScript to the following one with objects having the same key 'name' ?</p> <pre><code>const myArray = ['mark', 'david', 'monica']; </code></pre> <p>Desired Output:</p> <pre><code>const myArray = [{name: 'mark'}, {name: 'david'}, {name: 'monica'}]; </code></pre>
0debug
void HELPER(access_check_cp_reg)(CPUARMState *env, void *rip, uint32_t syndrome) { const ARMCPRegInfo *ri = rip; int target_el; if (arm_feature(env, ARM_FEATURE_XSCALE) && ri->cp < 14 && extract32(env->cp15.c15_cpar, ri->cp, 1) == 0) { raise_exception(env, EXCP_UDEF, syndrome, exception_target_el(env)); } if (!ri->accessfn) { return; } switch (ri->accessfn(env, ri)) { case CP_ACCESS_OK: return; case CP_ACCESS_TRAP: target_el = exception_target_el(env); break; case CP_ACCESS_TRAP_EL2: assert(!arm_is_secure(env) && !arm_current_el(env) == 3); target_el = 2; break; case CP_ACCESS_TRAP_EL3: target_el = 3; break; case CP_ACCESS_TRAP_UNCATEGORIZED: target_el = exception_target_el(env); syndrome = syn_uncategorized(); break; default: g_assert_not_reached(); } raise_exception(env, EXCP_UDEF, syndrome, target_el); }
1threat
static int process_line(URLContext *h, char *line, int line_count, int *new_location) { HTTPContext *s = h->priv_data; char *tag, *p, *end; if (line[0] == '\0') return 0; p = line; if (line_count == 0) { while (!isspace(*p) && *p != '\0') p++; while (isspace(*p)) p++; s->http_code = strtol(p, &end, 10); av_dlog(NULL, "http_code=%d\n", s->http_code); if (s->http_code >= 400 && s->http_code < 600 && s->http_code != 401) { end += strspn(end, SPACE_CHARS); av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", s->http_code, end); return -1; } } else { while (*p != '\0' && *p != ':') p++; if (*p != ':') return 1; *p = '\0'; tag = line; p++; while (isspace(*p)) p++; if (!av_strcasecmp(tag, "Location")) { strcpy(s->location, p); *new_location = 1; } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) { s->filesize = atoll(p); } else if (!av_strcasecmp (tag, "Content-Range")) { const char *slash; if (!strncmp (p, "bytes ", 6)) { p += 6; s->off = atoll(p); if ((slash = strchr(p, '/')) && strlen(slash) > 0) s->filesize = atoll(slash+1); } h->is_streamed = 0; } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5)) { h->is_streamed = 0; } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) { s->filesize = -1; s->chunksize = 0; } else if (!av_strcasecmp (tag, "WWW-Authenticate")) { ff_http_auth_handle_header(&s->auth_state, tag, p); } else if (!av_strcasecmp (tag, "Authentication-Info")) { ff_http_auth_handle_header(&s->auth_state, tag, p); } else if (!av_strcasecmp (tag, "Connection")) { if (!strcmp(p, "close")) s->willclose = 1; } } return 1; }
1threat
Execute command on host during docker build : <p>Is it possible to create <code>Dockerfile</code> that executes a command on host when image is being build?</p> <p><strong>Now I'm doing:</strong></p> <pre><code>./script_that_creates_magic_file.sh docker build . </code></pre> <p>with Dockerfile:</p> <pre><code>FROM alpine COPY magic_file </code></pre> <p><strong>I want to be able to do:</strong></p> <pre><code>docker build . </code></pre> <p>with Dockerfile:</p> <pre><code>FROM alpine # invoke script_that_creates_magic_file.sh on the host COPY magic_file </code></pre> <p>Of course, this script is in the same directory as Dockerfile.</p>
0debug
static void tcg_reg_alloc_start(TCGContext *s) { int i; TCGTemp *ts; for(i = 0; i < s->nb_globals; i++) { ts = &s->temps[i]; if (ts->fixed_reg) { ts->val_type = TEMP_VAL_REG; } else { ts->val_type = TEMP_VAL_MEM; } } for(i = s->nb_globals; i < s->nb_temps; i++) { ts = &s->temps[i]; ts->val_type = TEMP_VAL_DEAD; ts->mem_allocated = 0; ts->fixed_reg = 0; } for(i = 0; i < TCG_TARGET_NB_REGS; i++) { s->reg_to_temp[i] = -1; } }
1threat
static void fill_mbaff_ref_list(H264Context *h){ int list, i, j; for(list=0; list<2; list++){ for(i=0; i<h->ref_count[list]; i++){ Picture *frame = &h->ref_list[list][i]; Picture *field = &h->ref_list[list][16+2*i]; field[0] = *frame; for(j=0; j<3; j++) field[0].linesize[j] <<= 1; field[1] = field[0]; for(j=0; j<3; j++) field[1].data[j] += frame->linesize[j]; h->luma_weight[list][16+2*i] = h->luma_weight[list][16+2*i+1] = h->luma_weight[list][i]; h->luma_offset[list][16+2*i] = h->luma_offset[list][16+2*i+1] = h->luma_offset[list][i]; for(j=0; j<2; j++){ h->chroma_weight[list][16+2*i][j] = h->chroma_weight[list][16+2*i+1][j] = h->chroma_weight[list][i][j]; h->chroma_offset[list][16+2*i][j] = h->chroma_offset[list][16+2*i+1][j] = h->chroma_offset[list][i][j]; } } } for(j=0; j<h->ref_count[1]; j++){ for(i=0; i<h->ref_count[0]; i++) h->implicit_weight[j][16+2*i] = h->implicit_weight[j][16+2*i+1] = h->implicit_weight[j][i]; memcpy(h->implicit_weight[16+2*j], h->implicit_weight[j], sizeof(*h->implicit_weight)); memcpy(h->implicit_weight[16+2*j+1], h->implicit_weight[j], sizeof(*h->implicit_weight)); } }
1threat
Calling of subclass methods in heritance : <p>I have a class Customer which inherits by class RichPerson and class PoorPerson..it is store in ArrayList cus... however , some of subclass methods are different and i'm unable to call the subclass methods when accessing Customer array list.. like cus.get(0).description.. </p>
0debug
Is it possible to give AWT applications sharp taskbar icons in Windows 10 : <p>I'm trying to set the icon of a Java AWT application so it renders in native resolution on the Windows 10 taskbar (including when desktop scaling is set above 100%). It seems that by default, if an executable embeds an icon containing multiple sizes, Windows seems to pick a size larger than the actual size of taskbar icons and downsize it (at 100% scale it resizes the 32 pixel icon to 24, <em>even if a 24 pixel icon is supplied</em>, and similarly for other scales.)</p> <p>I've solved this problem for C++ MFC applications by loading just the correctly sized icon as a resource and sending a WM_SETICON message to the window, which results in a nice sharp icon on the taskbar and alt-tab dialog.</p> <pre><code>smallIcon = (HICON)LoadImage( myInstance, MAKEINTRESOURCE(smallIconRes), IMAGE_ICON, smallIconSize, smallIconSize, LR_DEFAULTCOLOR ); SendMessage(hWnd, WM_SETICON, ICON_SMALL, (LPARAM)smallIcon); bigIcon = (HICON)LoadImage( myInstance, MAKEINTRESOURCE(bigIconRes), IMAGE_ICON, bigIconSize, bigIconSize, LR_DEFAULTCOLOR ); SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM)bigIcon); </code></pre> <p>That approach doesn't seem to work for Java applications - a WM_SETICON message with wParam set to ICON_SMALL works fine, but the equivalent with ICON_BIG is ignored.</p> <p>If I try to use Java's API to set the icon, by doing this</p> <pre><code> List&lt;Image&gt; icons = new ArrayList&lt;Image&gt;(); icons.add(windowIcons.getIcon(20)); // small icons are 20x20 pixels icons.add(windowIcons.getIcon(30)); // large are 30x30 at 125% scale setIconImages(icons); </code></pre> <p>the correct icon is used but it appears blurry, as if something has resized it to the "expected" size and then resized it back. Left here is how it appears, right is the contents of the icon file.</p> <p><a href="https://i.stack.imgur.com/45pv2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/45pv2.png" alt="Java application&#39;s icon vs. how it should look"></a></p> <p>So, my question is: what can I do in this Java application to make Windows render the icon I give it on the taskbar without scaling it and blurring the details?</p>
0debug
What is the most performant way for dynamic styling in React-Native? : <p> In React-Native, you can use <a href="https://facebook.github.io/react-native/docs/stylesheet" rel="noreferrer">Stylesheet</a> to create css-like stylesheets. The main reason of using <code>styleshee.create</code> in favor of plain js-objects is increased performance. However, you often might want to style components dynamically, often based on their props. I basically found three approaches of doing this:</p> <p><strong><em>Note for the following examples:</strong> Consider <code>const styles ...</code> to be declared outside of the Component, as it's a common pattern and you might want to share styles between different Components. Consider everything below the tree dots as part of the render function.</em></p> <ol> <li><p>Using an array of styles:</p> <pre><code>const styles = StyleSheet.create({viewStyle: {backgroundColor:'red'}}) ... return &lt;View style={[styles.viewStyle, {color: this.props.color}]} /&gt; </code></pre></li> <li><p>Using Stylesheet.flatten:</p> <pre><code>const styles = StyleSheet.create({viewStyle: {backgroundColor:'red'}}) ... const flattenedStyle = StyleSheet.flatten(styles.viewStyle, {{color: this.props.color}}) return &lt;View style={flattenedStyle} /&gt; </code></pre> <p></p></li> <li><p>Using a function to create the stylesheet:</p> <pre><code>const styles = (color) =&gt; StyleSheet.create({ viewStyle: { backgroundColor:'red', color: color } }) ... const style = styles(this.props.color).viewStyle return &lt;View style={style} /&gt; </code></pre></li> </ol> <p>I am wondering which approach is the best regarding to performance, or if there even is another, more performant way? I think Option 2 and 3 are no way to go at all, because dynamically creating new stylesheets on prop-changes undermines the whole purpose of stylesheets. I am happy for any thought or hints on this subject!</p>
0debug
Unable to decode logic of this pattern : <p>I want to print a pattern, when the user input a no. 'N' it will print a pattern like below with all the outer arms of the pattern will contain 'N' '-'. </p> <pre><code> /\ / \ / /\ \ / / \ \ \ \ / / \ \/ / \ / \/ </code></pre> <p>I have tried a lot to decode, but i am unable to decode, i did tried few things. If someone help me or guide me with this logic, it will be great help.</p> <pre><code>int num=4; int input = num*2; String[][] arr = new String[input][input]; for (int i = 0; i &lt; input; i++) { for (int j = 0; j &lt; input; j++) { if (j+1== num - i) { arr[i][j] = "/"; System.out.print(arr[i][j]); } else if (j + 1 == num + i + 1) { arr[i][j] = "\\"; System.out.print(arr[i][j]); } else { arr[i][j] = "-"; System.out.print(arr[i][j]); } } System.out.println(); } </code></pre>
0debug
static void read_sbr_channel_pair_element(AACContext *ac, SpectralBandReplication *sbr, GetBitContext *gb) { if (get_bits1(gb)) skip_bits(gb, 8); if ((sbr->bs_coupling = get_bits1(gb))) { read_sbr_grid(ac, sbr, gb, &sbr->data[0]); copy_sbr_grid(&sbr->data[1], &sbr->data[0]); read_sbr_dtdf(sbr, gb, &sbr->data[0]); read_sbr_dtdf(sbr, gb, &sbr->data[1]); read_sbr_invf(sbr, gb, &sbr->data[0]); memcpy(sbr->data[1].bs_invf_mode[1], sbr->data[1].bs_invf_mode[0], sizeof(sbr->data[1].bs_invf_mode[0])); memcpy(sbr->data[1].bs_invf_mode[0], sbr->data[0].bs_invf_mode[0], sizeof(sbr->data[1].bs_invf_mode[0])); read_sbr_envelope(sbr, gb, &sbr->data[0], 0); read_sbr_noise(sbr, gb, &sbr->data[0], 0); read_sbr_envelope(sbr, gb, &sbr->data[1], 1); read_sbr_noise(sbr, gb, &sbr->data[1], 1); } else { read_sbr_grid(ac, sbr, gb, &sbr->data[0]); read_sbr_grid(ac, sbr, gb, &sbr->data[1]); read_sbr_dtdf(sbr, gb, &sbr->data[0]); read_sbr_dtdf(sbr, gb, &sbr->data[1]); read_sbr_invf(sbr, gb, &sbr->data[0]); read_sbr_invf(sbr, gb, &sbr->data[1]); read_sbr_envelope(sbr, gb, &sbr->data[0], 0); read_sbr_envelope(sbr, gb, &sbr->data[1], 1); read_sbr_noise(sbr, gb, &sbr->data[0], 0); read_sbr_noise(sbr, gb, &sbr->data[1], 1); } if ((sbr->data[0].bs_add_harmonic_flag = get_bits1(gb))) get_bits1_vector(gb, sbr->data[0].bs_add_harmonic, sbr->n[1]); if ((sbr->data[1].bs_add_harmonic_flag = get_bits1(gb))) get_bits1_vector(gb, sbr->data[1].bs_add_harmonic, sbr->n[1]); }
1threat
def average_Even(n) : if (n% 2!= 0) : return ("Invalid Input") return -1 sm = 0 count = 0 while (n>= 2) : count = count+1 sm = sm+n n = n-2 return sm // count
0debug
Force type conversion in python dataclass __init__ method : <p>I have the following very simple dataclass:</p> <pre><code>import dataclasses @dataclasses.dataclass class Test: value: int </code></pre> <p>I create an instance of the class but instead of an integer I use a string:</p> <pre><code>&gt;&gt;&gt; test = Test('1') &gt;&gt;&gt; type(test.value) &lt;class 'str'&gt; </code></pre> <p>What I actually want is a forced conversion to the datatype i defined in the class defintion:</p> <pre><code>&gt;&gt;&gt; test = Test('1') &gt;&gt;&gt; type(test.value) &lt;class 'int'&gt; </code></pre> <p>Do I have to write the <code>__init__</code> method manually or is there a simple way to achieve this?</p>
0debug
When is it appropriate to curry a function, and when is it not? Why? : <p>How could I write a javascript function knowing whether it needs to be curried?</p>
0debug
Change another module state from one module in Vuex : <p>I have two modules in my vuex store.</p> <pre><code>var store = new Vuex.Store({ modules: { loading: loading posts: posts } }); </code></pre> <p>In the module <code>loading</code>, I have a property <code>saving</code> which can be set either <code>true</code> or <code>false</code> and also have a mutation function named <code>TOGGLE_SAVING</code> to set this property.</p> <p>In the module <code>posts</code>, before and after fetching posts, I want to change the property <code>saving</code>. I am doing it by calling <code>commit('TOGGLE_SAVING')</code> from one of the actions in the <code>posts</code> module. </p> <pre><code>var getPosts = function (context) { contex.commit(TOGGLE_LOADING); }; </code></pre> <p>When it tried to commit, I got following error in the console</p> <pre><code>[vuex] unknown local mutation type: TOGGLE_LOADING, global type: posts/TOGGLE_LOADING </code></pre> <p>How can I mutate state in another module using <code>commit</code>?</p>
0debug
static void json_emit_element(QJSON *json, const char *name) { if (json->omit_comma) { json->omit_comma = false; } else { qstring_append(json->str, ", "); } if (name) { qstring_append(json->str, "\""); qstring_append(json->str, name); qstring_append(json->str, "\" : "); } }
1threat
Is WebAPI Body.json async? : `Body.json` [returns a promise][1]. Is this method asynchronous to avoid blocking on reading large inbound data streams? If this is correct, does it do something like `setTimeout(sampleStream, 0)` repeatedly until the end of the stream is found? [1]: https://developer.mozilla.org/en-US/docs/Web/API/Body/json
0debug
int64 float64_to_int64_round_to_zero( float64 a STATUS_PARAM ) { flag aSign; int16 aExp, shiftCount; bits64 aSig; int64 z; aSig = extractFloat64Frac( a ); aExp = extractFloat64Exp( a ); aSign = extractFloat64Sign( a ); if ( aExp ) aSig |= LIT64( 0x0010000000000000 ); shiftCount = aExp - 0x433; if ( 0 <= shiftCount ) { if ( 0x43E <= aExp ) { if ( a != LIT64( 0xC3E0000000000000 ) ) { float_raise( float_flag_invalid STATUS_VAR); if ( ! aSign || ( ( aExp == 0x7FF ) && ( aSig != LIT64( 0x0010000000000000 ) ) ) ) { return LIT64( 0x7FFFFFFFFFFFFFFF ); } } return (sbits64) LIT64( 0x8000000000000000 ); } z = aSig<<shiftCount; } else { if ( aExp < 0x3FE ) { if ( aExp | aSig ) STATUS(float_exception_flags) |= float_flag_inexact; return 0; } z = aSig>>( - shiftCount ); if ( (bits64) ( aSig<<( shiftCount & 63 ) ) ) { STATUS(float_exception_flags) |= float_flag_inexact; } } if ( aSign ) z = - z; return z; }
1threat
Unordered Random Numbers : <p>I have a problem. I'm trying to get 4 random numbers that will not be repeated and not ordered. For example (2,3,4,5) is not good, but (5,2,3,4) is ok. We've implemented an algorithm but something's wrong with it.</p> <pre><code> var needCreate = true; do { var lastIndex = int.MinValue; for (int i = 0; i &lt; 4; i++) { thisIndex = Random.Range(0, 5); UnorderedIndexes.Add(thisIndex); if (thisIndex &lt; lastindex) needCreate = false; lastIndex = thisIndex; } } while (needCreate); foreach (int index in UnorderedIndexes) Debug.Log(index); </code></pre>
0debug
def find_length(string, n): current_sum = 0 max_sum = 0 for i in range(n): current_sum += (1 if string[i] == '0' else -1) if current_sum < 0: current_sum = 0 max_sum = max(current_sum, max_sum) return max_sum if max_sum else 0
0debug
Is it possible to make a facebookfriend by using the Facebook API? : <p>I'm trying to make a workflow go smoother. </p> <p>Already tried to Google it, but I've got nothing to show for it.</p> <p>Can you guys help me?</p>
0debug
Xcode - changing the indentation rules for switch statements : <p>When I write a Swift switch statement it indents the code like this:</p> <pre><code>switch foo { case 1: // stuff happens default: // other stuff happens } </code></pre> <p>I want it to indent like this:</p> <pre><code>switch foo { case 1: // stuff happens default: // other stuff happens } </code></pre> <p>Is there any way to do this? All the questions I can find on the topic either point to plugins (which no longer work in the latest version of Xcode) or discuss which way is "correct" rather than offer a way to change it.</p>
0debug
e1000_mmio_map(PCIDevice *pci_dev, int region_num, uint32_t addr, uint32_t size, int type) { E1000State *d = (E1000State *)pci_dev; DBGOUT(MMIO, "e1000_mmio_map addr=0x%08x 0x%08x\n", addr, size); cpu_register_physical_memory(addr, PNPMMIO_SIZE, d->mmio_index); }
1threat
Foobar - Test cases not passing - Disorderly escape (python) : 0/10 test cases are passing. Here is the challenge description: (to keep formatting nice - i put the description in a paste bin) Link to challenge description: [https://pastebin.com/UQM4Hip9][1] [1]: https://pastebin.com/UQM4Hip9 Here is my trial code - PYTHON - (0/10 test cases passed) from math import factorial from collections import Counter from fractions import gcd def cycle_count(c, n): cc=factorial(n) for a, b in Counter(c).items(): cc//=(a**b)*factorial(b) return cc def cycle_partitions(n, i=1): yield [n] for i in range(i, n//2 + 1): for p in cycle_partitions(n-i, i): yield [i] + p def solution(w, h, s): grid=0 for cpw in cycle_partitions(w): for cph in cycle_partitions(h): m=cycle_count(cpw, w)*cycle_count(cph, h) grid+=m*(s**sum([sum([gcd(i, j) for i in cpw]) for j in cph])) return grid//(factorial(w)*factorial(h)) print(solution(2, 2, 2)) #Outputs 7 This code works in my python compiler on my computer but not on the foobar challenge?? Am I losing accuracy or something? Thank you for any time and help you can provide. If you downvote, can you provide a reason and not be so rude as this is a good question. I don't see anythign wrong with it.
0debug
How to remove title bar in awesome window manager ver >4 : <p>I've recently upgraded my machine, and am now at awesome version 4.x. There is now a titlebar of sorts with close, ontop, floating, maximized, etc... buttons on right. Can I get rid of this? What config would I use to have this be universally turned off?</p>
0debug
Javascript, take inputted string and print all possibilities. : I've been searching for ours all over the web, including here for a way to solve this project I have for homework this week. To answer your question, the professor gave us a book that in no way connects with the homework so my textbook has been all but useless. I am very new to Javascript and don't even know where to begin with this project. Project: "Write a JavaScript function that generates all combinations of an inputted word." Example: "dog" would print: dog dgo god gdo odg ogd I kinda wrote out the steps I need the code to make: 1. Ask user for a string. (i guess using some sort of input box but IDK which to use.) 2. Pass string to a function. 3. Function breaks the string into letters. 4. stores letters in an array. 5. Finds all combinations of stored array letters. 6. prints combinations in inner HTML. Like I said I am very new to JS and so please explain any answers and feel free to ask questions and I'll do my best to answer them quickly.
0debug
How to extract a specific list of files from a folder in Windows? : <p>I have a folder of around 3,000 music files of all the same type (.flac).</p> <p>I made an excel (and .txt) list of around 1,000 files in that folder that I want to move to a different folder.</p> <p>Is there a way to accomplish this without having to manually move each file by referencing the list?</p> <p>Thank you!</p>
0debug
how should I pass the reference of an object to another object of the same class? : I have a three classes A , B and C. I had created an object of class B(say XYZ1) inside A and had instantiated it with some values. How should I create an object of Class B(say XYZ2) inside C and pass the reference of XYZ1 to the newly created object XYZ2. So that XYZ2 also carries the same values as XYZ1? Thank you I hope I have not made the question very confusing. :P
0debug
Grouping i.e. () is not working properly : <pre><code>"&amp; Help is available in the Library, ".match(/(i)/) </code></pre> <p>This should be returning all the matches for "i". Instead it's returning only 2.</p> <p><a href="https://i.stack.imgur.com/gm9SA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gm9SA.png" alt="enter image description here"></a></p> <p>Two questions </p> <ol> <li><p>It should be returning all the matches as that is suggested by mdn </p></li> <li><p>What does index=7 mean in the array(in the picture)</p></li> </ol> <p>For reference, Here is the definition that found on mdn</p> <blockquote> <p>(x)<br> Matches x and remembers the match. These are called capturing groups.</p> <p>For example, /(foo)/ matches and remembers "foo" in "foo bar". </p> <p>The capturing groups are numbered according to the order of left parentheses of capturing groups, starting from 1. The matched substring can be recalled from the resulting array's elements <a href="https://i.stack.imgur.com/gm9SA.png" rel="nofollow noreferrer">1</a>, ..., [n] or from the predefined RegExp object's properties $1, ..., $9.</p> <p>Capturing groups have a performance penalty. If you don't need the matched substring to be recalled, prefer non-capturing parentheses (see below).</p> </blockquote>
0debug
int ff_dirac_golomb_read_16bit(DiracGolombLUT *lut_ctx, const uint8_t *buf, int bytes, uint8_t *_dst, int coeffs) { int i, b, c_idx = 0; int16_t *dst = (int16_t *)_dst; DiracGolombLUT *future[4], *l = &lut_ctx[2*LUT_SIZE + buf[0]]; INIT_RESIDUE(res, 0, 0); #define APPEND_RESIDUE(N, M) \ N |= M >> (N ## _bits); \ N ## _bits += (M ## _bits) for (b = 1; b <= bytes; b++) { future[0] = &lut_ctx[buf[b]]; future[1] = future[0] + 1*LUT_SIZE; future[2] = future[0] + 2*LUT_SIZE; future[3] = future[0] + 3*LUT_SIZE; if ((c_idx + 1) > coeffs) return c_idx; if (res_bits && l->sign) { int32_t coeff = 1; APPEND_RESIDUE(res, l->preamble); for (i = 0; i < (res_bits >> 1) - 1; i++) { coeff <<= 1; coeff |= (res >> (RSIZE_BITS - 2*i - 2)) & 1; } dst[c_idx++] = l->sign * (coeff - 1); res_bits = res = 0; } for (i = 0; i < LUT_BITS; i++) dst[c_idx + i] = l->ready[i]; c_idx += l->ready_num; APPEND_RESIDUE(res, l->leftover); l = future[l->need_s ? 3 : !res_bits ? 2 : res_bits & 1]; } return c_idx; }
1threat
Hi, can someone help me to display some information on joptionpane. : public class SimpleDialogueBox { public static void main(String[] args){ String name = JOptionPane.showInputDialog("Name"); String age = JOptionPane.showInputDialog("age"); String address = JOptionPane.showInputDialog("Address"); String contact = JOptionPane.showInputDialog("Contact Number"); JOptionPane.showMessageDialog(null, "User information is", name ); } } [i will like to have a display like this][1] [1]: https://i.stack.imgur.com/oYi1S.png
0debug
static int nut_read_packet(AVFormatContext *s, AVPacket *pkt) { NUTContext *nut = s->priv_data; StreamContext *stream; ByteIOContext *bc = &s->pb; int size, frame_code, flags, size_mul, size_lsb, stream_id; int key_frame = 0; int frame_type= 0; int64_t pts = 0; const int64_t frame_start= url_ftell(bc); if (url_feof(bc)) return -1; frame_code = get_byte(bc); if(frame_code == 'N'){ uint64_t tmp= frame_code; tmp<<=8 ; tmp |= get_byte(bc); tmp<<=16; tmp |= get_be16(bc); tmp<<=32; tmp |= get_be32(bc); if (tmp == KEYFRAME_STARTCODE) { frame_code = get_byte(bc); frame_type = 2; } else av_log(s, AV_LOG_ERROR, "error in zero bit / startcode %LX\n", tmp); } flags= nut->frame_code[frame_code].flags; size_mul= nut->frame_code[frame_code].size_mul; size_lsb= nut->frame_code[frame_code].size_lsb; stream_id= nut->frame_code[frame_code].stream_id_plus1 - 1; if(flags & FLAG_FRAME_TYPE){ reset(s); if(frame_type==2){ get_packetheader(nut, bc, 8+1, 0); }else{ get_packetheader(nut, bc, 1, 0); frame_type= 1; } } if(stream_id==-1) stream_id= get_v(bc); if(stream_id >= s->nb_streams){ av_log(s, AV_LOG_ERROR, "illegal stream_id\n"); return -1; } stream= &nut->stream[stream_id]; if(flags & FLAG_PRED_KEY_FRAME){ if(flags & FLAG_KEY_FRAME) key_frame= !stream->last_key_frame; else key_frame= stream->last_key_frame; }else{ key_frame= !!(flags & FLAG_KEY_FRAME); } if(flags & FLAG_PTS){ if(flags & FLAG_FULL_PTS){ pts= get_v(bc); }else{ int64_t mask = (1<<stream->msb_timestamp_shift)-1; int64_t delta= stream->last_pts - mask/2; pts= ((get_v(bc) - delta)&mask) + delta; } }else{ pts= stream->last_pts + stream->lru_pts_delta[(flags&12)>>2]; } if(size_mul <= size_lsb){ size= stream->lru_size[size_lsb - size_mul]; }else{ if(flags & FLAG_DATA_SIZE) size= size_mul*get_v(bc) + size_lsb; else size= size_lsb; } av_new_packet(pkt, size); get_buffer(bc, pkt->data, size); pkt->stream_index = stream_id; if (key_frame) pkt->flags |= PKT_FLAG_KEY; pkt->pts = pts * AV_TIME_BASE * stream->rate_den / stream->rate_num; update(nut, stream_id, frame_start, frame_type, frame_code, key_frame, size, pts); return 0; }
1threat
int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue, Error **errp) { int ret = -1; Error *local_err = NULL; BlockDriver *drv; QemuOpts *opts; const char *value; bool read_only; assert(reopen_state != NULL); assert(reopen_state->bs->drv != NULL); drv = reopen_state->bs->drv; opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort); qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err); if (local_err) { error_propagate(errp, local_err); ret = -EINVAL; goto error; } update_flags_from_options(&reopen_state->flags, opts); value = qemu_opt_get(opts, "node-name"); if (value) { qdict_put_str(reopen_state->options, "node-name", value); } value = qemu_opt_get(opts, "driver"); if (value) { qdict_put_str(reopen_state->options, "driver", value); } read_only = !(reopen_state->flags & BDRV_O_RDWR); ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err); if (local_err) { error_propagate(errp, local_err); goto error; } bdrv_reopen_perm(queue, reopen_state->bs, &reopen_state->perm, &reopen_state->shared_perm); ret = bdrv_flush(reopen_state->bs); if (ret) { error_setg_errno(errp, -ret, "Error flushing drive"); goto error; } if (drv->bdrv_reopen_prepare) { ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err); if (ret) { if (local_err != NULL) { error_propagate(errp, local_err); } else { error_setg(errp, "failed while preparing to reopen image '%s'", reopen_state->bs->filename); } goto error; } } else { error_setg(errp, "Block format '%s' used by node '%s' " "does not support reopening files", drv->format_name, bdrv_get_device_or_node_name(reopen_state->bs)); ret = -1; goto error; } if (qdict_size(reopen_state->options)) { const QDictEntry *entry = qdict_first(reopen_state->options); do { QString *new_obj = qobject_to_qstring(entry->value); const char *new = qstring_get_str(new_obj); const char *old = qdict_get_try_str(reopen_state->bs->options, entry->key); if (!old || strcmp(new, old)) { error_setg(errp, "Cannot change the option '%s'", entry->key); ret = -EINVAL; goto error; } } while ((entry = qdict_next(reopen_state->options, entry))); } ret = bdrv_check_perm(reopen_state->bs, queue, reopen_state->perm, reopen_state->shared_perm, NULL, errp); if (ret < 0) { goto error; } ret = 0; error: qemu_opts_del(opts); return ret; }
1threat
How to add a gap in a line html : <p>I am in HTML, and I'm making a header for my website. I have a website title, followed by some links to various pages. By default, they are right next to each other, and I want them to be apart. I've tried the simple option of just adding multiple spaces, but it puts it as just 1 space.</p>
0debug
How to structure Firestore database in chat app? : <p>The simplest way of storing chat messages is probably this:</p> <pre><code>message: -message1 { "user1" "user2" "message" "date" } -message2 -message3 </code></pre> <p>When the app grows in size (a lot of messages), and operations on database are done with <code>.whereEqualTo</code> are there any disadvantages of structuring chat app messages this way? Like with database iterating through all messages ?</p> <p>Because if there are problems with this approach, i've seen for example this way of structuring database, that would segregate messages in different chat rooms</p> <pre><code>chats: { -chat1 { "lastMessage" "timestamp" "users": {user1, user2} } -chat2 -chat3 } messages: { -chat1 { "message" "date" } } </code></pre> <p>But in this example, adding new message would require user to make 2 write operations, one writing new message and one updating <code>chat</code> document with new <code>lastMessage</code> and <code>timestamp</code> client-side, or creating a cloud function to update <code>chat</code> document with new values, when new message is added. </p> <p>So, is the first option valid, or should I go with something like the second example?</p>
0debug
Why does the site add code to my index at run-time : <p>I have a problem with my website. The problem is that the site adds code to my index file when running it.</p> <p>This is the code in my index file:</p> <pre><code>for(i = 0; i &lt; game.length; i++){ $('.games').append('&lt;div class="slide304"&gt;&lt;div class="center"&gt;&lt;div id="gameTicker'+ i +'"&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div'); } </code></pre> <p>But at runtime the code becomes this:</p> <pre><code>for(i = 0; i &lt; game.length; i++){ $('.games').append('&lt;div class="slide304"&gt;&lt;div class="center"&gt;&lt;div id="gameTicker'+ i +'"&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div');&gt; + h + ":" + m; </code></pre> <p>As you can see it adds <code>&gt; + h + ":" + m;</code> at the end of that jquery. This is a problem because now my site can't run due to syntax error <strong>"unexpected token >"</strong></p> <p>Does anyone know why it adds code at the end of that code and how to prevent it? </p>
0debug
How to pass props to keyframes in styled-component with react? : <p>I have following code and I want to pass value of <code>y</code> from react component to <code>moveVertically</code> keyframe. Is it possible to do so ?</p> <pre><code>import React from 'react'; import styled, {keyframes} from 'styled-components'; const moveVertically = keyframes` 0% { transform : translateY(0px) } 100% { transform : translateY(-1000px) //I need y here } `; //I can access y in here via props but can't send it above const BallAnimation = styled.g` animation : ${moveVertically} ${props =&gt; props.time}s linear `; export default function CannonBall(props) { const cannonBallStyle = { fill: '#777', stroke: '#444', strokeWidth: '2px', }; return ( &lt;BallAnimation time = {4} y = {-1000}&gt; &lt;circle cx = {0} cy = {0} r="25" style = {cannonBallStyle}/&gt; &lt;/BallAnimation&gt; ); } </code></pre>
0debug
static void colo_compare_complete(UserCreatable *uc, Error **errp) { CompareState *s = COLO_COMPARE(uc); Chardev *chr; char thread_name[64]; static int compare_id; if (!s->pri_indev || !s->sec_indev || !s->outdev) { error_setg(errp, "colo compare needs 'primary_in' ," "'secondary_in','outdev' property set"); return; } else if (!strcmp(s->pri_indev, s->outdev) || !strcmp(s->sec_indev, s->outdev) || !strcmp(s->pri_indev, s->sec_indev)) { error_setg(errp, "'indev' and 'outdev' could not be same " "for compare module"); return; } if (find_and_check_chardev(&chr, s->pri_indev, errp) || !qemu_chr_fe_init(&s->chr_pri_in, chr, errp)) { return; } if (find_and_check_chardev(&chr, s->sec_indev, errp) || !qemu_chr_fe_init(&s->chr_sec_in, chr, errp)) { return; } if (find_and_check_chardev(&chr, s->outdev, errp) || !qemu_chr_fe_init(&s->chr_out, chr, errp)) { return; } net_socket_rs_init(&s->pri_rs, compare_pri_rs_finalize, s->vnet_hdr); net_socket_rs_init(&s->sec_rs, compare_sec_rs_finalize, s->vnet_hdr); g_queue_init(&s->conn_list); s->connection_track_table = g_hash_table_new_full(connection_key_hash, connection_key_equal, g_free, connection_destroy); sprintf(thread_name, "colo-compare %d", compare_id); qemu_thread_create(&s->thread, thread_name, colo_compare_thread, s, QEMU_THREAD_JOINABLE); compare_id++; return; }
1threat
Seperating text files : Im trying to read a text file called myfile.txt and copy lines 2,4,6 into a text file called even.txt and copy lines 1,3,5 into odd.txt.im new to progrmming and this is probably vry wrong.Any help woould be appriciated. int main() { FILE *fp; FILE *feven; FILE *fodd; int lines = 0; fp = fopen("myfile.txt","r"); if (fp ==NULL) { printf("Cannot open file.\n"); exit(1); } feven = fopen("even.txt","w"); if (feven ==NULL) { printf("Cannot open file.\n"); exit(1); } fodd = fopen("odd.txt","w"); if (fodd ==NULL) { printf("Cannot open file.\n"); exit(1); } while (fscanf(fp, "%s") != EOF) { lines ++; if (lines%2=0) {fprintf(feven,"%s \n");} else {fprintf(fodd,"%s \n",);} } } //end while }//end program
0debug
SwsContext *sws_getContext(int srcW, int srcH, enum PixelFormat srcFormat, int dstW, int dstH, enum PixelFormat dstFormat, int flags, SwsFilter *srcFilter, SwsFilter *dstFilter, const double *param) { SwsContext *c; int i; int usesVFilter, usesHFilter; int unscaled; int srcRange, dstRange; SwsFilter dummyFilter= {NULL, NULL, NULL, NULL}; #if ARCH_X86 if (flags & SWS_CPU_CAPS_MMX) __asm__ volatile("emms\n\t"::: "memory"); #endif #if !CONFIG_RUNTIME_CPUDETECT flags &= ~(SWS_CPU_CAPS_MMX|SWS_CPU_CAPS_MMX2|SWS_CPU_CAPS_3DNOW|SWS_CPU_CAPS_ALTIVEC|SWS_CPU_CAPS_BFIN); flags |= ff_hardcodedcpuflags(); #endif if (!rgb15to16) sws_rgb2rgb_init(flags); unscaled = (srcW == dstW && srcH == dstH); srcRange = handle_jpeg(&srcFormat); dstRange = handle_jpeg(&dstFormat); if (!isSupportedIn(srcFormat)) { av_log(NULL, AV_LOG_ERROR, "swScaler: %s is not supported as input pixel format\n", sws_format_name(srcFormat)); return NULL; } if (!isSupportedOut(dstFormat)) { av_log(NULL, AV_LOG_ERROR, "swScaler: %s is not supported as output pixel format\n", sws_format_name(dstFormat)); return NULL; } i= flags & ( SWS_POINT |SWS_AREA |SWS_BILINEAR |SWS_FAST_BILINEAR |SWS_BICUBIC |SWS_X |SWS_GAUSS |SWS_LANCZOS |SWS_SINC |SWS_SPLINE |SWS_BICUBLIN); if(!i || (i & (i-1))) { av_log(NULL, AV_LOG_ERROR, "swScaler: Exactly one scaler algorithm must be chosen\n"); return NULL; } if (srcW<4 || srcH<1 || dstW<8 || dstH<1) { av_log(NULL, AV_LOG_ERROR, "swScaler: %dx%d -> %dx%d is invalid scaling dimension\n", srcW, srcH, dstW, dstH); return NULL; } if(srcW > VOFW || dstW > VOFW) { av_log(NULL, AV_LOG_ERROR, "swScaler: Compile-time maximum width is "AV_STRINGIFY(VOFW)" change VOF/VOFW and recompile\n"); return NULL; } if (!dstFilter) dstFilter= &dummyFilter; if (!srcFilter) srcFilter= &dummyFilter; FF_ALLOCZ_OR_GOTO(NULL, c, sizeof(SwsContext), fail); c->av_class = &sws_context_class; c->srcW= srcW; c->srcH= srcH; c->dstW= dstW; c->dstH= dstH; c->lumXInc= ((srcW<<16) + (dstW>>1))/dstW; c->lumYInc= ((srcH<<16) + (dstH>>1))/dstH; c->flags= flags; c->dstFormat= dstFormat; c->srcFormat= srcFormat; c->dstFormatBpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[dstFormat]); c->srcFormatBpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[srcFormat]); c->vRounder= 4* 0x0001000100010001ULL; usesVFilter = (srcFilter->lumV && srcFilter->lumV->length>1) || (srcFilter->chrV && srcFilter->chrV->length>1) || (dstFilter->lumV && dstFilter->lumV->length>1) || (dstFilter->chrV && dstFilter->chrV->length>1); usesHFilter = (srcFilter->lumH && srcFilter->lumH->length>1) || (srcFilter->chrH && srcFilter->chrH->length>1) || (dstFilter->lumH && dstFilter->lumH->length>1) || (dstFilter->chrH && dstFilter->chrH->length>1); getSubSampleFactors(&c->chrSrcHSubSample, &c->chrSrcVSubSample, srcFormat); getSubSampleFactors(&c->chrDstHSubSample, &c->chrDstVSubSample, dstFormat); if (isAnyRGB(dstFormat) && !(flags&SWS_FULL_CHR_H_INT)) c->chrDstHSubSample=1; c->vChrDrop= (flags&SWS_SRC_V_CHR_DROP_MASK)>>SWS_SRC_V_CHR_DROP_SHIFT; c->chrSrcVSubSample+= c->vChrDrop; if (isAnyRGB(srcFormat) && !(flags&SWS_FULL_CHR_H_INP) && srcFormat!=PIX_FMT_RGB8 && srcFormat!=PIX_FMT_BGR8 && srcFormat!=PIX_FMT_RGB4 && srcFormat!=PIX_FMT_BGR4 && srcFormat!=PIX_FMT_RGB4_BYTE && srcFormat!=PIX_FMT_BGR4_BYTE && ((dstW>>c->chrDstHSubSample) <= (srcW>>1) || (flags&(SWS_FAST_BILINEAR|SWS_POINT)))) c->chrSrcHSubSample=1; if (param) { c->param[0] = param[0]; c->param[1] = param[1]; } else { c->param[0] = c->param[1] = SWS_PARAM_DEFAULT; } c->chrSrcW= -((-srcW) >> c->chrSrcHSubSample); c->chrSrcH= -((-srcH) >> c->chrSrcVSubSample); c->chrDstW= -((-dstW) >> c->chrDstHSubSample); c->chrDstH= -((-dstH) >> c->chrDstVSubSample); sws_setColorspaceDetails(c, ff_yuv2rgb_coeffs[SWS_CS_DEFAULT], srcRange, ff_yuv2rgb_coeffs[SWS_CS_DEFAULT] , dstRange, 0, 1<<16, 1<<16); if (unscaled && !usesHFilter && !usesVFilter && (srcRange == dstRange || isAnyRGB(dstFormat))) { ff_get_unscaled_swscale(c); if (c->swScale) { if (flags&SWS_PRINT_INFO) av_log(c, AV_LOG_INFO, "using unscaled %s -> %s special converter\n", sws_format_name(srcFormat), sws_format_name(dstFormat)); return c; } } if (flags & SWS_CPU_CAPS_MMX2) { c->canMMX2BeUsed= (dstW >=srcW && (dstW&31)==0 && (srcW&15)==0) ? 1 : 0; if (!c->canMMX2BeUsed && dstW >=srcW && (srcW&15)==0 && (flags&SWS_FAST_BILINEAR)) { if (flags&SWS_PRINT_INFO) av_log(c, AV_LOG_INFO, "output width is not a multiple of 32 -> no MMX2 scaler\n"); } if (usesHFilter) c->canMMX2BeUsed=0; } else c->canMMX2BeUsed=0; c->chrXInc= ((c->chrSrcW<<16) + (c->chrDstW>>1))/c->chrDstW; c->chrYInc= ((c->chrSrcH<<16) + (c->chrDstH>>1))/c->chrDstH; if (flags&SWS_FAST_BILINEAR) { if (c->canMMX2BeUsed) { c->lumXInc+= 20; c->chrXInc+= 20; } else if (flags & SWS_CPU_CAPS_MMX) { c->lumXInc = ((srcW-2)<<16)/(dstW-2) - 20; c->chrXInc = ((c->chrSrcW-2)<<16)/(c->chrDstW-2) - 20; } } { #if ARCH_X86 && (HAVE_MMX2 || CONFIG_RUNTIME_CPUDETECT) && CONFIG_GPL if (c->canMMX2BeUsed && (flags & SWS_FAST_BILINEAR)) { c->lumMmx2FilterCodeSize = initMMX2HScaler( dstW, c->lumXInc, NULL, NULL, NULL, 8); c->chrMmx2FilterCodeSize = initMMX2HScaler(c->chrDstW, c->chrXInc, NULL, NULL, NULL, 4); #ifdef MAP_ANONYMOUS c->lumMmx2FilterCode = mmap(NULL, c->lumMmx2FilterCodeSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); c->chrMmx2FilterCode = mmap(NULL, c->chrMmx2FilterCodeSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); #elif HAVE_VIRTUALALLOC c->lumMmx2FilterCode = VirtualAlloc(NULL, c->lumMmx2FilterCodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); c->chrMmx2FilterCode = VirtualAlloc(NULL, c->chrMmx2FilterCodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); #else c->lumMmx2FilterCode = av_malloc(c->lumMmx2FilterCodeSize); c->chrMmx2FilterCode = av_malloc(c->chrMmx2FilterCodeSize); #endif if (!c->lumMmx2FilterCode || !c->chrMmx2FilterCode) goto fail; FF_ALLOCZ_OR_GOTO(c, c->hLumFilter , (dstW /8+8)*sizeof(int16_t), fail); FF_ALLOCZ_OR_GOTO(c, c->hChrFilter , (c->chrDstW /4+8)*sizeof(int16_t), fail); FF_ALLOCZ_OR_GOTO(c, c->hLumFilterPos, (dstW /2/8+8)*sizeof(int32_t), fail); FF_ALLOCZ_OR_GOTO(c, c->hChrFilterPos, (c->chrDstW/2/4+8)*sizeof(int32_t), fail); initMMX2HScaler( dstW, c->lumXInc, c->lumMmx2FilterCode, c->hLumFilter, c->hLumFilterPos, 8); initMMX2HScaler(c->chrDstW, c->chrXInc, c->chrMmx2FilterCode, c->hChrFilter, c->hChrFilterPos, 4); #ifdef MAP_ANONYMOUS mprotect(c->lumMmx2FilterCode, c->lumMmx2FilterCodeSize, PROT_EXEC | PROT_READ); mprotect(c->chrMmx2FilterCode, c->chrMmx2FilterCodeSize, PROT_EXEC | PROT_READ); #endif } else #endif { const int filterAlign= (flags & SWS_CPU_CAPS_MMX) ? 4 : (flags & SWS_CPU_CAPS_ALTIVEC) ? 8 : 1; if (initFilter(&c->hLumFilter, &c->hLumFilterPos, &c->hLumFilterSize, c->lumXInc, srcW , dstW, filterAlign, 1<<14, (flags&SWS_BICUBLIN) ? (flags|SWS_BICUBIC) : flags, srcFilter->lumH, dstFilter->lumH, c->param) < 0) goto fail; if (initFilter(&c->hChrFilter, &c->hChrFilterPos, &c->hChrFilterSize, c->chrXInc, c->chrSrcW, c->chrDstW, filterAlign, 1<<14, (flags&SWS_BICUBLIN) ? (flags|SWS_BILINEAR) : flags, srcFilter->chrH, dstFilter->chrH, c->param) < 0) goto fail; } } { const int filterAlign= (flags & SWS_CPU_CAPS_MMX) && (flags & SWS_ACCURATE_RND) ? 2 : (flags & SWS_CPU_CAPS_ALTIVEC) ? 8 : 1; if (initFilter(&c->vLumFilter, &c->vLumFilterPos, &c->vLumFilterSize, c->lumYInc, srcH , dstH, filterAlign, (1<<12), (flags&SWS_BICUBLIN) ? (flags|SWS_BICUBIC) : flags, srcFilter->lumV, dstFilter->lumV, c->param) < 0) goto fail; if (initFilter(&c->vChrFilter, &c->vChrFilterPos, &c->vChrFilterSize, c->chrYInc, c->chrSrcH, c->chrDstH, filterAlign, (1<<12), (flags&SWS_BICUBLIN) ? (flags|SWS_BILINEAR) : flags, srcFilter->chrV, dstFilter->chrV, c->param) < 0) goto fail; #if ARCH_PPC && HAVE_ALTIVEC FF_ALLOC_OR_GOTO(c, c->vYCoeffsBank, sizeof (vector signed short)*c->vLumFilterSize*c->dstH, fail); FF_ALLOC_OR_GOTO(c, c->vCCoeffsBank, sizeof (vector signed short)*c->vChrFilterSize*c->chrDstH, fail); for (i=0;i<c->vLumFilterSize*c->dstH;i++) { int j; short *p = (short *)&c->vYCoeffsBank[i]; for (j=0;j<8;j++) p[j] = c->vLumFilter[i]; } for (i=0;i<c->vChrFilterSize*c->chrDstH;i++) { int j; short *p = (short *)&c->vCCoeffsBank[i]; for (j=0;j<8;j++) p[j] = c->vChrFilter[i]; } #endif } c->vLumBufSize= c->vLumFilterSize; c->vChrBufSize= c->vChrFilterSize; for (i=0; i<dstH; i++) { int chrI= i*c->chrDstH / dstH; int nextSlice= FFMAX(c->vLumFilterPos[i ] + c->vLumFilterSize - 1, ((c->vChrFilterPos[chrI] + c->vChrFilterSize - 1)<<c->chrSrcVSubSample)); nextSlice>>= c->chrSrcVSubSample; nextSlice<<= c->chrSrcVSubSample; if (c->vLumFilterPos[i ] + c->vLumBufSize < nextSlice) c->vLumBufSize= nextSlice - c->vLumFilterPos[i]; if (c->vChrFilterPos[chrI] + c->vChrBufSize < (nextSlice>>c->chrSrcVSubSample)) c->vChrBufSize= (nextSlice>>c->chrSrcVSubSample) - c->vChrFilterPos[chrI]; } FF_ALLOC_OR_GOTO(c, c->lumPixBuf, c->vLumBufSize*2*sizeof(int16_t*), fail); FF_ALLOC_OR_GOTO(c, c->chrPixBuf, c->vChrBufSize*2*sizeof(int16_t*), fail); if (CONFIG_SWSCALE_ALPHA && isALPHA(c->srcFormat) && isALPHA(c->dstFormat)) FF_ALLOCZ_OR_GOTO(c, c->alpPixBuf, c->vLumBufSize*2*sizeof(int16_t*), fail); for (i=0; i<c->vLumBufSize; i++) { FF_ALLOCZ_OR_GOTO(c, c->lumPixBuf[i+c->vLumBufSize], VOF+1, fail); c->lumPixBuf[i] = c->lumPixBuf[i+c->vLumBufSize]; } for (i=0; i<c->vChrBufSize; i++) { FF_ALLOC_OR_GOTO(c, c->chrPixBuf[i+c->vChrBufSize], (VOF+1)*2, fail); c->chrPixBuf[i] = c->chrPixBuf[i+c->vChrBufSize]; } if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) for (i=0; i<c->vLumBufSize; i++) { FF_ALLOCZ_OR_GOTO(c, c->alpPixBuf[i+c->vLumBufSize], VOF+1, fail); c->alpPixBuf[i] = c->alpPixBuf[i+c->vLumBufSize]; } for (i=0; i<c->vChrBufSize; i++) memset(c->chrPixBuf[i], 64, (VOF+1)*2); assert(2*VOFW == VOF); assert(c->chrDstH <= dstH); if (flags&SWS_PRINT_INFO) { if (flags&SWS_FAST_BILINEAR) av_log(c, AV_LOG_INFO, "FAST_BILINEAR scaler, "); else if (flags&SWS_BILINEAR) av_log(c, AV_LOG_INFO, "BILINEAR scaler, "); else if (flags&SWS_BICUBIC) av_log(c, AV_LOG_INFO, "BICUBIC scaler, "); else if (flags&SWS_X) av_log(c, AV_LOG_INFO, "Experimental scaler, "); else if (flags&SWS_POINT) av_log(c, AV_LOG_INFO, "Nearest Neighbor / POINT scaler, "); else if (flags&SWS_AREA) av_log(c, AV_LOG_INFO, "Area Averaging scaler, "); else if (flags&SWS_BICUBLIN) av_log(c, AV_LOG_INFO, "luma BICUBIC / chroma BILINEAR scaler, "); else if (flags&SWS_GAUSS) av_log(c, AV_LOG_INFO, "Gaussian scaler, "); else if (flags&SWS_SINC) av_log(c, AV_LOG_INFO, "Sinc scaler, "); else if (flags&SWS_LANCZOS) av_log(c, AV_LOG_INFO, "Lanczos scaler, "); else if (flags&SWS_SPLINE) av_log(c, AV_LOG_INFO, "Bicubic spline scaler, "); else av_log(c, AV_LOG_INFO, "ehh flags invalid?! "); av_log(c, AV_LOG_INFO, "from %s to %s%s ", sws_format_name(srcFormat), #ifdef DITHER1XBPP dstFormat == PIX_FMT_BGR555 || dstFormat == PIX_FMT_BGR565 || dstFormat == PIX_FMT_RGB444BE || dstFormat == PIX_FMT_RGB444LE || dstFormat == PIX_FMT_BGR444BE || dstFormat == PIX_FMT_BGR444LE ? "dithered " : "", #else "", #endif sws_format_name(dstFormat)); if (flags & SWS_CPU_CAPS_MMX2) av_log(c, AV_LOG_INFO, "using MMX2\n"); else if (flags & SWS_CPU_CAPS_3DNOW) av_log(c, AV_LOG_INFO, "using 3DNOW\n"); else if (flags & SWS_CPU_CAPS_MMX) av_log(c, AV_LOG_INFO, "using MMX\n"); else if (flags & SWS_CPU_CAPS_ALTIVEC) av_log(c, AV_LOG_INFO, "using AltiVec\n"); else av_log(c, AV_LOG_INFO, "using C\n"); if (flags & SWS_CPU_CAPS_MMX) { if (c->canMMX2BeUsed && (flags&SWS_FAST_BILINEAR)) av_log(c, AV_LOG_VERBOSE, "using FAST_BILINEAR MMX2 scaler for horizontal scaling\n"); else { if (c->hLumFilterSize==4) av_log(c, AV_LOG_VERBOSE, "using 4-tap MMX scaler for horizontal luminance scaling\n"); else if (c->hLumFilterSize==8) av_log(c, AV_LOG_VERBOSE, "using 8-tap MMX scaler for horizontal luminance scaling\n"); else av_log(c, AV_LOG_VERBOSE, "using n-tap MMX scaler for horizontal luminance scaling\n"); if (c->hChrFilterSize==4) av_log(c, AV_LOG_VERBOSE, "using 4-tap MMX scaler for horizontal chrominance scaling\n"); else if (c->hChrFilterSize==8) av_log(c, AV_LOG_VERBOSE, "using 8-tap MMX scaler for horizontal chrominance scaling\n"); else av_log(c, AV_LOG_VERBOSE, "using n-tap MMX scaler for horizontal chrominance scaling\n"); } } else { #if ARCH_X86 av_log(c, AV_LOG_VERBOSE, "using x86 asm scaler for horizontal scaling\n"); #else if (flags & SWS_FAST_BILINEAR) av_log(c, AV_LOG_VERBOSE, "using FAST_BILINEAR C scaler for horizontal scaling\n"); else av_log(c, AV_LOG_VERBOSE, "using C scaler for horizontal scaling\n"); #endif } if (isPlanarYUV(dstFormat)) { if (c->vLumFilterSize==1) av_log(c, AV_LOG_VERBOSE, "using 1-tap %s \"scaler\" for vertical scaling (YV12 like)\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C"); else av_log(c, AV_LOG_VERBOSE, "using n-tap %s scaler for vertical scaling (YV12 like)\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C"); } else { if (c->vLumFilterSize==1 && c->vChrFilterSize==2) av_log(c, AV_LOG_VERBOSE, "using 1-tap %s \"scaler\" for vertical luminance scaling (BGR)\n" " 2-tap scaler for vertical chrominance scaling (BGR)\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C"); else if (c->vLumFilterSize==2 && c->vChrFilterSize==2) av_log(c, AV_LOG_VERBOSE, "using 2-tap linear %s scaler for vertical scaling (BGR)\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C"); else av_log(c, AV_LOG_VERBOSE, "using n-tap %s scaler for vertical scaling (BGR)\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C"); } if (dstFormat==PIX_FMT_BGR24) av_log(c, AV_LOG_VERBOSE, "using %s YV12->BGR24 converter\n", (flags & SWS_CPU_CAPS_MMX2) ? "MMX2" : ((flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C")); else if (dstFormat==PIX_FMT_RGB32) av_log(c, AV_LOG_VERBOSE, "using %s YV12->BGR32 converter\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C"); else if (dstFormat==PIX_FMT_BGR565) av_log(c, AV_LOG_VERBOSE, "using %s YV12->BGR16 converter\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C"); else if (dstFormat==PIX_FMT_BGR555) av_log(c, AV_LOG_VERBOSE, "using %s YV12->BGR15 converter\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C"); else if (dstFormat == PIX_FMT_RGB444BE || dstFormat == PIX_FMT_RGB444LE || dstFormat == PIX_FMT_BGR444BE || dstFormat == PIX_FMT_BGR444LE) av_log(c, AV_LOG_VERBOSE, "using %s YV12->BGR12 converter\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C"); av_log(c, AV_LOG_VERBOSE, "%dx%d -> %dx%d\n", srcW, srcH, dstW, dstH); av_log(c, AV_LOG_DEBUG, "lum srcW=%d srcH=%d dstW=%d dstH=%d xInc=%d yInc=%d\n", c->srcW, c->srcH, c->dstW, c->dstH, c->lumXInc, c->lumYInc); av_log(c, AV_LOG_DEBUG, "chr srcW=%d srcH=%d dstW=%d dstH=%d xInc=%d yInc=%d\n", c->chrSrcW, c->chrSrcH, c->chrDstW, c->chrDstH, c->chrXInc, c->chrYInc); } c->swScale= ff_getSwsFunc(c); return c; fail: sws_freeContext(c); return NULL; }
1threat