problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
Creating a big pandas Dataframe : <p>My code is retrieving historical data of 365 days back from today of 50 different stocks.</p>
<p>I want to store all those data in one dataframe to make it easier to analyse, here I want to filter all those data, date wise and calculate number of advancing/declining stocks at a given date.</p>
<p>My code:</p>
<pre><code>import datetime
from datetime import date, timedelta
import pandas as pd
import nsepy as ns
#setting default dates
end_date = date.today()
start_date = end_date - timedelta(365)
#Deriving the names of 50 stocks in Nifty 50 Index
nifty_50 = pd.read_html('https://en.wikipedia.org/wiki/NIFTY_50')
nifty50_symbols = nifty_50[1][1]
for x in nifty50_symbols:
data = ns.get_history(symbol = x, start=start_date, end=end_date)
big_df = pd.concat(data)
</code></pre>
<p>Output:</p>
<pre><code>Traceback (most recent call last):
File "F:\My\Getting data from NSE\advances.py", line 27, in <module>
big_df = pd.concat(data)
File "C:\Users\Abinash\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\reshape\concat.py", line 212, in concat
copy=copy)
File "C:\Users\Abinash\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\reshape\concat.py", line 227, in __init__
'"{name}"'.format(name=type(objs).__name__))
TypeError: first argument must be an iterable of pandas objects, you passed an object of type "DataFrame"
</code></pre>
<p>I am very new to python, I went through the tutorial of pandas and saw that pandas.concat was used to merge multiple dataframes into one. I might have understood that wrong.</p>
| 0debug
|
document.getElementById("attribute_orderfield1_value").innerHTML fails writing into input field : <p>I have a little problem by writing some text into this input-field.</p>
<pre><code><input type="text" data-pseudo-text="true" data-selector=".attribute-orderfield1--hidden" placeholder="some text" name="attribute_orderfield1_value" id="attribute_orderfield1_value" class="input--attribute-orderfield1" data-type-aof="input">
</code></pre>
<p>I tried it before in a test without the attribute data-type-aof and it worked.</p>
<pre><code>document.getElementById("attribute_orderfield1_value").innerHTML = "some text";
</code></pre>
<p>Is this attribute preventing writing into the field via JS?</p>
| 0debug
|
I am trying to print crystal report reprts "bill.rpt" could not print or save as a pdf to my development enironment : 1. ***Description** I am using windows xp sp3, crystal report basic version 10.5.3700.0(followed by c:\windows\assembly), visual studio
2008, mssql 2008 R2.
**Error** Error in File C:\DOCUME~1\NKT\LOCALS~1\Temp\Bill {CE9EC584-2281}.rpt:
**Error description**
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace
for more information about the error and where it originated in the
code.
**Exception Details:** System.Runtime.InteropServices.COMException: Error in File C:\DOCUME~1\NKT\LOCALS~1\Temp\Bill
{CE9EC584-2281-4C5F-89ED-54C60AFCC0CB}.rpt:
The table could not be found.
**Source Error:**
Line 2697: myReportDocument.SetDataSource(ds); Line
2698: //myReportDocument.PrintToPrinter(1, true,0,0);
Line 2699: myReportDocument.PrintToPrinter(1, false,
0, 0);
Source File: c:\Documents and Settings\NKT\My Documents\Visual
Studio 2008\Projects\\ParlerBill.aspx.cs Line: 2699
**Here is my .cs file code snippet**
//--Opening Sql Connection
String strConn = ConfigurationManager.AppSettings["connectionString"];
SqlConnection sqlConn = new SqlConnection(strConn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(strCmd, sqlConn);
sqlConn.Open();
//--this statement is very important, here the table name should
match with the XML Schema table name.
da.Fill(ds, "customerbilldetail");
//--Closing Sql Connection
sqlConn.Close();
//--(Optional) I have used it to disable the properties
CrystalReportViewer1.Visible = true;
CrystalReportViewer1.DisplayGroupTree = false;
CrystalReportViewer1.HasCrystalLogo = false;
//--Initializing CrystalReport
ReportDocument myReportDocument;
myReportDocument = new ReportDocument();
myReportDocument.Load(Server.MapPath("~//Repport/Bill.rpt"));
myReportDocument.SetDatabaseLogon("sa", "saa");
myReportDocument.SetDataSource(ds);
//myReportDocument.PrintToPrinter(1, true,0,0);
myReportDocument.PrintToPrinter(1, false, 0, 0);
here the error is throwing, Please help me to out...Thanks
| 0debug
|
static void xics_realize(DeviceState *dev, Error **errp)
{
XICSState *icp = XICS(dev);
ICSState *ics = icp->ics;
Error *error = NULL;
int i;
if (!icp->nr_servers) {
error_setg(errp, "Number of servers needs to be greater 0");
return;
}
spapr_rtas_register("ibm,set-xive", rtas_set_xive);
spapr_rtas_register("ibm,get-xive", rtas_get_xive);
spapr_rtas_register("ibm,int-off", rtas_int_off);
spapr_rtas_register("ibm,int-on", rtas_int_on);
spapr_register_hypercall(H_CPPR, h_cppr);
spapr_register_hypercall(H_IPI, h_ipi);
spapr_register_hypercall(H_XIRR, h_xirr);
spapr_register_hypercall(H_EOI, h_eoi);
ics->nr_irqs = icp->nr_irqs;
ics->offset = XICS_IRQ_BASE;
ics->icp = icp;
object_property_set_bool(OBJECT(icp->ics), true, "realized", &error);
if (error) {
error_propagate(errp, error);
return;
}
icp->ss = g_malloc0(icp->nr_servers*sizeof(ICPState));
for (i = 0; i < icp->nr_servers; i++) {
char buffer[32];
object_initialize(&icp->ss[i], sizeof(icp->ss[i]), TYPE_ICP);
snprintf(buffer, sizeof(buffer), "icp[%d]", i);
object_property_add_child(OBJECT(icp), buffer, OBJECT(&icp->ss[i]), NULL);
object_property_set_bool(OBJECT(&icp->ss[i]), true, "realized", &error);
if (error) {
error_propagate(errp, error);
return;
}
}
}
| 1threat
|
static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
uint8_t *buf, int count)
{
BDRVRawState *s = bs->opaque;
int ret;
ret = fd_open(bs);
if (ret < 0)
return ret;
ret = pread(s->fd, buf, count, offset);
if (ret == count)
goto label__raw_read__success;
if ((ret == 0) && bs->growable) {
int64_t size = raw_getlength(bs);
if (offset >= size) {
memset(buf, 0, count);
ret = count;
goto label__raw_read__success;
}
}
DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
"] read failed %d : %d = %s\n",
s->fd, bs->filename, offset, buf, count,
bs->total_sectors, ret, errno, strerror(errno));
if (bs->type == BDRV_TYPE_CDROM) {
ret = pread(s->fd, buf, count, offset);
if (ret == count)
goto label__raw_read__success;
ret = pread(s->fd, buf, count, offset);
if (ret == count)
goto label__raw_read__success;
DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
"] retry read failed %d : %d = %s\n",
s->fd, bs->filename, offset, buf, count,
bs->total_sectors, ret, errno, strerror(errno));
}
label__raw_read__success:
return (ret < 0) ? -errno : ret;
}
| 1threat
|
Typescript: change function type so that it returns new value : <p>Basically, I want something like this:</p>
<pre><code>export type ReturnValueMapper<Func extends (...args: Args[] /* impossible */ ) => any, ReturnValue> = (...args: Args[]) => ReturnValue;
</code></pre>
<p>I'm almost sure that it's impossible, but I haven't found exact confirmation.</p>
<hr>
<p>The use case is improving types for <a href="https://github.com/acdlite/recompose/blob/master/docs/API.md#withstatehandlers" rel="noreferrer">recompose's withStateHandlers</a>, enabling defining state updaters like this:</p>
<pre><code>interface StateUpdaters {
update(field: string): void; // I don't want to specify Partial<State> here
}
</code></pre>
| 0debug
|
Is it possible to set a hostname in a Kubernetes replication controller? : <p>I need to set a static hostname in a Kubernetes replication controller. Docker supports it with some runtime flags, however, Kubernetes replication controllers don't appear to support it.
The environment: OS - CentOS 6.6
Approach to use sysctl to change the variable kernel.hostname does not work for a K8s replication controller. The host name is not changed.
Use:
sysctl kernel.hostname
to read the current hostname, and
sysctl kernel.hostname=NEW_HOSTNAME</p>
<p>Is it possible to set a hostname in a Kubernetes replication controller?</p>
| 0debug
|
A java prgm to find & print the duplicate words and their no.of occurrences in string : <p><a href="https://i.stack.imgur.com/GYhJZ.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>Write a program to find the duplicate words and their number of occurrences in a string.
Thee program what i have type has been attached. when i run the program, its not displaying the output except for it is asking-</p>
<p>"Enter the sentence"
"It has eaten a lot of it"</p>
| 0debug
|
window.location.href = 'http://attack.com?user=' + user_input;
| 1threat
|
static inline void RENAME(yuvPlanartoyuy2)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,
long width, long height,
long lumStride, long chromStride, long dstStride, long vertLumPerChroma)
{
long y;
const long chromWidth= width>>1;
for(y=0; y<height; y++)
{
#ifdef HAVE_MMX
asm volatile(
"xor %%"REG_a", %%"REG_a" \n\t"
ASMALIGN16
"1: \n\t"
PREFETCH" 32(%1, %%"REG_a", 2) \n\t"
PREFETCH" 32(%2, %%"REG_a") \n\t"
PREFETCH" 32(%3, %%"REG_a") \n\t"
"movq (%2, %%"REG_a"), %%mm0 \n\t"
"movq %%mm0, %%mm2 \n\t"
"movq (%3, %%"REG_a"), %%mm1 \n\t"
"punpcklbw %%mm1, %%mm0 \n\t"
"punpckhbw %%mm1, %%mm2 \n\t"
"movq (%1, %%"REG_a",2), %%mm3 \n\t"
"movq 8(%1, %%"REG_a",2), %%mm5 \n\t"
"movq %%mm3, %%mm4 \n\t"
"movq %%mm5, %%mm6 \n\t"
"punpcklbw %%mm0, %%mm3 \n\t"
"punpckhbw %%mm0, %%mm4 \n\t"
"punpcklbw %%mm2, %%mm5 \n\t"
"punpckhbw %%mm2, %%mm6 \n\t"
MOVNTQ" %%mm3, (%0, %%"REG_a", 4)\n\t"
MOVNTQ" %%mm4, 8(%0, %%"REG_a", 4)\n\t"
MOVNTQ" %%mm5, 16(%0, %%"REG_a", 4)\n\t"
MOVNTQ" %%mm6, 24(%0, %%"REG_a", 4)\n\t"
"add $8, %%"REG_a" \n\t"
"cmp %4, %%"REG_a" \n\t"
" jb 1b \n\t"
::"r"(dst), "r"(ysrc), "r"(usrc), "r"(vsrc), "g" (chromWidth)
: "%"REG_a
);
#else
#if defined ARCH_ALPHA && defined HAVE_MVI
#define pl2yuy2(n) \
y1 = yc[n]; \
y2 = yc2[n]; \
u = uc[n]; \
v = vc[n]; \
asm("unpkbw %1, %0" : "=r"(y1) : "r"(y1)); \
asm("unpkbw %1, %0" : "=r"(y2) : "r"(y2)); \
asm("unpkbl %1, %0" : "=r"(u) : "r"(u)); \
asm("unpkbl %1, %0" : "=r"(v) : "r"(v)); \
yuv1 = (u << 8) + (v << 24); \
yuv2 = yuv1 + y2; \
yuv1 += y1; \
qdst[n] = yuv1; \
qdst2[n] = yuv2;
int i;
uint64_t *qdst = (uint64_t *) dst;
uint64_t *qdst2 = (uint64_t *) (dst + dstStride);
const uint32_t *yc = (uint32_t *) ysrc;
const uint32_t *yc2 = (uint32_t *) (ysrc + lumStride);
const uint16_t *uc = (uint16_t*) usrc, *vc = (uint16_t*) vsrc;
for(i = 0; i < chromWidth; i += 8){
uint64_t y1, y2, yuv1, yuv2;
uint64_t u, v;
asm("ldq $31,64(%0)" :: "r"(yc));
asm("ldq $31,64(%0)" :: "r"(yc2));
asm("ldq $31,64(%0)" :: "r"(uc));
asm("ldq $31,64(%0)" :: "r"(vc));
pl2yuy2(0);
pl2yuy2(1);
pl2yuy2(2);
pl2yuy2(3);
yc += 4;
yc2 += 4;
uc += 4;
vc += 4;
qdst += 4;
qdst2 += 4;
}
y++;
ysrc += lumStride;
dst += dstStride;
#elif __WORDSIZE >= 64
int i;
uint64_t *ldst = (uint64_t *) dst;
const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;
for(i = 0; i < chromWidth; i += 2){
uint64_t k, l;
k = yc[0] + (uc[0] << 8) +
(yc[1] << 16) + (vc[0] << 24);
l = yc[2] + (uc[1] << 8) +
(yc[3] << 16) + (vc[1] << 24);
*ldst++ = k + (l << 32);
yc += 4;
uc += 2;
vc += 2;
}
#else
int i, *idst = (int32_t *) dst;
const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;
for(i = 0; i < chromWidth; i++){
#ifdef WORDS_BIGENDIAN
*idst++ = (yc[0] << 24)+ (uc[0] << 16) +
(yc[1] << 8) + (vc[0] << 0);
#else
*idst++ = yc[0] + (uc[0] << 8) +
(yc[1] << 16) + (vc[0] << 24);
#endif
yc += 2;
uc++;
vc++;
}
#endif
#endif
if((y&(vertLumPerChroma-1))==(vertLumPerChroma-1) )
{
usrc += chromStride;
vsrc += chromStride;
}
ysrc += lumStride;
dst += dstStride;
}
#ifdef HAVE_MMX
asm( EMMS" \n\t"
SFENCE" \n\t"
:::"memory");
#endif
}
| 1threat
|
static void run_dependent_requests(BDRVQcowState *s, QCowL2Meta *m)
{
if (m->nb_clusters != 0) {
QLIST_REMOVE(m, next_in_flight);
}
if (!qemu_co_queue_empty(&m->dependent_requests)) {
qemu_co_mutex_unlock(&s->lock);
while(qemu_co_queue_next(&m->dependent_requests));
qemu_co_mutex_lock(&s->lock);
}
}
| 1threat
|
Apple push notification curl: (16) Error in the HTTP2 framing layer : <p>i do run this command on ubuntu terminal</p>
<blockquote>
<p>curl --verbose -H 'apns-topic: Skios.TripBruCACT' --header "Content-Type: application/json" --data '{"aps":{"content-available":1,"alert":"hi","sound":"default"}}' --cert /home/mohamed/Downloads/Prod2.pem:a1B23 --http2 '<a href="https://api.push.apple.com/3/device/19297dba97212ac6fd16b9cd50f2d86629aed0e49576b2b52ed05086087da802" rel="noreferrer">https://api.push.apple.com/3/device/19297dba97212ac6fd16b9cd50f2d86629aed0e49576b2b52ed05086087da802</a>'</p>
</blockquote>
<p>but it return <strong>curl: (16) Error in the HTTP2 framing layer</strong></p>
<p>Here are the whole result</p>
<pre><code>* Trying 17.188.145.163...
* Connected to api.push.apple.com (17.188.145.163) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
* CAfile: /etc/ssl/certs/ca-certificates.crt CApath: none
* TLSv1.2 (OUT), TLS header, Certificate Status (22):
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Request CERT (13):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Certificate (11):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS handshake, CERT verify (15):
* TLSv1.2 (OUT), TLS change cipher, Client hello (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS change cipher, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES256-GCM-SHA384
* ALPN, server accepted to use h2
* Server certificate:
* subject: CN=api.push.apple.com; OU=management:idms.group.533599; O=Apple Inc.; ST=California; C=US
* start date: Aug 28 19:03:46 2015 GMT
* expire date: Sep 26 19:03:46 2017 GMT
* subjectAltName: host "api.push.apple.com" matched cert's "api.push.apple.com"
* issuer: CN=Apple IST CA 2 - G1; OU=Certification Authority; O=Apple Inc.; C=US
* SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* TCP_NODELAY set
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0xdb69a0)
> POST /3/device/19297dba97212ac6fd16b9cd50f2d86629aed0e49576b2b52ed05086087da802 HTTP/1.1
> Host: api.push.apple.com
> User-Agent: curl/7.50.0
> Accept: */*
> apns-topic: Skios.TripBruCACT
> Content-Type: application/json
> Content-Length: 62
>
* Connection state changed (MAX_CONCURRENT_STREAMS updated)!
* We are completely uploaded and fine
* Closing connection 0
* TLSv1.2 (OUT), TLS alert, Client hello (1):
curl: (16) Error in the HTTP2 framing layer
</code></pre>
<p>but i got in last line this error</p>
<blockquote>
<p>curl: (16) Error in the HTTP2 framing layer</p>
</blockquote>
| 0debug
|
How to setSupportActionBar in a view that extends LifecycleActivity : <p>I had an Activity that extended AppCompactActivity, and in <code>onCreate</code> method I setted the <code>Toolbar</code> using <code>setSupportActionBar</code> method in the usual way:</p>
<pre><code>public class StepMasterActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step_master);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);`
}
}
</code></pre>
<p>But now I have a <a href="https://developer.android.com/topic/libraries/architecture/viewmodel.html#the_lifecycle_of_a_viewmodel" rel="noreferrer">ViewModel</a> component and to share data between fragments that are the children of this activity and manages lifecycles I have to get this component in Activity and so I make this extend LifecycleActivity. </p>
<pre><code>public class StepMasterActivity extends LifecycleActivity {
@Override
public class StepMasterActivity extends LifecycleActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step_master);
// setToolbar();
SharedViewModel sharedViewModel = ViewModelProviders.of(this).get(SharedViewModel.class);
}
}
</code></pre>
<p>But I noticed that LifecycleActivity has nothing to do with AppCompatActivity neither FragmentActivity does.</p>
<pre><code>public class LifecycleActivity extends FragmentActivity implements LifecycleRegistryOwner {
private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);
public LifecycleActivity() {
}
public LifecycleRegistry getLifecycle() {
return this.mRegistry;
}
}
</code></pre>
<p>Am I doing something wrong? </p>
| 0debug
|
Creating a Object Array From an Array : <p>I have an array like this:</p>
<pre><code>const companyNames = ["A", "B", "C"];
</code></pre>
<p>I want to convert it to a something like this:</p>
<pre><code>const companyNames = {
0: 'A',
1: 'B',
2: 'C'
};
</code></pre>
| 0debug
|
static av_always_inline int rv40_loop_filter_strength(uint8_t *src,
int step, int stride,
int beta, int beta2,
int edge,
int *p1, int *q1)
{
int sum_p1p0 = 0, sum_q1q0 = 0, sum_p1p2 = 0, sum_q1q2 = 0;
int strong0 = 0, strong1 = 0;
uint8_t *ptr;
int i;
for (i = 0, ptr = src; i < 4; i++, ptr += stride) {
sum_p1p0 += ptr[-2*step] - ptr[-1*step];
sum_q1q0 += ptr[ 1*step] - ptr[ 0*step];
}
*p1 = FFABS(sum_p1p0) < (beta << 2);
*q1 = FFABS(sum_q1q0) < (beta << 2);
if(!*p1 && !*q1)
return 0;
if (!edge)
return 0;
for (i = 0, ptr = src; i < 4; i++, ptr += stride) {
sum_p1p2 += ptr[-2*step] - ptr[-3*step];
sum_q1q2 += ptr[ 1*step] - ptr[ 2*step];
}
strong0 = *p1 && (FFABS(sum_p1p2) < beta2);
strong1 = *q1 && (FFABS(sum_q1q2) < beta2);
return strong0 && strong1;
}
| 1threat
|
output FILE ,is this a fault? :
my code here
#include <stdio.h>
#include<iostream>
#include<conio.h>
char filename[100];
FILE *stream, *stream2;
char s[20];
struct date
{
int day, month, year;
};
struct employee
{
int ID;
char name[100];
date birthdate;
char address[20];
char rank[20];
int money;
};
void main()
{
errno_t err;
// Open for read (will fail if file "crt_fopen_s.c" does not exist)
// Open for write
err = fopen_s(&stream2, "C:/Users/Van/Desktop/LAALAL/fool.txt", "w+");
if (err == 0)
{
employee nv;
std::cout << "\nInput information of an employee:\n";
std::cout << "\tInput ID : ";
std::cin >> nv.ID;
std::cin.sync();
std::cout << "\tInput name : ";
std::cin.clear();
gets_s(s);
gets_s(nv.name);
std::cout << "\tInput birthdate (Day Month Year ) : ";
std::cin >> nv.birthdate.day >> nv.birthdate.month >> nv.birthdate.year;
std::cout << "\tInput address: ";
std::cin.clear();
gets_s(s);
gets_s(nv.address);
std::cout << "\tInput rank : ";
std::cin.clear();
gets_s(s);
gets_s(nv.rank);
std::cout << "\tMoney : ";
std::cin >> nv.money;
std::cin.sync();
std::fwrite(&nv, sizeof(nv), 1, stream2);
std::fclose(stream2);
}
}
Well i don't meet the problem with code but when i input my information to txt file , i cant read the output in txt file ,here is the picture of my output
[enter image description here][1]
What is my problems??
Thanks in advance for your time !!!
[1]: http://i.stack.imgur.com/gaPqY.png
| 0debug
|
static void spapr_machine_class_init(ObjectClass *oc, void *data)
{
MachineClass *mc = MACHINE_CLASS(oc);
sPAPRMachineClass *smc = SPAPR_MACHINE_CLASS(oc);
FWPathProviderClass *fwc = FW_PATH_PROVIDER_CLASS(oc);
NMIClass *nc = NMI_CLASS(oc);
HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(oc);
mc->desc = "pSeries Logical Partition (PAPR compliant)";
mc->init = ppc_spapr_init;
mc->reset = ppc_spapr_reset;
mc->block_default_type = IF_SCSI;
mc->max_cpus = MAX_CPUMASK_BITS;
mc->no_parallel = 1;
mc->default_boot_order = "";
mc->default_ram_size = 512 * M_BYTE;
mc->kvm_type = spapr_kvm_type;
mc->has_dynamic_sysbus = true;
mc->pci_allow_0_address = true;
mc->get_hotplug_handler = spapr_get_hotplug_handler;
hc->pre_plug = spapr_machine_device_pre_plug;
hc->plug = spapr_machine_device_plug;
hc->unplug = spapr_machine_device_unplug;
mc->cpu_index_to_socket_id = spapr_cpu_index_to_socket_id;
smc->dr_lmb_enabled = true;
smc->tcg_default_cpu = "POWER8";
mc->query_hotpluggable_cpus = spapr_query_hotpluggable_cpus;
fwc->get_dev_path = spapr_get_fw_dev_path;
nc->nmi_monitor_handler = spapr_nmi;
smc->phb_placement = spapr_phb_placement;
}
| 1threat
|
In what cases would I want to use inline assembly code in C/C++ code : <p>I just read that assembly code can be included directly in C/C++ programs, like,</p>
<pre><code>__asm statement
__asm {
statement-1
statement-2
...
statement-n
}
</code></pre>
<p>I'm just wondering in what cases would it be useful to include assembly code in C/C++.</p>
| 0debug
|
Does git store the read, write, execute permissions for files? : <p>I wanted to make some files in git read only. But I couldn't find any good documentation on doing this.</p>
<p><strong>Does git store the read, write, execute permissions for files?</strong></p>
| 0debug
|
How to write conditional select insert statement , to fetch record from a table, and based on some particular columns values : for eg:
1) Table1 --c1,c2,c3 (1,10,123)
2) Table2 --c1,c2,c3,c4
Now i want to select record from table1 and if c3 column value starting two digit is 12 then i have to populate AA, in Table2 c4 column.
Table1 -- (1,10,123)
Table2 --(1,10,123,AA)
| 0debug
|
Angular2 - root relative imports : <p>I have a problem with imports in angular2/typescript. I'd like to use imports with some root like 'app/components/calendar', instead only way I am able to use is something like:</p>
<pre><code>//app/views/order/order-view.ts
import {Calendar} from '../../components/calendar
</code></pre>
<p>where Calendar is defined like:</p>
<pre><code>//app/components/calendar.ts
export class Calendar {
}
</code></pre>
<p>and this obviously gets much worse the lower in hierarchy you go, deepest is '../../..' but it is still very bad and brittle. Is there any way how to use paths relative to project root? </p>
<p>I am working in Visual Studio, and relative imports seem to be the only thing that makes VS able to recognize these imports.y</p>
| 0debug
|
Problem to import "ProgressDialog" in android studio : I want to use Progress Dialog in project,but its class does not add to the program!
what is the problem?
| 0debug
|
Java Eclipse; How do i Subtract two arrays : Can someone help me, I have an array A and B , i want to subtract it but i want their result to be a array C
If i have an
Array A[] = ( 2,2,2)
Array B[] = (1,1,1)
I want to A-B to create a = Array C
Array C[] = (1,1,1)
How can i make this ?
| 0debug
|
MongoDB $lookup not using index : <p>I'm writing a query that requires a $lookup between two tables and as I understand it, it's essential that the foreignField have an index in order to perform this join in a timely fashion. However, even after adding an index on the field, the query is still falling back to COLLSCAN.</p>
<pre><code>db.users.aggregate([
{$lookup:{ from: "transactions", localField: '_id', foreignField: 'uid', as: 'transaction' }},
{ $match: { transaction: { "$size" : 0} } },
{ $count: "total"},
], { explain: true })
</code></pre>
<p>This returns:</p>
<pre><code>"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "test.users",
"indexFilterSet" : false,
"parsedQuery" : {
},
"winningPlan" : {
"stage" : "COLLSCAN",
"direction" : "forward"
},
"rejectedPlans" : [ ]
}
</code></pre>
<p>As I mentioned, I do have the <em>uid</em> field indexed in the transactions collection:</p>
<pre><code>> db.transactions.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.transactions"
},
{
"v" : 1,
"key" : {
"uid" : 1
},
"name" : "uid_1",
"ns" : "test.transactions"
}
]
</code></pre>
<p>The query takes a few minutes to run in a DB of approximately 7M documents. I'm using MongoDB v3.4.7. Any idea as to what I could be doing wrong? Thanks in advance!</p>
| 0debug
|
AVInputFormat *av_probe_input_format3(AVProbeData *pd, int is_opened, int *score_ret)
{
AVProbeData lpd = *pd;
AVInputFormat *fmt1 = NULL, *fmt;
int score, nodat = 0, score_max=0;
if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
int id3len = ff_id3v2_tag_len(lpd.buf);
if (lpd.buf_size > id3len + 16) {
lpd.buf += id3len;
lpd.buf_size -= id3len;
}else
nodat = 1;
}
fmt = NULL;
while ((fmt1 = av_iformat_next(fmt1))) {
if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
continue;
score = 0;
if (fmt1->read_probe) {
score = fmt1->read_probe(&lpd);
if(fmt1->extensions && av_match_ext(lpd.filename, fmt1->extensions))
score = FFMAX(score, nodat ? AVPROBE_SCORE_MAX/4-1 : 1);
} else if (fmt1->extensions) {
if (av_match_ext(lpd.filename, fmt1->extensions)) {
score = 50;
}
}
if (score > score_max) {
score_max = score;
fmt = fmt1;
}else if (score == score_max)
fmt = NULL;
}
*score_ret= score_max;
return fmt;
}
| 1threat
|
int avresample_set_matrix(AVAudioResampleContext *avr, const double *matrix,
int stride)
{
int in_channels, out_channels, i, o;
in_channels = av_get_channel_layout_nb_channels(avr->in_channel_layout);
out_channels = av_get_channel_layout_nb_channels(avr->out_channel_layout);
if ( in_channels < 0 || in_channels > AVRESAMPLE_MAX_CHANNELS ||
out_channels < 0 || out_channels > AVRESAMPLE_MAX_CHANNELS) {
av_log(avr, AV_LOG_ERROR, "Invalid channel layouts\n");
return AVERROR(EINVAL);
}
if (avr->am->matrix)
av_freep(avr->am->matrix);
#define CONVERT_MATRIX(type, expr) \
avr->am->matrix_## type[0] = av_mallocz(out_channels * in_channels * \
sizeof(*avr->am->matrix_## type[0])); \
if (!avr->am->matrix_## type[0]) \
return AVERROR(ENOMEM); \
for (o = 0; o < out_channels; o++) { \
if (o > 0) \
avr->am->matrix_## type[o] = avr->am->matrix_## type[o - 1] + \
in_channels; \
for (i = 0; i < in_channels; i++) { \
double v = matrix[o * stride + i]; \
avr->am->matrix_## type[o][i] = expr; \
} \
} \
avr->am->matrix = (void **)avr->am->matrix_## type;
switch (avr->mix_coeff_type) {
case AV_MIX_COEFF_TYPE_Q8:
CONVERT_MATRIX(q8, av_clip_int16(lrint(256.0 * v)))
break;
case AV_MIX_COEFF_TYPE_Q15:
CONVERT_MATRIX(q15, av_clipl_int32(llrint(32768.0 * v)))
break;
case AV_MIX_COEFF_TYPE_FLT:
CONVERT_MATRIX(flt, v)
break;
default:
av_log(avr, AV_LOG_ERROR, "Invalid mix coeff type\n");
return AVERROR(EINVAL);
}
return 0;
}
| 1threat
|
void FUNCC(ff_h264_idct8_dc_add)(uint8_t *_dst, DCTELEM *block, int stride){
int i, j;
int dc = (((dctcoef*)block)[0] + 32) >> 6;
INIT_CLIP
pixel *dst = (pixel*)_dst;
stride /= sizeof(pixel);
for( j = 0; j < 8; j++ )
{
for( i = 0; i < 8; i++ )
dst[i] = CLIP( dst[i] + dc );
dst += stride;
}
}
| 1threat
|
static int nut_read_close(AVFormatContext *s)
{
NUTContext *nut = s->priv_data;
av_freep(&nut->time_base);
av_freep(&nut->stream);
return 0;
}
| 1threat
|
static void virtio_crypto_initfn(Object *obj)
{
VirtIOCryptoPCI *dev = VIRTIO_CRYPTO_PCI(obj);
virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev),
TYPE_VIRTIO_CRYPTO);
object_property_add_alias(obj, "cryptodev", OBJECT(&dev->vdev),
"cryptodev", &error_abort);
}
| 1threat
|
static int dnxhd_decode_dct_block_10_444(const DNXHDContext *ctx,
RowContext *row, int n)
{
return dnxhd_decode_dct_block(ctx, row, n, 6, 32, 6);
}
| 1threat
|
How to compose two functions whose outer function supplies arguments to the inner function : <p>I have two similar codes that need to be parsed and I'm not sure of the most pythonic way to accomplish this.</p>
<p>Suppose I have two similar "codes"</p>
<pre><code>secret_code_1 = 'asdf|qwer-sdfg-wert$$otherthing'
secret_code_2 = 'qwersdfg-qw|er$$otherthing'
</code></pre>
<p>both codes end with <code>$$otherthing</code> and contain a number of values separated by <code>-</code></p>
<p>At first I thought of using <code>functools.wrap</code> to separate some of the common logic from the logic specific to each type of code, something like this:</p>
<pre><code>from functools import wraps
def parse_secret(f):
@wraps(f)
def wrapper(code, *args):
_code = code.split('$$')[0]
return f(code, *_code.split('-'))
return wrapper
@parse_secret
def parse_code_1b(code, a, b, c):
a = a.split('|')[0]
return (a,b,c)
@parse_secret
def parse_code_2b(code, a, b):
b = b.split('|')[1]
return (a,b)
</code></pre>
<p>However doing it this way makes it kind of confusing what parameters you should actually pass to the <code>parse_code_*</code> functions i.e.</p>
<pre><code>parse_code_1b(secret_code_1)
parse_code_2b(secret_code_2)
</code></pre>
<p>So to keep the formal parameters of the function easier to reason about I changed the logic to something like this:</p>
<pre><code>def _parse_secret(parse_func, code):
_code = code.split('$$')[0]
return parse_func(code, *_code.split('-'))
def _parse_code_1(code, a, b, c):
"""
a, b, and c are descriptive parameters that explain
the different components in the secret code
returns a tuple of the decoded parts
"""
a = a.split('|')[0]
return (a,b,c)
def _parse_code_2(code, a, b):
"""
a and b are descriptive parameters that explain
the different components in the secret code
returns a tuple of the decoded parts
"""
b = b.split('|')[1]
return (a,b)
def parse_code_1(code):
return _parse_secret(_parse_code_1, code)
def parse_code_2(code):
return _parse_secret(_parse_code_2, code)
</code></pre>
<p>Now it's easier to reason about what you pass to the functions:</p>
<pre><code>parse_code_1(secret_code_1)
parse_code_2(secret_code_2)
</code></pre>
<p>However this code is significantly more verbose.</p>
<p>Is there a better way to do this? Would an object-oriented approach with classes make more sense here?</p>
<p><a href="https://repl.it/Exqh/7" rel="noreferrer">repl.it example</a></p>
| 0debug
|
How to printing out certain values of an array : I'm working on a program which requires the input/output of multiple data types, including a char which stands for the type of sport a patron is making a reservation for, an int which represents their age, and a double that is the output based on the patrons age and sport they want to reserve a spot for, which represents their insurance rate.
So, the logic of the program simplified is Enter program --> choose to add a reservation --> enter sport using a char --> enter age using an int --> compute the insurance rate given those circumstances and return it to display to the user.
I will be using arrays for the char, storing the sport they wish to partake in, an array for the age, an index integer which will keep track of which spot in the array that the user is entering the data into, and I might need to make an array for the insurance rate.
Anyways, TL;DR how can I say, access the specific elements of an array to print out something like "a patron the age of patron_age[index] reserved a session of sport_type[index]" in a function based off of which sport the user is requesting to see information on? I'm really lost.
Here's the code if that helps. It's nowhere close to done yet.
http://pastebin.com/t0citrGE
| 0debug
|
How do you display an image from s3 on a website? : <p>I am new to web development and to s3 and was wondering how I might be able to display an image thats inside my bucket, Im able to get a list of image and folder names inside the bucket but I want to find out how to display the images. Would I need to provide a URL for my image tag in html?</p>
| 0debug
|
Regex patter to allow space : I have one regex which allows one Upper case, one Lower case, 8-16 characters and Most special characters and space. I want add allow space in the regex.
My regex is as follow :
(?=^.{8,16}$)(?=.*[\!\"\#\$\%\&\'\(\)\*\+\,\-\.\/\:\;\<\>\=\?\@\[\]\{\}\\\\\^\_\`\~\|])(?=.*[a-z])(?=.*[A-Z])(?!.*\s)[0-9a-zA-Z\!\"\#\$\%\&\'\(\)\*\+\,\-\.\/\:\;\<\>\=\?\@\[\]\{\}\\\\\^\_\`\~\|]]*$
I just want to add space in this. I have tried **\s** and **[ ]?** but nothing works.
I have checked the regex on https://regex101.com/
Any suggestions would be appreciated.
| 0debug
|
static void sd_close(BlockDriverState *bs)
{
Error *local_err = NULL;
BDRVSheepdogState *s = bs->opaque;
SheepdogVdiReq hdr;
SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
unsigned int wlen, rlen = 0;
int fd, ret;
DPRINTF("%s\n", s->name);
fd = connect_to_sdog(s, &local_err);
if (fd < 0) {
error_report_err(local_err);
return;
}
memset(&hdr, 0, sizeof(hdr));
hdr.opcode = SD_OP_RELEASE_VDI;
hdr.type = LOCK_TYPE_NORMAL;
hdr.base_vdi_id = s->inode.vdi_id;
wlen = strlen(s->name) + 1;
hdr.data_length = wlen;
hdr.flags = SD_FLAG_CMD_WRITE;
ret = do_req(fd, s->bs, (SheepdogReq *)&hdr,
s->name, &wlen, &rlen);
closesocket(fd);
if (!ret && rsp->result != SD_RES_SUCCESS &&
rsp->result != SD_RES_VDI_NOT_LOCKED) {
error_report("%s, %s", sd_strerror(rsp->result), s->name);
}
aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd,
false, NULL, NULL, NULL, NULL);
closesocket(s->fd);
qapi_free_SocketAddressLegacy(s->addr);
}
| 1threat
|
Importing Module without routes : <p>I have a situation where our main app lazily loads other modules: </p>
<pre><code>//main NgModule
RouterModule.forRoot(
[
{path:'profile', loadChildren:'path/to/profile.module#ProfileModule},
{path:'classroom', loadChildren:'path/to/classroom.module#ClassroomModule},
{path:'tests', loadChildren:'path/to/test.module#TestsModule}
])
</code></pre>
<p>Now the profile module has a few components in it that are necessary for the Classroom module. </p>
<pre><code>//Profile NgModule
RouterModule.forChild(
[
{path:'', component:ProfileComponent,
])
//Classroom NgModule
imports: [
ProfileModule,
RouterModule.forChild(
[
{path:'', component:ClassroomComponent} //this requires a component in ProfileModule
])
]
</code></pre>
<p>This compiles nicely but when I try to navigate to '/classroom' all I get is the ProfileComponent </p>
<p>I suppose this is because the ProfileModules route configuration is being combined with the ClassroomModule route configuration. Is there a way I could prevent this from happening? I'd prefer not having to remove all of the shared components from ProfileModule and putting them into a new shared module if possible. </p>
| 0debug
|
how to join in SQL Server by date Valid_from/Valid_to : want join in SQL Server by date Valid_from/Valid_to
[Pic_output][1]
[1]: https://i.stack.imgur.com/CSkyW.png
thank you for help ^^
| 0debug
|
static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
int64_t align, QEMUIOVector *qiov, int flags)
{
int64_t total_bytes, max_bytes;
int ret = 0;
uint64_t bytes_remaining = bytes;
int max_transfer;
assert(is_power_of_2(align));
assert((offset & (align - 1)) == 0);
assert((bytes & (align - 1)) == 0);
assert(!qiov || bytes == qiov->size);
assert((bs->open_flags & BDRV_O_NO_IO) == 0);
max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
align);
assert(!(flags & ~(BDRV_REQ_NO_SERIALISING | BDRV_REQ_COPY_ON_READ)));
if (flags & BDRV_REQ_COPY_ON_READ) {
mark_request_serialising(req, bdrv_get_cluster_size(bs));
}
if (!(flags & BDRV_REQ_NO_SERIALISING)) {
wait_serialising_requests(req);
}
if (flags & BDRV_REQ_COPY_ON_READ) {
int64_t start_sector = offset >> BDRV_SECTOR_BITS;
int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
unsigned int nb_sectors = end_sector - start_sector;
int pnum;
ret = bdrv_is_allocated(bs, start_sector, nb_sectors, &pnum);
if (ret < 0) {
goto out;
}
if (!ret || pnum != nb_sectors) {
ret = bdrv_co_do_copy_on_readv(bs, offset, bytes, qiov);
goto out;
}
}
total_bytes = bdrv_getlength(bs);
if (total_bytes < 0) {
ret = total_bytes;
goto out;
}
max_bytes = ROUND_UP(MAX(0, total_bytes - offset), align);
if (bytes <= max_bytes && bytes <= max_transfer) {
ret = bdrv_driver_preadv(bs, offset, bytes, qiov, 0);
goto out;
}
while (bytes_remaining) {
int num;
if (max_bytes) {
QEMUIOVector local_qiov;
num = MIN(bytes_remaining, MIN(max_bytes, max_transfer));
assert(num);
qemu_iovec_init(&local_qiov, qiov->niov);
qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);
ret = bdrv_driver_preadv(bs, offset + bytes - bytes_remaining,
num, &local_qiov, 0);
max_bytes -= num;
qemu_iovec_destroy(&local_qiov);
} else {
num = bytes_remaining;
ret = qemu_iovec_memset(qiov, bytes - bytes_remaining, 0,
bytes_remaining);
}
if (ret < 0) {
goto out;
}
bytes_remaining -= num;
}
out:
return ret < 0 ? ret : 0;
}
| 1threat
|
static int dxtory_decode_v2_410(AVCodecContext *avctx, AVFrame *pic,
const uint8_t *src, int src_size)
{
GetByteContext gb;
GetBitContext gb2;
int nslices, slice, slice_height, ref_slice_height;
int cur_y, next_y;
uint32_t off, slice_size;
uint8_t *Y, *U, *V;
int ret;
bytestream2_init(&gb, src, src_size);
nslices = bytestream2_get_le16(&gb);
off = FFALIGN(nslices * 4 + 2, 16);
if (src_size < off) {
av_log(avctx, AV_LOG_ERROR, "no slice data\n");
return AVERROR_INVALIDDATA;
}
if (!nslices || avctx->height % nslices) {
avpriv_request_sample(avctx, "%d slices for %dx%d", nslices,
avctx->width, avctx->height);
return AVERROR_PATCHWELCOME;
}
ref_slice_height = avctx->height / nslices;
if ((avctx->width & 3) || (avctx->height & 3)) {
avpriv_request_sample(avctx, "Frame dimensions %dx%d",
avctx->width, avctx->height);
}
avctx->pix_fmt = AV_PIX_FMT_YUV410P;
if ((ret = ff_get_buffer(avctx, pic, 0)) < 0)
return ret;
Y = pic->data[0];
U = pic->data[1];
V = pic->data[2];
cur_y = 0;
next_y = ref_slice_height;
for (slice = 0; slice < nslices; slice++) {
slice_size = bytestream2_get_le32(&gb);
slice_height = (next_y & ~3) - (cur_y & ~3);
if (slice_size > src_size - off) {
av_log(avctx, AV_LOG_ERROR,
"invalid slice size %"PRIu32" (only %"PRIu32" bytes left)\n",
slice_size, src_size - off);
return AVERROR_INVALIDDATA;
}
if (slice_size <= 16) {
av_log(avctx, AV_LOG_ERROR, "invalid slice size %"PRIu32"\n", slice_size);
return AVERROR_INVALIDDATA;
}
if (AV_RL32(src + off) != slice_size - 16) {
av_log(avctx, AV_LOG_ERROR,
"Slice sizes mismatch: got %"PRIu32" instead of %"PRIu32"\n",
AV_RL32(src + off), slice_size - 16);
}
init_get_bits(&gb2, src + off + 16, (slice_size - 16) * 8);
dx2_decode_slice_410(&gb2, avctx->width, slice_height, Y, U, V,
pic->linesize[0], pic->linesize[1],
pic->linesize[2]);
Y += pic->linesize[0] * slice_height;
U += pic->linesize[1] * (slice_height >> 2);
V += pic->linesize[2] * (slice_height >> 2);
off += slice_size;
cur_y = next_y;
next_y += ref_slice_height;
}
return 0;
}
| 1threat
|
static void ff_h264_idct_add16intra_sse2(uint8_t *dst, const int *block_offset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]){
int i;
for(i=0; i<16; i+=2){
if(nnzc[ scan8[i+0] ]|nnzc[ scan8[i+1] ])
ff_x264_add8x4_idct_sse2 (dst + block_offset[i], block + i*16, stride);
else if(block[i*16]|block[i*16+16])
ff_h264_idct_dc_add8_mmx2(dst + block_offset[i], block + i*16, stride);
}
}
| 1threat
|
Swift 2 get Double hours from double minute : Im using swift 2 , i have **double myMinute** and i want to convert it to double hours(myHours) how can i do it ? My codes under below
let myMinute : Double = 62.0
let myHours : Double = ?
| 0debug
|
How to check which the current Route is? : <p>I want to navigate to different Routes using a Drawer, though I do not want to open a new instance of a Route each time I tap on it if I am already on that Route, rather I would prefer that in this case a new Route is not opened. This is my code so far:</p>
<pre><code>Widget build(BuildContext context){
return new Drawer(
child:
new ListView(
children: <Widget>[
new ListTile(
title: new Text("NewRoute"),
onTap: () {
Navigator.of(context).pop;
Navigator.of(context).pushNamed('/NewRoute');
}
)
)
)
}
</code></pre>
<p>I want to use a conditional statement to check whether we are on a certain route. I know there is a way to check which Route we are on currently with the isCurrent of the Route class</p>
<p><a href="https://docs.flutter.io/flutter/widgets/Route/isCurrent.html" rel="noreferrer">https://docs.flutter.io/flutter/widgets/Route/isCurrent.html</a></p>
<p>though I am not sure how to implement it.</p>
<p>Thank you in advance!</p>
| 0debug
|
static int tight_fill_palette(VncState *vs, int x, int y,
size_t count, uint32_t *bg, uint32_t *fg,
struct QDict **palette)
{
int max;
max = count / tight_conf[vs->tight_compression].idx_max_colors_divisor;
if (max < 2 &&
count >= tight_conf[vs->tight_compression].mono_min_rect_size) {
max = 2;
}
if (max >= 256) {
max = 256;
}
switch(vs->clientds.pf.bytes_per_pixel) {
case 4:
return tight_fill_palette32(vs, x, y, max, count, bg, fg, palette);
case 2:
return tight_fill_palette16(vs, x, y, max, count, bg, fg, palette);
default:
max = 2;
return tight_fill_palette8(vs, x, y, max, count, bg, fg, palette);
}
return 0;
}
| 1threat
|
Augmentations for the global scope can only be directly nested in external modules or ambient module declarations(2669) : <p>I would like to store my NodeJS config in the global scope.</p>
<p>I tried to follow this => <a href="https://stackoverflow.com/questions/35074713/extending-typescript-global-object-in-node-js">Extending TypeScript Global object in node.js</a> and other solution on stackoverflow, </p>
<p>I made a file called global.d.ts where I have the following code </p>
<pre><code>declare global {
namespace NodeJS {
interface Global {
config: MyConfigType
}
}
}
</code></pre>
<blockquote>
<p>Augmentations for the global scope can only be directly nested in
external modules or ambient module declarations.ts(2669)</p>
</blockquote>
<p>but doing this works fine =></p>
<pre><code>declare module NodeJS {
interface Global {
config: MyConfigType
}
}
</code></pre>
<p>the problem is, I need to import the file <code>MyConfigType</code> to type the config, but the second option do not allow that.</p>
| 0debug
|
Airflow: PythonOperator: why to include 'ds' arg? : <p>While defining a function to be later used as a python_callable, why is 'ds' included as the first arg of the function?</p>
<p>For example:</p>
<pre><code>def python_func(ds, **kwargs):
pass
</code></pre>
<p>I looked into the Airflow documentation, but could not find any explanation.</p>
| 0debug
|
static void set_string(Object *obj, Visitor *v, void *opaque,
const char *name, Error **errp)
{
DeviceState *dev = DEVICE(obj);
Property *prop = opaque;
char **ptr = qdev_get_prop_ptr(dev, prop);
Error *local_err = NULL;
char *str;
if (dev->realized) {
qdev_prop_set_after_realize(dev, name, errp);
return;
}
visit_type_str(v, &str, name, &local_err);
if (local_err) {
error_propagate(errp, local_err);
return;
}
if (*ptr) {
g_free(*ptr);
}
*ptr = str;
}
| 1threat
|
How to sorting XmlNodeList when hirarchy is different in C# : Can you please tell me how to sorting code tag value as per given attribute value.
Please reply me as soon as possible
I have also asked same question in Microsoft forum
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Input:
<category>
<code type="pub">e00001</code>
<title>cat1</title>
<ranking>0</ranking>
</category>
<category>
<span>
<code type="pub">e00004</code>
</span>
<title>cat2</title>
<ranking>1</ranking>
</category>
<category>
<code type="pub">e00003</code>
<title>awe</title>
<ranking>10</ranking>
</category>
<category>
<span>
<code type="pub">e00002</code>
</span>
<title>zrt</title>
<ranking>6</ranking>
</category>
Output:
<category>
<code type="pub">e00001</code>
<title>cat1</title>
<ranking>0</ranking>
</category>
<category>
<span>
<code type="pub">e00002</code>
</span>
<title>zrt</title>
<ranking>6</ranking>
</category>
<category>
<code type="pub">e00003</code>
<title>awe</title>
<ranking>10</ranking>
</category>
<category>
<span>
<code type="pub">e00004</code>
</span>
<title>cat2</title>
<ranking>1</ranking>
</category>
| 0debug
|
How do I define a datetime field in a python dataclass? : <p>trying to get the syntax of the Python 3.7 new dataclass right.</p>
<p>if I want to include a datetime value in my dataclass,</p>
<pre><code>import datetime
from dataclasses import dataclass
@dataclass
class MyExampleWithDateTime:
mystring: str
myint: int
mydatetime: ???
</code></pre>
<p>What should I write for ??? for a datetime field?</p>
| 0debug
|
Ruby Error on method: Array can't be coerced into Fixnum : I'm a beginner Ruby coder and working on a simple multiplying method.
CODE:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: Ruby -->
def multiply(*numbers)
product = 1
numbers.each{|number|
product *= number
}
return product
end
puts multiply([2, 3, 4, 5])
<!-- end snippet -->
OUTPUT:
`*': Array can't be coerced into Fixnum (TypeError)
from calculator.rb:26:in `block in multiply'
from calculator.rb:24:in `each'
from calculator.rb:24:in `multiply'
from calculator.rb:31:in `<main>'
I get this error. It seems the method isn't allowing me to use ".each" on the array.
Also, I want to keep the parameter as *numbers in case it's not an array but two numbers to multiply. I should bring it to your attention that the method works fine when the parameter being passed are two numbers and not an array (i.e. multiply(2, 4)
Thanks in advance :D
| 0debug
|
Vue js error: Component template should contain exactly one root element : <p>I don't know what the error is, so far I am testing through console log to check for changes after selecting a file (for uploading).</p>
<p>When I run <code>$ npm run watch</code>, i get the following error:</p>
<blockquote>
<p>"Webpack is watching the files…</p>
<p>95% emitting </p>
<p>ERROR Failed to compile with 1 errors<br>
19:42:29</p>
<p>error in ./resources/assets/js/components/File.vue</p>
<p>(Emitted value instead of an instance of Error) Vue template syntax
error:</p>
<p>Component template should contain exactly one root element. If you
are using v-if on multiple elements, use v-else-if to chain them
instead.</p>
<p>@ ./resources/assets/js/components/AvatarUpload.vue 5:2-181 @
./resources/assets/js/app.js @ multi ./resources/assets/js/app.js
./resources/assets/sass/app.scss"</p>
</blockquote>
<p>My File.vue is</p>
<pre><code><template>
<div class="form-group">
<label for="avatar" class="control-label">Avatar</label>
<input type="file" v-on:change="fileChange" id="avatar">
<div class="help-block">
Help block here updated 4 🍸 ...
</div>
</div>
<div class="col-md-6">
<input type="hidden" name="avatar_id">
<img class="avatar" title="Current avatar">
</div>
</template>
<script>
export default{
methods: {
fileChange(){
console.log('Test of file input change')
}
}
}
</script>
</code></pre>
<p>Any ideas on how to solve this? What is actually the error?</p>
| 0debug
|
What does ArrayIndexoutofBoundsException mean here? : <p>Given a string, print the number of alphabets present in the string.
Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows.Each test case contains a single string.
Output:
Print the number of alphabets present in the string.</p>
<p>This is a question i have been trying to solve this question on eclipse but it keeps throwing ArrayIndexoutOfBoundsException in line 7 of my code. I tried understanding what i've done wrong but i have not been able to.
Could some one please explain whats wrong here . I have attached the code.</p>
<pre><code>public class solution {
public static void main(String[] args){
String s = "baibiasbfi" ;
int count =0;
for(int i=0;i<=s.length();i++){
char[] a= s.toCharArray();
if(a[i]>='a'&& a[i]<='z'||a[i]>='A'&&a[i]<='Z')
count++;}
System.out.println(count);
}
}
</code></pre>
| 0debug
|
Name webpack chunks from react-loadable : <p>I've successfully added react-loadable library in my project to enable code splitting, the only problem I've found is that the chunks generated by webpack are not named, they are given integer names.</p>
<p>My code for react-loadable use is</p>
<pre class="lang-js prettyprint-override"><code>const AppRootLoadable = Loadable({
loader: () => import(/* webpackChunkName: "app" */ './App'),
loading: () => null,
render(loaded) {
const Component = loaded.default;
return <Component />;
},
});
</code></pre>
<p>I've added the comment to tell webpack 3 that I want this chunk to be named app. Have I done something wrong?</p>
| 0debug
|
Swift "retry" logic on request : <p>So i'm a bit lost on how to implement a retry logic when my upload request fail.</p>
<p>Here is my code i would like some guidance on how to do it</p>
<pre><code>func startUploading(failure failure: (NSError) -> Void, success: () -> Void, progress: (Double) -> Void) {
DDLogDebug("JogUploader: Creating jog: \(self.jog)")
API.sharedInstance.createJog(self.jog,
failure: { error in
failure(error)
}, success: {_ in
success()
})
}
</code></pre>
| 0debug
|
(probably) very simply SQL query needed : Having a slow day....could use some assistance writing an SQL query.
I have a list of individuals within families (first and last names), and a second table which lists a subset of those individuals. I would like to create a third table which flags every individual within a family if ANY of the individuals are not listed in the second table. The goal is essentially to flag "incomplete" families.
Below is an example of the two input tables, and the desired third table.
[Example of problem][1]
As I said...very simple...having a slow day. Thanks!
[1]: https://i.stack.imgur.com/oyues.png
| 0debug
|
"Could not find or load main class java.se.ee" while running sdkmanager --licences : <p>When building my project on android studio, it asks me to accept the license agreements and complete the installation of the missing components using the Android Studio SDK Manager.</p>
<p>When I run "./sdkmanager --licenses", I have the "Could not find or load main class java.se.ee" error.</p>
<p>I found a lot of similar issues on stackoverflow, but non of the solutions provided worked for me.</p>
<p>I already tried:
1- downgrade to java 8</p>
<p>2- export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'</p>
<p>3- change sdkmanager file by adding : DEFAULT_JVM_OPTS='"-Dcom.android.sdklib.toolsdir=$APP_HOME" -XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'</p>
| 0debug
|
want to get the php executable result? : I have two files name test.txt that will contains the template code i need to evalute this template according to the php..I tried to evalute it using php eval() function but cant get the result ...thanks in advance
test.txt
@$firmware_path=true;
@$DIALPLAN=1312321;
@$MAX_LINES=3;
@$data=array();
@$OPERATOR_IP='';
@$enabled=true;
@ if ($firmware_path)
@{
firmware server: http://{$OPERATOR_IP}{$firmware_path}
@ }
@ for ($i = 1; $i <= $MAX_LINES; $i++)
@ {
@ $enabled = isset($LINES[$i - 1]);
@ if ($enabled)
@{
@ $data = $LINES[$i -1];
@ if ($data['USER_FULLNAME'])
@{
@ if ($PHONE_LABEL)
@{
@ $screenName = $data['USER_FULLNAME'] . ' ' . $data['TELNUM'];
@ $screenName2 = $PHONE_LABEL;
@ }
@else
@{
@ $screenName = $data['USER_FULLNAME'];
@ $screenName2 = $data['TELNUM'];
@ }
@ }
@else
@{
@ $screenName = $data['TELNUM'];
@ $screenName2 = $PHONE_LABEL;
@ }
@ }
@ }
index.php
<?php
$file = fopen("test.txt","r");
$arr=array();
while(! feof($file))
{
$arr[]=fgets($file);
}
$format='';
foreach($arr as $key=>$value)
{
if(substr(ltrim($value), 0, 1) === '@')
{
$result=str_replace('@','',$value);
$format.=$result.PHP_EOL;
}
else
{
$format.='$final="'.$value.'";';
}
}
$format.=' return $final;';
echo eval($format);
?>
the result should be generated according to php
| 0debug
|
static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun,
uint8_t *buf, void *hba_private)
{
SCSIRequest *req;
req = scsi_req_alloc(&scsi_generic_req_ops, d, tag, lun, hba_private);
return req;
}
| 1threat
|
c# limit decimal value to 2 places : <p>I found a ton of answers but none work for me, can anyone help me with this problem.
I have a formula witch gives a very extensive result and only want a value like for instance 1,25 </p>
<p>I tried several codes but none worked, what i have now is:</p>
<pre><code> uw = (adp * ufa + adv * ug + perv * wmk) / ac;
String.Format("{0:.##}", uw);
resposta.Text = uw.ToString();
</code></pre>
<p><code>resposta</code> is a <code>label</code> in witch i display the answer.
<code>uw</code> is <code>decimal</code>.</p>
<p>I dont want to round the value, just limit the numbers. </p>
<p>Thansk for the assist,</p>
| 0debug
|
Docker: could not read CA certificate : <p>I installed Docker on Windows 10 Pro and I can't get it to work.</p>
<p>When I try to run hello-world I get</p>
<pre><code>could not read CA certificate
</code></pre>
<p>It's looking for the certificates in the machine/machines/default . However that folder didn't exist.</p>
<p>I created a machine called "default" (which created the above mentioned folder) but that didn't help.</p>
<p>Before that I created another machine called "dev" which seems to have certificates, but that doesn't seem to be helping either.</p>
<p>Also there are certificate files in machine/machines - I don't know if I should somehow point Docker to look in that folder (instead of machine/machines/default) ?</p>
<p>I'm pretty new to Docker so I might be missing something. However I've been at this all day, read the Docker documentation, tried plenty of solutions and similar answers but nothing seems to be working. </p>
| 0debug
|
missing right paranthesis Oracle while creating table : oracle error
SQL> desc user_details;
Name Null? Type
----------------------------------------- -------- --------------
USER_ID NUMBER(38)
NAME VARCHAR2(20)
DOB DATE
CONTACT NUMBER(38)
EMAIL NOT NULL VARCHAR2(50)
TYPE VARCHAR2(4)
create table user_reg
(
reg_id int primary key,
pass varchar(50),
email varchar(20) foreign key preferences user_details(user_id)
);
this is what error i got while creating table user_reg
| 0debug
|
static int decode_slice(AVCodecContext *avctx, ProresThreadData *td)
{
ProresContext *ctx = avctx->priv_data;
int mb_x_pos = td->x_pos;
int mb_y_pos = td->y_pos;
int pic_num = ctx->pic_num;
int slice_num = td->slice_num;
int mbs_per_slice = td->slice_width;
const uint8_t *buf;
uint8_t *y_data, *u_data, *v_data;
AVFrame *pic = avctx->coded_frame;
int i, sf, slice_width_factor;
int slice_data_size, hdr_size, y_data_size, u_data_size, v_data_size;
int y_linesize, u_linesize, v_linesize;
buf = ctx->slice_data[slice_num].index;
slice_data_size = ctx->slice_data[slice_num + 1].index - buf;
slice_width_factor = av_log2(mbs_per_slice);
y_data = pic->data[0];
u_data = pic->data[1];
v_data = pic->data[2];
y_linesize = pic->linesize[0];
u_linesize = pic->linesize[1];
v_linesize = pic->linesize[2];
if (pic->interlaced_frame) {
if (!(pic_num ^ pic->top_field_first)) {
y_data += y_linesize;
u_data += u_linesize;
v_data += v_linesize;
}
y_linesize <<= 1;
u_linesize <<= 1;
v_linesize <<= 1;
}
if (slice_data_size < 6) {
av_log(avctx, AV_LOG_ERROR, "slice data too small\n");
return AVERROR_INVALIDDATA;
}
hdr_size = buf[0] >> 3;
y_data_size = AV_RB16(buf + 2);
u_data_size = AV_RB16(buf + 4);
v_data_size = slice_data_size - y_data_size - u_data_size - hdr_size;
if (v_data_size < 0 || hdr_size < 6) {
av_log(avctx, AV_LOG_ERROR, "invalid data size\n");
return AVERROR_INVALIDDATA;
}
sf = av_clip(buf[1], 1, 224);
sf = sf > 128 ? (sf - 96) << 2 : sf;
if (ctx->qmat_changed || sf != ctx->prev_slice_sf) {
ctx->prev_slice_sf = sf;
for (i = 0; i < 64; i++) {
ctx->qmat_luma_scaled[ctx->dsp.idct_permutation[i]] = ctx->qmat_luma[i] * sf;
ctx->qmat_chroma_scaled[ctx->dsp.idct_permutation[i]] = ctx->qmat_chroma[i] * sf;
}
}
decode_slice_plane(ctx, td, buf + hdr_size, y_data_size,
(uint16_t*) (y_data + (mb_y_pos << 4) * y_linesize +
(mb_x_pos << 5)), y_linesize,
mbs_per_slice, 4, slice_width_factor + 2,
ctx->qmat_luma_scaled);
decode_slice_plane(ctx, td, buf + hdr_size + y_data_size, u_data_size,
(uint16_t*) (u_data + (mb_y_pos << 4) * u_linesize +
(mb_x_pos << ctx->mb_chroma_factor)),
u_linesize, mbs_per_slice, ctx->num_chroma_blocks,
slice_width_factor + ctx->chroma_factor - 1,
ctx->qmat_chroma_scaled);
decode_slice_plane(ctx, td, buf + hdr_size + y_data_size + u_data_size,
v_data_size,
(uint16_t*) (v_data + (mb_y_pos << 4) * v_linesize +
(mb_x_pos << ctx->mb_chroma_factor)),
v_linesize, mbs_per_slice, ctx->num_chroma_blocks,
slice_width_factor + ctx->chroma_factor - 1,
ctx->qmat_chroma_scaled);
return 0;
}
| 1threat
|
How to Descrypt Password in SQL Server 2012 R2 using DES? : I want to decrypt password in sql server 2012 R2 using DES to send that password in the mail using SQL JOB.
Can Anyone help Me ?
Thanks in advance.
| 0debug
|
Graceful shutdown with Generic Host in .NET Core 2.1 : <p>.NET Core 2.1 introduced new Generic Host, which allows to host non-HTTP workloads with all benefits of Web Host. Currently, there is no much information and recipes with it, but I used following articles as a starting point:</p>
<p><a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-2.1" rel="noreferrer">https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-2.1</a></p>
<p><a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.1" rel="noreferrer">https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.1</a></p>
<p><a href="https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/multi-container-microservice-net-applications/background-tasks-with-ihostedservice" rel="noreferrer">https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/multi-container-microservice-net-applications/background-tasks-with-ihostedservice</a></p>
<p>My .NET Core application starts, listens for new requests via RabbitMQ message broker and shuts down by user request (usually by Ctrl+C in console). However, shutdown is not graceful - application still have unfinished background threads while it returns control to OS. I see it by console messages - when I press Ctrl+C in console I see few lines of console output from my application, then OS command prompt and then again console output from my application.</p>
<p>Here is my code:</p>
<p><strong>Program.cs</strong></p>
<pre><code>public class Program
{
public static async Task Main(string[] args)
{
var host = new HostBuilder()
.ConfigureHostConfiguration(config =>
{
config.SetBasePath(AppContext.BaseDirectory);
config.AddEnvironmentVariables(prefix: "ASPNETCORE_");
config.AddJsonFile("hostsettings.json", optional: true);
})
.ConfigureAppConfiguration((context, config) =>
{
var env = context.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
config.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
if (env.IsProduction())
config.AddDockerSecrets();
config.AddEnvironmentVariables();
})
.ConfigureServices((context, services) =>
{
services.AddLogging();
services.AddHostedService<WorkerPoolHostedService>();
// ... other services
})
.ConfigureLogging((context, logging) =>
{
if (context.HostingEnvironment.IsDevelopment())
logging.AddDebug();
logging.AddSerilog(dispose: true);
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(context.Configuration)
.CreateLogger();
})
.UseConsoleLifetime()
.Build();
await host.RunAsync();
}
}
</code></pre>
<p><strong>WorkerPoolHostedService.cs</strong></p>
<pre><code>internal class WorkerPoolHostedService : IHostedService
{
private IList<VideoProcessingWorker> _workers;
private CancellationTokenSource _stoppingCts = new CancellationTokenSource();
protected WorkerPoolConfiguration WorkerPoolConfiguration { get; }
protected RabbitMqConfiguration RabbitMqConfiguration { get; }
protected IServiceProvider ServiceProvider { get; }
protected ILogger<WorkerPoolHostedService> Logger { get; }
public WorkerPoolHostedService(
IConfiguration configuration,
IServiceProvider serviceProvider,
ILogger<WorkerPoolHostedService> logger)
{
this.WorkerPoolConfiguration = new WorkerPoolConfiguration(configuration);
this.RabbitMqConfiguration = new RabbitMqConfiguration(configuration);
this.ServiceProvider = serviceProvider;
this.Logger = logger;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
var connectionFactory = new ConnectionFactory
{
AutomaticRecoveryEnabled = true,
UserName = this.RabbitMqConfiguration.Username,
Password = this.RabbitMqConfiguration.Password,
HostName = this.RabbitMqConfiguration.Hostname,
Port = this.RabbitMqConfiguration.Port,
VirtualHost = this.RabbitMqConfiguration.VirtualHost
};
_workers = Enumerable.Range(0, this.WorkerPoolConfiguration.WorkerCount)
.Select(i => new VideoProcessingWorker(
connectionFactory: connectionFactory,
serviceScopeFactory: this.ServiceProvider.GetRequiredService<IServiceScopeFactory>(),
logger: this.ServiceProvider.GetRequiredService<ILogger<VideoProcessingWorker>>(),
cancellationToken: _stoppingCts.Token))
.ToList();
this.Logger.LogInformation("Worker pool started with {0} workers.", this.WorkerPoolConfiguration.WorkerCount);
}
public async Task StopAsync(CancellationToken cancellationToken)
{
this.Logger.LogInformation("Stopping working pool...");
try
{
_stoppingCts.Cancel();
await Task.WhenAll(_workers.SelectMany(w => w.ActiveTasks).ToArray());
}
catch (AggregateException ae)
{
ae.Handle((Exception exc) =>
{
this.Logger.LogError(exc, "Error while cancelling workers");
return true;
});
}
finally
{
if (_workers != null)
{
foreach (var worker in _workers)
worker.Dispose();
_workers = null;
}
}
}
}
</code></pre>
<p><strong>VideoProcessingWorker.cs</strong></p>
<pre><code>internal class VideoProcessingWorker : IDisposable
{
private readonly Guid _id = Guid.NewGuid();
private bool _disposed = false;
protected IConnection Connection { get; }
protected IModel Channel { get; }
protected IServiceScopeFactory ServiceScopeFactory { get; }
protected ILogger<VideoProcessingWorker> Logger { get; }
protected CancellationToken CancellationToken { get; }
public VideoProcessingWorker(
IConnectionFactory connectionFactory,
IServiceScopeFactory serviceScopeFactory,
ILogger<VideoProcessingWorker> logger,
CancellationToken cancellationToken)
{
this.Connection = connectionFactory.CreateConnection();
this.Channel = this.Connection.CreateModel();
this.Channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
this.ServiceScopeFactory = serviceScopeFactory;
this.Logger = logger;
this.CancellationToken = cancellationToken;
#region [ Declare ]
// ...
#endregion
#region [ Consume ]
// ...
#endregion
}
// ... worker logic ...
public void Dispose()
{
if (!_disposed)
{
this.Channel.Close(200, "Goodbye");
this.Channel.Dispose();
this.Connection.Close();
this.Connection.Dispose();
this.Logger.LogDebug("Worker {0}: disposed.", _id);
}
_disposed = true;
}
}
</code></pre>
<p>So, when I press Ctrl+C I see following output in console (when there is no request processing):</p>
<blockquote>
<p>Stopping working pool...<br>
<strong>command prompt</strong><br>
Worker <strong>id</strong>: disposed.</p>
</blockquote>
<p>How to shutdown gracefully?</p>
| 0debug
|
What does "cpu_time" represent exactly in libvirt? : <p>I can pull the following CPU values from libvirt:</p>
<pre><code>virsh domstats vm1 --cpu-total
Domain: 'vm1'
cpu.time=6173016809079111
cpu.user=26714880000000
cpu.system=248540680000000
virsh cpu-stats vm1 --total
Total:
cpu_time 6173017.263233824 seconds
user_time 26714.890000000 seconds
system_time 248540.700000000 seconds
</code></pre>
<p>What does the cpu_time figure represent here exactly?</p>
<p>I'm looking to calculate CPU utilization as a percentage using this data.</p>
<p>Thanks</p>
| 0debug
|
Converting seven segment to number : <p>I want to convert seven segment <strong>numbers</strong> to normal string in java. For example, if input string like this</p>
<p>input</p>
<pre><code> _ _ _ _ _ _ _ _
| _| _||_||_ |_ ||_||_|| |
||_ _| | _||_| ||_| _||_|
</code></pre>
<p>output should be like</p>
<pre><code>1234567890
</code></pre>
<p>I have found <a href="https://stackoverflow.com/a/42178177/9114020">this JavaScript</a> answer, and I'm trying to convert it to java.</p>
<p>for now I have:</p>
<pre><code>private static void get7segment(String ascii)
{
String[] splited="909561432".split("");
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
map.put(0, 63);
map.put(1, 6);
map.put(2, 91);
map.put(3, 79);
map.put(4, 102);
map.put(5, 109);
map.put(6, 125);
map.put(7, 7);
map.put(8, 127);
map.put(9, 111);
}
</code></pre>
<p>any help would be appricheate</p>
| 0debug
|
Phusion Passenger process stuck on (forking...) Rails : <p>Today I updated to the newest updated package for Nginx and Passenger. After the update, my app now has a (forking...) process that wasn't there before and doesn't seem to go away. Yet it is taking up memory and <code>sudo /usr/sbin/passenger-memory-stats</code> reports the following.</p>
<pre><code>--------- Nginx processes ----------
PID PPID VMSize Private Name
------------------------------------
1338 1 186.0 MB 0.8 MB nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
1345 1338 186.3 MB 1.1 MB nginx: worker process
### Processes: 2
### Total private dirty RSS: 1.91 MB
---- Passenger processes -----
PID VMSize Private Name
------------------------------
1312 378.8 MB 2.1 MB Passenger watchdog
1320 663.8 MB 4.2 MB Passenger core
1768 211.5 MB 29.0 MB Passenger AppPreloader: /home/ubuntu/my-app
1987 344.1 MB 52.2 MB Passenger AppPreloader: /home/ubuntu/my-app (forking...)
2008 344.2 MB 41.1 MB Passenger AppPreloader: /home/ubuntu/my-app (forking...)
### Processes: 5
### Total private dirty RSS: 128.62 MB
</code></pre>
<p>I have the <code>passenger_max_pool_size 2</code>. <code>sudo /usr/sbin/passenger-status</code> reports that two are currently open. The server is receiving no hits at the moment besides me using the site.</p>
<pre><code>Version : 5.3.0
Date : 2018-05-14 00:41:05 +0000
Instance: ql2TTnkw (nginx/1.14.0 Phusion_Passenger/5.3.0)
----------- General information -----------
Max pool size : 2
App groups : 1
Processes : 2
Requests in top-level queue : 0
----------- Application groups -----------
/home/ubuntu/my-app (production):
App root: /home/ubuntu/my-app
Requests in queue: 0
* PID: 1987 Sessions: 0 Processed: 1 Uptime: 3m 36s
CPU: 0% Memory : 52M Last used: 3m 36s ago
* PID: 2008 Sessions: 0 Processed: 1 Uptime: 3m 35s
CPU: 0% Memory : 41M Last used: 3m 35s ago
</code></pre>
<p>Passenger never did this before the update and keeps the (forking...) always there now and it seems to have two apps running when it only needs one. I have searched their documents and know when it uses forking and when it doesn't and when it kills app automatically after a certain amount of time. Did they update something with the newest update that I missed in the docs? It seems that <code>2008 344.2 MB 89.4 MB Passenger AppPreloader: /home/ubuntu/my-app (forking...)</code> always shows now and sometimes even has two of those when before the update I always had the process show without the <code>(forking...)</code>.</p>
| 0debug
|
How to Insert and sort the data at the same time using java : This is the sample code which I have written
```
String sql =" INSERT INTO "+tablename+" (id,timestamp,type,current_num_workers,target_num_workers)
VALUES (?,?,?,?,?)";
PreparedStatement pstmt=con.prepareStatement(sql);
System.out.println("Fetching records in ascending order...");
String se="SELECT * FROM " + tablename + " ORDER BY type ASC";
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1, id);
pstmt.setString(2, timestamp);
pstmt.setString(3, type);
pstmt.setString(4, current_num_workers);
pstmt.setString(5, target_num_workers);
pstmt.executeUpdate();
pstmt.executeUpdate();
```
This is the exception which I am facing
```
Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: A result set was
generated for update.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:226)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement
(SQLServerPreparedStatement.java:592)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute
(SQLServerPreparedStatement.java:508)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7240)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2869)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:243)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:218)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate
(SQLServerPreparedStatement.java:461)
```
Help me to resolve this and where I should sort and insert the details at the same time.
| 0debug
|
Find all indexes of substrings in a string and respective limits with javascript : <p>I need a function that would return information on the position of substrings in a larger string with javascript. I don't know if something like this exists natively so I want to take my chances here.</p>
<p>For example, having the following input string:</p>
<p><code>"dog elephant you me test another test what thesis"</code></p>
<p>And if I have the following array:</p>
<p><code>array("Dog", "test", "not this one", "what the heck", "thesis")</code></p>
<p>What is the most efficient way to <strong>indexOf</strong> the position of all these elements in the input string? Having the function return an object with information like this:</p>
<ul>
<li>"Dog" - from 0 to 3</li>
<li>"test" - from (where <code>test</code> begins) to (where it ends)</li>
<li>"not this one" - null (not in the string)</li>
<li>"what the heck" - null (not in the string)</li>
<li>"thesis" - from (where <code>thesis</code> begins) to (where it ends)</li>
</ul>
<p>Does anyone have any idea?
Tyvm!</p>
| 0debug
|
How to pass context down to the Enzyme mount method to test component which includes Material UI component? : <p>I am trying to use <code>mount</code> from Enzyme to test my component in which a several Material UI component are nested. I get this error when running the test:</p>
<p><code>TypeError: Cannot read property 'prepareStyles' of undefined</code></p>
<p>After some digging, <a href="https://github.com/callemall/material-ui/issues/4021">I did found that a theme needs to be passed down in a context</a>. I am doing that in the test but still get this error. </p>
<p>My test:</p>
<pre><code>import expect from 'expect';
import React, {PropTypes} from 'react';
import {mount} from 'enzyme';
import SearchBar from './SearchBar';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
function setup() {
const muiTheme = getMuiTheme();
const props = {
closeSearchBar: () => {},
fetchSearchData: () => {},
data: [],
searching: false
};
return mount(<SearchBar {...props} />, {context: {muiTheme}});
}
describe('SearchBar Component', ()=> {
it('Renders search toolbar properly', () => {
const wrapper = setup();
expect(wrapper.find('.toolbar').length).toBe(1);
expect(wrapper.find('button').length).toBe(1);
});
});
</code></pre>
<p>My searchbar component is a stateless component, so I am not pulling in any context. But even when I am, I still get the same error. </p>
<p>What am I doing wrong?</p>
| 0debug
|
Facing a 'strange' runtime error to run a simple program : <p>I am using Windows 10 Pro 64-bit and and Dev C++ compliler(TDM-GCC 4.9.2 64-bit release). How to resolve the above cited error.</p>
<p>Below link for screenshot:</p>
<p><a href="https://i.stack.imgur.com/Wdttj.png" rel="nofollow noreferrer">https://i.stack.imgur.com/Wdttj.png</a></p>
| 0debug
|
void ff_get_wav_header(AVIOContext *pb, AVCodecContext *codec, int size)
{
int id;
id = avio_rl16(pb);
codec->codec_type = AVMEDIA_TYPE_AUDIO;
codec->codec_tag = id;
codec->channels = avio_rl16(pb);
codec->sample_rate = avio_rl32(pb);
codec->bit_rate = avio_rl32(pb) * 8;
codec->block_align = avio_rl16(pb);
if (size == 14) {
codec->bits_per_coded_sample = 8;
}else
codec->bits_per_coded_sample = avio_rl16(pb);
if (size >= 18) {
int cbSize = avio_rl16(pb);
size -= 18;
cbSize = FFMIN(size, cbSize);
if (cbSize >= 22 && id == 0xfffe) {
codec->bits_per_coded_sample = avio_rl16(pb);
codec->channel_layout = avio_rl32(pb);
id = avio_rl32(pb);
avio_skip(pb, 12);
cbSize -= 22;
size -= 22;
}
codec->extradata_size = cbSize;
if (cbSize > 0) {
codec->extradata = av_mallocz(codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
avio_read(pb, codec->extradata, codec->extradata_size);
size -= cbSize;
}
if (size > 0)
avio_skip(pb, size);
}
codec->codec_id = ff_wav_codec_get_id(id, codec->bits_per_coded_sample);
if (codec->codec_id == CODEC_ID_AAC_LATM) {
codec->channels = 0;
codec->sample_rate = 0;
}
}
| 1threat
|
Should Node.js apps be published to npm? : <p>I am making a Node.js server application. It is hosted on GitHub and I thought that I would publish it to npm to make it easier to install for users.</p>
<p>The problem is, when I run npm install my-app, it installs it to the node_modules directory. I would like it to be installed into the current directory, kind of like a git clone would do.</p>
<p>Is this a valid use case for npm publish? Or should I just stick with the git clone, npm install, npm start flow?</p>
| 0debug
|
static void ff_h264_idct_add_mmx(uint8_t *dst, int16_t *block, int stride)
{
__asm__ volatile(
"movq (%0), %%mm0 \n\t"
"movq 8(%0), %%mm1 \n\t"
"movq 16(%0), %%mm2 \n\t"
"movq 24(%0), %%mm3 \n\t"
:: "r"(block) );
__asm__ volatile(
IDCT4_1D( %%mm2, %%mm1, %%mm0, %%mm3, %%mm4 )
"movq %0, %%mm6 \n\t"
TRANSPOSE4( %%mm3, %%mm1, %%mm0, %%mm2, %%mm4 )
"paddw %%mm6, %%mm3 \n\t"
IDCT4_1D( %%mm4, %%mm2, %%mm3, %%mm0, %%mm1 )
"pxor %%mm7, %%mm7 \n\t"
:: "m"(ff_pw_32));
__asm__ volatile(
STORE_DIFF_4P( %%mm0, %%mm1, %%mm7)
"add %1, %0 \n\t"
STORE_DIFF_4P( %%mm2, %%mm1, %%mm7)
"add %1, %0 \n\t"
STORE_DIFF_4P( %%mm3, %%mm1, %%mm7)
"add %1, %0 \n\t"
STORE_DIFF_4P( %%mm4, %%mm1, %%mm7)
: "+r"(dst)
: "r" ((x86_reg)stride)
);
}
| 1threat
|
How could I know if my integer array contains characters? : for example my array contains elements like 56,12,ew34,45 or 56,12,34rt,45 how can I show that the array is not integer array?
| 0debug
|
Using AWS Certificate Manager (ACM Certificate) with Elastic Beanstalk : <p>When you have a certificate for your domain issued through AWS Certificate Manager, how do you apply that certificate to an Elastic Beanstalk application.</p>
<p>Yes, the Elastic Beanstalk application is load balanced and does have an ELB associated with it.</p>
<p>I know I can apply it directly to the ELB my self. But I want to apply it through Elastic Beanstalk so the env configuration is saved onto the Cloud Formation template.</p>
| 0debug
|
How to add clickable link inside sting in swift : Is there any way of adding link inside string in swift without using textview ?
I mean line "message that should show <a href='link'> Link goes here </a> in alert "
| 0debug
|
Methods for using Git with Google Colab : <p>Are there any recommended methods to integrate git with colab?</p>
<p>For example, is it possible to work off code from google source repositories or the likes?</p>
<p>Neither google drive nor cloud storage can be used for git functionality.</p>
<p>So I was wondering if there is a way to still do it?</p>
| 0debug
|
How do you import type definitions from `@types` typescript 2.0 : <p>I'm using typescript 2.0 with the lastest <code>ionic@RC.0</code> build process.</p>
<p>I installed the google-maps types like this: </p>
<p><code>npm install @types/google-maps --save-dev --save-exact</code></p>
<p>and I'm trying to import some of the type definitions into my code like this</p>
<pre><code>/// <reference types="google-maps" />
import { LatLng, LatLngBounds } from 'google-maps';
</code></pre>
<p>but I get this typescript error:</p>
<p><code>./node_modules/@types/google-maps/index.d.ts has no exported member 'LatLng'</code></p>
<p>and if I look in the source, I actually find the definition in</p>
<p><code>./node_modules/@types/google-maps/node_modules/@types/googlemaps/index.d.ts</code></p>
| 0debug
|
ssize_t v9fs_get_xattr(FsContext *ctx, const char *path,
const char *name, void *value, size_t size)
{
XattrOperations *xops = get_xattr_operations(ctx->xops, name);
if (xops) {
return xops->getxattr(ctx, path, name, value, size);
}
errno = -EOPNOTSUPP;
return -1;
}
| 1threat
|
connection.query('SELECT * FROM users WHERE username = ' + input_string)
| 1threat
|
How to save the rotation of an image on server ? : $filename = '01.jpg';
$degrees = 90;
// Content type
header('Content-type: image/jpeg');
// Load
$source = imagecreatefromjpeg($filename);
// Rotate
$rotate = imagerotate($source, $degrees, 0);
// Output
$rotate = imagejpeg($rotate);
I am using this please explain how to update those image
| 0debug
|
Write to a file with sudo privileges in Python : <p>The following code throws an error if it's run by a non-root user for a file owned by root, even when the non-root user has sudo privileges:</p>
<pre><code>try:
f = open(filename, "w+")
except IOError:
sys.stderr.write('Error: Failed to open file %s' % (filename))
f.write(response + "\n" + new_line)
f.close()
</code></pre>
<p>Is there a way to run <code>open(filename, "w+")</code> with sudo privileges, or an alternative function that does this?</p>
| 0debug
|
why does numpy normalize these equivalent arrays differently? : <p>The two arrays <code>raw_document_scores</code> and <code>raw_doc_scores1 are equal</code>, evidenced by <code>raw_document_scores==raw_doc_scores1</code> returning an array of all trues. However, when I check if </p>
<pre><code>raw_document_scores/np.linalg.norm(raw_document_scores, 1, axis=1).reshape(-1,1) \
== raw_doc_scores1/np.linalg.norm(raw_doc_scores1, 1, axis=1).reshape(-1,1)
</code></pre>
<p>I get false for some entries. I subtracted the two arrays to see how much each entry differs by, and it's less than e-18, so they are approximately equal. However, why are they not exactly equal, if the input arrays are exactly equal? Are the first two arrays not actually equal, and python/numpy is lying when it says all their entries are equal? Here is an image to show what happened.</p>
<p><a href="https://i.stack.imgur.com/7mYLJ.png" rel="nofollow noreferrer">difference</a></p>
| 0debug
|
db.execute('SELECT * FROM products WHERE product_id = ' + product_input)
| 1threat
|
Show max variable price in shop page : <p>I want to display the maximum variation price in woocommerce shop page under product title. </p>
<p>I have tried using this code but does not seem to work, only breaks my site instead.</p>
<p>add_filter( ‘woocommerce_variable_sale_price_html’, ‘con_show_max_variation_price_only’, 10, 2 );
add_filter( ‘woocommerce_variable_price_html’, ‘con_show_max_variation_price_only’, 10, 2 );</p>
<p>function con_show_max_variation_price_only( $price, $product ) {</p>
<p>// Main Variation Price
$prices = array( $product->get_variation_price( ‘max’, true ), $product->get_variation_price( ‘min’, true ) );</p>
<p>$price = $prices[0] !== $prices[1] ? sprintf( __( ‘%1$s’, ‘woocommerce’ ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );</p>
| 0debug
|
adding data in table in MS teams message card : <p>Want to display data in table like this in the message card. Any pointers???</p>
<p><a href="https://i.stack.imgur.com/f6ggE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f6ggE.png" alt="enter image description here"></a></p>
| 0debug
|
static void fw_cfg_init1(DeviceState *dev)
{
FWCfgState *s = FW_CFG(dev);
MachineState *machine = MACHINE(qdev_get_machine());
assert(!object_resolve_path(FW_CFG_PATH, NULL));
object_property_add_child(OBJECT(machine), FW_CFG_NAME, OBJECT(s), NULL);
qdev_init_nofail(dev);
fw_cfg_add_bytes(s, FW_CFG_SIGNATURE, (char *)"QEMU", 4);
fw_cfg_add_bytes(s, FW_CFG_UUID, &qemu_uuid, 16);
fw_cfg_add_i16(s, FW_CFG_NOGRAPHIC, (uint16_t)!machine->enable_graphics);
fw_cfg_add_i16(s, FW_CFG_NB_CPUS, (uint16_t)smp_cpus);
fw_cfg_add_i16(s, FW_CFG_BOOT_MENU, (uint16_t)boot_menu);
fw_cfg_bootsplash(s);
fw_cfg_reboot(s);
s->machine_ready.notify = fw_cfg_machine_ready;
qemu_add_machine_init_done_notifier(&s->machine_ready);
}
| 1threat
|
TypeError: 'float' object is not callable (Finding Averages of a list of numbers) : sales = [49.99, 20, 155.20, 71.65, 91.07]
length = len(sales)
max_value = max(sales)
min_value = min(sales)
sum_of_values = sum(sales)
print(length, max_value, min_value, sum_value)
average = float(sum_of_values/length)
answer = round(average,2)
print(answer)
im trying to get a sum of the numbers in the list and then finding the average, rounding the average to 2 decimal places, and then printing it. how would i fix this error?
| 0debug
|
Android: method for executing code after button onClick() is executed : Is there any method with Android for Buttons that can be run post clicking a button. For example; something along the lines of btn.postClick() or btn.postExecute?
| 0debug
|
void *cpu_register_map_client(void *opaque, void (*callback)(void *opaque))
{
MapClient *client = qemu_malloc(sizeof(*client));
client->opaque = opaque;
client->callback = callback;
LIST_INSERT_HEAD(&map_client_list, client, link);
return client;
}
| 1threat
|
What is the internal sorting technique used in comparator and comparable interfaces and why? : <p>With regards to both <strong>Comparable and Comparator interface</strong> in Java, i wanted to ask, what is the <strong>sorting technique used internally</strong>, and any reason for using the sorting technique in comparison to other sort techniques? </p>
| 0debug
|
static coroutine_fn void reconnect_to_sdog(void *opaque)
{
Error *local_err = NULL;
BDRVSheepdogState *s = opaque;
AIOReq *aio_req, *next;
aio_set_fd_handler(s->aio_context, s->fd, NULL, NULL, NULL);
close(s->fd);
s->fd = -1;
while (s->co_send != NULL) {
co_write_request(opaque);
}
while (s->fd < 0) {
s->fd = get_sheep_fd(s, &local_err);
if (s->fd < 0) {
DPRINTF("Wait for connection to be established\n");
error_report("%s", error_get_pretty(local_err));
error_free(local_err);
co_aio_sleep_ns(bdrv_get_aio_context(s->bs), QEMU_CLOCK_REALTIME,
1000000000ULL);
}
};
QLIST_FOREACH_SAFE(aio_req, &s->inflight_aio_head, aio_siblings, next) {
QLIST_REMOVE(aio_req, aio_siblings);
QLIST_INSERT_HEAD(&s->failed_aio_head, aio_req, aio_siblings);
}
while (!QLIST_EMPTY(&s->failed_aio_head)) {
aio_req = QLIST_FIRST(&s->failed_aio_head);
QLIST_REMOVE(aio_req, aio_siblings);
QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
resend_aioreq(s, aio_req);
}
}
| 1threat
|
How can I get something specific from json in node.js : <p>I am trying to get a youtube subscriber count using googles node.js API <a href="https://github.com/googleapis/google-api-nodejs-client" rel="nofollow noreferrer">https://github.com/googleapis/google-api-nodejs-client</a> and I am also using the youtube data api from google <a href="https://developers.google.com/youtube/v3/" rel="nofollow noreferrer">https://developers.google.com/youtube/v3/</a> I am trying to get subscriberCount from here <a href="https://www.googleapis.com/youtube/v3/channels?part=statistics&id=channel_id&key=api_key" rel="nofollow noreferrer">https://www.googleapis.com/youtube/v3/channels?part=statistics&id=channel_id&key=api_key</a> and here's what I have
here is my code and what I am getting <a href="https://hastebin.com/sotejijole.js" rel="nofollow noreferrer">https://hastebin.com/sotejijole.js</a>, subscriberCount is in statistics: [Object] but I don't know how I can get to it.</p>
| 0debug
|
static void superh_cpu_realizefn(DeviceState *dev, Error **errp)
{
SuperHCPU *cpu = SUPERH_CPU(dev);
SuperHCPUClass *scc = SUPERH_CPU_GET_CLASS(dev);
cpu_reset(CPU(cpu));
scc->parent_realize(dev, errp);
}
| 1threat
|
How to use an image instead of an icon in flutter? : <p>I am currently doing something like this</p>
<pre><code>new Tab(icon: new Icon(Icons.arrow_forward), text: "Browse"),
</code></pre>
<p>However I would like to use an image as an icon . I get images using </p>
<pre><code>new Image.asset("assets/img/logo.png"),
</code></pre>
<p>My question is how can i use that image as an icon in my tab shown above ?</p>
| 0debug
|
How to upload file from resources using selenium webdriver : <p>I want to upload a file with selenium webdriver. The file is in resources folder of my project, how can i do ?</p>
| 0debug
|
static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
bool assign, uint32_t size, bool datamatch)
{
int ret;
struct kvm_ioeventfd iofd;
iofd.datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0;
iofd.addr = addr;
iofd.len = size;
iofd.flags = 0;
iofd.fd = fd;
if (!kvm_enabled()) {
return -ENOSYS;
}
if (datamatch) {
iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
}
if (!assign) {
iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
}
ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
if (ret < 0) {
return -errno;
}
return 0;
}
| 1threat
|
static inline void array_free(array_t* array)
{
if(array->pointer)
free(array->pointer);
array->size=array->next=0;
}
| 1threat
|
Using Laravel Socialite with an API? : <p>I'm trying to use Laravel Socialite package over an api. I try to pass the code into my api to fetch the user but it keeps giving me an error:</p>
<pre><code>Fatal error: Call to a member function pull() on null
</code></pre>
<p>Since I'm doing the request over an API, I take the following steps.</p>
<p>Send a request to api for the url to fetch the code:</p>
<pre><code>Socialite::with('facebook')->stateless()->redirect()->getTargetUrl()
</code></pre>
<p>Then make a request with the above fetched url, which redirects with the <code>code</code> parameter.</p>
<p>Send the code to the api and fetch the user:</p>
<pre><code>$fb_user = Socialite::with('facebook')->user();
</code></pre>
<p>This is where it crashes. I'm not sure why. </p>
<p>I've used the package before and it works fine when I just have an app that reloads the page. But when I send it to an api (on a different domain) it crashes. I'm thinking there is some issue with how the code is generated. Is there anyway to fix this?</p>
| 0debug
|
plsql procedure that will detele rows : I have a table: USERS, with fields: username,fname, lname, age
I need to create procedure that will delete username from parameter, if the age if less than 18
I did some code, but it won't work:
create procedure delete_user(username in varchar2)
as
begin
if exists (delete from username where age < 18);
dmbs_output.put_line(username);
end;
exec detele_user('mrgreen');
| 0debug
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.