problem stringlengths 26 131k | labels class label 2 classes |
|---|---|
static int spdif_write_packet(struct AVFormatContext *s, AVPacket *pkt)
{
IEC958Context *ctx = s->priv_data;
int ret, padding;
ctx->out_bytes = pkt->size;
ctx->length_code = FFALIGN(pkt->size, 2) << 3;
ret = ctx->header_info(s, pkt);
if (ret < 0)
return -1;
if (!ctx->pkt_offset)
return 0;
padding = (ctx->pkt_offset - BURST_HEADER_SIZE - ctx->out_bytes) >> 1;
if (padding < 0) {
av_log(s, AV_LOG_ERROR, "bitrate is too high\n");
return -1;
}
put_le16(s->pb, SYNCWORD1);
put_le16(s->pb, SYNCWORD2);
put_le16(s->pb, ctx->data_type);
put_le16(s->pb, ctx->length_code);
#if HAVE_BIGENDIAN
put_buffer(s->pb, ctx->out_buf, ctx->out_bytes & ~1);
#else
av_fast_malloc(&ctx->buffer, &ctx->buffer_size, ctx->out_bytes + FF_INPUT_BUFFER_PADDING_SIZE);
if (!ctx->buffer)
return AVERROR(ENOMEM);
ff_spdif_bswap_buf16((uint16_t *)ctx->buffer, (uint16_t *)ctx->out_buf, ctx->out_bytes >> 1);
put_buffer(s->pb, ctx->buffer, ctx->out_bytes & ~1);
#endif
if (ctx->out_bytes & 1)
put_be16(s->pb, ctx->out_buf[ctx->out_bytes - 1]);
for (; padding > 0; padding--)
put_be16(s->pb, 0);
av_log(s, AV_LOG_DEBUG, "type=%x len=%i pkt_offset=%i\n",
ctx->data_type, ctx->out_bytes, ctx->pkt_offset);
put_flush_packet(s->pb);
return 0;
} | 1threat |
pass data from ajax in php : i want to pass data from ajax. can anybody please tell me how is that possible??
here is my index.php
<form method="post" action="">
<input type="text" id="class_name" name="class_name">
<input type="hidden" name="user_id" id="user_id" value="<?=$user_id?>" />
<button id="submit" name="submit" value="submit" type="submit"></button>
</form>
and here is update.php
<?
if(isset($_POST['submit'])) {
user_id= $_POST['user_id'];
class_name= $_POSt['class_name'];
$date= date("M d , Y");
$sql_ins="insert into chat set user_id='$user_id', class_name='$class_name',
time=now(),date='$date'";
$sql_que=$db->db_query($sql_ins);
}
?>
how can i pass this data into server via ajax not from action..??
what is the ajax script for that??
Thanks in advance
| 0debug |
How to fix Connection reset by peer message from apache-spark? : <p>I keep getting the the following exception very frequently and I wonder why this is happening? After researching I found I could do <code>.set("spark.submit.deployMode", "nio");</code> but that did not work either and I am using spark 2.0.0 </p>
<pre><code>WARN TransportChannelHandler: Exception in connection from /172.31.3.245:46014
java.io.IOException: Connection reset by peer
at sun.nio.ch.FileDispatcherImpl.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
at sun.nio.ch.IOUtil.read(IOUtil.java:192)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
at io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:221)
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:898)
at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:242)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:119)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354)
at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:112)
</code></pre>
| 0debug |
connection.query('SELECT * FROM users WHERE username = ' + input_string) | 1threat |
Git repository setup for a Docker application consisting of multiple repositories : <p>Given the following structure;</p>
<pre><code>├── api/ - A PHP application, to have its own repository
├── docker/ - Docker configuration for shared containers (MySQL, Nginx)
├── docker-compose.yml - Defines all of the services
└── web-client/ - A standalone Angular application, to have its own repository
</code></pre>
<p>Currently the entire application is in one repository but I am looking to split into separate repositories. Development has not started so there is no issue with maintaining any history etc.</p>
<p>Firstly, is defining all of the services in a root level <code>docker-compose</code> file the best way to go about this, or should the <code>api</code> and <code>web-client</code> be more isolated with their own <code>docker-compose</code>, thus managed completely separately? If separate, is it possible to still have one "<code>depends_on</code>" another?</p>
<p>Secondly, what is the best way to manage repositories for this? The root level code (<code>docker-compose.yml</code> and <code>docker/</code>) should exist in one repository, but that also depends on the other two repositories being present, presumably as children. I looked into git submodules for this but it seems as though the parent repository has to be tied to specific commits in the children, which may make working on multiple parallel features difficult?</p>
| 0debug |
What is the difference between the predict and predict_on_batch methods of a Keras model? : <p>According to the keras <a href="https://keras.io/models/sequential/" rel="noreferrer">documentation</a>:</p>
<pre><code>predict_on_batch(self, x)
Returns predictions for a single batch of samples.
</code></pre>
<p>However, there does not seem to be any difference with the standard <code>predict</code> method when called on a batch, whether it being with one or multiple elements.</p>
<pre><code>model.predict_on_batch(np.zeros((n, d_in)))
</code></pre>
<p>is the same as </p>
<pre><code>model.predict(np.zeros((n, d_in)))
</code></pre>
<p>(a <code>numpy.ndarray</code> of shape <code>(n, d_out</code>)</p>
| 0debug |
static av_cold int wmv2_encode_init(AVCodecContext *avctx){
Wmv2Context * const w= avctx->priv_data;
if(ff_MPV_encode_init(avctx) < 0)
return -1;
ff_wmv2_common_init(w);
avctx->extradata_size= 4;
avctx->extradata= av_mallocz(avctx->extradata_size + 10);
encode_ext_header(w);
return 0;
}
| 1threat |
fork join not giving better performace : i am trying to check performance of following code but everytime i am getting sequential operation gives better performance as compared to fork join
problem i want to find max integer
public class GetMaxIntegerProblem {
private final int[] intArray;
private int start;
private int end;
private int size;
public GetMaxIntegerProblem(int[] intArray, int start, int end) {
super();
this.intArray = intArray;
this.start = start;
this.end = end;
size = end - start;
}
public int getMaxSequentially() {
int max = Integer.MIN_VALUE;
for (int i = start; i < end; i++) {
int n = intArray[i];
max = n > max ? n : max;
}
return max;
}
public int getSize() {
return size;
}
public GetMaxIntegerProblem getMaxIntegerSubProblem(int subStart, int subEnd) {
return new GetMaxIntegerProblem(this.intArray, start + subStart, start + subEnd);
}
}
my action for fork join
import java.util.concurrent.RecursiveAction;
public class GetMaxIntegerAction extends RecursiveAction {
private final int threshold;
private final GetMaxIntegerProblem problem;
private int result;
public GetMaxIntegerAction(int threshold, GetMaxIntegerProblem problem) {
super();
this.threshold = threshold;
this.problem = problem;
}
@Override
protected void compute() {
if (problem.getSize() < threshold) {
result = problem.getMaxSequentially();
} else {
int midPoint = problem.getSize() / 2;
GetMaxIntegerProblem leftProblem = problem.getMaxIntegerSubProblem(0, midPoint);
GetMaxIntegerProblem rightProblem = problem.getMaxIntegerSubProblem(midPoint + 1, problem.getSize());
GetMaxIntegerAction left = new GetMaxIntegerAction(threshold, leftProblem);
GetMaxIntegerAction right = new GetMaxIntegerAction(threshold, rightProblem);
invokeAll(left, right);
result = Math.max(left.result, right.result);
}
}
}
my Main program for testing
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
public class GetMaxIntegerMain {
public GetMaxIntegerMain() {
// TODO Auto-generated constructor stub
}
private Random random = new Random();
private void fillRandomArray(int[] randomArray) {
for (int i = 0; i < randomArray.length; i++) {
randomArray[i] = random.nextInt(10000);
}
}
/**
* @param args
*/
public static void main(String[] args) {
GetMaxIntegerMain mainexcution=new GetMaxIntegerMain();
int arrayLength = 10_00_000;
int array[] = new int[arrayLength];
mainexcution.fillRandomArray(array);
GetMaxIntegerProblem problem=new GetMaxIntegerProblem(array, 0, array.length);
//No. of times sequential &
//Parallel operation should be performed to warm up HotSpot JVM
final int iterations = 10;
long start = System.nanoTime();
int maxSeq=0;
for (int i = 0; i < iterations; i++) {
maxSeq=problem.getMaxSequentially();
}
long endSeq=System.nanoTime();
long totalSeq=endSeq-start;
System.out.println(" time for seq "+(endSeq-start));
System.out.println("Number of processor available: " + Runtime.getRuntime().availableProcessors());
//Default parallelism level = Runtime.getRuntime().availableProcessors()
int threads=Runtime.getRuntime().availableProcessors();
ForkJoinPool fjpool = new ForkJoinPool(64);
long startParallel = System.nanoTime();
for (int i = 0; i < iterations; i++) {
GetMaxIntegerAction action=new GetMaxIntegerAction(5000, problem);
fjpool.invoke(action);
}
long endParallel = System.nanoTime();
long totalP=endParallel-startParallel;
System.out.println(" time for parallel "+totalP);
double speedup=(double)(totalSeq/totalP);
System.out.println(" speedup "+speedup);
System.out.println("Number of steals: " + fjpool.getStealCount() + "\n");
}
}
every time i am running this code i am getting forkjoin specific code takes 400% more time. i tried with various combination of threshold but i am not getting to success.
i am running this code on **Intel Core i3 Processor 3.3 GHz 64 bit on windows 10**
it will be great help if someone can provide some pointers on this problem
| 0debug |
IntelliJ: Display .java extension in Packages View : <p>I am pretty new to IntelliJ and I can't find an option to display all file extension in the packages view (in my case .java).</p>
<p><a href="https://i.stack.imgur.com/M5fbV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/M5fbV.png" alt="My problem of the viewer"></a></p>
<p>As you can see on the sceenshot it just says "Main" or "Controller" on the left package explorer view.</p>
<p>Is there any option to make it display Main.Java and Controller.java (like in the editor view on the right side)?</p>
<p>Thanks a lot!</p>
| 0debug |
Portfolio gallery without "all" filter : <p>I'm currently working on a portfolio gallery, I found one on w3schools: <br><br><a href="https://www.w3schools.com/howto/howto_js_portfolio_filter.asp" rel="nofollow noreferrer">https://www.w3schools.com/howto/howto_js_portfolio_filter.asp</a></p>
<p>My only question is, is it possible to remove the "show all" filter and just have it selected on another filter by default?</p>
| 0debug |
JAVA: You have an error in your SQL syntax; check the manual that corresponds? : <p>I'm using <strong>Java + MySQL</strong> for a game server project of mine. I'm having a problem though -</p>
<pre><code>MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(connection) (`uuid`, `name`, `join_date`, `group`) VALUES (5dcd14f9 at line 1
</code></pre>
<p>The uuid should be 5dcd14f9-....-.....-...
Dots are characters that should exist there, and the dashes are just dashes.
For some reason I'm having a problem where it only gets the first part of the uuid.
Am I missing something, or is there actually something wrong with my syntax?
That's my code which is basically the error:</p>
<pre><code>PreparedStatement addPlayer = mySQL.getConnection().prepareStatement("INSERT INTO " + mySQL.getConnection() + " (uuid, name, join_date, group) VALUES (?,?,?,?)");
</code></pre>
<p>I of course cast the uuid to a string and add it as a value to the first column.
I've looked at other solutions and tried them but they didn't seem to work.</p>
| 0debug |
static int decode_block(MJpegDecodeContext *s, DCTELEM *block,
int component, int dc_index, int ac_index, int16_t *quant_matrix)
{
int code, i, j, level, val;
val = mjpeg_decode_dc(s, dc_index);
if (val == 0xffff) {
av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
return -1;
}
val = val * quant_matrix[0] + s->last_dc[component];
s->last_dc[component] = val;
block[0] = val;
i = 0;
{OPEN_READER(re, &s->gb)
for(;;) {
UPDATE_CACHE(re, &s->gb);
GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2)
if (code == 0x10)
break;
i += ((unsigned)code) >> 4;
code &= 0xf;
if(code){
if(code > MIN_CACHE_BITS - 16){
UPDATE_CACHE(re, &s->gb)
}
{
int cache=GET_CACHE(re,&s->gb);
int sign=(~cache)>>31;
level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
}
LAST_SKIP_BITS(re, &s->gb, code)
if (i >= 63) {
if(i == 63){
j = s->scantable.permutated[63];
block[j] = level * quant_matrix[j];
break;
}
av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
return -1;
}
j = s->scantable.permutated[i];
block[j] = level * quant_matrix[j];
}
}
CLOSE_READER(re, &s->gb)}
return 0;
}
| 1threat |
Variadic template only compiles when forward declared : <p>I have a variadic template that inherits from all template arguments:</p>
<pre><code>template <typename... Ts>
struct derived : Ts...
{
};
</code></pre>
<p>I would also like to have a facility for expressing the type of "existing <code>derived</code> with added template arguments". My attempt at this is:</p>
<pre><code>// Do not ODR-use (goes in namespace impl or similar)!
template<class ... NewInputs, class ... ExistingInputs>
auto addedHelper(const derived<ExistingInputs...>&)
-> derived<ExistingInputs..., NewInputs...>;
template<class ExistingInput, class ... NewInputs>
using Added = decltype(addedHelper<NewInputs...>(std::declval<ExistingInput>()));
</code></pre>
<p>As a simple example, <code>Added<derived<A, B>, C></code> should be <code>derived<A, B, C></code>. I use the helper function for template argument deduction of the first parameter pack.</p>
<p>My problem: For some reason, I can use this successfully with incomplete types if <code>derived</code> has been forward declared, but <strong>not</strong> if it was defined.</p>
<p><strong>Why does this code <a href="https://godbolt.org/z/ePhquh" rel="noreferrer">not compile</a>:</strong></p>
<pre><code>#include <utility>
template <typename... Ts>
struct derived : Ts...
{};
template<class ... NewInputs, class ... ExistingInputs>
auto addedHelper(const derived<ExistingInputs...>&)
-> derived<ExistingInputs..., NewInputs...>;
template<class ExistingInput, class ... NewInputs>
using Added = decltype(addedHelper<NewInputs...>(std::declval<ExistingInput>()));
struct A;
struct B;
struct C;
// Goal: This forward declaration should work (with incomplete A, B, C).
auto test(derived<A, B> in) -> Added<decltype(in), C>;
struct A {};
struct B {};
struct C {};
void foo()
{
auto abc = test({});
static_assert(std::is_same_v<decltype(abc), derived<A, B, C>>, "Pass");
}
</code></pre>
<p><strong>Whereas this code <a href="https://godbolt.org/z/qow3Kb" rel="noreferrer">does compile</a>:</strong></p>
<pre><code>#include <utility>
template <typename... Ts>
struct derived;
template<class ... NewInputs, class ... ExistingInputs>
auto addedHelper(const derived<ExistingInputs...>&)
-> derived<ExistingInputs..., NewInputs...>;
template<class ExistingInput, class ... NewInputs>
using Added = decltype(addedHelper<NewInputs...>(std::declval<ExistingInput>()));
struct A;
struct B;
struct C;
// Goal: This forward declaration should work (with incomplete A, B, C).
auto test(derived<A, B> in) -> Added<decltype(in), C>;
template <typename... Ts>
struct derived : Ts...
{};
struct A {};
struct B {};
struct C {};
void foo()
{
auto abc = test({});
static_assert(std::is_same_v<decltype(abc), derived<A, B, C>>, "Pass");
}
</code></pre>
<p>For convenience, here are both cases at once (comment in/out <code>#define FORWARD_DECLARED</code>): <a href="https://godbolt.org/z/7gM52j" rel="noreferrer">https://godbolt.org/z/7gM52j</a></p>
<p>I do not understand how code could possibly become illegal by replacing a forward declaration by the respective definition (which would otherwise just come later).</p>
| 0debug |
Handle big data in datatables codeigniter with mySQL : <p>Please help,
I want to show data which the result of computation on codeigniter. I've 7789 data and it's run so long. Can anybody help me to solve my problem?</p>
| 0debug |
Insert 2D Array into MySQL Database : <p>So i have a multidimensional array as follows:</p>
<pre><code>int[][] multiarray = {
{ 0, 1, 0, 1, 0 },
{ 1, 0, 1, 0, 1 },
{ 0, 1, 0, 1, 0 },
{ 1, 0, 1, 0, 1 },
{ 0, 1, 0, 1, 0 },
};
</code></pre>
<p>I have a MySQL database with 5 columns:</p>
<pre><code>|number1|number2|number3|number4|number5|
</code></pre>
<p>My question is, how would i insert this array into the mysql database?</p>
<p>Thanks</p>
| 0debug |
Backing up MongoDB, Need service to transfer the dump to another server? : <p>I just go the backup service on Ubuntu to work so now I get very nice bson and json dumps which I wanted. </p>
<p>My problem is I can only get the server to backup to a folder on the server.</p>
<p>So what I do today is login to the server with filezilla and copy the files manually to my machine (where I store all backups). I do this every day.</p>
<p>Is there a way to automate this? A windows service that can log on to a FTP once a day and copy the files to local machine? </p>
| 0debug |
static bool select_accel_fn(const void *buf, size_t len)
{
uintptr_t ibuf = (uintptr_t)buf;
#ifdef CONFIG_AVX2_OPT
if (len % 128 == 0 && ibuf % 32 == 0 && (cpuid_cache & CACHE_AVX2)) {
return buffer_zero_avx2(buf, len);
}
if (len % 64 == 0 && ibuf % 16 == 0 && (cpuid_cache & CACHE_SSE4)) {
return buffer_zero_sse4(buf, len);
}
#endif
if (len % 64 == 0 && ibuf % 16 == 0 && (cpuid_cache & CACHE_SSE2)) {
return buffer_zero_sse2(buf, len);
}
return buffer_zero_int(buf, len);
}
| 1threat |
Cardview - edittext + image + buttons : I have problem with **Cardview**. I want this XML makes nicer, so I wanted to add CardView (**or do you have better idea?**), but I always screw up .... Can you help me please?
MY XML
<ImageView
android:id="@+id/StoryImageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:src="@drawable/page34"/>
<EditText
android:id="@+id/storyTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/choiceButton1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/StoryImageView"
android:background="@null"
android:cursorVisible="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:lineSpacingMultiplier="1.2"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:paddingTop="15dp"
android:text="TEXT TEXT TEXT
TEXT TEXT TEXT
TEXT TEXT TEXT
TEXT TEXT TEXT
TEXT TEXT TEXT
TEXT TEXT TEXT
TEXT TEXT TEXT
TEXT TEXT TEXT
TEXT TEXT TEXT
TEXT TEXT TEXT
"
android:textColor="#9E9E9E"
android:textSize="16sp"
tools:textColor="#9E9E9E"/>
<Button
android:id="@+id/choiceButton1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/choiceButton2"
android:layout_marginTop="3dp"
android:background="#212121"
android:text="button1"
android:textColor="#b71c1c"/>
<Button
android:id="@+id/choiceButton2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="11dp"
android:layout_marginTop="3dp"
android:background="#212121"
android:text="button2"
android:textColor="#b71c1c"/>
This all is in:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_story"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#212121"
tools:context="com.my.project">
</RelativeLayout>
[And in app looks like this - click][1]
Thank you very much guys :)
[1]: https://i.stack.imgur.com/1zNp6.jpg | 0debug |
Check a variable is a multiple of 10 and if not how do i round it up or down to the closest multiple of 10? : I need my program to check an in putted variable (e_gtin) and then calculate the GTIN from it (times the 1,3,5 and 7th number by three then add the 7 numbers up and divide by the nearest 10 times table) So far, it times the numbers and adds them up but I don't know where to go from there in terms of making it a multiple of ten
Any help would be appreciated.
e_gtin = input("Enter a 7 digit number - ")
gtin1 = int(e_gtin[0]) *3
print("First Digit of the GTIN8 code - ",gtin1)
gtin2 = int(e_gtin[1])
print("Second Digit of the GTIN8 code - ",gtin2)
gtin3 = int(e_gtin[2]) *3
print("Third Digit of the GTIN8 code - ",gtin3)
gtin4 = int(e_gtin[3])
print("Fourth Digit of the GTIN8 code - ",gtin4)
gtin5 = int(e_gtin[4]) *3
print("Fith Digit of the GTIN8 code - ",gtin5)
gtin6 = int(e_gtin[5])
print("Sixth Digit of the GTIN8 code - ",gtin6)
gtin7 = int(e_gtin[6]) *3
print("Seventh Digit of the GTIN8 code - ",gtin7)
GTIN7 = gtin1+ gtin2 + gtin3 + gtin4 + gtin5 + gtin6 + gtin7
from there how do I check its a multiple of ten and if it isn't how do I check which way to round, and then how do I round it?
Thanks in advance
Also this is to help with my practice GCSE Programming Coursework, which is why I'm bad with python.
| 0debug |
C++ error expected unqualified : <p>Okay so im trying to do some old quiz from my university and i have a question and this is the answer like this , when i try it on Dev-C++ its say wrong , but the teacher say its correct </p>
<pre><code>#include <iostream>
using namespace std;
void add (int,int);
int substract(int,int);
int multiply(int,int);
void divide(int,int);
int main()
{
int a,b;
cout<<"Please Enter The Value of a: ";
cin>>a;
cout<<"Please Enter The Value of b: ";
cin>>b;
add(a,b);
cout<<"The substract a-b is: "<<substract(a,b)<<endl;
cout<<"The multiply a*b is : "<<multiply(a,b)<<endl;
divide(a,b);
return 0;
}
void add (int a,int b);
{
cout<<"There sum is: "<<a+b<<endl;
}
int substract(int a,int b);
{
return (a-b);
}
int multiply (int a,int b);
{
return (a*b);
}
void divide (int a,int b);
{
cout<<"There divide is: "<<a/b<<endl;
}
</code></pre>
| 0debug |
db.execute('SELECT * FROM products WHERE product_id = ' + product_input) | 1threat |
static unsigned int get_video_format_idx(AVCodecContext *avctx)
{
unsigned int ret_idx = 0;
unsigned int idx;
unsigned int num_formats = sizeof(ff_schro_video_format_info) /
sizeof(ff_schro_video_format_info[0]);
for (idx = 1; idx < num_formats; ++idx) {
const SchroVideoFormatInfo *vf = &ff_schro_video_format_info[idx];
if (avctx->width == vf->width &&
avctx->height == vf->height) {
ret_idx = idx;
if (avctx->time_base.den == vf->frame_rate_num &&
avctx->time_base.num == vf->frame_rate_denom)
return idx;
}
}
return ret_idx;
}
| 1threat |
static int gen_rp_interrupts_init(PCIDevice *d, Error **errp)
{
int rc;
rc = msix_init_exclusive_bar(d, GEN_PCIE_ROOT_PORT_MSIX_NR_VECTOR, 0);
if (rc < 0) {
assert(rc == -ENOTSUP);
error_setg(errp, "Unable to init msix vectors");
} else {
msix_vector_use(d, 0);
}
return rc;
}
| 1threat |
Single patter returns different objects : So i am in big mess here. I can say my questions are few. I tried to make singleton patter but returns me two different objects. This is what i made (saw in another post) and tried to test it.
class Singleton
{
private static $instance = [];
public function __construct(){}
public function __clone(){}
public function __wakeup(){
throw new Exception("Cannot unserialize singleton");
}
public static function getInstance()
{
$class = get_called_class();
if(!isset(self::$instance[$class])){
self::$instance[$class] = new static();
}
return self::$instance[$class];
}
}
class Dog extends Singleton
{
public $name;
public function __construct($name)
{
$this->name = $name;
}
}
$dog = new Dog("Jorko");
$dog2 = new Dog("Peshko");
echo $dog->name; // returns "Jorko"
echo $dog2->name; // returns "Pesho"
I thought the second object (`$dog2`) should not be created and i will get `$dog` again. And why are we creating empty `__constructor` in the `class Singleton` also why are we using this `get_called_class` i mean according to php manual `Gets the name of the class the static method is called in.` that is what it returns but isn't `new static`. I thought that `new static` do the same thing. I am in a real mess. Search around the web but can't get it clear in my head. Thank you a lot! | 0debug |
Parallelism isn't reducing the time in dataset map : <p><a href="https://www.tensorflow.org/versions/r1.4/api_docs/python/tf/data/Dataset#map" rel="noreferrer">TF Map function supports parallel calls</a>. I'm seeing no improvements passing <code>num_parallel_calls</code> to map. With <code>num_parallel_calls=1</code> and <code>num_parallel_calls=10</code>, there is no improvement in performance run time. Here is a simple code</p>
<pre><code>import time
def test_two_custom_function_parallelism(num_parallel_calls=1, batch=False,
batch_size=1, repeat=1, num_iterations=10):
tf.reset_default_graph()
start = time.time()
dataset_x = tf.data.Dataset.range(1000).map(lambda x: tf.py_func(
squarer, [x], [tf.int64]),
num_parallel_calls=num_parallel_calls).repeat(repeat)
if batch:
dataset_x = dataset_x.batch(batch_size)
dataset_y = tf.data.Dataset.range(1000).map(lambda x: tf.py_func(
squarer, [x], [tf.int64]), num_parallel_calls=num_parallel_calls).repeat(repeat)
if batch:
dataset_y = dataset_x.batch(batch_size)
X = dataset_x.make_one_shot_iterator().get_next()
Y = dataset_x.make_one_shot_iterator().get_next()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
i = 0
while True:
try:
res = sess.run([X, Y])
i += 1
if i == num_iterations:
break
except tf.errors.OutOfRangeError as e:
pass
</code></pre>
<p>Here are the timings</p>
<pre><code>%timeit test_two_custom_function_parallelism(num_iterations=1000,
num_parallel_calls=2, batch_size=2, batch=True)
370ms
%timeit test_two_custom_function_parallelism(num_iterations=1000,
num_parallel_calls=5, batch_size=2, batch=True)
372ms
%timeit test_two_custom_function_parallelism(num_iterations=1000,
num_parallel_calls=10, batch_size=2, batch=True)
384ms
</code></pre>
<p>I used <code>%timeit</code> in Juypter notebook. What am I doing it wrong?</p>
| 0debug |
How do I write clipboard contents to text file? : <p>I need to write the contents of the clipboard to a text file. I've searched here for an answer but didn't find anything that worked for my situation. Just need a simple example.</p>
<p>Thanks in advance...</p>
| 0debug |
Calling Stored Procedures using LINQ : I have SP written on SQL Server:
- the input is `XML`
- It has a different OUTPUT
`ALTER PROCEDURE [dbo].[uspMyProcedure](
@XML XML,
@FamilySent INT = 0 OUTPUT ,
@FamilyImported INT = 0 OUTPUT)`
- The status is returned via `RETURN` and `SELECT` is also called
`SELECT Result FROM @tblResult
RETURN 0 --ALL OK
END`
How to set about calling this procedure in C#, Net. Core, EntityFrameworkCore using LINQ?
*The question about SP was already asked, but I can not find the answer for this situation* | 0debug |
What is the purpose of :after ? : I have seen lately many :after in front-end css and to me it seems like : hover but there's must be a differnce so I want to understand exactly how it works/applies.
Thanks very much. | 0debug |
List all public packages in the npm registry : <p>For research purposes, I'd like to list <em>all</em> the packages that are available on npm. How can I do this?</p>
<p>Some old docs at <a href="https://github.com/npm/registry/blob/master/docs/REGISTRY-API.md#get-all" rel="noreferrer">https://github.com/npm/registry/blob/master/docs/REGISTRY-API.md#get-all</a> mention an <code>/-/all</code> endpoint that presumably once worked, but <a href="http://registry.npmjs.org/-/all" rel="noreferrer">http://registry.npmjs.org/-/all</a> now just returns <code>{"message":"deprecated"}</code>.</p>
| 0debug |
Xcode 9: Provisioning profile is Xcode managed, but signing settings require a manually managed profile : <p>I need to archive my app for submission to iTunes Connect.</p>
<p>It was OK with Xcode 8.3.3:<br>
<a href="https://i.stack.imgur.com/rpB0D.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rpB0D.png" alt="enter image description here"></a></p>
<p>It's NOT OK with Xcode 9.0:<br>
<a href="https://i.stack.imgur.com/64ZeZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/64ZeZ.png" alt="enter image description here"></a></p>
<p>When archiving, I get:</p>
<blockquote>
<p>Code Signing Error: Provisioning profile "XC iOS: *" is Xcode managed, but signing settings require a manually managed profile.<br>
Code Signing Error: Code signing is required for product type 'Application' in SDK 'iOS 11.0'</p>
</blockquote>
<p>The two screenshots are taken from the same computer, same workspace.
<a href="https://i.stack.imgur.com/J5rBo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/J5rBo.png" alt="enter image description here"></a></p>
<p>I can't use "Automatic" because it would change the provisioning profile to a different one, then after uploading to iTunes Connect I would get:</p>
<blockquote>
<p><strong>Potential Loss of Keychain Access</strong> - The previous version of software has an application-identifier value of ['YBDK7H6MLG.com.ef.english24-7'] and the new version of software being submitted has an application-identifier of ['GEEM4BQ58H.com.ef.english24-7']. This will result in a loss of keychain access.</p>
</blockquote>
<p><strong>How do I make a release targeting iOS 11 without losing keychain access?</strong></p>
| 0debug |
static void stereo_processing(PSContext *ps, float (*l)[32][2], float (*r)[32][2], int is34)
{
int e, b, k;
float (*H11)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H11;
float (*H12)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H12;
float (*H21)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H21;
float (*H22)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H22;
int8_t *opd_hist = ps->opd_hist;
int8_t *ipd_hist = ps->ipd_hist;
int8_t iid_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];
int8_t icc_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];
int8_t ipd_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];
int8_t opd_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];
int8_t (*iid_mapped)[PS_MAX_NR_IIDICC] = iid_mapped_buf;
int8_t (*icc_mapped)[PS_MAX_NR_IIDICC] = icc_mapped_buf;
int8_t (*ipd_mapped)[PS_MAX_NR_IIDICC] = ipd_mapped_buf;
int8_t (*opd_mapped)[PS_MAX_NR_IIDICC] = opd_mapped_buf;
const int8_t *k_to_i = is34 ? k_to_i_34 : k_to_i_20;
TABLE_CONST float (*H_LUT)[8][4] = (PS_BASELINE || ps->icc_mode < 3) ? HA : HB;
if (ps->num_env_old) {
memcpy(H11[0][0], H11[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H11[0][0][0]));
memcpy(H11[1][0], H11[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H11[1][0][0]));
memcpy(H12[0][0], H12[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H12[0][0][0]));
memcpy(H12[1][0], H12[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H12[1][0][0]));
memcpy(H21[0][0], H21[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H21[0][0][0]));
memcpy(H21[1][0], H21[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H21[1][0][0]));
memcpy(H22[0][0], H22[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H22[0][0][0]));
memcpy(H22[1][0], H22[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H22[1][0][0]));
}
if (is34) {
remap34(&iid_mapped, ps->iid_par, ps->nr_iid_par, ps->num_env, 1);
remap34(&icc_mapped, ps->icc_par, ps->nr_icc_par, ps->num_env, 1);
if (ps->enable_ipdopd) {
remap34(&ipd_mapped, ps->ipd_par, ps->nr_ipdopd_par, ps->num_env, 0);
remap34(&opd_mapped, ps->opd_par, ps->nr_ipdopd_par, ps->num_env, 0);
}
if (!ps->is34bands_old) {
map_val_20_to_34(H11[0][0]);
map_val_20_to_34(H11[1][0]);
map_val_20_to_34(H12[0][0]);
map_val_20_to_34(H12[1][0]);
map_val_20_to_34(H21[0][0]);
map_val_20_to_34(H21[1][0]);
map_val_20_to_34(H22[0][0]);
map_val_20_to_34(H22[1][0]);
ipdopd_reset(ipd_hist, opd_hist);
}
} else {
remap20(&iid_mapped, ps->iid_par, ps->nr_iid_par, ps->num_env, 1);
remap20(&icc_mapped, ps->icc_par, ps->nr_icc_par, ps->num_env, 1);
if (ps->enable_ipdopd) {
remap20(&ipd_mapped, ps->ipd_par, ps->nr_ipdopd_par, ps->num_env, 0);
remap20(&opd_mapped, ps->opd_par, ps->nr_ipdopd_par, ps->num_env, 0);
}
if (ps->is34bands_old) {
map_val_34_to_20(H11[0][0]);
map_val_34_to_20(H11[1][0]);
map_val_34_to_20(H12[0][0]);
map_val_34_to_20(H12[1][0]);
map_val_34_to_20(H21[0][0]);
map_val_34_to_20(H21[1][0]);
map_val_34_to_20(H22[0][0]);
map_val_34_to_20(H22[1][0]);
ipdopd_reset(ipd_hist, opd_hist);
}
}
for (e = 0; e < ps->num_env; e++) {
for (b = 0; b < NR_PAR_BANDS[is34]; b++) {
float h11, h12, h21, h22;
h11 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][0];
h12 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][1];
h21 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][2];
h22 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][3];
if (!PS_BASELINE && ps->enable_ipdopd && 2*b <= NR_PAR_BANDS[is34]) {
float h11i, h12i, h21i, h22i;
float ipd_adj_re, ipd_adj_im;
int opd_idx = opd_hist[b] * 8 + opd_mapped[e][b];
int ipd_idx = ipd_hist[b] * 8 + ipd_mapped[e][b];
float opd_re = pd_re_smooth[opd_idx];
float opd_im = pd_im_smooth[opd_idx];
float ipd_re = pd_re_smooth[ipd_idx];
float ipd_im = pd_im_smooth[ipd_idx];
opd_hist[b] = opd_idx & 0x3F;
ipd_hist[b] = ipd_idx & 0x3F;
ipd_adj_re = opd_re*ipd_re + opd_im*ipd_im;
ipd_adj_im = opd_im*ipd_re - opd_re*ipd_im;
h11i = h11 * opd_im;
h11 = h11 * opd_re;
h12i = h12 * ipd_adj_im;
h12 = h12 * ipd_adj_re;
h21i = h21 * opd_im;
h21 = h21 * opd_re;
h22i = h22 * ipd_adj_im;
h22 = h22 * ipd_adj_re;
H11[1][e+1][b] = h11i;
H12[1][e+1][b] = h12i;
H21[1][e+1][b] = h21i;
H22[1][e+1][b] = h22i;
}
H11[0][e+1][b] = h11;
H12[0][e+1][b] = h12;
H21[0][e+1][b] = h21;
H22[0][e+1][b] = h22;
}
for (k = 0; k < NR_BANDS[is34]; k++) {
float h[2][4];
float h_step[2][4];
int start = ps->border_position[e];
int stop = ps->border_position[e+1];
float width = 1.f / (stop - start);
b = k_to_i[k];
h[0][0] = H11[0][e][b];
h[0][1] = H12[0][e][b];
h[0][2] = H21[0][e][b];
h[0][3] = H22[0][e][b];
if (!PS_BASELINE && ps->enable_ipdopd) {
if ((is34 && k <= 13 && k >= 9) || (!is34 && k <= 1)) {
h[1][0] = -H11[1][e][b];
h[1][1] = -H12[1][e][b];
h[1][2] = -H21[1][e][b];
h[1][3] = -H22[1][e][b];
} else {
h[1][0] = H11[1][e][b];
h[1][1] = H12[1][e][b];
h[1][2] = H21[1][e][b];
h[1][3] = H22[1][e][b];
}
}
h_step[0][0] = (H11[0][e+1][b] - h[0][0]) * width;
h_step[0][1] = (H12[0][e+1][b] - h[0][1]) * width;
h_step[0][2] = (H21[0][e+1][b] - h[0][2]) * width;
h_step[0][3] = (H22[0][e+1][b] - h[0][3]) * width;
if (!PS_BASELINE && ps->enable_ipdopd) {
h_step[1][0] = (H11[1][e+1][b] - h[1][0]) * width;
h_step[1][1] = (H12[1][e+1][b] - h[1][1]) * width;
h_step[1][2] = (H21[1][e+1][b] - h[1][2]) * width;
h_step[1][3] = (H22[1][e+1][b] - h[1][3]) * width;
}
ps->dsp.stereo_interpolate[!PS_BASELINE && ps->enable_ipdopd](
l[k] + start + 1, r[k] + start + 1,
h, h_step, stop - start);
}
}
}
| 1threat |
Can we do CRUD Operation on sql MDF file with out Management Studio : i have a sql mdf file and i want to do Insert, Delete , update queries on that with out sql management studio
because it is located is remote system and i want to give some updated as add column to table and delete data | 0debug |
In java,about inputing using Scanner class : what i understood from my past experiences is .nextInt() or .nextDouble() would keep on searching until the integer or the double is found in the same or the next line it doesn't matter,while to read a string as input through scanner class .next() considers those strings before space and keeps the cursor in the same line,where as .nextLine() would consider the leftovers by the .next() if used before the .nextLine() in code,could someone help me understand this in more detail,espically about .nextLine() where it starts and where the cursor ends?Also,please tell me if any mistakes i thought are correct. | 0debug |
c++ class destructor deleting some but not all member data : <p>I've read through different resources but feel like I'm missing something. I'm explicitly calling the destructor when a variable (numItems) reaches zero. I have a loop that prints all the class objects (students), but while any object that had the destructor called on it has a blank first and last name, the ID and numItems variables still exist. Am I misunderstanding how the destructor works? Why would it delete some but not all of the member attributes?</p>
<p>Also, the "items" are stored in a dynamic array. I can set and access them as long as the array is public. But even using setters, the program crashes if I attempt to populate a private array. </p>
<p>Header:</p>
<pre><code>#ifndef STUDENT_H
#define STUDENT_H
#include <string>
#include <iomanip>
#include <iostream>
#include <algorithm>
#define ARRAY_MAX 15
using namespace std;
class Student
{
private:
string firstName, lastName;
unsigned int ID, numItems = 0;
typedef string* StringPtr;
//StringPtr items;
public:
int capacity = 15;
string *items = new string[capacity];
Student();
Student(const unsigned int id, const string fName, const string lName);
string getfName() const;
string getlName() const;
unsigned int getnumItems() const;
string getItem(int num);
unsigned int getID() const;
void setfName(string fname);
void setlName(string lname);
void setID(unsigned int id);
void setItem(string str, int num);
int CheckoutCount();
bool CheckOut(const string& item);
bool CheckIn(const string& item);
bool HasCheckedOut(const string& item);
void Clear();
~Student();
//const Student operator+(string rhs);
//void operator+=(string rhs);
//bool operator==(Student rhs);
friend istream& operator>>(istream& input, Student& stu);
friend ostream& operator<<(ostream& output, const Student& stu);
};
#endif // STUDENT_H
</code></pre>
<p>Definitions:</p>
<pre><code>#include "student.h"
using namespace std;
Student::Student()
{
}
Student::Student(const unsigned int id, const string fName, const string lName)
{
firstName = fName;
lastName = lName;
ID = id;
}
string Student::getfName() const
{
return firstName;
}
string Student::getlName() const
{
return lastName;
}
unsigned int Student::getnumItems() const
{
return numItems;
}
string Student::getItem(int num)
{
return items[num];
}
unsigned int Student::getID() const
{
return ID;
}
void Student::setfName(string fname)
{
firstName = fname;
}
void Student::setlName(string lname)
{
lastName = lname;
}
void Student::setID(unsigned int id)
{
if ((id >= 1000) && (id <= 100000))
{
ID = id;
}
else
{
cout << "Attempted ID for " << firstName << " " << lastName << " is invalid. Must be between 1000 and 100,000." << endl;
}
}
void Student::setItem(string str, int num)
{
items[num] = str;
}
int Student::CheckoutCount()
{
return numItems;
}
bool Student::CheckOut(const string & item)
{
if (this->HasCheckedOut(item) == true)
{
return false; // already found item in list, CheckOut failed...
}
else
{
items[numItems] = item;
numItems++;
return true; // CheckOut successful
}
}
bool Student::CheckIn(const string & item)
{
for (int i = 0; i < numItems; i++)
{
if (items[i] == item)
{
for (; i < numItems - 1; i++)
{
// Assign the next element to current location.
items[i] = items[i + 1];
}
// Remove the last element as it has been moved to previous index.
items[numItems - 1] = "";
numItems = numItems - 1;
if (numItems == 0)
{
this->~Student();
}
return true;
}
}
return false;
}
bool Student::HasCheckedOut(const string & item)
{
string *end = items + numItems;
string *result = find(items, end, item);
if (result != end)
{
return true; // found value at "result" pointer location...
}
else
return false;
}
void Student::Clear()
{
ID = 0;
firstName = "";
lastName = "";
delete[] items;
}
Student::~Student()
{
}
istream & operator>>(istream & input, Student & stu)
{
string temp;
input >> stu.ID >> stu.firstName >> stu.lastName >> stu.numItems;
int loopnum = stu.numItems;
if (loopnum > 0)
{
for (int i = 0; i < loopnum; i++)
{
input >> temp;
stu.setItem(temp, i);
}
}
return input;
}
ostream & operator<<(ostream & output, const Student & stu)
{
string s = stu.firstName + " " + stu.lastName;
output << setw(8) << stu.ID << setw(16) << s << setw(8) << stu.numItems;
int loopnum = stu.numItems;
if (loopnum > 0)
{
for (int i = 0; i < loopnum; i++)
{
output << stu.items[i] << " ";
}
}
output << endl << endl;
return output;
}
</code></pre>
<p>Main:</p>
<pre><code>#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include "student.h"
using namespace std;
void fcheck(ifstream &mystream);
int main()
{
ifstream sin("students.txt"); // File input/output variables
ifstream fin("checkins.txt");
ifstream chin("checkouts.txt");
ofstream sout("UpdatedStudentsC.txt");
Student stu1, stu2;
fcheck(sin);
fcheck(fin);
fcheck(chin);
typedef Student* StuPtr;
StuPtr studentList;
int stud_capacity = 50;
studentList = new Student[stud_capacity];
int num_studs = 0;
sout << std::setiosflags(std::ios::left); // justify output to format properly.
while (sin.good()) // While there's data in the file, do stuff.
{
sin >> stu1;
stu1.CheckIn("Towel");
stu1.CheckIn("Locker");
if (stu1.getnumItems() == 0)
{
stu1.~Student();
}
studentList[num_studs] = stu1;
num_studs++;
sout << stu1;
}
for (int i = 0; i < 16; i++)
{
cout << studentList[i].getID() << " " << studentList[i].getfName() << " " << studentList[i].getnumItems() << endl;
}
system("pause");
// Close files
fin.close();
chin.close();
sout.close();
sin.close();
// Quit without error
return 0;
}
void fcheck(ifstream &mystream)
{
if (!mystream) // If we can't find the input file, quit with error message.
{
cout << "file not opened!" << endl;
system("pause");
exit(1);
}
}
</code></pre>
| 0debug |
jQuer - does't react to hasClass() : So I got this problem. The jQuery hasClass() isn't working as it should. When I click on text it should give it a class (and it does), but it doesn't check if it has that class?
Can someone help me?
There is my code!
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
$(document).ready(function() {
$('#example').on('click', function() {
$(this).addClass("redText");
});
if ( $('#example').hasClass("redText") ) {
$('#example').addClass("bigText");
}
});
<!-- language: lang-css -->
.redText{
color: red;
}
.bigText{
font-size: 20px;
}
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="example">Hey</div>
<!-- end snippet -->
| 0debug |
How to fix 'onClick to show content' : I have simple side navigation on my webpage, and have little problem i think with javascript code. What i need? When user open that page and choose to see content from category of 'Audi' to show sub-category in this case to show ( audi a4 and audi a5). Now is set to opened so user don't need to click on category 'Audi' to see content.
<h4>Side navigation</h4>
<nav class="checklist side-nav-toggle ajax">
<h5><a href="#" class="opened">Audi</h5>
<ul class="scroll-list" style="display:block;">
<li><a href="#" rel="nofollow">Audi A3</a></li>
<li><a href="#" rel="nofollow">Audi A5</a></li>
</ul>
</nav>
If you need more information, please write me i will answer immediately. Thanks all, and sorry for my bad english.
Thanks all | 0debug |
Why my html and js only works on codepen : <p>Here is the link of my work, it works perfectly on Codepen, but when i move it to my github personal page, it won't work. There is no response when i push my search botton.
<a href="https://gist.github.com/Airhaoran/eec810eda0299297a59d83d353d732ea" rel="nofollow">https://gist.github.com/Airhaoran/eec810eda0299297a59d83d353d732ea</a></p>
| 0debug |
void ide_atapi_cmd(IDEState *s)
{
uint8_t *buf = s->io_buffer;
const struct AtapiCmd *cmd = &atapi_cmd_table[s->io_buffer[0]];
#ifdef DEBUG_IDE_ATAPI
{
int i;
printf("ATAPI limit=0x%x packet:", s->lcyl | (s->hcyl << 8));
for(i = 0; i < ATAPI_PACKET_SIZE; i++) {
printf(" %02x", buf[i]);
}
printf("\n");
}
#endif
if (s->sense_key == UNIT_ATTENTION && !(cmd->flags & ALLOW_UA)) {
ide_atapi_cmd_check_status(s);
return;
}
if (!(cmd->flags & ALLOW_UA) &&
!s->tray_open && blk_is_inserted(s->blk) && s->cdrom_changed) {
if (s->cdrom_changed == 1) {
ide_atapi_cmd_error(s, NOT_READY, ASC_MEDIUM_NOT_PRESENT);
s->cdrom_changed = 2;
} else {
ide_atapi_cmd_error(s, UNIT_ATTENTION, ASC_MEDIUM_MAY_HAVE_CHANGED);
s->cdrom_changed = 0;
}
return;
}
if ((cmd->flags & CHECK_READY) &&
(!media_present(s) || !blk_is_inserted(s->blk)))
{
ide_atapi_cmd_error(s, NOT_READY, ASC_MEDIUM_NOT_PRESENT);
return;
}
if (cmd->handler && !(cmd->flags & NONDATA)) {
if (!(atapi_byte_count_limit(s) || s->atapi_dma)) {
ide_abort_command(s);
return;
}
}
if (cmd->handler) {
cmd->handler(s, buf);
return;
}
ide_atapi_cmd_error(s, ILLEGAL_REQUEST, ASC_ILLEGAL_OPCODE);
}
| 1threat |
JAVA Confused by ArrayList Initialization : I am confused by the line "**res.add(new ArrayList<Integer>(temp))**;" in function dfs, could you please tell me why it's wrong if I just use **res.add(temp)**? Thank you guys.
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res=new ArrayList<>();
if(nums.length==0||nums==null)
return res;
Arrays.sort(nums);
List<Integer> temp=new ArrayList<>();
dfs(nums,0,res,temp);
return res;
}
public void dfs(int[] nums, int index, List<List<Integer>> res, List<Integer> temp) {
res.add(new ArrayList<Integer>(temp));
for(int i=index;i<nums.length;i++) {
temp.add(nums[i]);
dfs(nums,i+1,res,temp);
temp.remove(temp.size()-1);
}
} | 0debug |
static int qemu_rdma_exchange_send(RDMAContext *rdma, RDMAControlHeader *head,
uint8_t *data, RDMAControlHeader *resp,
int *resp_idx,
int (*callback)(RDMAContext *rdma))
{
int ret = 0;
if (rdma->control_ready_expected) {
RDMAControlHeader resp;
ret = qemu_rdma_exchange_get_response(rdma,
&resp, RDMA_CONTROL_READY, RDMA_WRID_READY);
if (ret < 0) {
return ret;
}
}
if (resp) {
ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_DATA);
if (ret) {
fprintf(stderr, "rdma migration: error posting"
" extra control recv for anticipated result!");
return ret;
}
}
ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);
if (ret) {
fprintf(stderr, "rdma migration: error posting first control recv!");
return ret;
}
ret = qemu_rdma_post_send_control(rdma, data, head);
if (ret < 0) {
fprintf(stderr, "Failed to send control buffer!\n");
return ret;
}
if (resp) {
if (callback) {
DDPRINTF("Issuing callback before receiving response...\n");
ret = callback(rdma);
if (ret < 0) {
return ret;
}
}
DDPRINTF("Waiting for response %s\n", control_desc[resp->type]);
ret = qemu_rdma_exchange_get_response(rdma, resp,
resp->type, RDMA_WRID_DATA);
if (ret < 0) {
return ret;
}
qemu_rdma_move_header(rdma, RDMA_WRID_DATA, resp);
if (resp_idx) {
*resp_idx = RDMA_WRID_DATA;
}
DDPRINTF("Response %s received.\n", control_desc[resp->type]);
}
rdma->control_ready_expected = 1;
return 0;
}
| 1threat |
Generate access token with IdentityServer4 without password : <p>I have created ASP.NET Core WebApi protected with IdentityServer4 using ROPC flow (using this example: <a href="https://github.com/robisim74/AngularSPAWebAPI" rel="noreferrer">https://github.com/robisim74/AngularSPAWebAPI</a>).</p>
<p>How to manually generate access_token from the server without password?</p>
| 0debug |
How do linked list work if nothing has been added to them and you try to pring that variable. : I have a linked list and want to print it out in the end. My questions is, if the linked list variable in the struct is left untouched and nothing is added to the list, if I try to print using `while(school->student != NULL)` will this work?
Note: I have no made the list NULL at any point, I have just allocated name and not touched the list.
struct School{
char *name;
Student *list; <--- Linked list
} School;
struct Student{
char *name;
Student *next;
} Student;
Now if I want to print this list will this work? | 0debug |
how read csv row file with python with specific value of colun : Je voudrais parcourrir des données sous format CSV.
pour cela j'utilise ceci:
`with open("file.csv", "rb") as f:
reader = csv.reader(f,delimiter=';')
for row in reader:
print row`
Donnée:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<table>
<tr>
<th>Prenom</th>
<th>Nom</th>
<th>Profession</th>
</tr>
<tr>
<td>Mike</td>
<td>Stuntman</td>
<td>Cascadeur</td>
</tr>
<tr>
<td>Man</td>
<td>Pink</td>
<td>Prof</td>
</tr>
<tr>
<td>Win</td>
<td>Red</td>
<td>Actor</td>
</tr>
<tr>
<td>DJef</td>
<td>Bleu</td>
<td>agric</td>
</tr>
<tr>
<td>DEEN</td>
<td>Red</td>
<td>Fisher</td>
</tr>
</table>
<!-- end snippet -->
Avec ce bout de code je peux afficher mon tableau et aussi une colonne spécifique.
mais je voudrais pourvoir par exemple afficher les toutes les colonnes avec comme condition tous les éléments de la deuxieme colonne qui ont pour valeur = RED
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<table>
<tr>
<th>Prenom</th>
<th>Nom</th>
<th>Profession</th>
</tr>
<tr>
<td>Win</td>
<td>Red</td>
<td>Actor</td>
</tr>
<tr>
<td>DEEN</td>
<td>Red</td>
<td>Fisher</td>
</tr>
<!-- end snippet -->
| 0debug |
Postgres shuts down immediately when started with docker-compose : <p>Postgres shuts down immediately when started with docker-compose. The yaml file used is below</p>
<pre><code>version: '2'
services:
postgres:
image: postgres:9.5
container_name: local-postgres9.5
ports:
- "5432:5432"
</code></pre>
<p>The log when docker-compose up command is executed</p>
<pre><code>Creating local-postgres9.5
Attaching to local-postgres9.5
local-postgres9.5 | The files belonging to this database system will be owned by user "postgres".
local-postgres9.5 | This user must also own the server process.
local-postgres9.5 |
local-postgres9.5 | The database cluster will be initialized with locale "en_US.utf8".
local-postgres9.5 | The default database encoding has accordingly been set to "UTF8".
local-postgres9.5 | The default text search configuration will be set to "english".
local-postgres9.5 |
local-postgres9.5 | Data page checksums are disabled.
local-postgres9.5 |
local-postgres9.5 | fixing permissions on existing directory /var/lib/postgresql/data ... ok
local-postgres9.5 | creating subdirectories ... ok
local-postgres9.5 | selecting default max_connections ... 100
local-postgres9.5 | selecting default shared_buffers ... 128MB
local-postgres9.5 | selecting dynamic shared memory implementation ... posix
local-postgres9.5 | creating configuration files ... ok
local-postgres9.5 | creating template1 database in /var/lib/postgresql/data/base/1 ... ok
local-postgres9.5 | initializing pg_authid ... ok
local-postgres9.5 | initializing dependencies ... ok
local-postgres9.5 | creating system views ... ok
local-postgres9.5 | loading system objects' descriptions ... ok
local-postgres9.5 | creating collations ... ok
local-postgres9.5 | creating conversions ... ok
local-postgres9.5 | creating dictionaries ... ok
local-postgres9.5 | setting privileges on built-in objects ... ok
local-postgres9.5 | creating information schema ... ok
local-postgres9.5 | loading PL/pgSQL server-side language ... ok
local-postgres9.5 | vacuuming database template1 ... ok
local-postgres9.5 | copying template1 to template0 ... ok
local-postgres9.5 | copying template1 to postgres ... ok
local-postgres9.5 | syncing data to disk ... ok
local-postgres9.5 |
local-postgres9.5 | WARNING: enabling "trust" authentication for local connections
local-postgres9.5 | You can change this by editing pg_hba.conf or using the option -A, or
local-postgres9.5 | --auth-local and --auth-host, the next time you run initdb.
local-postgres9.5 |
local-postgres9.5 | Success. You can now start the database server using:
local-postgres9.5 |
local-postgres9.5 | pg_ctl -D /var/lib/postgresql/data -l logfile start
local-postgres9.5 |
local-postgres9.5 | ****************************************************
local-postgres9.5 | WARNING: No password has been set for the database.
local-postgres9.5 | This will allow anyone with access to the
local-postgres9.5 | Postgres port to access your database. In
local-postgres9.5 | Docker's default configuration, this is
local-postgres9.5 | effectively any other container on the same
local-postgres9.5 | system.
local-postgres9.5 |
local-postgres9.5 | Use "-e POSTGRES_PASSWORD=password" to set
local-postgres9.5 | it in "docker run".
local-postgres9.5 | ****************************************************
local-postgres9.5 | waiting for server to start....LOG: database system was shut down at 2016-05-16 16:51:54 UTC
local-postgres9.5 | LOG: MultiXact member wraparound protections are now enabled
local-postgres9.5 | LOG: database system is ready to accept connections
local-postgres9.5 | LOG: autovacuum launcher started
local-postgres9.5 | done
local-postgres9.5 | server started
local-postgres9.5 | ALTER ROLE
local-postgres9.5 |
local-postgres9.5 |
local-postgres9.5 | /docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/*
local-postgres9.5 |
local-postgres9.5 | LOG: received fast shutdown request
local-postgres9.5 | LOG: aborting any active transactions
local-postgres9.5 | LOG: autovacuum launcher shutting down
local-postgres9.5 | LOG: shutting down
local-postgres9.5 | waiting for server to shut down....LOG: database system is shut down
local-postgres9.5 | done
local-postgres9.5 | server stopped
local-postgres9.5 |
local-postgres9.5 | PostgreSQL init process complete; ready for start up.
local-postgres9.5 |
local-postgres9.5 | LOG: database system was shut down at 2016-05-16 16:51:55 UTC
local-postgres9.5 | LOG: MultiXact member wraparound protections are now enabled
local-postgres9.5 | LOG: database system is ready to accept connections
local-postgres9.5 | LOG: autovacuum launcher started
</code></pre>
<p>Postgres seems to work fine when a container is started using the same image with docker run</p>
<pre><code>docker run --name local-postgres9.5 -p 5432:5432 postgres:9.5
</code></pre>
| 0debug |
Certain Lines produce Syntax Errors : <p>I have just started out with python and I have a tiny question that hopefully someone can help me in answering on my own. </p>
<p>I have a homework problem that is bugging me. I completed the process as needed, but for some reason when I run it, it comes back with a syntax error and I'm not sure why.
I am getting a syntax error on the "Print("Tax:",...) line, but I can't even get it to print the first (Meal_Cost) either. Please help!!</p>
<pre><code>meal_cost = 10.00
tax_rate = 0.08
tip_rate = 0.20
print('Subtotal:',(meal_cost)
print('Tax:',(tax_rate * meal_cost)
print('Tip:',(meal_cost * tip_rate)
print('Total:',(meal_cost + tip_rate + tax_rate)
</code></pre>
<p>I am expected to have the outcome be: </p>
<pre><code>Subtotal: 10.00
Tax: 0.8
Tip: 2.0
Total: 12.8
</code></pre>
<p>I have tried moving certain values around and that does not help at all. I have checked and double checked my (). </p>
| 0debug |
static void verdex_init(ram_addr_t ram_size, int vga_ram_size,
const char *boot_device,
const char *kernel_filename, const char *kernel_cmdline,
const char *initrd_filename, const char *cpu_model)
{
struct pxa2xx_state_s *cpu;
int index;
uint32_t verdex_rom = 0x02000000;
uint32_t verdex_ram = 0x10000000;
if (ram_size < (verdex_ram + verdex_rom + PXA2XX_INTERNAL_SIZE)) {
fprintf(stderr, "This platform requires %i bytes of memory\n",
verdex_ram + verdex_rom + PXA2XX_INTERNAL_SIZE);
exit(1);
}
cpu = pxa270_init(verdex_ram, cpu_model ?: "pxa270-c0");
index = drive_get_index(IF_PFLASH, 0, 0);
if (index == -1) {
fprintf(stderr, "A flash image must be given with the "
"'pflash' parameter\n");
exit(1);
}
if (!pflash_cfi01_register(0x00000000, qemu_ram_alloc(verdex_rom),
drives_table[index].bdrv, sector_len, verdex_rom / sector_len,
2, 0, 0, 0, 0)) {
fprintf(stderr, "qemu: Error registering flash memory.\n");
exit(1);
}
cpu->env->regs[15] = 0x00000000;
smc91c111_init(&nd_table[0], 0x04000300,
pxa2xx_gpio_in_get(cpu->gpio)[99]);
}
| 1threat |
void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
{
RAMBlock *block;
ram_addr_t offset;
int flags;
void *area, *vaddr;
QLIST_FOREACH(block, &ram_list.blocks, next) {
offset = addr - block->offset;
if (offset < block->length) {
vaddr = block->host + offset;
if (block->flags & RAM_PREALLOC_MASK) {
;
} else {
flags = MAP_FIXED;
munmap(vaddr, length);
if (mem_path) {
#if defined(__linux__) && !defined(TARGET_S390X)
if (block->fd) {
#ifdef MAP_POPULATE
flags |= mem_prealloc ? MAP_POPULATE | MAP_SHARED :
MAP_PRIVATE;
flags |= MAP_PRIVATE;
#endif
area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
flags, block->fd, offset);
} else {
flags |= MAP_PRIVATE | MAP_ANONYMOUS;
area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
flags, -1, 0);
}
#endif
} else {
#if defined(TARGET_S390X) && defined(CONFIG_KVM)
flags |= MAP_SHARED | MAP_ANONYMOUS;
area = mmap(vaddr, length, PROT_EXEC|PROT_READ|PROT_WRITE,
flags, -1, 0);
flags |= MAP_PRIVATE | MAP_ANONYMOUS;
area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
flags, -1, 0);
#endif
}
if (area != vaddr) {
fprintf(stderr, "Could not remap addr: %lx@%lx\n",
length, addr);
exit(1);
}
qemu_madvise(vaddr, length, QEMU_MADV_MERGEABLE);
}
return;
}
}
} | 1threat |
How to make Visual Studio Code check entire project for errors? : <p>I'm using VS Code for TypeScript/JavaScript development. When I open a file it will check that file for errors. The problem is if I'm refactoring (like I move some shared code to a new location or change a name) it won't show me the errors this caused until I open the file with the problem. ...so if I want to do extensive refactoring I have to open every file just to make it scan the file for errors.</p>
<p>How can I make VS Code scan the whole project for errors without having to open each file one by one manually?</p>
| 0debug |
Why my javascript if condition is not working? : I just write the following code
$("ul > li > a").click(function() {
var value = $(this)[0].innerText;
console.log(value);
if(value == "Gallery") {
console.log("a");
} else {
console.log("b");
}
});
First console log print Gallery. But if condition goes to else statement why it's happening i can't understand.
Please see this image.
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/3UIFc.png | 0debug |
Get prop of an obj inside obj using string : <p>Let's say I have this obj here:</p>
<pre><code>let obj1 ={
a: 4,
b: {
ab: 44,
c: {
tres: 100
}
}
};
</code></pre>
<p>How can I access the <strong>tres</strong> property using a string? I can access <strong>b</strong> object using this code:</p>
<pre><code>let prop = "b";
console.log(obj1[prop]); // returns b property
</code></pre>
<p>But how can I get access to a <strong>tres</strong> property that resides inside <strong>c</strong> inside <strong>b</strong> inside <strong>obj1</strong> object?</p>
| 0debug |
Sorting in sql server by two columns : I've an employee table with below details
EMPid TimeIn. TimeOut
123 1 Jan 2016 10:10 NULL
123 NULL 1 Jan 2016 18:30
123 1 Jan 2016 9:10 NULL
123 NULL 1 Jan 2016 18:00
I need output with order by time in ascending order. Below is sample output.
EMPid TimeIn. TimeOut
123 1 Jan 2016 9:10 NULL
123 1 Jan 2016 10:10 NULL
123 NULL 1 Jan 2016 18:00
123 NULL 1 Jan 2016 18:30
| 0debug |
(python) I keep getting the error "string index out of range" : so I'm doing some homework and i'm kinda stumped, the assignment is to create a program that makes a email address based on your first and last name and the year you started school, but for some reason I cant get the email to generate I keep getting the "String index out of range" error.
Here is my code:
# a graphical program that creates a student email adress
from graphics import *
import math
#setting up the window
win = GraphWin("email",400,400)
win.setBackground("yellow")
#setting up the input
instructions = Text(Point(160,50), "For your email, enter your first and last name,\n and the year you are starting school.")
instructions.draw(win)
fstName = Text(Point(100,100),"What is your first name?: ")
fstName.draw(win)
fstNameInput = Entry(Point(260,100), 10)
fstNameInput.draw(win)
lstName = Text(Point(100,150), "what is your last name?: ")
lstName.draw(win)
lstNameInput = Entry(Point(260,150), 15)
lstNameInput.draw(win)
year = Text(Point(130,200), "What year are you starting school?: ")
year.draw(win)
yearInput = Entry(Point(280,200), 4)
yearInput.draw(win)
#Line break
linBreak = Text(Point(200,289), "=======================================")
linBreak.draw(win)
#Output
email = Text(Point(50,315), "Your email is: ")
email.draw(win)
emailOutput = Entry(Point(200,340), 50)
emailOutput.draw(win)
#setting up The process
fst_name = fstNameInput.getText()
lst_name = lstNameInput.getText()
YEAR = yearInput.getText()
#Button
button = Rectangle(Point(130,250),Point(210,279))
button.draw(win)
buttonCenter = button.getCenter()
buttonText = Text(buttonCenter, "Enter")
buttonText.draw(win)
#button function (got help for this on stack overflow)
def inside(point, rectangle):
ll = rectangle.getP1()
ur = rectangle.getP2()
return ll.getX() < point.getX() < ur.getX() and ll.getY() < point.getY() < ur.getY()
while True:
click = win.getMouse()
if click is None:
emailOutput.setText("")
elif inside(click, button):
emailOutput.setText(fst_name[0] + lst_name + YEAR + "@student.kathycollege.edu")
break;
| 0debug |
i want to remove double quouta from my string type variable says currentdate in C# : i have a variable "currntdate" type string
value store in this variable "'2017-08-03'"
now i want to remove double qouta "
Regards,
Manish | 0debug |
Should I Unsubscribe reactive form's valueChanges? : <p>Is it necessary to unsubscribe reactive form control's valueChanges subscription or Angular will unsubscribe it for us ?</p>
<p>In <strong>Router</strong> : <br>
According to the official documentation, Angular should unsubscribe for you, but apparently, there is a <a href="https://github.com/angular/angular/issues/16261" rel="noreferrer">bug</a>.</p>
<p>So my concern here is the same for FormControl's valueChanges.</p>
| 0debug |
how to set showModalBottomSheet to full height : <p>i use showRoundedModalBottomSheet, how to adjust this modal height till below the appbar?</p>
<p><a href="https://i.stack.imgur.com/ilEcY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ilEcY.png" alt="enter image description here"></a></p>
| 0debug |
Is there any difference between AES_128_CBC and AES_128_CBC_SHA algoritham? : Is there any difference between AES_128_CBC and AES_128_CBC_SHA algoritham? I have a client document which says AES_128_CBC_SHA algorithm for data encryption. could anybody can share some Library files (.net, C,C#) which does AES_128_CBC_SHA algorithm. I am using LabVIEW for data encryption.
My module will accept encrypted data in AES_128-CBC_SHA algorithm.
| 0debug |
Replace Words in the parentheses to put into quotations - Unix / Linux : I want to replace the words in the parentheses to put into quotations.
Below is the data I have in one of the variable data -
SELECT * FROM ( SELECT Table1 file2.txt file.txt QUEUES QDefinitions
Parameters TRAP-Deposit-DSTran.dat.2016-08-07 FROM CS_CASE WHERE
ANT_CD='FI_BASE_TENANT') t1 LEFT OUTER JOIN Table2 t2 ON t2.CASE_ID=t1.CASE_ID LEFT OUTER JOIN Table3 t3 ON t3.SERVICE_XID=t1.SERVICE_XID LEFT OUTER JOIN Table4 t4 ON t4.SERVICE_ID=t1.SERVICE_ID WHERE ( t1.CASESTATUs_CD = (NEW,RETIRED,PENDING,OPEN,CLOSED) OR t1.CASE_STATUS_NUM = (1,2,3,4) ) GROUP BY t1.CASE_REFERENCE,t2.LAST_SCRFP,t1.SERVICE_ID ORDER BY t2.LAST_SCRFP DESC
Here is what I want.
SELECT * FROM ( SELECT Table1 file2.txt file.txt QUEUES QDefinitions
Parameters TRAP-Deposit-DSTran.dat.2016-08-07 FROM CS_CASE WHERE
ANT_CD='FI_BASE_TENANT') t1 LEFT OUTER JOIN Table2 t2 ON t2.CASE_ID=t1.CASE_ID LEFT OUTER JOIN Table3 t3 ON t3.SERVICE_XID=t1.SERVICE_XID LEFT OUTER JOIN Table4 t4 ON t4.SERVICE_ID=t1.SERVICE_ID WHERE ( t1.CASESTATUs_CD = ('NEW','RETIRED','PENDING','OPEN','CLOSED') OR t1.CASE_STATUS_NUM = (1,2,3,4) ) GROUP BY t1.CASE_REFERENCE,t2.LAST_SCRFP,t1.SERVICE_ID ORDER BY t2.LAST_SCRFP DESC
Previously I have used sed command as below
sed -E 's/\(([^(,$1)'\'']+)\)/('\''\1'\'')/g' Filename.txt
| 0debug |
Positive and negative numbers with ArrayList : <p>How do I seprate positive and negative numbers? I have this code:</p>
<pre><code>import java.util.ArrayList;
import java.swing.JOptionPane;
public class Test {
public static void main(String[] args) {
ArrayList al = new ArrayList();
int num=Integer.parseInt(JOptionPane.showInputDialog("How many numbers?"));
for (int i=0 ; i < num ; i++) {
al.add(Integer.parseInt(JOptionPane.showInputDialog("What numbers?")));
}
}
}
</code></pre>
<p>Let's say I want to add 5 numbers. <code>-2, -7, 8, 4, -1</code></p>
<p>I need the output to be <code>Positive = 8, 4</code> and <code>Negative = -2, -7, -1</code></p>
| 0debug |
def add_string(list,string):
add_string=[string.format(i) for i in list]
return add_string | 0debug |
Awk commands for changing letters in a file with multiple outputs : <p>I have an input file which looks like this:</p>
<pre><code>input.txt
THISISANEXAMPLEOFANINPUTFILEWITHALONGSTRINGOFTEXT
</code></pre>
<p>I have another file with positions of letters i want to change and the letter i want to change it to, such as this:</p>
<pre><code>textpos.txt
Position Text_Change
1 A
2 B
3 X
</code></pre>
<p>(Actually there will be about 10,000 alphabet changes)</p>
<p>And I would like one separate output file for each text change, which should look like this:</p>
<pre><code>output1.txt
AHISISANEXAMPLEOFANINPUTFILEWITHALONGSTRINGOFTEXT
</code></pre>
<p>Next one:</p>
<pre><code>output2.txt
TBISISANEXAMPLEOFANINPUTFILEWITHALONGSTRINGOFTEXT
</code></pre>
<p>Next one: </p>
<pre><code>output3.txt
THXSISANEXAMPLEOFANINPUTFILEWITHALONGSTRINGOFTEXT
</code></pre>
<p>I would like to learn how to do this in an awk command and a pythonic way as well, and was wondering what would be the best and quickest way to do this?</p>
<p>Thanks in advance.</p>
| 0debug |
static av_always_inline void dist_scale(HEVCContext *s, Mv *mv,
int min_pu_width, int x, int y,
int elist, int ref_idx_curr, int ref_idx)
{
RefPicList *refPicList = s->ref->refPicList;
MvField *tab_mvf = s->ref->tab_mvf;
int ref_pic_elist = refPicList[elist].list[TAB_MVF(x, y).ref_idx[elist]];
int ref_pic_curr = refPicList[ref_idx_curr].list[ref_idx];
if (ref_pic_elist != ref_pic_curr)
mv_scale(mv, mv, s->poc - ref_pic_elist, s->poc - ref_pic_curr);
}
| 1threat |
Python How to add a value to a dictionary value : <p>So I have this code (python):</p>
<pre><code> dictionary = {
gold:10
}
</code></pre>
<p>How can I add 50 to the value to the dictionary.gold</p>
| 0debug |
In Java (android), what is a good way to create accurate consecutive timers? : <p>What would be the most accurate solution to have multiple consecutive timers in Java / android? Or in other words, what is the best option to delay the next piece of code until the current timer has finished?</p>
<p>Background information if the question is unclear:
To practice coding, I would like to create a free app w/o ads to help practice freediving. The basic idea is to have several timers that run after each other. Example:</p>
<ol>
<li>2 minutes breath up</li>
<li>hold your breath for 2 minutes</li>
<li>2 minutes breath up</li>
<li>hold your breath for 2 minutes + 15 seconds</li>
<li>2 minutes breath up</li>
<li>hold your breath for 2 minutes + 15 seconds + 15 seconds
and so on; usually 8 rounds of breath holding which leads to 16 consecutive timers</li>
</ol>
<p>At first I thought I can use the timer class but I don't know how to pause the code until the timer is finished. So all the timers ran simultaneously.
I have read about CountDownLatch and Handler but I don't have enough experience to judge what would be best for my purpose. I did a python version before and used sleep. It worked fine, but for longer timers it was inaccurate by a few seconds which is a problem. </p>
<p>Another option, I believe, is to use a regular timer but run a while loop until the displayed text == 0. I don't know if this infinite loop would crash the application, interfere with the timer's accuracy or has any other negative side effects.</p>
<p>Any help / thoughts would be appreciated. Thanks!</p>
| 0debug |
void fw_cfg_add_string(FWCfgState *s, uint16_t key, const char *value)
{
size_t sz = strlen(value) + 1;
return fw_cfg_add_bytes(s, key, (uint8_t *)g_memdup(value, sz), sz);
}
| 1threat |
Are private members of the superclass also instantiated, when a subclass is instantiated? : <p>In java, in a subclass, how can super() or non-private methods that were defined in the superclass access private members of the superclass, </p>
<p>private members are not inherited in the subclass, therefore when we instantiate the subclass, private members are not instantiated, i.e. they don't exist, how can you access something that does not exist?</p>
| 0debug |
explain logics of dealing with objects in setOnItemClickListener in android : Look at the following code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
word word = words.get(position);
mMediaPlayer = MediaPlayer.create(FamilyActivity.this, word.getAudioResourceId());
mMediaPlayer.start();
//*************Releasing resources
mMediaPlayer.setOnCompletionListener(mCompletionListener);
}
});
}
It belongs to a listview. when a row in that listview is clicked, this method recognize the click and plays the corresponding song for that item.
In the forth line you see this code :` word word = words.get(position);`What is "position"?And what is ".get()" method?and can we save them in a word object?Would you explain this specific line of code,please?
Thank you in advance!
--------------------------------------------------
PS:For more detail I'm gonna show you the "word" class and also "words" arraylist in case you needed to explain:
public class word {
//////Atributes
private String mDefaultTranslation;
private String mMiwokTranslation;
private int mImageResourceId=NO_IMAGE_PROVIDED;
private static final int NO_IMAGE_PROVIDED=-1;
private int mAudioResourceId;
//Constructor
public word(String defaultTranslation,String miwokTranslation,int audioResourceId){
mDefaultTranslation=defaultTranslation;
mMiwokTranslation=miwokTranslation;
mAudioResourceId=audioResourceId;
}
public word(String defaultTranslation,String miwokTranslation,int ImageResourceId,int audioResourceId){
mDefaultTranslation=defaultTranslation;
mMiwokTranslation=miwokTranslation;
mImageResourceId=ImageResourceId;
mAudioResourceId=audioResourceId;
}
//Getters
public String getDefaultTranslation(){
return mDefaultTranslation;
}
public String getMiwokTranslation(){
return mMiwokTranslation;
}
public int getImageResourceId(){return mImageResourceId;}
public boolean hasImage(){return mImageResourceId != NO_IMAGE_PROVIDED;}
public int getAudioResourceId(){return mAudioResourceId;}
and this is "words" arraylist:
final ArrayList<word> words = new ArrayList<word>();
words.add(new word("father", "әpә", R.drawable.family_father, R.raw.family_father));
words.add(new word("mother", "әṭa", R.drawable.family_mother, R.raw.family_mother));
words.add(new word("son", "angsi", R.drawable.family_son, R.raw.family_son));
words.add(new word("daughter", "tune", R.drawable.family_daughter, R.raw.family_daughter));
words.add(new word("older brother", "taachi", R.drawable.family_older_brother, R.raw.family_older_brother));
words.add(new word("younger brother", "chalitti", R.drawable.family_younger_brother, R.raw.family_younger_brother));
words.add(new word("older sister", "teṭe", R.drawable.family_younger_sister, R.raw.family_older_sister));
words.add(new word("ounger sister", "kolliti", R.drawable.family_younger_sister, R.raw.family_younger_sister));
words.add(new word("grandmother", "ama", R.drawable.family_grandmother, R.raw.family_grandmother));
words.add(new word("grandfather", "paapa", R.drawable.family_grandfather, R.raw.family_grandfather));
| 0debug |
javascript closures not retaining variable values from outer scope : <pre><code>.filter('asRelapsedTime', function(ConfigService) {
var DECIMAL_STYLE = ',';
return function(value, decimalPlaces) {
let decimalizedNumber;
if (decimalPlaces) {
decimalizedNumber = value.toFixed(decimalPlaces | 0);
} else {
decimalizedNumber = value.toString();
}
decimalizedNumber = decimalizedNumber.replace('.'. DECIMAL_STYLE);
return decimalizedNumber;
};
});
</code></pre>
<p>From the above code, DECIMAL_STYLE should be available for use within the inner function. However it is not. What am I missing here ?</p>
| 0debug |
Use host networking and additional networks in docker compose : <p>I'm trying to set up a dev environment for my project.</p>
<p>I have a container (ms1) which should be put in his own network ("services" in my case), and a container (apigateway) which should access that network while exposing an http port to the host's network.</p>
<p>Ideally my docker compose file would look like this:</p>
<pre><code>version: '2'
services:
ms1:
expose:
- "13010"
networks:
services:
aliases:
- ms1
apigateway:
networks:
services:
aliases:
- api
network_mode: "host"
networks:
services:
</code></pre>
<p>docker-compose doesn't allow to use network_mode and networks at the same time.</p>
<p>Do I have other alternatives?</p>
<p>At the moment I'm using this:</p>
<pre><code> apigateway:
networks:
services:
aliases:
- api
ports:
- "127.0.0.1:10000:13010"
</code></pre>
<p>and then apigateway container listens on 0.0.0.0:13010. It works but it is slow and it freezes if the host's internet connection goes down.</p>
<p>Also, I'm planning on using vagrant in the future upon docker, does it allow to solve in a clean way?</p>
| 0debug |
In TypeScript, What is the type of Image? : <p>I'm declaring an interface which will contains image also. What type do i need to give to it.</p>
<pre><code>export interface AdInterface {
email: string;
mobile: number;
image?: ??
}
</code></pre>
| 0debug |
HOW TO CREATE BUTTON FOR TRAFFIC LIGHT CODE IN JAVASCRIPT? : I intend to include a button in my traffic light code so that the user can click on it to activate the traffic light however, i am unsure of where to place it in my code. Any help would be greatly appreciated!
This is my code:
<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "traffic light_1.png"
var image2 = new Image()
image2.src = "traffic light_2.png"
var image3 = new Image()
image3.src = "traffic light_3.png"
var image4 = new Image()
image4.src = "traffic light_2.png"
</script>
</head>
<body>
<p><img src="traffic light_1.png" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
var step=1;
function slideit()
{
document.images.slide.src = eval("image"+step+".src");
if(step<4)
step++;
else
step=1;
setTimeout("slideit()",3000);
}
slideit();
</script>
</body> | 0debug |
Parse error: syntax error, unexpected ';' ... on line 87 : <p>My problem is this,the problem I checked more time but not found the problem,why give me this error.</p>
<pre><code>$i=0;
while(count($profile->vehicles)>=$i)
{
echo '
<div class="name col-md-4 col-lg-4">
<h3>'.$profile->vehicles['cars'][$i]['name'].'</h3>
</div>
<div class="post_date col-md-3 col-lg-3">
<h3>'.date("d/m/Y", strtotime($profile->vehicles['cars'][$i]['post_date']).'</h3>
</div>
<div class="views col-md-3 col-lg-3">
<h3>Views:<span>'.$profile->vehicles['cars'][$i]['views'].'</span></h3>
</div>
<div class="edit col-md-2 col-lg-2">
<h3><a href="?page=profile&parent=edit&id='.$profile->vehicles['cars'][$i]['id'].'" >Edit</a></h3>
</div>
';<--Here is the error
$i++;
}
</code></pre>
| 0debug |
Can't initalize a vector with a variable int : I was under the impression that vector could be created using a variable integer. I got this impression from the second answer here: http://stackoverflow.com/questions/14459248/how-to-create-an-array-when-the-size-is-a-variable-not-a-constant
However I still get the "constant int" error message for the code below:
#include <vector>
size_t ports_specified = std::count(Ports.begin(), Ports.end(), '+');
const int num_ports = static_cast<int>(ports_specified++);
std::vector<string> port_info[num_ports];
Any ideas? | 0debug |
Keras learning rate not changing despite decay in SGD : <p>For some reason my learning rate does not appear to change eventhough I set a decay factor. I added a callback to view the learning rate and it appears to be the same after each epoch. Why is it not changing</p>
<pre><code>class LearningRatePrinter(Callback):
def init(self):
super(LearningRatePrinter, self).init()
def on_epoch_begin(self, epoch, logs={}):
print('lr:', self.model.optimizer.lr.get_value())
lr_printer = LearningRatePrinter()
model = Sequential()
model.add(Flatten(input_shape = (28, 28)))
model.add(Dense(200, activation = 'tanh'))
model.add(Dropout(0.5))
model.add(Dense(20, activation = 'tanh'))
model.add(Dense(10, activation = 'softmax'))
print('Compiling Model')
sgd = SGD(lr = 0.01, decay = 0.1, momentum = 0.9, nesterov = True)
model.compile(loss = 'categorical_crossentropy', optimizer = sgd)
print('Fitting Data')
model.fit(x_train, y_train, batch_size = 128, nb_epoch = 400, validation_data = (x_test, y_test), callbacks = [lr_printer])
lr: 0.009999999776482582
Epoch 24/400
60000/60000 [==============================] - 0s - loss: 0.7580 - val_loss: 0.6539
lr: 0.009999999776482582
Epoch 25/400
60000/60000 [==============================] - 0s - loss: 0.7573 - val_loss: 0.6521
lr: 0.009999999776482582
Epoch 26/400
60000/60000 [==============================] - 0s - loss: 0.7556 - val_loss: 0.6503
lr: 0.009999999776482582
Epoch 27/400
60000/60000 [==============================] - 0s - loss: 0.7525 - val_loss: 0.6485
lr: 0.009999999776482582
Epoch 28/400
60000/60000 [==============================] - 0s - loss: 0.7502 - val_loss: 0.6469
lr: 0.009999999776482582
Epoch 29/400
60000/60000 [==============================] - 0s - loss: 0.7494 - val_loss: 0.6453
lr: 0.009999999776482582
Epoch 30/400
60000/60000 [==============================] - 0s - loss: 0.7483 - val_loss: 0.6438
lr: 0.009999999776482582
Epoch 31/400
</code></pre>
| 0debug |
How to optimize this c program to find th eprime factorisation of a number : I have written a code for prime factorization of a number but i dont know how to optimize it to get better result for larger digits can anyone have idea about that?
#include<stdio.h>
int prime(int p, int q, int r);
int main(){
int n,c=0;
scanf("%d",&n);
for(int j=2;j<=n;j++){
int t=0;
for(int i=1;i<=j;i++){
if(j%i==0){
t++;
}
}
if(t==2){
// printf(" %d ",j);
c=prime(n,j,0);
if(c!=0){
printf(" %d ",j);
printf(" %d \n",c);
}
}
}
return 0;
}
int prime(int p,int q,int r){
if(p%q==0){
r++;
prime(p/q,q,r);
}
else{
return r;
}
} | 0debug |
How to convert dd-mm-yyyy Format to MM/dd/yyyy in C#? : <p>I am trying to convert string <code>dd-mm-yyyy</code> to <code>MM/dd/yyyy</code>. I have tried different ways but nothing worked. My current logic is:</p>
<pre><code> string convertDate = DateTime.ParseExact(date, "dd-mm-yyyy", CultureInfo.InvariantCulture)
.ToString("MM/dd/yyyy",CultureInfo.InvariantCulture);
</code></pre>
<p>It is not converting the date as expected. It puts month on place of day and day on place of month and if day greater than 12 than it sets month to 01.</p>
| 0debug |
How to add comment in apache httpd.conf not as a complete line? : <p>In an apache conf file, if a line is start with <code>#</code>, that line is counted as comment. For example,</p>
<pre><code>#This is a comment line
#And then the following is some real settings:
AllowOverride None
</code></pre>
<p>However, this is not allowed.</p>
<pre><code>#And then the following is some real settings:
AllowOverride None #A comment that starts in the middle of line
</code></pre>
<p>Is it possible to starts a comment in the middle of the line? And if yes, how?</p>
| 0debug |
static void gen_store_exclusive(DisasContext *s, int rd, int rt, int rt2,
TCGv addr, int size)
{
TCGv tmp;
int done_label;
int fail_label;
fail_label = gen_new_label();
done_label = gen_new_label();
tcg_gen_brcond_i32(TCG_COND_NE, addr, cpu_exclusive_addr, fail_label);
switch (size) {
case 0:
tmp = gen_ld8u(addr, IS_USER(s));
break;
case 1:
tmp = gen_ld16u(addr, IS_USER(s));
break;
case 2:
case 3:
tmp = gen_ld32(addr, IS_USER(s));
break;
default:
abort();
}
tcg_gen_brcond_i32(TCG_COND_NE, tmp, cpu_exclusive_val, fail_label);
dead_tmp(tmp);
if (size == 3) {
TCGv tmp2 = new_tmp();
tcg_gen_addi_i32(tmp2, addr, 4);
tmp = gen_ld32(tmp2, IS_USER(s));
dead_tmp(tmp2);
tcg_gen_brcond_i32(TCG_COND_NE, tmp, cpu_exclusive_high, fail_label);
dead_tmp(tmp);
}
tmp = load_reg(s, rt);
switch (size) {
case 0:
gen_st8(tmp, addr, IS_USER(s));
break;
case 1:
gen_st16(tmp, addr, IS_USER(s));
break;
case 2:
case 3:
gen_st32(tmp, addr, IS_USER(s));
break;
default:
abort();
}
if (size == 3) {
tcg_gen_addi_i32(addr, addr, 4);
tmp = load_reg(s, rt2);
gen_st32(tmp, addr, IS_USER(s));
}
tcg_gen_movi_i32(cpu_R[rd], 0);
tcg_gen_br(done_label);
gen_set_label(fail_label);
tcg_gen_movi_i32(cpu_R[rd], 1);
gen_set_label(done_label);
tcg_gen_movi_i32(cpu_exclusive_addr, -1);
}
| 1threat |
My list view is not scrolling when i used it as child of scrollview : <p>I am trying to add list view under scroll view so that i can scroll whole page as well as my list view but my list view is not scrolling while my whole page is scrolling. </p>
<p>This is my XML :</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/gray">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/toolbar"
android:background="@color/white">
<LinearLayout
android:id="@+id/layout_form"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginBottom="5dp"
android:background="@color/trans_white"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/list_prdt_detail"
android:divider="@color/white"
android:layout_marginBottom="50dp"
android:scrollbars="vertical"/>
</LinearLayout>
</ScrollView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2"
android:layout_gravity="center"
android:gravity="center"
android:layout_alignParentBottom="true">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ADD TO CART"
android:background="@color/orange"
android:layout_weight="1"
android:layout_gravity="center"
android:gravity="center"
android:padding="20dp"
android:textColor="@color/white"
android:fontFamily="sans-serif"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="BUY NOW"
android:background="@color/red"
android:layout_weight="1"
android:layout_gravity="center"
android:gravity="center"
android:padding="20dp"
android:textColor="@color/white"
android:fontFamily="sans-serif"/>
</LinearLayout>
</RelativeLayout>
</code></pre>
<p>This is my java : </p>
<pre><code> listAdapter = new
AdapterProddetail(Productdetail.this,al_prod_id,
al_prod_image,al_prod_name,al_prod_price,
al_prod_disc,al_prod_discount,al_prod_stock,al_prod_cc);
list_prdt_detail.setAdapter(listAdapter);
list_prdt_detail.setOnItemClickListener(this);
list_prdt_detail.setOnTouchListener(new
ListView.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch
events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
// Allow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
} // Handle ListView touch events.
v.onTouchEvent(event);
return true;
}
});
</code></pre>
<p>I have add java code that will disallow scroll intercept but still list view not scrolling.Please help me to overcome this situation.</p>
| 0debug |
Implementation of simple game with many rounds and players : <p>I have to make a game where n people play hangman and the game keeps their results and if they win the round, then they go on until there is only one player left(that player wins) or none left(nobody wins). My hangman code is ready, so I do not need anything concerning the hangman function. However, I need some help to make a function that does the following:</p>
<p>1)Asks how many players will play</p>
<p>2)Asks their names and stores them</p>
<p>3)Plays the first round and if hangman()==True (meaning the player won) for a player, then this player goes on to the next round, otherwise not</p>
<p>4)If somebody wins, then we have a winner and the game ends</p>
<p>I have already made the part that the game asks the number of player, asks their names and makes them play. My hangman() function returns either True or False. However, it seems that I have a problem. Every time a player plays the game, the hangman() function runs twice. I don't know why this happens. I would like some help fixing that and also to write the part where each round is played. </p>
<pre><code>def game():
players_dict={}
results=[]
num_of_players=int(input('How many players will play? '))
for i in range(1,num_of_players+1):
a=input('Give the name of Player {}: '.format(i))
players_dict['Player {}'.format(i)]=a
for i in range(1,num_of_players+1):
print(players_dict['Player {}'.format(i)])
hangman()
if hangman()==False:
results+=False
else:
results+=True
</code></pre>
| 0debug |
static int rtc_start_timer(struct qemu_alarm_timer *t)
{
int rtc_fd;
unsigned long current_rtc_freq = 0;
TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
if (rtc_fd < 0)
return -1;
ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
if (current_rtc_freq != RTC_FREQ &&
ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
"error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
"type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
goto fail;
}
if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
fail:
close(rtc_fd);
return -1;
}
enable_sigio_timer(rtc_fd);
t->priv = (void *)(long)rtc_fd;
return 0;
}
| 1threat |
Get file's signed URL from amazon s3 using Filesystem Laravel 5.2 : <p>I'm looking for a good solution to get the signed url from amazon s3.</p>
<p>I have a version working with it, but not using laravel:</p>
<pre class="lang-php prettyprint-override"><code>private function getUrl ()
{
$distribution = $_SERVER["AWS_CDN_URL"];
$cf = Amazon::getCFClient();
$url = $cf->getSignedUrl(array(
'url' => $distribution . self::AWS_PATH.rawurlencode($this->fileName),
'expires' => time() + (session_cache_expire() * 60)));
return $url;
}
</code></pre>
<p>I don't know if this is the best way to do with laravel, considering it has a entire file system to work... </p>
<p>But if don't have another way, how do I get the client? Debugging I've found an instance of it inside the Filesystem object, but it is protected...</p>
| 0debug |
Extraction Integers and Charachters from String : i am solving mathematical expression problem using Stack Data Structure and i get stuck at extracting numbers and math signs from the string. What i want to do is to make a program to evaluate a given expression.
My question is, how to extract all numbers and signs from string into new string array.
Input: 12*1*145*2+8*1*1+2*3+2+4
The new string array should be:
String[] expArray={"12","*","1","*","145","*","2","+","8","*","1","*","1","+","2","*","3","+","2","+","4"}
I tried with nextInt(), split(), next(), nextByte() but it was unsuccessful.
Don't worry about anything else. I just mentioned the Problem just to got clear on what i am talking about.
Hope i am clear. If question feel free to ask. I need this urgent.
Thanks in advice
UPDATE: I don't need solution with building integers like array[i]*10+array[i+1] or something similar. What i need is more optimal solution. | 0debug |
What is wrong with this C++ class? : <p>Here is the code that I have so far: </p>
<pre><code>#include <iostream>
using namespace std;
class Rectangle
{
private:
double width, height;
public:
Rectangle();
double Set(double x, double y);
double getArea();
double getPerimeter();
};
Rectangle::Rectangle()
{
width = 1;
height = 1;
}
double Rectangle::Set(double x, double y)
{
width = x;
height = y;
}
double Rectangle::getArea()
{
double area = height * width;
return area;
}
double Rectangle::getPerimeter()
{
double perimeter = (width * 2) + (height * 2);
return perimeter;
}
int main()
{
double width, height;
cout << "Enter the width and height of a rectangle:";
cin >> width >> height;
cout << "The area is " << Rectangle::getArea << " and the perimeter is " << Rectangle::getPerimeter << endl;
}
</code></pre>
<p>When running this code I get the error : "'Rectangle::getArea': non-standard syntax; use '&' to create a pointer to member"
I get the same error about the Rectangle::getPerimeter
I am not sure what the problem is, I am new to making classes in C++ obviously, so I am having some trouble. Any suggestions?</p>
| 0debug |
Int object not iterable? (Python) (URGENT, NEEDED BY TONIGHT) : This is really urgent and I need this tomorrow, I cant seem to find a solution anywhere, I have a script that runs a facial recognition script, but for some reason its telling me this exact error:
----------
File "box.py",line 98, in <module>
label,confidence = model.predict(crop)
TypeError: 'int' object is not iterable
----------
My code thats actually important to the problem:
----------
import cv2
#Creates model to be the facerecognizer
model = cv2.face.createEigenFaceRecognizer()
#Defines the model as a training image taken previously
model.load(config.TRAINING_FILE)
#Initializes the camera as camera
camera = config.get_camera()
#Takes a picture using the camera
image = camera.read()
#Converts to grayscale
image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
#Results if it found a face
result = face.detect_single(image)
#Tells you to keep taking a picture until you have a face recognized
if result is None:
print 'Could not see face! Retake picture!'
continue
#gets dimensions of the face
x,y,w,h = result
#resizes the face
crop = face.resize(face.crop(image, x, y, w, h))
#Tests face against the previously taken model
label, confidence = model.predict(crop) **<--- This is where the error is**
#Im not 100% as to what this does, I got this part on the internet
result = cv2.face.MinDistancePredictCollector()
model.predict(crop)
label = result.getLabel()
confidence = result.getDist()
Thats basically it (Theres obviously some more code set up inside and between but it isnt important or relevant to the issue, at least I dont think, I need this urgently so please somebody respond quick, Im using Python 2.7 with opencv 3.1.0 on a raspbian raspberry pi 3 if you need that information
| 0debug |
How to keep user information after login in JavaFX Desktop Application : <p>I have an application with login screen, after the user is authenticated some "data" is retrieved from a database (username and privileges), until here everything is well. </p>
<p>After the login process I need to access to the privileges to generate some menus across different JavaFX scenes, this all throughout the entire application in any moment, but I don´t know how to do it.</p>
<p>What I am looking for is a behavior such as SESSION variable in PHP (yep, I come from web development), which keeps information alive and accesible during a certain period of time (usually while user is logged in).</p>
<p>The information I have found about this topic is unclear and outdated, I mean, solutions that do not apply for JavaFX 2 or solutions with old design patterns.</p>
<p>I have created an image because in other forums I have found the same question but that is misunderstood, so I hope this could help.</p>
<p>Thanks to everyone.</p>
<p><a href="https://i.stack.imgur.com/9kEqB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9kEqB.png" alt="enter image description here"></a></p>
| 0debug |
MySql: join two table and get not common data : I have two tables all_jobs and jobs_applied. Problem is i want to get the list of jobs from all_jobs table. At the moment i have this query but it is only giving me common records from both table.
SELECT b.uid,a.jobtitle, a.job_id,
FROM job_posting a left join job_applied b on a.job_id = b.job_id
Where b.uid != 10 and disable=0 and draft =0
Can anybody advise me on this?
Thanks
| 0debug |
gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
GIOCondition condition, void *opaque)
{
VncState *vs = opaque;
if (condition & G_IO_IN) {
vnc_client_read(vs);
}
if (condition & G_IO_OUT) {
vnc_client_write(vs);
}
return TRUE;
}
| 1threat |
Python: split all occurences and keep separator : I've already read [this][1] and [this][2] and [this][3] and lots of others. They don't answer to my problem.
I'd like to filter a string that may contain emails **or** strings starting by "@" (like emails but without the text before the "@"). I've tested many ones but one of the simplest that begins to get close is:
import re
re.split(r'(@)', "test @aa test2 @bb @cc t-es @dd-@ee, test@again")
Out[40]:
['test ', '@', 'aa test2 ', '@', 'bb ', '@', 'cc t-es ', '@', 'dd-', '@', 'ee, test', '@', 'again']
I'm looking for the right regexp that could give me:
['test ', '@aa test2 ', '@bb ', '@cc t-es ', '@dd-', '@ee', 'test@again']
[1]: https://stackoverflow.com/questions/2136556/in-python-how-do-i-split-a-string-and-keep-the-separators
[2]: https://www.w3schools.com/python/ref_string_split.asp
[3]: https://www.programiz.com/python-programming/regex
| 0debug |
uint8_t *xen_map_cache(target_phys_addr_t phys_addr, target_phys_addr_t size,
uint8_t lock)
{
MapCacheEntry *entry, *pentry = NULL;
target_phys_addr_t address_index = phys_addr >> MCACHE_BUCKET_SHIFT;
target_phys_addr_t address_offset = phys_addr & (MCACHE_BUCKET_SIZE - 1);
target_phys_addr_t __size = size;
trace_xen_map_cache(phys_addr);
if (address_index == mapcache->last_address_index && !lock && !__size) {
trace_xen_map_cache_return(mapcache->last_address_vaddr + address_offset);
return mapcache->last_address_vaddr + address_offset;
}
if ((address_offset + (__size % MCACHE_BUCKET_SIZE)) > MCACHE_BUCKET_SIZE)
__size += MCACHE_BUCKET_SIZE;
if (__size % MCACHE_BUCKET_SIZE)
__size += MCACHE_BUCKET_SIZE - (__size % MCACHE_BUCKET_SIZE);
if (!__size)
__size = MCACHE_BUCKET_SIZE;
entry = &mapcache->entry[address_index % mapcache->nr_buckets];
while (entry && entry->lock && entry->vaddr_base &&
(entry->paddr_index != address_index || entry->size != __size ||
!test_bits(address_offset >> XC_PAGE_SHIFT, size >> XC_PAGE_SHIFT,
entry->valid_mapping))) {
pentry = entry;
entry = entry->next;
}
if (!entry) {
entry = g_malloc0(sizeof (MapCacheEntry));
pentry->next = entry;
xen_remap_bucket(entry, __size, address_index);
} else if (!entry->lock) {
if (!entry->vaddr_base || entry->paddr_index != address_index ||
entry->size != __size ||
!test_bits(address_offset >> XC_PAGE_SHIFT, size >> XC_PAGE_SHIFT,
entry->valid_mapping)) {
xen_remap_bucket(entry, __size, address_index);
}
}
if(!test_bits(address_offset >> XC_PAGE_SHIFT, size >> XC_PAGE_SHIFT,
entry->valid_mapping)) {
mapcache->last_address_index = -1;
trace_xen_map_cache_return(NULL);
return NULL;
}
mapcache->last_address_index = address_index;
mapcache->last_address_vaddr = entry->vaddr_base;
if (lock) {
MapCacheRev *reventry = g_malloc0(sizeof(MapCacheRev));
entry->lock++;
reventry->vaddr_req = mapcache->last_address_vaddr + address_offset;
reventry->paddr_index = mapcache->last_address_index;
reventry->size = entry->size;
QTAILQ_INSERT_HEAD(&mapcache->locked_entries, reventry, next);
}
trace_xen_map_cache_return(mapcache->last_address_vaddr + address_offset);
return mapcache->last_address_vaddr + address_offset;
}
| 1threat |
Are Action and Action<T> completely different? : <p>I want to check <code>if (obj is Action)</code> but don't know its parameters?</p>
<p>so I want to execute this code whether the obj is <code>Action</code>, <code>Action<string></code>, or
<code>Action<sting, int, bool></code>.. etc.</p>
<pre><code>if(obj is Action)
{
//..
}
</code></pre>
| 0debug |
How to render first item in flatlist to full width and remaining items in 2 coloumns :
I need data in react native flaist to display as first item taking full width and remaining elements in single row 2 cloumns.
Item 1
Item 2 item3
Item4 item5
Item6 item 7 and so on | 0debug |
Identity equality for arguments of types Int and Int is deprecated : <p>Just fyi, this is my first question on StackOverflow and I'm really new in Kotlin.</p>
<p>While working on a project that's fully Kotlin (ver 1.1.3-2), I see a warning on the following code (with the comments for you curious lads):</p>
<pre><code> // Code below is to handle presses of Volume up or Volume down.
// Without this, after pressing volume buttons, the navigation bar will
// show up and won't hide
val decorView = window.decorView
decorView
.setOnSystemUiVisibilityChangeListener { visibility ->
if (visibility and View.SYSTEM_UI_FLAG_FULLSCREEN === 0) {
decorView.systemUiVisibility = flags
}
}
</code></pre>
<p>The warning is for <em>visibility and View.SYSTEM_UI_FLAG_FULLSCREEN === 0</em>, and it says <em>Identity equality for arguments of types Int and Int is deprecated</em>.</p>
<p>How should I change the code and why was it deprecated in the first place (for knowledge's sake)?</p>
| 0debug |
PostgreSQL query to get the current password : <p>I want to write a query which should result me the following details:</p>
<p>Host,
Port,
Username,
Password.</p>
| 0debug |
static void vfio_probe_nvidia_bar5_quirk(VFIOPCIDevice *vdev, int nr)
{
VFIOQuirk *quirk;
VFIONvidiaBAR5Quirk *bar5;
VFIOConfigWindowQuirk *window;
if (!vfio_pci_is(vdev, PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID) ||
!vdev->has_vga || nr != 5) {
return;
}
quirk = g_malloc0(sizeof(*quirk));
quirk->mem = g_malloc0(sizeof(MemoryRegion) * 4);
quirk->nr_mem = 4;
bar5 = quirk->data = g_malloc0(sizeof(*bar5) +
(sizeof(VFIOConfigWindowMatch) * 2));
window = &bar5->window;
window->vdev = vdev;
window->address_offset = 0x8;
window->data_offset = 0xc;
window->nr_matches = 2;
window->matches[0].match = 0x1800;
window->matches[0].mask = PCI_CONFIG_SPACE_SIZE - 1;
window->matches[1].match = 0x88000;
window->matches[1].mask = PCIE_CONFIG_SPACE_SIZE - 1;
window->bar = nr;
window->addr_mem = bar5->addr_mem = &quirk->mem[0];
window->data_mem = bar5->data_mem = &quirk->mem[1];
memory_region_init_io(window->addr_mem, OBJECT(vdev),
&vfio_generic_window_address_quirk, window,
"vfio-nvidia-bar5-window-address-quirk", 4);
memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,
window->address_offset,
window->addr_mem, 1);
memory_region_set_enabled(window->addr_mem, false);
memory_region_init_io(window->data_mem, OBJECT(vdev),
&vfio_generic_window_data_quirk, window,
"vfio-nvidia-bar5-window-data-quirk", 4);
memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,
window->data_offset,
window->data_mem, 1);
memory_region_set_enabled(window->data_mem, false);
memory_region_init_io(&quirk->mem[2], OBJECT(vdev),
&vfio_nvidia_bar5_quirk_master, bar5,
"vfio-nvidia-bar5-master-quirk", 4);
memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,
0, &quirk->mem[2], 1);
memory_region_init_io(&quirk->mem[3], OBJECT(vdev),
&vfio_nvidia_bar5_quirk_enable, bar5,
"vfio-nvidia-bar5-enable-quirk", 4);
memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,
4, &quirk->mem[3], 1);
QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
trace_vfio_quirk_nvidia_bar5_probe(vdev->vbasedev.name);
}
| 1threat |
Can you update the web.config file for an Azure web app without redeploying? : <p>I would like to update a database connection string in the web.config file for an application that is currently hosted in Azure as a web app.</p>
<p>Seems that you can RDP into an Azure cloud service role but not a web app. If you can't RDP into an Azure web app, is there another way to update the connection string without redeploying?</p>
| 0debug |
How do you make a brick die? and hen it dies, it blows up : I am tryna make a part die, but i dont exactly know how | 0debug |
static void rng_egd_free_request(RngRequest *req)
{
g_free(req->data);
g_free(req);
}
| 1threat |
Visual Studio - Create Class library targeting .Net Core : <p>How do I create a class library targeting .Net Core in visual studio 2015?<br/>
I found this getting started “<a href="https://dotnet.github.io/getting-started/">guide</a>”, which shows how to create a new .Net Core project using the <em>dotnet</em> command line tool.<br/>
Do I need to create somehow a VS project manual based on the generated files (<em>project.json</em>…)?<br/>
Is there a way to create a .Net Core DLL inside of VS without using the “dotnet” tool?</p>
| 0debug |
How to find if a number is prime or not without division repeatedly : <p>I was told to make a program in C to find whether a number is prime or not and factorize it. I used repeated division method, i.e. I repeatedly divide the number by integers starting from 1 to that number, and if the remaining is 0 not more than 2 cases(1 and that number) the number is a prime number, otherwise it's not. But my teacher said that if a large number was there in input, the program would take much time to process it, so it was wrong. He said to create a new program but I can't understand how can I check if a number is prime or not without this method, so please anyone help me.</p>
| 0debug |
alert('Hello ' + user_input); | 1threat |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.