problem
stringlengths
26
131k
labels
class label
2 classes
How do I format my output as a 4-by-4 matrix? : <pre><code>class By { public static void main(String args[]) throws InterruptedException { String key = "Hello world";// plaintext byte[] x = key.getBytes(); StringBuilder sb = new StringBuilder(); for (int i = 0; i &lt; x.length; i++) { int b = (int) x[i]; sb.append(Integer.toHexString(b)); } System.out.println(sb.toString()); } } This program output is: 48656c6c6f20776f726c64 I need my output to be a 4-by-4 matrix as such: 1st row is:: 48 6f 72 00 2nd row is:: 65 20 6c 00 3rd row is:: 6c 77 64 00 4th row is:: 6c 6f 00 00 </code></pre> <p>How do I write code for this in java?Please anyone show me the code to get my required output.</p>
0debug
Excel need to match and paste to an adjacent cell : <p>So the formula needs to look at column D IN SHEET 1, go over to sheet 2, if it finds a match in column A, then paste the coordinates in column B into sheet 1 column E.<a href="http://i.stack.imgur.com/rehLP.png" rel="nofollow">IMAGE</a></p>
0debug
PHP beginner - Can global variable be used by other page? : I try to to write in test1.php <?php $a = 5; $b = 7; ?> in test2.php <?php global $a, $b; echo $a + $b; ?> but result is 0. So Could it be used in other page? or should I use session ?
0debug
How are variables in Java called that are set once but never again and are not final? : <p>I have several variables I need to set only once but never again after starting the application, such as SCREEN_WIDTH, ARRAY_X_LENGTH, TIME_APP_STARTED etc.</p> <p>I do not declare these final because the software will decide what value to assign to them, not me manually. I capitalize the words though so that I can see that no other code will assign any value to it, only 1.</p> <p>Is this a bad programming practice, and if yes, what should I do, I usually just have a file containing all these ''final'' variables and my flags, I do not like storing them locally.</p>
0debug
static uint64_t msix_pba_mmio_read(void *opaque, target_phys_addr_t addr, unsigned size) { PCIDevice *dev = opaque; return pci_get_long(dev->msix_pba + addr); }
1threat
void scsi_req_cancel(SCSIRequest *req) { trace_scsi_req_cancel(req->dev->id, req->lun, req->tag); if (!req->enqueued) { return; } scsi_req_ref(req); scsi_req_dequeue(req); req->io_canceled = true; if (req->aiocb) { bdrv_aio_cancel(req->aiocb); } }
1threat
How to specify a Moment.js object annotation in Flow : <p>I'm currently learning Flow by applying it to an existing project and looking to annotate function parameters as a Moment.JS objects. </p> <p>Using <a href="https://github.com/flowtype/flow-typed/" rel="noreferrer">flow-typed</a> I was able to install a library definition for Moment.JS which appears to have the type I'm looking for:</p> <pre><code>declare class moment$Moment { static ISO_8601: string; static (string?: string, format?: string|Array&lt;string&gt;, locale?: string, strict?: bool): moment$Moment; static (initDate: ?Object|number|Date|Array&lt;number&gt;|moment$Moment|string): moment$Moment; static unix(seconds: number): moment$Moment; static utc(): moment$Moment; ... </code></pre> <p>However when I try to annotate function parameters as Moment.JS objects, Flow fails to recognize them as such. In the following function <code>startDate</code> and <code>endDate</code> are Moment.JS date objects.</p> <pre><code>const filterByDateWhereClause = (startDate: Moment, endDate: Moment): string =&gt; {...}; </code></pre> <p>Flow gives the following error:</p> <pre><code>const filterByDateWhereClause = (startDate: Moment, endDate: Moment): string =&gt; ^^^^^^ identifier `Moment`. Could not resolve name </code></pre> <p>Is this even possible with Flow? Or do I need to duplicate the <code>type</code> for the Moment.JS object identical to the one in the library definition provided by flow-type? I'd prefer not to do this as the libdef is fairly lengthy. </p> <p>For example:</p> <pre><code>declare class Moment { static ISO_8601: string; static (string?: string, format?: string|Array&lt;string&gt;, locale?: string, strict?: bool): moment$Moment; static (initDate: ?Object|number|Date|Array&lt;number&gt;|moment$Moment|string): moment$Moment; static unix(seconds: number): moment$Moment; static utc(): moment$Moment; ... const filterByDateWhereClause = (startDate: Moment, endDate: Moment): string =&gt; {...}; </code></pre> <p>What am I missing?</p>
0debug
How to mane an "in" statement inclusive-only in SQL : I have a subset of values that I want to evaluate against a row in SQL. Select count(*) cnt from table_name c where c.table_row in ('value 1','value 2', 'value 3') and other statements; This works fine as long as I only want to determine if "table_row" contains one of those three values. What I want, however, is to determine if table_row contains **only** those values. Is there any SQL statement that can perform an inclusive-only 'in' statement, so that for the "cnt" in the above query, I will only get a result if 'table_row' is in the set indicated by the query?
0debug
Design a System for faster retrieval and modification without burdening the Heap Memory : <p>I need to design a system where data is received via ServerSocket and the data should be readily available for retrieval and modification. Currently, all the data is stored in ConcurrentHashMap.</p> <p>Data will be refreshed when the application restarts.</p> <p>Maintaining a Flat File and data retrieval from the file will add some delay.</p> <p>Is there any better approach to solve this kind of problem.</p>
0debug
format value type float in (Programming Language C/C++) : <p>How show 00156,00</p> <pre><code>float number = 156; printf("%5.2f",number); </code></pre> <p>The output of the example above:</p> <p>Output: 156.00</p>
0debug
static inline int wnv1_get_code(WNV1Context *w, int base_value) { int v = get_vlc2(&w->gb, code_vlc.table, CODE_VLC_BITS, 1); if (v == 15) return ff_reverse[get_bits(&w->gb, 8 - w->shift)]; else return base_value + ((v - 7) << w->shift); }
1threat
int virtio_load(VirtIODevice *vdev, QEMUFile *f, int version_id) { int i, ret; int32_t config_len; uint32_t num; uint32_t features; BusState *qbus = qdev_get_parent_bus(DEVICE(vdev)); VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus); VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev); vdev->device_endian = VIRTIO_DEVICE_ENDIAN_UNKNOWN; if (k->load_config) { ret = k->load_config(qbus->parent, f); if (ret) return ret; } qemu_get_8s(f, &vdev->status); qemu_get_8s(f, &vdev->isr); qemu_get_be16s(f, &vdev->queue_sel); if (vdev->queue_sel >= VIRTIO_QUEUE_MAX) { return -1; } qemu_get_be32s(f, &features); vdev->guest_features = features; config_len = qemu_get_be32(f); qemu_get_buffer(f, vdev->config, MIN(config_len, vdev->config_len)); while (config_len > vdev->config_len) { qemu_get_byte(f); config_len--; } num = qemu_get_be32(f); if (num > VIRTIO_QUEUE_MAX) { error_report("Invalid number of virtqueues: 0x%x", num); return -1; } for (i = 0; i < num; i++) { vdev->vq[i].vring.num = qemu_get_be32(f); if (k->has_variable_vring_alignment) { vdev->vq[i].vring.align = qemu_get_be32(f); } vdev->vq[i].vring.desc = qemu_get_be64(f); qemu_get_be16s(f, &vdev->vq[i].last_avail_idx); vdev->vq[i].signalled_used_valid = false; vdev->vq[i].notification = true; if (vdev->vq[i].vring.desc) { virtio_queue_update_rings(vdev, i); } else if (vdev->vq[i].last_avail_idx) { error_report("VQ %d address 0x0 " "inconsistent with Host index 0x%x", i, vdev->vq[i].last_avail_idx); return -1; } if (k->load_queue) { ret = k->load_queue(qbus->parent, i, f); if (ret) return ret; } } virtio_notify_vector(vdev, VIRTIO_NO_VECTOR); if (vdc->load != NULL) { ret = vdc->load(vdev, f, version_id); if (ret) { return ret; } } if (vdc->vmsd) { ret = vmstate_load_state(f, vdc->vmsd, vdev, version_id); if (ret) { return ret; } } ret = vmstate_load_state(f, &vmstate_virtio, vdev, 1); if (ret) { return ret; } if (vdev->device_endian == VIRTIO_DEVICE_ENDIAN_UNKNOWN) { vdev->device_endian = virtio_default_endian(); } if (virtio_64bit_features_needed(vdev)) { uint64_t features64 = vdev->guest_features; if (virtio_set_features_nocheck(vdev, features64) < 0) { error_report("Features 0x%" PRIx64 " unsupported. " "Allowed features: 0x%" PRIx64, features64, vdev->host_features); return -1; } } else { if (virtio_set_features_nocheck(vdev, features) < 0) { error_report("Features 0x%x unsupported. " "Allowed features: 0x%" PRIx64, features, vdev->host_features); return -1; } } rcu_read_lock(); for (i = 0; i < num; i++) { if (vdev->vq[i].vring.desc) { uint16_t nheads; nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx; if (nheads > vdev->vq[i].vring.num) { error_report("VQ %d size 0x%x Guest index 0x%x " "inconsistent with Host index 0x%x: delta 0x%x", i, vdev->vq[i].vring.num, vring_avail_idx(&vdev->vq[i]), vdev->vq[i].last_avail_idx, nheads); return -1; } vdev->vq[i].used_idx = vring_used_idx(&vdev->vq[i]); vdev->vq[i].shadow_avail_idx = vring_avail_idx(&vdev->vq[i]); vdev->vq[i].inuse = (uint16_t)(vdev->vq[i].last_avail_idx - vdev->vq[i].used_idx); if (vdev->vq[i].inuse > vdev->vq[i].vring.num) { error_report("VQ %d size 0x%x < last_avail_idx 0x%x - " "used_idx 0x%x", i, vdev->vq[i].vring.num, vdev->vq[i].last_avail_idx, vdev->vq[i].used_idx); return -1; } } } rcu_read_unlock(); return 0; }
1threat
Write in a txt file in PYTHON with class name which varie (0 to N) : I have a class name myClass which contain some attributes (attribute0, attibute1...). I have create N myClass (myClass0, myClass1...). To write in a .txt file myClass0.attribute0: fichier = open("myFile.txt", "a") fichier.write("{}".format(myClass0.attribute0)) I want to write in the file myFile.txt myClassN.attribute0 with N for 0 to 9: fichier = open("myFile.txt", "a") fichier.write("{}".format(myClass0.attribute0)) fichier.write("{}".format(myClass1.attribute0)) . . . fichier.write("{}".format(myClass9.attribute0)) How to do it in a loop ? Thanks a lot.
0debug
batch file code to detect 32-bit vs 64-bit office not working : <p>I'm trying to put together a batch file that would select the appropriate bit version of executables when run by the user. I found this code on stackoverflow: <a href="https://stackoverflow.com/questions/35820375/batch-file-check-office-architecture-version">Batch file check office architecture version</a> The problem is that it does not work when I paste it into a text file on my desktop and rename it .bat in my virtual machine that has 64-bit Office 2010 installed: it claims it is 32-bit, the default value set in the code. Not being adept in checking registry entries, I'm wondering if there isn't a ready-made version out there somewhere that actually works. I'm also wondering why there isn't a simple way to determine this. I would have thought that this is something that Microsoft would make easily accessible to developers. </p>
0debug
grouping the batch in sql server : have a scenario wherein I have Id|rank| date 1 | 7 |07/08/2015 1 | 7 |09/08/2015 1 | 8 |16/08/2015 1 | 8 |17/08/2015 1 | 7 |19/08/2015 1 | 7 |15/08/2015 2 | 7 |01/08/2015 2 | 7 |02/08/2015 2 | 8 |16/08/2015 2 | 8 |17/08/2015 2 | 7 |26/08/2015 2 | 7 |28/08/2015 My desired solution is 1 | 7 |07/08/2015 |1 1 | 7 |09/08/2015 |1 1 | 8 |16/08/2015 |2 1 | 8 |17/08/2015 |2 1 | 7 |19/08/2015 |3 1 | 7 |15/08/2015 |3 2 | 7 |01/08/2015 |4 2 | 7 |02/08/2015 |4 2 | 8 |16/08/2015 |5 2 | 8 |17/08/2015 |5 2 | 7 |26/08/2015 |6 2 | 7 |28/08/2015 |6 i.e for each block of id and rank I want to add the new column and updated the same.
0debug
static void eepro100_cu_command(EEPRO100State * s, uint8_t val) { eepro100_tx_t tx; uint32_t cb_address; switch (val) { case CU_NOP: break; case CU_START: if (get_cu_state(s) != cu_idle) { logout("CU state is %u, should be %u\n", get_cu_state(s), cu_idle); } set_cu_state(s, cu_active); s->cu_offset = s->pointer; next_command: cb_address = s->cu_base + s->cu_offset; cpu_physical_memory_read(cb_address, (uint8_t *) & tx, sizeof(tx)); uint16_t status = le16_to_cpu(tx.status); uint16_t command = le16_to_cpu(tx.command); logout ("val=0x%02x (cu start), status=0x%04x, command=0x%04x, link=0x%08x\n", val, status, command, tx.link); bool bit_el = ((command & 0x8000) != 0); bool bit_s = ((command & 0x4000) != 0); bool bit_i = ((command & 0x2000) != 0); bool bit_nc = ((command & 0x0010) != 0); uint16_t cmd = command & 0x0007; s->cu_offset = le32_to_cpu(tx.link); switch (cmd) { case CmdNOp: break; case CmdIASetup: cpu_physical_memory_read(cb_address + 8, &s->macaddr[0], 6); TRACE(OTHER, logout("macaddr: %s\n", nic_dump(&s->macaddr[0], 6))); break; case CmdConfigure: cpu_physical_memory_read(cb_address + 8, &s->configuration[0], sizeof(s->configuration)); TRACE(OTHER, logout("configuration: %s\n", nic_dump(&s->configuration[0], 16))); break; case CmdMulticastList: break; case CmdTx: (void)0; uint32_t tbd_array = le32_to_cpu(tx.tx_desc_addr); uint16_t tcb_bytes = (le16_to_cpu(tx.tcb_bytes) & 0x3fff); TRACE(RXTX, logout ("transmit, TBD array address 0x%08x, TCB byte count 0x%04x, TBD count %u\n", tbd_array, tcb_bytes, tx.tbd_count)); assert(!bit_nc); assert(tcb_bytes <= 2600); if (!((tcb_bytes > 0) || (tbd_array != 0xffffffff))) { logout ("illegal values of TBD array address and TCB byte count!\n"); } uint8_t buf[2600]; uint16_t size = 0; uint32_t tbd_address = cb_address + 0x10; assert(tcb_bytes <= sizeof(buf)); while (size < tcb_bytes) { uint32_t tx_buffer_address = ldl_phys(tbd_address); uint16_t tx_buffer_size = lduw_phys(tbd_address + 4); tbd_address += 8; TRACE(RXTX, logout ("TBD (simplified mode): buffer address 0x%08x, size 0x%04x\n", tx_buffer_address, tx_buffer_size)); tx_buffer_size = MIN(tx_buffer_size, sizeof(buf) - size); cpu_physical_memory_read(tx_buffer_address, &buf[size], tx_buffer_size); size += tx_buffer_size; } if (tbd_array == 0xffffffff) { } else { uint8_t tbd_count = 0; if (device_supports_eTxCB(s) && !(s->configuration[6] & BIT(4))) { assert(tcb_bytes == 0); for (; tbd_count < 2; tbd_count++) { uint32_t tx_buffer_address = ldl_phys(tbd_address); uint16_t tx_buffer_size = lduw_phys(tbd_address + 4); uint16_t tx_buffer_el = lduw_phys(tbd_address + 6); tbd_address += 8; TRACE(RXTX, logout ("TBD (extended flexible mode): buffer address 0x%08x, size 0x%04x\n", tx_buffer_address, tx_buffer_size)); tx_buffer_size = MIN(tx_buffer_size, sizeof(buf) - size); cpu_physical_memory_read(tx_buffer_address, &buf[size], tx_buffer_size); size += tx_buffer_size; if (tx_buffer_el & 1) { break; } } } tbd_address = tbd_array; for (; tbd_count < tx.tbd_count; tbd_count++) { uint32_t tx_buffer_address = ldl_phys(tbd_address); uint16_t tx_buffer_size = lduw_phys(tbd_address + 4); uint16_t tx_buffer_el = lduw_phys(tbd_address + 6); tbd_address += 8; TRACE(RXTX, logout ("TBD (flexible mode): buffer address 0x%08x, size 0x%04x\n", tx_buffer_address, tx_buffer_size)); tx_buffer_size = MIN(tx_buffer_size, sizeof(buf) - size); cpu_physical_memory_read(tx_buffer_address, &buf[size], tx_buffer_size); size += tx_buffer_size; if (tx_buffer_el & 1) { break; } } } TRACE(RXTX, logout("%p sending frame, len=%d,%s\n", s, size, nic_dump(buf, size))); qemu_send_packet(s->vc, buf, size); s->statistics.tx_good_frames++; break; case CmdTDR: TRACE(OTHER, logout("load microcode\n")); break; default: missing("undefined command"); } stw_phys(cb_address, status | 0x8000 | 0x2000); if (bit_i) { eepro100_cx_interrupt(s); } if (bit_el) { set_cu_state(s, cu_idle); eepro100_cna_interrupt(s); } else if (bit_s) { set_cu_state(s, cu_suspended); eepro100_cna_interrupt(s); } else { TRACE(OTHER, logout("CU list with at least one more entry\n")); goto next_command; } TRACE(OTHER, logout("CU list empty\n")); break; case CU_RESUME: if (get_cu_state(s) != cu_suspended) { logout("bad CU resume from CU state %u\n", get_cu_state(s)); set_cu_state(s, cu_suspended); } if (get_cu_state(s) == cu_suspended) { TRACE(OTHER, logout("CU resuming\n")); set_cu_state(s, cu_active); goto next_command; } break; case CU_STATSADDR: s->statsaddr = s->pointer; TRACE(OTHER, logout("val=0x%02x (status address)\n", val)); break; case CU_SHOWSTATS: TRACE(OTHER, logout("val=0x%02x (dump stats)\n", val)); dump_statistics(s); break; case CU_CMD_BASE: TRACE(OTHER, logout("val=0x%02x (CU base address)\n", val)); s->cu_base = s->pointer; break; case CU_DUMPSTATS: TRACE(OTHER, logout("val=0x%02x (dump stats and reset)\n", val)); dump_statistics(s); memset(&s->statistics, 0, sizeof(s->statistics)); break; case CU_SRESUME: missing("CU static resume"); break; default: missing("Undefined CU command"); } }
1threat
Developer name constraints in App Store : <p>I'm creating my developer account and I have to choose developer name now. I wonder if I can use any name that is availeable or should I use my own name and surname. The problem is that I dont have company with that name. Can google ban my account because I have same name as some other company(even if they created their developer account after me)?</p>
0debug
Fetching all the records between start date and date that has been provided by the user using php, mysql : I have a start date and end date that has been stored in the database . I want to fetch record from start date to end date using php Mysql how can i get the records between those dates
0debug
How to return multiple values in a function (Python)? : <p>So I'm new to coding and working my way through the Titanic data set from Kaggle. In the data frame there are columns labeled "Age" and "Sex." I want to make a new column that has 4 values that indicate for different things: 0: Male aged 16 or over 1: Female aged 16 or over 2: Male aged 15 or younger 3: Female aged 15 or younger</p> <p>So far I've gotten this, but this just splits it up into 3 values, not the 4 I'm looking for.</p> <pre><code>def person_detail(Person): Age, Sex = Person return 2 if Age &lt; 16 else Sex </code></pre> <p>I then apply the function to the "Age" and "Sex" columns to get a new column. I know that you can't have two returns, but if it gets across what I am trying to accomplish, it would look something like the below.</p> <pre><code>def person_detail(Person): Age, Sex = Person return 2 if Age &lt; 16 and Sex == 0 return 3 if Age &lt; 16 and Sex == 1 else Sex </code></pre> <p>Thanks in advance. For reference in the "Sex" column 0 is for male, and 1 is for female.</p>
0debug
SQL Server: Auto Increment Decimal Column : I need to auto increment a decimal Column in SQL SERVER 2014
0debug
db.execute('SELECT * FROM employees WHERE id = ' + user_input)
1threat
static void block_dirty_bitmap_add_abort(BlkActionState *common) { BlockDirtyBitmapAdd *action; BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState, common, common); action = common->action->u.block_dirty_bitmap_add; if (state->prepared) { qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort); } }
1threat
Java EE? -insert record into database only if it does not exist : I have a table in a database called MYUSER, I am trying to create a method that will check if the Myuser object I pass into it already exists as a row within the database, and then insert that object as a row if it does not exist. [I have very little experience in java, especially in regards to writing code that interacts with a dataBase which is why I'm struggling with this simple task] My attempt at creating said method is below however I just cannot wrap my head around how to implement this correctly public boolean createRecord(Myuser myuser) { Connection cnnct = null; PreparedStatement pStmnt = null; try { cnnct = getConnection(); String preQueryStatement = "SELECT * FROM MYUSER WHERE MYUSER.USERID = ?;"; pStmnt = cnnct.prepareStatement(preQueryStatement); if (pStmnt.getResultSet() == null) { String insertStatement = "INSERT INTO MYUSER VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; PreparedStatement ps = cnnct.prepareStatement(insertStatement); ps.setString(1, myuser.getUserid()); ps.setString(2, myuser.getName()); ps.setString(3, myuser.getPassword()); ps.setString(4, myuser.getEmail()); ps.setString(5, myuser.getPhone()); ps.setString(6, myuser.getAddress()); ps.setString(7, myuser.getSecQn()); ps.setString(8, myuser.getSecAns()); System.out.println("new user inserted"); return true; } else { System.out.println("user already in data base"); return false; } } catch (SQLException ex) { while (ex != null) { ex.printStackTrace(); ex = ex.getNextException(); } } catch (IOException ex) { ex.printStackTrace(); } finally { if (pStmnt != null) { try { pStmnt.close(); } catch (SQLException e) { } } if (cnnct!= null) { try { cnnct.close(); } catch (SQLException sqlEx) { } } } }
0debug
Add a dash between running numbers and comma between non-running numbers : I would like to replace a set of running and non running numbers with commas and hyphens where appropriate. Using STUFF & XML PATH I was able to accomplish some of what I want by getting something like 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 15, 19, 20, 21, 22, 24. WITH CTE AS ( SELECT DISTINCT t1.ORDERNo, t1.Part, t2.LineNum FROM [DBName].[DBA].Table1 t1 JOIN Table2 t2 ON t2.Part = t1.Part WHERE t1.ORDERNo = 'AB12345') SELECT c1.SQ, c1.Part, STUFF((SELECT ', ' + CAST(LineNum AS VARCHAR(5)) FROM CTE c2 WHERE c2.SQ = c1.SQ FOR XML PATH('')), 1, 2, '') AS [LineNums] FROM CTE c1 GROUP BY c1.SQ, c1.Part I would like to have 1-10, 13, 15, 19, 20-22, 24.
0debug
Sql Devloper - Use concat with GROUP BY function for COUNTING (Error ORA-00904) : I am working on a mock database for a project and I have two tables: CUSTOMERS AND ORDERS Both tables look like this CUSTOMERS: custID, custLName, custFName, custAddress, custTown, custPostcode, custPhone, custEmail And ORDERS: orderID, orderDate, dispatchDate, custID (foreign key) I am trying to generate a query that returns the full name and phone number of the customer who has made the most orders. This is my query below however it is returning an error on the GROUP BY function stating ORA-00904: "CUSTOMER": invalid identifier SELECT b.custFName || ' ' || b.custLName || ', ' || b.custPhone AS Customer, COUNT(DISTINCT o.custID) AS Orders_Placed FROM CUSTOMERS b, ORDERS o GROUP BY Customer HAVING COUNT(DISTINCT o.custID) AND b.custID = o.custID ORDER BY o.custID DESC;
0debug
static int qemu_reset_requested(void) { int r = reset_requested; reset_requested = 0; return r; }
1threat
static void intra_predict_mad_cow_dc_l00_8x8_msa(uint8_t *src, int32_t stride) { uint8_t lp_cnt; uint32_t src0 = 0; uint64_t out0, out1; for (lp_cnt = 0; lp_cnt < 4; lp_cnt++) { src0 += src[lp_cnt * stride - 1]; } src0 = (src0 + 2) >> 2; out0 = src0 * 0x0101010101010101; out1 = 0x8080808080808080; for (lp_cnt = 4; lp_cnt--;) { SD(out0, src); SD(out1, src + stride * 4); src += stride; } }
1threat
textview position by backgorund imageview : i have background imageview(green with 3 red circle) and 3 textview (A,B,C). how can i put textviews exactly on center of red circles that support multi screen devices , portrait/landscape ? [![enter image description here][1]][1] [1]: http://i.stack.imgur.com/mTaaR.png
0debug
fetching json object from json string : hii need some urgent help. i am new to andorid and i am developing app which has server side functionality. i am getting response in json format my response is shown as this image i knw how to parse json using vally but i dont know hot to pasrse using GSOn. previous code of my app was writen by some one else. now i have to complete this code. but i dnt knw how he getting data from json string i need json arrays in different activty. array response[image][1] here is some snaps of my code code for adapter for activty one topicListAdapter = new TopicListAdapter(TopicActivity.this, myCourseListMain. getCourseArrayList().get(Integer.parseInt(course_position)). getTopicListMain().getTopicDetailsArrayList(), flag); listAlltopics.setAdapter(topicListAdapter); in which i got list of topics here is code for second activty list adpater lessionListAdapter = new LessionListAdapter(LessionActivity.this, myCourseListMain. getCourseArrayList(). get(Integer.parseInt(course_position)). getTopicListMain().getTopicDetailsArrayList().get(Integer.parseInt(topic_position)).getLessionArrayList(), flag); bye this code i got array of lession in second activity now i want sublession array in 3 rd activty but i dont knw how to get it here is what i tried lessionListAdapter = new DummyAdapter(DummyTopicList.this, myCourseListMain . getCourseArrayList(). get(Integer.parseInt(course_position)). getTopicListMain() . getTopicDetailsArrayList() .get(Integer.parseInt(topic_position)). getLessionLIstMain() .getLessionLIstDetailArrayList().get(Integer.parseInt(lession_position)). , flag); listAlllessions.setAdapter(lessionListAdapter); here are some other classes which helpful to you for understand public class MyCourseListMain { @SerializedName("data") private ArrayList<Course> courseArrayList; public ArrayList<Course> getCourseArrayList() { return courseArrayList; } public void setCourseArrayList(ArrayList<Course> courseArrayList) { this.courseArrayList = courseArrayList; } } class for couse public class Course { @SerializedName("img") private String img; @SerializedName("title") private String title; @SerializedName("institute_id") private String institute_id; @SerializedName("institute_name") private String institute_name; @SerializedName("expired") private String expired; @SerializedName("status") private String status; @SerializedName("subscribe_box") private String subscribe_box; @SerializedName("expire_on") private String expire_on; @SerializedName("item_id") private String item_id; @SerializedName("rated") private String rated; private TopicListMain topicListMain; public String getRated() { return rated; } public void setRated(String rated) { this.rated = rated; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getInstitute_id() { return institute_id; } public void setInstitute_id(String institute_id) { this.institute_id = institute_id; } public String getInstitute_name() { return institute_name; } public void setInstitute_name(String institute_name) { this.institute_name = institute_name; } public String getExpired() { return expired; } public void setExpired(String expired) { this.expired = expired; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getSubscribe_box() { return subscribe_box; } public void setSubscribe_box(String subscribe_box) { this.subscribe_box = subscribe_box; } public String getExpire_on() { return expire_on; } public void setExpire_on(String expire_on) { this.expire_on = expire_on; } public String getItem_id() { return item_id; } public void setItem_id(String item_id) { this.item_id = item_id; } public TopicListMain getTopicListMain() { return topicListMain; } public void setTopicListMain(TopicListMain topicListMain) { this.topicListMain = topicListMain; } } class for topiclist_main public class TopicListMain { @SerializedName("data") private ArrayList<TopicDetails> topicDetailsArrayList; public ArrayList<TopicDetails> getTopicDetailsArrayList() { return topicDetailsArrayList; } public void setTopicDetailsArrayList(ArrayList<TopicDetails> topicDetailsArrayList) { this.topicDetailsArrayList = topicDetailsArrayList; }} class for topic details public class TopicDetails { @SerializedName("topic_id") private String topic_id; @SerializedName("title") private String title; @SerializedName("locked") private String locked; @SerializedName("lessons") private ArrayList<Lession> lessionArrayList; private LessionLIstMain lessionLIstMain; public LessionLIstMain getLessionLIstMain() { return lessionLIstMain; } public void setLessionLIstMain(LessionLIstMain lessionLIstMain) { this.lessionLIstMain = lessionLIstMain; } public String getTopic_id() { return topic_id; } public void setTopic_id(String topic_id) { this.topic_id = topic_id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLocked() { return locked; } public void setLocked(String locked) { this.locked = locked; } public ArrayList<Lession> getLessionArrayList() { return lessionArrayList; } public void setLessionArrayList(ArrayList<Lession> lessionArrayList) { this.lessionArrayList = lessionArrayList; }} i hope oneone will answer it soon. thanks in advanced. [1]: https://drive.google.com/open?id=0B9qgugNyvGRiWmRDNDFBOEt1WFU
0debug
static uint32_t rtas_set_allocation_state(uint32_t idx, uint32_t state) { sPAPRDRConnector *drc = spapr_drc_by_index(idx); sPAPRDRConnectorClass *drck; if (!drc) { return RTAS_OUT_PARAM_ERROR; } drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc); return drck->set_allocation_state(drc, state); }
1threat
React.js How to render component inside component? : <p>I am stuck. I have several seperate components on seperate files. If I render them in main.jsx like following: </p> <pre><code>ReactDOM.render(&lt;LandingPageBox/&gt;, document.getElementById("page-landing")); ReactDOM.render(&lt;TopPlayerBox topPlayersData={topPlayersData}/&gt;, document.getElementById("wrapper profile-data-wrapper")); ReactDOM.render(&lt;RecentGamesBox recentGamesData={recentGamesData}/&gt;, document.getElementById("history wrapper")); </code></pre> <p>Everything works fine, but I wonder if it is a good practice? Maybe it is possible to do something like there would be only one ReactDom.render like: </p> <pre><code>ReactDOM.render(&lt;LandingPageBox recentGamesData={recentGamesData} topPlayersData={topPlayersData}/&gt;, document.getElementById("page-landing")); </code></pre> <p>I tried different kinds of variatons of LandingPageBox to somehow include those other two components, but had no luck. They sometimes rendered outside the page and so on. I thought it should look something like this:</p> <pre><code>import React from 'react'; import RecentGames from '../RecentGames/RecentGames.jsx'; import TopPlayers from '../TopPlayers/TopPlayers.jsx'; import PageTop from './PageTop.jsx'; import PageBottom from './PageBottom.jsx'; class LandingPageBox extends React.Component { render() { return ( &lt;body className="page-landing"&gt; &lt;PageTop&gt; &lt;TopPlayers topPlayersData={this.props.topPlayersData} /&gt; &lt;/PageTop&gt; &lt;PageBottom&gt; &lt;RecentGames recentGamesData= {this.props.recentGamesData}/&gt; &lt;/PageBottom&gt; &lt;/body&gt; ); } } export default LandingPageBox; </code></pre> <p>But this code only renders PageTop and PageBottom, without player or game components. </p> <p>So my question would be, how to set up LandingPageBox file so that TopPlayers component would render inside PageTop component and RecentGames component would render inside PageBottom component? Thank you.</p>
0debug
Spark RDD: add field from RDD to other RDD : I'm using Pyspark and have to use RDDs (not dataframes) to do the following: I have two RDDs, rdd1, containing more than 100 fields with names and rdd2, containing one field called "city". rdd1 and rdd2 have the same number of rows (same length). rdd1 is like: >Row(name="Jack",age=35,state="California",..) Row(name"Jane", age=29,state="Florida",...) ... rdd2 is like: >Row(city="LA") Row(city="Miami") .. I would like rdd1 to become: >Row(name="Jack", age=35, state="California",...,city="LA") ... Everything I've tried just failed. Any advice?
0debug
kubectl YAML config file equivalent of "kubectl run ... -i --tty ..." : <p>I've been using "kubectl run" with assorted flags to run Jobs interactively, but have recently outgrown what I can do with those flags, and have graduated to using YAML config files to describe my jobs.</p> <p>However, I can't find an equivalent to the "-i" and "--tty" flags, to attach to the Job I'm creating. </p> <p>Is there an equivalent YAML spec for:</p> <pre><code>kubectl run myjob \ -i \ --tty \ --image=grc.io/myproj/myimg:mytag \ --restart=Never \ --rm \ -- \ my_command </code></pre> <p>Or is this maybe not the right approach?</p>
0debug
def check_type(test_tuple): res = True for ele in test_tuple: if not isinstance(ele, type(test_tuple[0])): res = False break return (res)
0debug
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 0 : <p>I don't know what ist wrong, it can read it, but then it tells me Index 1 out of bounds for length 0. What does it mean?</p> <pre><code>public class Kreisberechnung3 { public static void main(String[] args) { String einheit = args[1]; double radius = Double.parseDouble(args[0]); double umfang = 2.0 * 3.1415926 * radius; double flaeche = 3.1415926 * radius * radius; System.out.print("Umfang: "); System.out.print(umfang); System.out.println(" " + einheit); System.out.print("Fläche: "); System.out.print(flaeche); System.out.println(" " + einheit + '\u00b2'); } } </code></pre>
0debug
Get Records count of specified date-range from database, if no record present for one of the date then return count as '0' C# : I want List (containing count and date) of record from database for specifies date-range if for some date, records are not available in database then that date should be in list with count = 0 public JsonResult GetApplicationUsage(DateTime startDate, DateTime endDate) { var AppUsageGraph = appUsageLogRepository.GetDateWiseUsageAsync(startDate.Date, endDate.Date); return Json(AppUsageGraph); }
0debug
Crash Report for Flutter : <p>I am new to flutter. I developed one Wallpaper App using flutter and upload in playstore. Now i need to track crash report for that app. In Android have <a href="http://try.crashlytics.com/" rel="noreferrer">crashlytics</a> to all report crash and more fearure's. Is <a href="http://try.crashlytics.com/" rel="noreferrer">crashlytics</a> support in flutter ?. I looked <a href="https://pub.dartlang.org/packages/sentry" rel="noreferrer">sentry</a> plugin but it's not free. Any help Appreciable.</p>
0debug
Make a Tuple from two dictionaries in python : suppose i have a dictionary a={1:2,2:3} and b={3:4,4:5} I want to make a tuple such that t=({1:2,2:3},{3:4,4:5}) please help!
0debug
Kotlin Property: "Type parameter of a property must be used in its receiver type" : <p>I have the following simple Kotlin extension functions:</p> <pre><code>// Get the views of ViewGroup inline val ViewGroup.views: List&lt;View&gt; get() = (0..childCount - 1).map { getChildAt(it) } // Get the views of ViewGroup of given type inline fun &lt;reified T : View&gt; ViewGroup.getViewsOfType() : List&lt;T&gt; { return this.views.filterIsInstance&lt;T&gt;() } </code></pre> <p>This code compiles and works fine. But, I want the function <code>getViewsOfType</code> to be a property, just like the <code>views</code>. Android Studio even suggests it. I let AS do the refactoring and it generates this code:</p> <pre><code>inline val &lt;reified T : View&gt; ViewGroup.viewsOfType: List&lt;T&gt; get() = this.views.filterIsInstance&lt;T&gt;() </code></pre> <p>But this code doesn't compile. It causes error: "Type parameter of a property must be used in its receiver type"</p> <p>What is the issue here? Searching for help on this error doesn't seem to lead to an answer.</p>
0debug
Need help powershell : Need help in sorting out a data from my output and then display 'ALL OK' or 'NOT OK'. Invoke-Command -ComputerName XXXXX,XXXX -ScriptBlock { hastatus -sum; VXPRINT -VPl } -credential XXXXX -- SYSTEM STATE -- System State Frozen A XXXXXXXXXXXXX RUNNING 0 A XXXXXXXXXXXXX RUNNING 0 Once i get this output, I want to showonly a output saying ALL OK when STATE is RUNNING and if the STATE is Faulted or anyother string then say NOT OK.. Please help
0debug
static void spapr_rtc_class_init(ObjectClass *oc, void *data) { DeviceClass *dc = DEVICE_CLASS(oc); dc->realize = spapr_rtc_realize; dc->vmsd = &vmstate_spapr_rtc; spapr_rtas_register(RTAS_GET_TIME_OF_DAY, "get-time-of-day", rtas_get_time_of_day); spapr_rtas_register(RTAS_SET_TIME_OF_DAY, "set-time-of-day", rtas_set_time_of_day); }
1threat
breakpoint() using ipdb by default : <p>Is it possible that installing <em>ipdb</em> (or some other package written to do it explicitely) will result in <code>breakpoint()</code> running <em>ipdb</em> instead of <em>pdb</em> without binding <code>sys.breakpointhook()</code> to <em>ipdb</em>?</p> <p><a href="https://www.python.org/dev/peps/pep-0553/" rel="noreferrer">https://www.python.org/dev/peps/pep-0553/</a></p> <p>I'm not asking if ipdb does that or if it will, but if its possible to code that. I know that I can set environment variable <code>PYTHONBREAKPOINT=ipdb.set_trace</code>. The question is if its possible to trigger this behavior by just installing <code>ipdb</code>.</p>
0debug
Flutter - Custom Font not displaying : <p>This is an excerpt of my pubspec.yaml file:</p> <pre><code>flutter: uses-material-design: true fonts: - family: Coiny fonts: - asset: fonts/Coiny-Regular.ttf </code></pre> <p>I am trying to use the font called "Coiny" from the Google Fonts page. I created a fonts folder inside my root directory and put it in there.</p> <p>In my code, I do this:</p> <pre><code>new Text("Testtext", style: new TextStyle(fontFamily: "Coiny")), </code></pre> <p>But it has no effect. I have encountered a similar problem in the past with the Barrio font. But it seemed to work after some time, which is not the case with this one.</p>
0debug
please assist me to add google ads on my websitei tried they arent showing : i wish to get a guide on how to add google ads on html of my website i tried they are not showing <!DOCTYPE html> <html> <head> <title>WEB DEVELOPMENT TUTORIAL</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <header> <div class="main"> <div class="logo"> <img src="logo.jpg"> </div> <ul> <li class="active"><a href="#">Home</a></li> <li><a href="dailyposted.php">DAILY BETTING TIPS</a></li> <li><a href="megaposted.php">MEGAJACKPOT PREDICTIONS</a></li> <li><a href="midweekposted.php">MIDWEEKJACKPOT PREDICTIONS</a></li> <li><a href="https://www.goal.com">TRANSFER NEWS</a></li> </ul> </div> <div class="title"> <h1>SURE DAILY BETTING TIPS</h1> </div> <div class="button"> <a href="#" class="btn">WATCH VIDEO</a> <a href="#" class="btn">LEARN MORE</a> </div> i tried to add google auto ads here. The website shows nothing even after 4 hours.please help.is there any test ads for website please aslso <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <script> (adsbygoogle = window.adsbygoogle || []).push({ google_ad_client: "ca-pub-2870870041610409", enable_page_level_ads: true }); </script> </header> </body> </html>
0debug
void vnc_zlib_clear(VncState *vs) { if (vs->zlib_stream.opaque) { deflateEnd(&vs->zlib_stream); } buffer_free(&vs->zlib); }
1threat
compile c program on windows with assembleur code : hi i use dev cpp to compil the above code but a problem accure #include<stdio.h> int main(){ char s; __asm( "mov %ah, 1" "int 21h" "mov %ah,2" "mov %dl,%al" "int 21h" ); return 0; } the errer is > Error: junk `int 21hmov %ah' after expression Error: too many memory > references for `mov' so how to solve this peoblem and thank you
0debug
android Push notifications with Google Cloud Messaging Service : I am new in android development.I have to work on android GCM push notification. Am search lots of tutorials and videos but no one is helpful for me.I have to implement GCM in client project its urgent. Anyone help me to understand and how to work with GCM ?
0debug
How can I write following vector to csv file in r : <p><a href="https://i.stack.imgur.com/Xf96Z.png" rel="nofollow noreferrer">"tst2" is a matrix. I have converted in vector as C(tst2). I would like to write this vector/matrix into csv file </a></p>
0debug
static int aasc_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; AascContext *s = avctx->priv_data; int compr, i, stride, ret; if (buf_size < 4) if ((ret = ff_reget_buffer(avctx, s->frame)) < 0) { av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n"); return ret; } compr = AV_RL32(buf); buf += 4; buf_size -= 4; switch (compr) { case 0: stride = (avctx->width * 3 + 3) & ~3; for (i = avctx->height - 1; i >= 0; i--) { memcpy(s->frame->data[0] + i * s->frame->linesize[0], buf, avctx->width * 3); buf += stride; } break; case 1: bytestream2_init(&s->gb, buf, buf_size); ff_msrle_decode(avctx, (AVPicture*)s->frame, 8, &s->gb); break; default: av_log(avctx, AV_LOG_ERROR, "Unknown compression type %d\n", compr); } *got_frame = 1; if ((ret = av_frame_ref(data, s->frame)) < 0) return ret; return buf_size; }
1threat
List files recursively in Kotlin : <p>to list files in a directory with kotlin, i used list() and listFiles() functions:</p> <pre><code>File("/tmp").list().forEach { println(it) } File("/tmp").listFiles().forEach { println(it) } </code></pre> <p>but, how can i list files recursively?</p>
0debug
Can't install matplotlib on Mac (Python) : <p>I am French, I am a student in chemistry and I don't know much about Python. I need to install matplotlib on my Mac for my program to work fine, but I tried and it didn't work... Can you help me ? Thank you very much </p> <p><a href="https://i.stack.imgur.com/3MdLq.png" rel="nofollow noreferrer">enter image description here</a></p>
0debug
static int flic_decode_frame_24BPP(AVCodecContext *avctx, void *data, int *got_frame, const uint8_t *buf, int buf_size) { FlicDecodeContext *s = avctx->priv_data; GetByteContext g2; int pixel_ptr; unsigned char palette_idx1; unsigned int frame_size; int num_chunks; unsigned int chunk_size; int chunk_type; int i, j, ret; int lines; int compressed_lines; signed short line_packets; int y_ptr; int byte_run; int pixel_skip; int pixel_countdown; unsigned char *pixels; int pixel; unsigned int pixel_limit; bytestream2_init(&g2, buf, buf_size); if ((ret = ff_reget_buffer(avctx, s->frame)) < 0) return ret; pixels = s->frame->data[0]; pixel_limit = s->avctx->height * s->frame->linesize[0]; frame_size = bytestream2_get_le32(&g2); bytestream2_skip(&g2, 2); num_chunks = bytestream2_get_le16(&g2); bytestream2_skip(&g2, 8); if (frame_size > buf_size) frame_size = buf_size; if (frame_size < 16) frame_size -= 16; while ((frame_size > 0) && (num_chunks > 0) && bytestream2_get_bytes_left(&g2) >= 4) { int stream_ptr_after_chunk; chunk_size = bytestream2_get_le32(&g2); if (chunk_size > frame_size) { av_log(avctx, AV_LOG_WARNING, "Invalid chunk_size = %u > frame_size = %u\n", chunk_size, frame_size); chunk_size = frame_size; } stream_ptr_after_chunk = bytestream2_tell(&g2) - 4 + chunk_size; chunk_type = bytestream2_get_le16(&g2); switch (chunk_type) { case FLI_256_COLOR: case FLI_COLOR: ff_dlog(avctx, "Unexpected Palette chunk %d in non-palettized FLC\n", chunk_type); bytestream2_skip(&g2, chunk_size - 6); break; case FLI_DELTA: case FLI_DTA_LC: y_ptr = 0; compressed_lines = bytestream2_get_le16(&g2); while (compressed_lines > 0) { if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk) break; line_packets = bytestream2_get_le16(&g2); if (line_packets < 0) { line_packets = -line_packets; y_ptr += line_packets * s->frame->linesize[0]; } else { compressed_lines--; pixel_ptr = y_ptr; CHECK_PIXEL_PTR(0); pixel_countdown = s->avctx->width; for (i = 0; i < line_packets; i++) { if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk) break; pixel_skip = bytestream2_get_byte(&g2); pixel_ptr += (pixel_skip*3); pixel_countdown -= pixel_skip; byte_run = sign_extend(bytestream2_get_byte(&g2), 8); if (byte_run < 0) { byte_run = -byte_run; pixel = bytestream2_get_le24(&g2); CHECK_PIXEL_PTR(3 * byte_run); for (j = 0; j < byte_run; j++, pixel_countdown -= 1) { AV_WL24(&pixels[pixel_ptr], pixel); pixel_ptr += 3; } } else { if (bytestream2_tell(&g2) + 2*byte_run > stream_ptr_after_chunk) break; CHECK_PIXEL_PTR(2 * byte_run); for (j = 0; j < byte_run; j++, pixel_countdown--) { pixel = bytestream2_get_le24(&g2); AV_WL24(&pixels[pixel_ptr], pixel); pixel_ptr += 3; } } } y_ptr += s->frame->linesize[0]; } } break; case FLI_LC: av_log(avctx, AV_LOG_ERROR, "Unexpected FLI_LC chunk in non-palettized FLC\n"); bytestream2_skip(&g2, chunk_size - 6); break; case FLI_BLACK: memset(pixels, 0x00, s->frame->linesize[0] * s->avctx->height); break; case FLI_BRUN: y_ptr = 0; for (lines = 0; lines < s->avctx->height; lines++) { pixel_ptr = y_ptr; bytestream2_skip(&g2, 1); pixel_countdown = (s->avctx->width * 3); while (pixel_countdown > 0) { if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk) break; byte_run = sign_extend(bytestream2_get_byte(&g2), 8); if (byte_run > 0) { palette_idx1 = bytestream2_get_byte(&g2); CHECK_PIXEL_PTR(byte_run); for (j = 0; j < byte_run; j++) { pixels[pixel_ptr++] = palette_idx1; pixel_countdown--; if (pixel_countdown < 0) av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) (linea%d)\n", pixel_countdown, lines); } } else { byte_run = -byte_run; if (bytestream2_tell(&g2) + byte_run > stream_ptr_after_chunk) break; CHECK_PIXEL_PTR(byte_run); for (j = 0; j < byte_run; j++) { palette_idx1 = bytestream2_get_byte(&g2); pixels[pixel_ptr++] = palette_idx1; pixel_countdown--; if (pixel_countdown < 0) av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) at line %d\n", pixel_countdown, lines); } } } y_ptr += s->frame->linesize[0]; } break; case FLI_DTA_BRUN: y_ptr = 0; for (lines = 0; lines < s->avctx->height; lines++) { pixel_ptr = y_ptr; bytestream2_skip(&g2, 1); pixel_countdown = s->avctx->width; while (pixel_countdown > 0) { if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk) break; byte_run = sign_extend(bytestream2_get_byte(&g2), 8); if (byte_run > 0) { pixel = bytestream2_get_le24(&g2); CHECK_PIXEL_PTR(3 * byte_run); for (j = 0; j < byte_run; j++) { AV_WL24(pixels + pixel_ptr, pixel); pixel_ptr += 3; pixel_countdown--; if (pixel_countdown < 0) av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d)\n", pixel_countdown); } } else { byte_run = -byte_run; if (bytestream2_tell(&g2) + 3 * byte_run > stream_ptr_after_chunk) break; CHECK_PIXEL_PTR(3 * byte_run); for (j = 0; j < byte_run; j++) { pixel = bytestream2_get_le24(&g2); AV_WL24(pixels + pixel_ptr, pixel); pixel_ptr += 3; pixel_countdown--; if (pixel_countdown < 0) av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d)\n", pixel_countdown); } } } y_ptr += s->frame->linesize[0]; } break; case FLI_COPY: case FLI_DTA_COPY: if (chunk_size - 6 > (unsigned int)(FFALIGN(s->avctx->width, 2) * s->avctx->height)*3) { av_log(avctx, AV_LOG_ERROR, "In chunk FLI_COPY : source data (%d bytes) " \ "bigger than image, skipping chunk\n", chunk_size - 6); bytestream2_skip(&g2, chunk_size - 6); } else { for (y_ptr = 0; y_ptr < s->frame->linesize[0] * s->avctx->height; y_ptr += s->frame->linesize[0]) { pixel_countdown = s->avctx->width; pixel_ptr = 0; while (pixel_countdown > 0) { pixel = bytestream2_get_le24(&g2); AV_WL24(&pixels[y_ptr + pixel_ptr], pixel); pixel_ptr += 3; pixel_countdown--; } if (s->avctx->width & 1) bytestream2_skip(&g2, 3); } } break; case FLI_MINI: bytestream2_skip(&g2, chunk_size - 6); break; default: av_log(avctx, AV_LOG_ERROR, "Unrecognized chunk type: %d\n", chunk_type); break; } if (stream_ptr_after_chunk - bytestream2_tell(&g2) >= 0) { bytestream2_skip(&g2, stream_ptr_after_chunk - bytestream2_tell(&g2)); } else { av_log(avctx, AV_LOG_ERROR, "Chunk overread\n"); break; } frame_size -= chunk_size; num_chunks--; } if ((bytestream2_get_bytes_left(&g2) != 0) && (bytestream2_get_bytes_left(&g2) != 1)) av_log(avctx, AV_LOG_ERROR, "Processed FLI chunk where chunk size = %d " \ "and final chunk ptr = %d\n", buf_size, bytestream2_tell(&g2)); if ((ret = av_frame_ref(data, s->frame)) < 0) return ret; *got_frame = 1; return buf_size; }
1threat
Creating a class library in visual studio code : <p>It might be a silly question, Let's say I don't have a Windows OS, have a Linux. I have created a .Net core console app, also want to create a class library and reference it in console app. I can't find if i am able to do it also couldn't find a sample on Microsoft .Net core page. Is there an extension in vs code? Or isn't it possible with it? If i am mistaken could you please guide me?</p>
0debug
Whats going wrong in the attached image? : I'm not able to set the below array of objects to the User class in TypeScript. let user: User[] = [{name: 'Naveen', address: [{'city': 'Bangalore'}]}]; ```class User { private name: string; private address: Address[]; constructor(name: string, address: Address[]) { this.name = name; this.address = address; } public set _name(name: string) { this.name = name; } public get _name() { return this.name; } } class Address { private city: string; constructor(city: string) { this.city = city; } public set _city(city: string) { this.city = city; } public get _city() { return this.city; } } let user: User[] = [{name: 'Naveen', address: [{'city': 'Bangalore'}]}];
0debug
Java: Order List of objects by values : <p>Hey everybody I have object which stores multiple integer values. I want it to sort it multiple times by descending order, one time descending by "Wins" value, another time descending by "Played" value etc... How can I do that ?</p>
0debug
is it possible to program in c language to search something in google and show the first search result as output? : <p>i am curious to know is it possible to write program in c language to search something in google and show the first search result as output accessing network? Is yes please tell me how with some codes.</p>
0debug
how to convert a string to an integer in java : <p>i get an error when try to convert a string to an integer</p> <pre><code> public static void main(String[] args){ String rate= "3.7"; int age=20; boolean istrue=true; double salary=60.4; //convert to String String Newsalary=String.valueOf(salary); String Newage=String.valueOf(age); String Newistrue=String.valueOf(istrue); //convert to Integer int Newrate= Integer.parseInt(rate);//here is the probleme int NewsalaryInt=(int) salary; //convert to double double NewrateDouble=Double.parseDouble(rate); double NewageDouble=(double) age; } } </code></pre> <p>the problem is when i convert rate varaible which is String to an integer</p>
0debug
Alpine Dockerfile Advantages of --no-cache Vs. rm /var/cache/apk/* : <p>When creating Dockerfiles using the Alpine image, I have often seen the use of the <code>apk --no-cache</code> and other times it is committed and instead I see <code>rm /var/cache/apk/*</code>.</p> <p>I am curious to know making use of the <code>--no-cache</code> eliminates the need to later do a <code>rm /var/cache/apk/*</code>. I would also like to know if one style is favored over another.</p>
0debug
Impact of matrix sparsity on cblas_gemm and cublasSgemm : I have recently discovered that the performance of a cblas_sgemm call for matrix multiplication dramatically improves if the matrices have a "large" number of zeros in them. It improves to the point that it beats its cublas cousin by more than a 100 times. This could be most probably attributed to some **automatic detection of sparsity** and suitable format conversion by cblas_sgemm function. Unfortunately, no such behavior is exhibited by its cuda counterpart i.e. cublasSgemm. So, the question is, how can I get the same type of optimization on cublasSgemm for matrices that **may have** a large number of zeros. And what technique does cblas_sgemm use to automatically adjust to sparse matrices? Please, do not recommend cuSparse / CUSP etc because 1. I am not sure about the sparsity of input matrices beforehand 2. I am working on an iterative algorithm where for initial few iterations the matrices **may be** sparse but gradually become dense as time goes on. Thanks in advance
0debug
from collections import Counter def count_Occurrence(tup, lst): count = 0 for item in tup: if item in lst: count+= 1 return count
0debug
Scheduling in a webpage release : <p>I have just started to learn html and css and curious to know if there's a way of scheduling changes to html code.</p> <p>To give you guys an idea of what I am looking to do...</p> <p>I am building a one page website that displays a quote or comment. I want this to change every day and wondered if there's a way of scheduling in that change so I don't have to change it at the start of every day.</p> <p>Helps to make life a little easier for me!</p> <p>Thanks so much</p> <p>Tom </p>
0debug
Refresh Header after Login in Angular2 : <p>So I have a header component that displays either the User's name or "Sign In" depending on whether they are logged in or not. I also have a Login component that does all of the business logic of logging in. They currently do not have a parent / child relationship.</p> <p>When the User logs in, the header does not refresh or change unless a full page refresh is done in the browser. I've been doing a lot of searching and reading online about different ways to do this. ngOnChanges, NgZone, ApplicationRef, and ChangeDetectorRef seem to be the most popular. I'm trying to implement this behavior in ChangeDetectorRef as this seems to be most relevant to my situation. However, I can't seem to find actual examples of how to use this. </p> <p>I've coded it up but it does not seem to do anything. Any advice would be appreciated. I'd even accept that I'm taking the wrong approach and need to use another solution besides ChangeDetectorRef.</p> <p><strong>LoginComponent</strong></p> <pre><code>import { Component, OnInit } from '@angular/core'; import { Response } from '@angular/http'; import { Router } from '@angular/router'; import { AuthenticationService } from '../service/authentication.service'; @Component({ selector: 'login-component', templateUrl: './login.component.html' }) export class LoginComponent implements OnInit { constructor(private router: Router, private authenticationService: AuthenticationService) { } ngOnInit() { // Resets the login service. // This is one of the events that should cause the refresh. this.authenticationService.logout(); } login() { /* Authentication code This is the other event that should cause the refresh. */ } } </code></pre> <p><strong>HeaderComponent</strong></p> <pre><code>import { ChangeDetectorRef, ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { Instance } from '../../entity/instance'; @Component({ selector: 'header-component', templateUrl: './html/header.component.html', changeDetection: ChangeDetectionStrategy.OnPush }) export class HeaderComponent { userName: string; constructor(private ref: ChangeDetectorRef) { this.ref.markForCheck(); } ngOnInit(): void { var currentUser = JSON.parse(localStorage.getItem('currentUser')); this.userName = currentUser &amp;&amp; currentUser.full_name; if (!this.userName) { this.userName = "User Name"; } } } </code></pre> <p><strong>AppComponent</strong></p> <pre><code>import { ChangeDetectorRef, ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { Instance } from './entity/instance'; import { InstanceService } from './service/instance.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], changeDetection: ChangeDetectionStrategy.OnPush }) export class AppComponent implements OnInit { instances: Instance[]; constructor(private instanceService: InstanceService) { } ngOnInit(): void { } } </code></pre> <p><strong>app.component.html</strong></p> <pre><code>&lt;header-component&gt;&lt;/header-component&gt; &lt;router-outlet&gt;&lt;/router-outlet&gt; </code></pre>
0debug
Why compilation error is giving in this java code? : <p>I was trying to compile the code and it shows a compilation error. Can anyone help me out to understand what is wrong in the code? I guess there should be a default constructor inside Mammal class but why?</p> <pre><code>class Mammal { public Mammal(int age) { System.out.print("Mammal"); } } public class Platypus extends Mammal { public Platypus() { System.out.print("Platypus"); } public static void main(String[] args) { new Mammal(7); //Compilation Error } } </code></pre>
0debug
static inline void gen_intermediate_code_internal(X86CPU *cpu, TranslationBlock *tb, bool search_pc) { CPUState *cs = CPU(cpu); CPUX86State *env = &cpu->env; DisasContext dc1, *dc = &dc1; target_ulong pc_ptr; uint16_t *gen_opc_end; CPUBreakpoint *bp; int j, lj; uint64_t flags; target_ulong pc_start; target_ulong cs_base; int num_insns; int max_insns; pc_start = tb->pc; cs_base = tb->cs_base; flags = tb->flags; dc->pe = (flags >> HF_PE_SHIFT) & 1; dc->code32 = (flags >> HF_CS32_SHIFT) & 1; dc->ss32 = (flags >> HF_SS32_SHIFT) & 1; dc->addseg = (flags >> HF_ADDSEG_SHIFT) & 1; dc->f_st = 0; dc->vm86 = (flags >> VM_SHIFT) & 1; dc->cpl = (flags >> HF_CPL_SHIFT) & 3; dc->iopl = (flags >> IOPL_SHIFT) & 3; dc->tf = (flags >> TF_SHIFT) & 1; dc->singlestep_enabled = cs->singlestep_enabled; dc->cc_op = CC_OP_DYNAMIC; dc->cc_op_dirty = false; dc->cs_base = cs_base; dc->tb = tb; dc->popl_esp_hack = 0; dc->mem_index = 0; if (flags & HF_SOFTMMU_MASK) { dc->mem_index = cpu_mmu_index(env); } dc->cpuid_features = env->features[FEAT_1_EDX]; dc->cpuid_ext_features = env->features[FEAT_1_ECX]; dc->cpuid_ext2_features = env->features[FEAT_8000_0001_EDX]; dc->cpuid_ext3_features = env->features[FEAT_8000_0001_ECX]; dc->cpuid_7_0_ebx_features = env->features[FEAT_7_0_EBX]; #ifdef TARGET_X86_64 dc->lma = (flags >> HF_LMA_SHIFT) & 1; dc->code64 = (flags >> HF_CS64_SHIFT) & 1; #endif dc->flags = flags; dc->jmp_opt = !(dc->tf || cs->singlestep_enabled || (flags & HF_INHIBIT_IRQ_MASK) #ifndef CONFIG_SOFTMMU || (flags & HF_SOFTMMU_MASK) #endif ); #if 0 if (!dc->addseg && (dc->vm86 || !dc->pe || !dc->code32)) printf("ERROR addseg\n"); #endif cpu_T[0] = tcg_temp_new(); cpu_T[1] = tcg_temp_new(); cpu_A0 = tcg_temp_new(); cpu_tmp0 = tcg_temp_new(); cpu_tmp1_i64 = tcg_temp_new_i64(); cpu_tmp2_i32 = tcg_temp_new_i32(); cpu_tmp3_i32 = tcg_temp_new_i32(); cpu_tmp4 = tcg_temp_new(); cpu_ptr0 = tcg_temp_new_ptr(); cpu_ptr1 = tcg_temp_new_ptr(); cpu_cc_srcT = tcg_temp_local_new(); gen_opc_end = tcg_ctx.gen_opc_buf + OPC_MAX_SIZE; dc->is_jmp = DISAS_NEXT; pc_ptr = pc_start; lj = -1; num_insns = 0; max_insns = tb->cflags & CF_COUNT_MASK; if (max_insns == 0) max_insns = CF_COUNT_MASK; gen_tb_start(); for(;;) { if (unlikely(!QTAILQ_EMPTY(&cs->breakpoints))) { QTAILQ_FOREACH(bp, &cs->breakpoints, entry) { if (bp->pc == pc_ptr && !((bp->flags & BP_CPU) && (tb->flags & HF_RF_MASK))) { gen_debug(dc, pc_ptr - dc->cs_base); break; } } } if (search_pc) { j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf; if (lj < j) { lj++; while (lj < j) tcg_ctx.gen_opc_instr_start[lj++] = 0; } tcg_ctx.gen_opc_pc[lj] = pc_ptr; gen_opc_cc_op[lj] = dc->cc_op; tcg_ctx.gen_opc_instr_start[lj] = 1; tcg_ctx.gen_opc_icount[lj] = num_insns; } if (num_insns + 1 == max_insns && (tb->cflags & CF_LAST_IO)) gen_io_start(); pc_ptr = disas_insn(env, dc, pc_ptr); num_insns++; if (dc->is_jmp) break; if (dc->tf || dc->singlestep_enabled || (flags & HF_INHIBIT_IRQ_MASK)) { gen_jmp_im(pc_ptr - dc->cs_base); gen_eob(dc); break; } if (tcg_ctx.gen_opc_ptr >= gen_opc_end || (pc_ptr - pc_start) >= (TARGET_PAGE_SIZE - 32) || num_insns >= max_insns) { gen_jmp_im(pc_ptr - dc->cs_base); gen_eob(dc); break; } if (singlestep) { gen_jmp_im(pc_ptr - dc->cs_base); gen_eob(dc); break; } } if (tb->cflags & CF_LAST_IO) gen_io_end(); gen_tb_end(tb, num_insns); *tcg_ctx.gen_opc_ptr = INDEX_op_end; if (search_pc) { j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf; lj++; while (lj <= j) tcg_ctx.gen_opc_instr_start[lj++] = 0; } #ifdef DEBUG_DISAS if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) { int disas_flags; qemu_log("----------------\n"); qemu_log("IN: %s\n", lookup_symbol(pc_start)); #ifdef TARGET_X86_64 if (dc->code64) disas_flags = 2; else #endif disas_flags = !dc->code32; log_target_disas(env, pc_start, pc_ptr - pc_start, disas_flags); qemu_log("\n"); } #endif if (!search_pc) { tb->size = pc_ptr - pc_start; tb->icount = num_insns; } }
1threat
Trying to run a C program on unix but a little confused with how input file is handled : I've tried to search for this but I'm having trouble figuring how to phrase my question so I figured I'd just ask here. So I'm trying to run a C program in a unix environment and I have an input file as well. The teacher said we can run it by typing in "gcc programName ./a.out inputFile" or "gcc programName ./a.out inputFile > viewFile" My question is how is this handled within the C program? Like is the input file being added as a parameter for main (or like its name or something) or is it acting like it's reading from system.in or something else? I'm getting a message saying that there's an error opening the input file and I have "int main(int argc, char* argv[])". If someone could explain what's going on and how the input file is handled, I'd really appreciate it.
0debug
Fortran error in geany : i am trying to run the sub routine in geany, bur it keeps me giving the following warning NPJ(I,J) = DBLE(((2)/((X(I+1))-(X(I-1))))*DBLE(-((1)/(X(I+1)-X(I)))-((1)/(X(I)- X(I-1)))))+ & 1 Warning: Possible change of value in conversion from REAL(8) to INTEGER(4) at (1) [ERROR][1] [1]: https://i.stack.imgur.com/dbITw.png AND everytime i run the program it gives that I am getting divisions by zero thanks a lot
0debug
Can't write number with FileWriter : <p>This is my code and I want b[i] will be write to the file name test.txt but it is not working. It's just write something like symbols. Thanks for helping.</p> <pre><code>public class btl { public static boolean IsPrime(int n) { if (n &lt; 2) { return false; } int squareRoot = (int) Math.sqrt(n); for (int i = 2; i &lt;= squareRoot; i++) { if (n % i == 0) { return false; } } return true; } public static void main(String args[]) { Scanner scanIn = new Scanner(System.in); int first = 0; int second = 0; try { System.out.println("Input First Number"); first = scanIn.nextInt(); System.out.println("Input Second Number"); second= scanIn.nextInt(); } catch(Exception e) { System.out.println("Something wrong!"); } int x = first; int y = second; int a; int[] b = new int[y]; Thread threadA = new Thread(new Runnable() { @Override public void run() { int c=0; for(int i=x; i&lt;y; i++) { if(IsPrime(i)) { b[c] = i; System.out.println(b[c]); c++; } } } }); threadA.start(); try(FileWriter fw = new FileWriter("test.txt")){ for(int i =0; i&lt;y; i++) { fw.write(b[i]); } } catch(IOException exc) { System.out.println("EROR! " + exc); } } } </code></pre> <p><a href="https://i.stack.imgur.com/6vAKC.png" rel="nofollow noreferrer">This is my display console</a></p> <p><a href="https://i.stack.imgur.com/UytDO.png" rel="nofollow noreferrer">And this is file "test.txt"</a></p> <p>I don't know why FileWriter writes symbols in file text.txt. I want it's number of array b[i].</p>
0debug
How can I protect a extarcted embedded resource? : <p>So I am working on a project where I need to build a login application that grants access to a embedded executable resource. I've been searching and didn't found a way to do that. From what a gatter, I cannot just execute without extracting it. So there must be a way for me to put a lock on the executable, like a password, this way, only my program will be able to access it. I do not have the source code for the executable. Is this possible? Thanks</p>
0debug
int text_console_init(QemuOpts *opts, CharDriverState **_chr) { CharDriverState *chr; TextConsole *s; unsigned width; unsigned height; chr = g_malloc0(sizeof(CharDriverState)); if (n_text_consoles == 128) { fprintf(stderr, "Too many text consoles\n"); exit(1); } text_consoles[n_text_consoles] = chr; n_text_consoles++; width = qemu_opt_get_number(opts, "width", 0); if (width == 0) width = qemu_opt_get_number(opts, "cols", 0) * FONT_WIDTH; height = qemu_opt_get_number(opts, "height", 0); if (height == 0) height = qemu_opt_get_number(opts, "rows", 0) * FONT_HEIGHT; if (width == 0 || height == 0) { s = new_console(NULL, TEXT_CONSOLE); } else { s = new_console(NULL, TEXT_CONSOLE_FIXED_SIZE); } if (!s) { g_free(chr); return -EBUSY; } s->chr = chr; s->g_width = width; s->g_height = height; chr->opaque = s; chr->chr_set_echo = text_console_set_echo; *_chr = chr; return 0; }
1threat
How to calculate the energy of the function tri(2t+5/6) using matlab? : <p>How to calculate the energy of the function tri(2t+5/6) using matlab?[where tri is triangular pulse function]</p>
0debug
Select an element place after a element with Jquery : I have this HTML code: <input type="password" name="USR_NewPassword" class="form-control" maxlength="50" required> <span class="input-group-addon"> <a href=""><i class="fa fa-eye"></i></a> </span> Why this isn't working if I would like to select the `<i>` element if clicked ? $('input[name="USR_NewPassword"] span > a').on('click', function(event) { ... });
0debug
NameError: name '*' is not defined : <p>Why this line <code>add(root, sum, 0)</code> gets <code>NameError: name 'add' is not defined</code> error?</p> <pre><code>class Solution: def rob(root: TreeNode) -&gt; int: sum = [0, 0] add(root, sum, 0) if sum[0] &lt; sum[1]: return sum[1] else: return sum[0] def add(node: TreeNode, sum: List[int], index: int): if not node: return sum[index] += node.val index += 1 if index &gt;= len(sum): index = 0; add(node.left, sum, index) add(node.right, sum, index) </code></pre>
0debug
static void event_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); dc->bus_type = TYPE_SCLP_EVENTS_BUS; dc->unplug = qdev_simple_unplug_cb; dc->init = event_qdev_init; dc->exit = event_qdev_exit; }
1threat
My while loop conditions aren't evaluating them as I'm expecting : <p>I'm trying to make an input validation function that checks to see if cin fails (this works fine) and I'm trying to also make it check to see if it's within the min max range that I pass by variable to the function. </p> <p>I've already tried messing around with different conditions and evaluating it by hand but it seems that either I'm missing some small minutia of the while loop or something total different.</p> <pre><code>void isValid(int &amp;value, std::string message, int min, int max) { while(((std::cout &lt;&lt; message) &amp;&amp; !(std::cin &gt;&gt; value)) &amp;&amp; ((value &gt;= min) &amp;&amp; (value &lt;= max))) { std::cout &lt;&lt; "Error with input" &lt;&lt; std::endl; std::cin.clear(); std::cin.ignore(std::numeric_limits&lt;int&gt;::max(), '\n'); } </code></pre> <p>I expect the output of isValid(-1, "Enter the test score: ", 0, 100) to keep asking for a valid input, but it accepts it as is.</p>
0debug
How to get ComputeIfPresent working with Map within Map? : <p>When trying to alter a Map using the <strong>computeIfPresent()</strong> method I have trouble implementing this method when I use an innerMap. </p> <p><strong>This works:</strong></p> <pre><code>Map&lt;String, Integer&gt; mapOne = new HashMap&lt;&gt;(); mapOne.computeIfPresent(key, (k, v) -&gt; v + 1); </code></pre> <p><strong>This doesn't work:</strong></p> <pre><code>Map&lt;String, Map&lt;String, Integer&gt;&gt; mapTwo = new HashMap&lt;&gt;(); mapTwo.computeIfPresent(key, (k, v) -&gt; v.computeIfPresent(anotherKey, (x, y) -&gt; y + 1); </code></pre> <p>In the second example I get the following error message: "Bad return type in lambda expression: Integer cannot be converted to <code>Map&lt;String, Integer&gt;</code>". My IDE recognizes v as a Map. But the function doesn't work.</p> <p>Apparently the method returns an Integer, but I fail to see how this differs from the first method with no Innermap. So far I haven't found a similar case online.</p> <p>How can I get this to work?</p>
0debug
TemplateNotFound error when running simple Airflow BashOperator : <p>I'm trying to write our first Airflow DAG, and I'm getting the following error when I try to list the tasks using command <code>airflow list_tasks orderwarehouse</code>:</p> <pre><code>Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/airflow/models.py", line 2038, in resolve_template_files setattr(self, attr, env.loader.get_source(env, content)[0]) File "/usr/local/lib/python2.7/site-packages/jinja2/loaders.py", line 187, in get_source raise TemplateNotFound(template) TemplateNotFound: ./home/deploy/airflow-server/task_scripts/orderwarehouse/load_warehouse_tables.sh </code></pre> <p>This DAG is not supposed to use a template. I'm only trying to run the shell script in the specified location per the instructions in <a href="https://airflow.incubator.apache.org/_modules/bash_operator.html#BashOperator" rel="noreferrer">the docs</a>. The shell script does exist in that location and is spelled correctly. My DAG looks like this:</p> <pre><code>from airflow import DAG from airflow.operators.bash_operator import BashOperator default_args = { 'owner': 'airflow', 'depends_on_past': False, 'start_date': datetime(2015, 6, 1), 'email': ['airflow@airflow.com'], 'email_on_failure': False, 'email_on_retry': False, 'retries': 1, 'retry_delay': timedelta(minutes=5), # 'queue': 'bash_queue', # 'pool': 'backfill', # 'priority_weight': 10, # 'end_date': datetime(2016, 1, 1), } orderwarehouse = DAG('orderwarehouse', default_args=default_args) load_mysql = BashOperator( task_id='load_warehouse_mysql', bash_command='./home/deploy/airflow-server/task_scripts/orderwarehouse/load_warehouse_tables.sh', dag=orderwarehouse) </code></pre> <p>Not sure why it thinks it needs to look for a Jinja template. Running out of ideas on this one, would appreciate if anyone can point me to where I'm going astray. Thanks.</p>
0debug
const char *cpu_parse_cpu_model(const char *typename, const char *cpu_model) { ObjectClass *oc; CPUClass *cc; Error *err = NULL; gchar **model_pieces; const char *cpu_type; model_pieces = g_strsplit(cpu_model, ",", 2); oc = cpu_class_by_name(typename, model_pieces[0]); if (oc == NULL) { g_strfreev(model_pieces); return NULL; } cpu_type = object_class_get_name(oc); cc = CPU_CLASS(oc); cc->parse_features(cpu_type, model_pieces[1], &err); g_strfreev(model_pieces); if (err != NULL) { error_report_err(err); return NULL; } return cpu_type; }
1threat
Is it safe to delete /root/sent in ubuntu? : <p>I have a server running ubuntu 14.04 What is inside of /root/sent? It is currently taking of 34GB of my server space. It is safe to delete it? </p>
0debug
How to call another classes super class? : <p>Lets say I have three classes, A,B,C. B inherits A, is there a way to access the getVal method of Class A, in C? </p> <pre><code> class A { getVal method } class B extends A { } Class C { main() { B x = new B x.getVal? } </code></pre>
0debug
static void mpegts_push_data(void *opaque, const uint8_t *buf, int buf_size, int is_start) { PESContext *pes = opaque; MpegTSContext *ts = pes->stream->priv_data; AVStream *st; const uint8_t *p; int len, code, codec_type, codec_id; if (is_start) { pes->state = MPEGTS_HEADER; pes->data_index = 0; } p = buf; while (buf_size > 0) { switch(pes->state) { case MPEGTS_HEADER: len = PES_START_SIZE - pes->data_index; if (len > buf_size) len = buf_size; memcpy(pes->header + pes->data_index, p, len); pes->data_index += len; p += len; buf_size -= len; if (pes->data_index == PES_START_SIZE) { #if 0 av_hex_dump(pes->header, pes->data_index); #endif if (pes->header[0] == 0x00 && pes->header[1] == 0x00 && pes->header[2] == 0x01) { code = pes->header[3] | 0x100; if (!((code >= 0x1c0 && code <= 0x1df) || (code >= 0x1e0 && code <= 0x1ef))) goto skip; if (!pes->st) { if (code >= 0x1c0 && code <= 0x1df) { codec_type = CODEC_TYPE_AUDIO; codec_id = CODEC_ID_MP2; } else { codec_type = CODEC_TYPE_VIDEO; codec_id = CODEC_ID_MPEG1VIDEO; } st = av_new_stream(pes->stream, pes->pid); if (st) { st->priv_data = pes; st->codec.codec_type = codec_type; st->codec.codec_id = codec_id; pes->st = st; } } pes->state = MPEGTS_PESHEADER_FILL; pes->total_size = (pes->header[4] << 8) | pes->header[5]; if (pes->total_size) pes->total_size += 6; pes->pes_header_size = pes->header[8] + 9; } else { skip: pes->state = MPEGTS_SKIP; continue; } } break; case MPEGTS_PESHEADER_FILL: len = pes->pes_header_size - pes->data_index; if (len > buf_size) len = buf_size; memcpy(pes->header + pes->data_index, p, len); pes->data_index += len; p += len; buf_size -= len; if (pes->data_index == pes->pes_header_size) { const uint8_t *r; unsigned int flags; flags = pes->header[7]; r = pes->header + 9; pes->pts = AV_NOPTS_VALUE; pes->dts = AV_NOPTS_VALUE; if ((flags & 0xc0) == 0x80) { pes->pts = get_pts(r); r += 5; } else if ((flags & 0xc0) == 0xc0) { pes->pts = get_pts(r); r += 5; pes->dts = get_pts(r); r += 5; } pes->state = MPEGTS_PAYLOAD; } break; case MPEGTS_PAYLOAD: if (pes->total_size) { len = pes->total_size - pes->data_index; if (len > buf_size) len = buf_size; } else { len = buf_size; } if (len > 0) { AVPacket *pkt = ts->pkt; if (pes->st && av_new_packet(pkt, len) == 0) { memcpy(pkt->data, p, len); pkt->stream_index = pes->st->index; pkt->pts = pes->pts; pes->pts = AV_NOPTS_VALUE; pes->dts = AV_NOPTS_VALUE; ts->stop_parse = 1; return; } } buf_size = 0; break; case MPEGTS_SKIP: buf_size = 0; break; } } }
1threat
Why does -Xrs reduce performance : <p>From IBM:</p> <blockquote> <p><strong>-Xrs</strong></p> <p>Disables signal handling in the JVM.</p> <p><strong>-Xrs</strong></p> <p>Setting -Xrs prevents the Java™ run time environment from handling any internally or externally generated signals such as SIGSEGV and SIGABRT. Any signals that are raised are handled by the default operating system handlers. <strong>Disabling signal handling in the JVM reduces performance by approximately 2-4%, depending on the application.</strong></p> <p><strong>-Xrs:sync</strong></p> <p>On UNIX systems, this option disables signal handling in the JVM for SIGSEGV, SIGFPE, SIGBUS, SIGILL, SIGTRAP, andSIGABRT signals. However, the JVM still handles the SIGQUIT and SIGTERM signals, among others. As with -Xrs, the use of <strong>-Xrs:sync reduces performance by approximately 2-4%, depending on the application.</strong></p> <p><strong>Note:</strong> Setting this option prevents dumps being generated by the JVM for signals such as SIGSEGV and SIGABRT, because the JVM is no longer intercepting these signals.</p> </blockquote> <p><a href="https://www-01.ibm.com/support/knowledgecenter/SSYKE2_7.0.0/com.ibm.java.aix.70.doc/diag/appendixes/cmdline/Xrs.html">https://www-01.ibm.com/support/knowledgecenter/SSYKE2_7.0.0/com.ibm.java.aix.70.doc/diag/appendixes/cmdline/Xrs.html</a></p> <p>From my understanding, <code>-Xrs</code> is really used to prevent dumps from being generated when certain OS Signals are intercepted.</p> <p>Since the JVM is no longer intercepting and handling these signals, it would stand to reason this would <em>increase</em> performance, not <em>decrease</em> it as claimed by IBM.</p> <p>Why does <code>-Xrs</code> reduce performance?</p>
0debug
unsigned long find_next_bit(const unsigned long *addr, unsigned long size, unsigned long offset) { const unsigned long *p = addr + BITOP_WORD(offset); unsigned long result = offset & ~(BITS_PER_LONG-1); unsigned long tmp; if (offset >= size) { return size; } size -= result; offset %= BITS_PER_LONG; if (offset) { tmp = *(p++); tmp &= (~0UL << offset); if (size < BITS_PER_LONG) { goto found_first; } if (tmp) { goto found_middle; } size -= BITS_PER_LONG; result += BITS_PER_LONG; } while (size & ~(BITS_PER_LONG-1)) { if ((tmp = *(p++))) { goto found_middle; } result += BITS_PER_LONG; size -= BITS_PER_LONG; } if (!size) { return result; } tmp = *p; found_first: tmp &= (~0UL >> (BITS_PER_LONG - size)); if (tmp == 0UL) { return result + size; } found_middle: return result + bitops_ffsl(tmp); }
1threat
Connection to SQL Workbench/J gets disconnected frequently : <p>The connection to SQL Workbench/J gets disconnected very frequently. Where can I change the settings so that it does not lose the connections for atleast an hour.</p> <p>Thanks</p>
0debug
Does not return result - PHP/JavaScript : I am trying to make a table where in the result site returns a value but for now nothing appears. I really appreciate your help. <tr> <th>Objetivo 1</th> <th> <div class="input-field col s12"> <input id="DataInicio" type = "date" class = "datepicker" name = "DataInicio" /> <label for="datainicio"></label> </div> </th> <th> <div class="input-field col s12"> <input id="DataFim" type = "date" class = "datepicker" name = "DataFim" /> <label for="datafim"></label> </div> </th> <th> <div class="input-field col s12"> <input id="avInicial1" type="text" class="validate" autocomplete="off" name="AvInicial" onchange="calculaResultado(1)"> <label for="avinicial"></label> </div> </th> <th> <div class="input-field col s12"> <input id="meta1" type="text" class="validate" autocomplete="off" name="Meta" onchange="calculaResultado(1)"> <label for="meta"></label> </div> </th> <th> <div class="input-field col s12"> <input id="AvIntercalar" type="text" class="validate" autocomplete="off" name="AvIntercalar"> <label for="avintercalar"></label> </div> </th> <th> <div class="input-field col s12"> <input id="avFinal1" type="text" class="validate" autocomplete="off" name="Avfinal" onchange="calculaResultado(1)"> <label for="avfinal"></label> </div> </th> <th> <div class="input-field col s12"> <input disabled id="resultado1"/> </div> </th> </tr> <script> (function calculaResultado(x){ console.log(x); a = document.getElementById('avInicial' + x).value; b = document.getElementById('meta' + x).value; c = document.getElementById('avFinal' + x).value; const resultado = ((c*100)/b); if(b === c){ return 1; //100% } else if (a > c) { return 0; // 0% } else { return resultado; } document.getElementById('resultado' + x).value = parseInt(resultado); })(); When I run and enter the values nothing happens in the result column. -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
0debug
Calling function with different arguments produces the same output. (C) : <p>I'm trying to make a program to generate 2 random numbers and print them to the screen. This is achieved by calling the Numbers function twice and assigning the value to num1 and num2 then calling PrintMsg twice also with those variables but instead the function prints the first value twice. </p> <p>In the debugger num1 and num2 are being set to 2 different numbers and the mode variable is being successfully passed through to the PrintMsg function.</p> <pre><code>// C program to generate random numbers #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; #include&lt;time.h&gt; int Numbers() { bool valid = false; int randNum; srand(time(0)); while(valid != true) { randNum = rand() % 100; if (randNum &gt; 0 &amp;&amp; randNum &lt;= 6) { valid = true; } } return(randNum); } void PrintMsg(int x, int mode) { if (mode == 1) { switch(x) { case 1: printf(" %d ", x); break; case 2: printf(" %d ", x); break; case 3: printf(" %d ", x); break; case 4: printf(" %d ", x); break; case 5: printf(" %d ", x); break; case 6: printf(" %d ", x); break; } } else if (mode == 2){ switch(x) { case 1: printf(" %d ", x); break; case 2: printf(" %d ", x); break; case 3: printf(" %d ", x); break; case 4: printf(" %d ", x); break; case 5: printf(" %d ", x); break; case 6: printf(" %d ", x); break; return; } } int main(void) { int num1; int num2; num1 = Numbers(); PrintMsg(num1, 1); num2 = Numbers(); PrintMsg(num2, 2); return 0; } </code></pre> <p>Thanks.</p>
0debug
Customize the d3 month or year tick format : <p>So I made a chart in d3 and used the default x axis format,</p> <pre><code>d3.axisBottom(x) </code></pre> <p>which output the following graph:</p> <p><a href="https://i.stack.imgur.com/yM3wM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yM3wM.png" alt="months and years"></a></p> <p>How can I manually create and customize this format? In particular, I'd like to use short month names, like "Oct", so that "October" doesn't obscure the following year label.</p>
0debug
Pip install without progress bars : <p>In my Django application I have a circle.yml file that runs 'pip install -r requirements/base.txt'. When I push up code, and check the CircleCI logs when there is an error, its hard to get to because there are so many dependencies and as of pip6 they started showing progress bars for the installations. Because of that it get busy pretty quick. I read on pip's github page that a few people were requesting a flag to the install command to remove the progress bars, but continue to show everything else like exceptions. something like </p> <p><code>pip install --no-progress-bar foo</code> </p> <p><a href="https://github.com/pypa/pip/pull/4194" rel="noreferrer">https://github.com/pypa/pip/pull/4194</a>. It doesn't look like this has been released yet though. Is there any way to currently do this without using --<strong>no-cache-dir</strong> ?</p>
0debug
static int ehci_process_itd(EHCIState *ehci, EHCIitd *itd, uint32_t addr) { USBDevice *dev; USBEndpoint *ep; uint32_t i, len, pid, dir, devaddr, endp; uint32_t pg, off, ptr1, ptr2, max, mult; ehci->periodic_sched_active = PERIODIC_ACTIVE; dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION); devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR); endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP); max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT); mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT); for(i = 0; i < 8; i++) { if (itd->transact[i] & ITD_XACT_ACTIVE) { pg = get_field(itd->transact[i], ITD_XACT_PGSEL); off = itd->transact[i] & ITD_XACT_OFFSET_MASK; ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK); ptr2 = (itd->bufptr[pg+1] & ITD_BUFPTR_MASK); len = get_field(itd->transact[i], ITD_XACT_LENGTH); if (len > max * mult) { len = max * mult; } if (len > BUFF_SIZE) { return -1; } qemu_sglist_init(&ehci->isgl, DEVICE(ehci), 2, ehci->as); if (off + len > 4096) { uint32_t len2 = off + len - 4096; uint32_t len1 = len - len2; qemu_sglist_add(&ehci->isgl, ptr1 + off, len1); qemu_sglist_add(&ehci->isgl, ptr2, len2); } else { qemu_sglist_add(&ehci->isgl, ptr1 + off, len); } pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT; dev = ehci_find_device(ehci, devaddr); ep = usb_ep_get(dev, pid, endp); if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) { usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false, (itd->transact[i] & ITD_XACT_IOC) != 0); usb_packet_map(&ehci->ipacket, &ehci->isgl); usb_handle_packet(dev, &ehci->ipacket); usb_packet_unmap(&ehci->ipacket, &ehci->isgl); } else { DPRINTF("ISOCH: attempt to addess non-iso endpoint\n"); ehci->ipacket.status = USB_RET_NAK; ehci->ipacket.actual_length = 0; } qemu_sglist_destroy(&ehci->isgl); switch (ehci->ipacket.status) { case USB_RET_SUCCESS: break; default: fprintf(stderr, "Unexpected iso usb result: %d\n", ehci->ipacket.status); case USB_RET_IOERROR: case USB_RET_NODEV: if (dir) { itd->transact[i] |= ITD_XACT_XACTERR; ehci_raise_irq(ehci, USBSTS_ERRINT); } break; case USB_RET_BABBLE: itd->transact[i] |= ITD_XACT_BABBLE; ehci_raise_irq(ehci, USBSTS_ERRINT); break; case USB_RET_NAK: ehci->ipacket.actual_length = 0; break; } if (!dir) { set_field(&itd->transact[i], len - ehci->ipacket.actual_length, ITD_XACT_LENGTH); } else { set_field(&itd->transact[i], ehci->ipacket.actual_length, ITD_XACT_LENGTH); } if (itd->transact[i] & ITD_XACT_IOC) { ehci_raise_irq(ehci, USBSTS_INT); } itd->transact[i] &= ~ITD_XACT_ACTIVE; } } return 0; }
1threat
Julia - Trim string whitespace and check length : <p>I'm new to Julia and I was wondering if there were any built in functions for trimming string whitespace? I also want to check the length of the string which I know I can do with <code>length(s) == 0</code>, but I wondered if there where other built in functions? Thanks! </p> <p>I'm basically trying to find the Julia equivalent to the following MATLAB code:</p> <pre><code>line = strtrim(line); if isempty(line), continue; end % Skip empty lines </code></pre>
0debug
document.write('<script src="evil.js"></script>');
1threat
Vue, is there a way to pass data between routes without URL params? : <p>I am looking how to pass data secretly between two separate components (not parent and child) without using URL params in my Vue2 app. This doesn't mean I am passing secrets but rather I just dont want the user to see it (only for UI considerations).</p> <p>I know Vue has <a href="https://vuejs.org/v2/guide/components-props.html" rel="noreferrer">Props</a> but they are meant for passing data between parent and child component. In my case, my URL will change but I don't want to pass data via visible params.</p> <p>Someone claimed to use props without URL params <a href="https://dev.to/aligoren/passing-data-to-a-router-link-in-vuejs-2cb0" rel="noreferrer">here</a> but I haven't been able to reproduce a working solution (getting undefined each time).</p> <p>I also checked out <a href="https://www.thepolyglotdeveloper.com/2017/11/pass-data-between-routes-vuejs-web-application/" rel="noreferrer">these</a> options but they are all using either URL or query params which as we know are visible.</p> <p>An ugly solution would be to write the data to local storage and then read it there but this creates a lot of overhead and complexity (like what if I only want this data to be read once, etc).</p> <p>Is there a more elegant solution to this problem?</p> <p>Thanks!</p>
0debug
static void pc_cpu_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev, Error **errp) { int idx; CPUState *cs; CPUArchId *cpu_slot; X86CPUTopoInfo topo; X86CPU *cpu = X86_CPU(dev); PCMachineState *pcms = PC_MACHINE(hotplug_dev); if (cpu->apic_id == UNASSIGNED_APIC_ID) { int max_socket = (max_cpus - 1) / smp_threads / smp_cores; if (cpu->socket_id < 0) { error_setg(errp, "CPU socket-id is not set"); } else if (cpu->socket_id > max_socket) { error_setg(errp, "Invalid CPU socket-id: %u must be in range 0:%u", cpu->socket_id, max_socket); if (cpu->core_id < 0) { error_setg(errp, "CPU core-id is not set"); } else if (cpu->core_id > (smp_cores - 1)) { error_setg(errp, "Invalid CPU core-id: %u must be in range 0:%u", cpu->core_id, smp_cores - 1); if (cpu->thread_id < 0) { error_setg(errp, "CPU thread-id is not set"); } else if (cpu->thread_id > (smp_threads - 1)) { error_setg(errp, "Invalid CPU thread-id: %u must be in range 0:%u", cpu->thread_id, smp_threads - 1); topo.pkg_id = cpu->socket_id; topo.core_id = cpu->core_id; topo.smt_id = cpu->thread_id; cpu->apic_id = apicid_from_topo_ids(smp_cores, smp_threads, &topo); cpu_slot = pc_find_cpu_slot(MACHINE(pcms), cpu->apic_id, &idx); if (!cpu_slot) { MachineState *ms = MACHINE(pcms); x86_topo_ids_from_apicid(cpu->apic_id, smp_cores, smp_threads, &topo); error_setg(errp, "Invalid CPU [socket: %u, core: %u, thread: %u] with" " APIC ID %" PRIu32 ", valid index range 0:%d", topo.pkg_id, topo.core_id, topo.smt_id, cpu->apic_id, ms->possible_cpus->len - 1); if (cpu_slot->cpu) { error_setg(errp, "CPU[%d] with APIC ID %" PRIu32 " exists", idx, cpu->apic_id); x86_topo_ids_from_apicid(cpu->apic_id, smp_cores, smp_threads, &topo); if (cpu->socket_id != -1 && cpu->socket_id != topo.pkg_id) { error_setg(errp, "property socket-id: %u doesn't match set apic-id:" " 0x%x (socket-id: %u)", cpu->socket_id, cpu->apic_id, topo.pkg_id); cpu->socket_id = topo.pkg_id; if (cpu->core_id != -1 && cpu->core_id != topo.core_id) { error_setg(errp, "property core-id: %u doesn't match set apic-id:" " 0x%x (core-id: %u)", cpu->core_id, cpu->apic_id, topo.core_id); cpu->core_id = topo.core_id; if (cpu->thread_id != -1 && cpu->thread_id != topo.smt_id) { error_setg(errp, "property thread-id: %u doesn't match set apic-id:" " 0x%x (thread-id: %u)", cpu->thread_id, cpu->apic_id, topo.smt_id); cpu->thread_id = topo.smt_id; cs = CPU(cpu); cs->cpu_index = idx; numa_cpu_pre_plug(cpu_slot, dev, errp);
1threat
static void piix4_pm_machine_ready(Notifier *n, void *opaque) { PIIX4PMState *s = container_of(n, PIIX4PMState, machine_ready); PCIDevice *d = PCI_DEVICE(s); MemoryRegion *io_as = pci_address_space_io(d); uint8_t *pci_conf; pci_conf = d->config; pci_conf[0x5f] = 0x10 | (memory_region_present(io_as, 0x378) ? 0x80 : 0); pci_conf[0x63] = 0x60; pci_conf[0x67] = (memory_region_present(io_as, 0x3f8) ? 0x08 : 0) | (memory_region_present(io_as, 0x2f8) ? 0x90 : 0); if (s->use_acpi_pci_hotplug) { pci_for_each_bus(d->bus, piix4_update_bus_hotplug, s); } else { piix4_update_bus_hotplug(d->bus, s); } }
1threat
static void test_self(void) { Coroutine *coroutine; coroutine = qemu_coroutine_create(verify_self); qemu_coroutine_enter(coroutine, coroutine); }
1threat
IBDesignable Build Failed : <p>I have Created <code>IBDesignable</code> and <code>IBInspectable</code> custom class to give shadow and corner radius for view</p> <p>But When I assign <code>Designable</code> class to <code>view</code>, I get Designable Build Failed</p> <p>This is my code </p> <pre><code>import Foundation import UIKit @IBDesignable class DesignableView: UIView { } @IBDesignable class DesignableButton: UIButton { } @IBDesignable class DesignableLabel: UILabel { } @IBDesignable class DesignableTableView: UITableView { } extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { if let color = layer.borderColor { return UIColor(cgColor: color) } return nil } set { if let color = newValue { layer.borderColor = color.cgColor } else { layer.borderColor = nil } } } @IBInspectable var shadowRadius: CGFloat { get { return layer.shadowRadius } set { layer.shadowRadius = newValue } } @IBInspectable var shadowOpacity: Float { get { return layer.shadowOpacity } set { layer.shadowOpacity = newValue } } @IBInspectable var shadowOffset: CGSize { get { return layer.shadowOffset } set { layer.shadowOffset = newValue } } @IBInspectable var shadowColor: UIColor? { get { if let color = layer.shadowColor { return UIColor(cgColor: color) } return nil } set { if let color = newValue { layer.shadowColor = color.cgColor } else { layer.shadowColor = nil } } } } </code></pre> <p>This is what I got </p> <p><a href="https://i.stack.imgur.com/LeXPP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LeXPP.png" alt="error"></a></p>
0debug
Refresh and fetch an entity after save (JPA/Spring Data/Hibernate) : <p>I've these two simple entities <code>Something</code> and <code>Property</code>. The <code>Something</code> entity has a many-to-one relationship to <code>Property</code>, so when I create a new <code>Something</code> row, I assign an existing <code>Property</code>.</p> <p><strong>Something:</strong></p> <pre><code>@Entity @Table(name = "something") public class Something implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @Column(name = "owner") private String owner; @ManyToOne private Property property; // getters and setters @Override public String toString() { return "Something{" + "id=" + getId() + ", name='" + getName() + "'" + ", owner='" + getOwner() + "'" + ", property=" + getProperty() + "}"; } </code></pre> <p><strong>Property:</strong></p> <pre><code>@Entity @Table(name = "property") public class Property implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "shape") private String shape; @Column(name = "color") private String color; @Column(name = "dimension") private Integer dimension; // getters and setters @Override public String toString() { return "Property{" + "id=" + getId() + ", shape='" + getShape() + "'" + ", color='" + getColor() + "'" + ", dimension='" + getDimension() + "'" + "}"; } } </code></pre> <p>This is the <code>SomethingRepository</code> (Spring):</p> <pre><code>@SuppressWarnings("unused") @Repository public interface SomethingRepository extends JpaRepository&lt;Something,Long&gt; { } </code></pre> <p>Through a REST controller and a JSON, I want to create a new <code>Something</code>:</p> <pre><code>@RestController @RequestMapping("/api") public class SomethingResource { private final SomethingRepository somethingRepository; public SomethingResource(SomethingRepository somethingRepository) { this.somethingRepository = somethingRepository; } @PostMapping("/somethings") public Something createSomething(@RequestBody Something something) throws URISyntaxException { Something result = somethingRepository.save(something); return result; } } </code></pre> <p>This is the JSON in input (the <code>property</code> <code>id</code> 1 is an existing row in the database):</p> <pre><code>{ "name": "MyName", "owner": "MySelf", "property": { "id": 1 } </code></pre> <p>}</p> <p>The problem is: after the method <code>.save(something)</code>, the variable <code>result</code> contains the persisted entity, but without the fields of field <code>property</code>, validated (they are <code>null</code>):</p> <p>Output JSON:</p> <pre><code>{ "id": 1, "name": "MyName", "owner": "MySelf", "property": { "id": 1, "shape": null, "color": null, "dimension": null } } </code></pre> <p>I expect that they are validated/returned after the save operation.</p> <p>To workaround this, I have to inject/declare the <code>EntityManager</code> in the REST controller, and call the method <code>EntityManager.refresh(something)</code> (or I have to call a <code>.findOne(something.getId())</code> method to have the complete persisted entity):</p> <pre><code>@RestController @RequestMapping("/api") @Transactional public class SomethingResource { private final SomethingRepository somethingRepository; private final EntityManager em; public SomethingResource(SomethingRepository somethingRepository, EntityManager em) { this.somethingRepository = somethingRepository; this.em = em; } @PostMapping("/somethings") public Something createSomething(@RequestBody Something something) throws URISyntaxException { Something result = somethingRepository.save(something); em.refresh(result); return result; } } </code></pre> <p>With this workaround, I've the expected saved entith (with a correct JSON):</p> <pre><code>{ "id": 4, "name": "MyName", "owner": "MySelf", "property": { "id": 1, "shape": "Rectangle", "color": "Red", "dimension": 50 } } </code></pre> <p>Is there an automatic method/annotation, with JPA or Spring or Hibernate, in order to have the "complete" persisted entity?</p> <p>I would like to avoid to declare the EntityManager in every REST or Service class, or I want avoid to call the .findOne(Long) method everytime I want the new refreshed persisted entity.</p> <p>Thanks a lot, Andrea</p>
0debug
static void nvdimm_build_ssdt(GSList *device_list, GArray *table_offsets, GArray *table_data, GArray *linker) { Aml *ssdt, *sb_scope, *dev; acpi_add_table(table_offsets, table_data); ssdt = init_aml_allocator(); acpi_data_push(ssdt->buf, sizeof(AcpiTableHeader)); sb_scope = aml_scope("\\_SB"); dev = aml_device("NVDR"); aml_append(dev, aml_name_decl("_HID", aml_string("ACPI0012"))); nvdimm_build_common_dsm(dev); nvdimm_build_device_dsm(dev); nvdimm_build_nvdimm_devices(device_list, dev); aml_append(sb_scope, dev); aml_append(ssdt, sb_scope); g_array_append_vals(table_data, ssdt->buf->data, ssdt->buf->len); build_header(linker, table_data, (void *)(table_data->data + table_data->len - ssdt->buf->len), "SSDT", ssdt->buf->len, 1, "NVDIMM"); free_aml_allocator(); }
1threat
str_replace, gives me the wrong result Only when numerals are in it : <pre><code>//post data $post = $_POST['username']; //str replace $print = str_replace([1,2,3,4,5], ['4A','6B','7C','2D','6F'], $post); //prints result echo "{\"username\":\"" . $print . "\"}"; </code></pre> <p>str replace works fine when it's just alpha (example: <code>TEST!@#test = 7160767124452671607671</code> which is just perfect, but as soon as digits come into play things get messy <code>$print</code> should output <code>{"username":"4A6B7C2D6F"}</code> if input <code>12345</code> the current output is <code>{"username":"2DA6B7C2D6F"}</code></p>
0debug
AWS EC2 - Can't launch an instance - Account blocked : <p>I'm trying to launch an EC2 instance on my personal AWS account, but getting the following error:</p> <pre><code>Launch Failed This account is currently blocked and not recognized as a valid account. Please contact aws-verification@amazon.com if you have questions. Hide launch log Creating security groups Successful (sg-77e2ae10) Authorizing inbound rules Successful Initiating launches FailureRetry </code></pre> <p>So I sent an email explaining, and got the following answer:</p> <pre><code>Greetings from Amazon Web Services. Thank you for contacting us regarding this matter. We reviewed your account and confirmed that your Amazon Web Services account has been successfully verified. You may now begin launching instances. Thank you for using Amazon Web Services. Sincerely, Amazon Web Services </code></pre> <p>But tried again and got the same error. Sent a new email, and got the same answer. Retried and still can't launch...</p> <p>Apparently there's no problem with my payment method or anything like that. Also tried to launch it in different regions, like n. virginia, oregon and são paulo. Got the same error.</p> <p>Any ideas? Thanks!</p>
0debug
Deploying dotnet core to Heroku : <p>I'm trying to deploy my dotnet core application to Heroku, but keep running up against this error:</p> <pre><code>Restore failed unknown keyword platform ! Push rejected, failed to compile Web app app. ! Push failed </code></pre> <p>When I use <code>dotnet run</code> from the CLI (I'm on a mac) everything runs fine. I've included my <code>Project.json</code> below in case that helps:</p> <pre><code>{ "dependencies": { "Microsoft.NETCore.App": { "version": "1.0.0", "type": "platform" }, "Microsoft.AspNetCore.Mvc": "1.0.0", "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0", "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0", "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0", "Microsoft.Extensions.Configuration.Json": "1.0.0", "Microsoft.Extensions.Configuration.CommandLine": "1.0.0", "Microsoft.Extensions.Logging": "1.0.0", "Microsoft.Extensions.Logging.Console": "1.0.0", "Microsoft.Extensions.Logging.Debug": "1.0.0", "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0", "Microsoft.EntityFrameworkCore.Sqlite": "1.0.0", "Microsoft.EntityFrameworkCore.Design": { "version": "1.0.0-preview2-final", "type": "build" } }, "tools": { "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2- final", "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final" }, "frameworks": { "netcoreapp1.0": { "imports": [ "dotnet5.6", "portable-net45+win8" ] } }, "buildOptions": { "emitEntryPoint": true, "preserveCompilationContext": true }, "runtimeOptions": { "configProperties": { "System.GC.Server": true } }, "publishOptions": { "include": [ "wwwroot", "Views", "Areas/**/Views", "appsettings.json", "web.config" ] }, "tooling": { "defaultNamespace": "Tokens_monolith" } } </code></pre>
0debug