text:
Q: Combobox with images Is it possible to create the ComboBox with images instead of strings? It doesn't support delegate:
ComboBox {
        currentIndex: 2
        model: ListModel {
            id: cbItems
            ListElement { imageHeight: 280; imageSource: "../images/tee3.png"  }
            ListElement { imageHeight: 300; imageSource: "../images/tee5.png"  }
            ListElement { imageHeight: 218; imageSource: "../images/tee1.png"  }
        }
        delegate: Image {
            height: imageHeight
            fillMode: Image.PreserveAspectFit
            source: imageSource
        }
        width: 200
    }

A: You can maybe do it by defining you own ComboBoxStyle (here the documentation) and playing with the label field which is a Component.

A: As skypjack said, done using ComboBoxStyle with signals
    ComboBox {
            id : cBox4
            height: 20
            width: 100

            anchors.left: parent.left
            anchors.leftMargin: 0
            anchors.top: parent.bottom
            anchors.topMargin: 10

            model : ListModel {
                id: cbItems
                ListElement { text: "type A"; imageHeight: 218; imageSource: "../images/teeA.png"  }
                ListElement { text: "type B"; imageHeight: 200; imageSource: "../images/teeB.png"  }
                ListElement { text: "type V"; imageHeight: 280; imageSource: "../images/teeV.png"  }
                ListElement { text: "type G"; imageHeight: 350; imageSource: "../images/teeG.png"  }
                ListElement { text: "type D"; imageHeight: 300; imageSource: "../images/teeD.png"  }
            }

            style: ComboBoxStyle {
                id: comStyle

                label: Item {
                    Text {
                        id: lblText
                        text: control.editText
                        font.pixelSize: p.pixelSize();

                        verticalAlignment: Text.AlignVCenter
                        horizontalAlignment: Text.AlignHCenter
                    }

                    Image {
                        anchors.right: lblText.left
                        anchors.rightMargin: 10
                        anchors.top: lblText.top
                        anchors.topMargin: 10

                        id: img
                        height: 280
                        fillMode: Image.PreserveAspectFit
                        source: "../images/teeA.png"

                        Component.onCompleted: {
                            cBox4.currentIndexChanged.connect(changeImage)
                        }

                        function changeImage() {
                            img.source = cbItems.get(cBox4.currentIndex).imageSource;
                            img.height = cbItems.get(cBox4.currentIndex).imageHeight;
                        }
                    }
                }
            }
        }

A: Not yet.
Though, it uses MenuItem for elements, which can have icon. So, if you patch ComboBox.qml to use icon from model, it should be displayed.


text:
Q: R plot for showing true/false positives I'm looking for a way to plot my data.  Suppose you have a number of algorithms that produce a ranked list, and a classifier that identifies each item in the list as true or false.  How can I produce a chart that puts each algorithm beside each other and each rank has its own square stacked as follow:
      __   __
 3   |TP| |FP|
     |__| |__|
 2   |FP| |TP|
     |__| |__|
 1   |TP| |TP|
     |__| |__|
      a    b

Where TP could be coloured green and FP could be coloured red for example.

A: You may use ggplot2 for drawing a stacked barplot. However a better way to compare the true/false positive/negatives of algorithms is precision/recall (same as selectivity/specificity) chart.

A: It can be done very easily with base R, using the heatmap() function.
Try this:
# Dataframe with TRUE/FALSE items
mydf <- data.frame(a = c(T, F, T), b = c(T, T,F))

# Transform booleans into 1s and 0s, and plot heatmap
heatmap(apply(mydf, 2, as.integer),
        col = c("red", "lightgreen"),
        xlab = "Algorithm",
        ylab = "Item",
        main = "False positives in red",
        Rowv = NA,
        Colv = NA,
        scale = "column")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Optimizing tensorflow to CPU use I have a model that needs to be optimized to CPU.
Currently the model takes a 1024 x 1024 bytes data.
images = img[y:y+1024,x:x+1024,:]

As per this document, they want to change the default tensorflow data format from NHCW to NCHW format.
How can I transform from NHWC to NCHW format?
https://software.intel.com/en-us/articles/tensorflow-optimizations-on-modern-intel-architecture

A:
As per this document, they want to change the default tensorflow data format from NHCW to NCHW format.

Actually, I've never seen any Tensorflow function that supports NHCW format. For example, tf.nn.conv2d and tf.nn.conv2d_transpose support NHWC (current default) and NCHW format. tf.nn.max_pool supports  NHWC, NCHW and NCHW_VECT_C (the last one is the most performant tensor format for cudnn6's quantized convolution, similar to NCHW).

How can I transform from NHCW to NCHW format?

But this transformation is possible, e.g. via tf.transpose that works with high-dimensional tensors as well:
# NHCW
original = tf.placeholder(dtype=tf.float32, shape=[None, 1024, 3, 1024])
# NCHW: swap 1 and 2 axis
transformed = tf.transpose(original, perm=[0, 2, 1, 3])

You can also do this in numpy via np.swapaxes(array, 1, 2).


text:
Q: How do I center links in a Community page's Tile Menu? I have a Community Page that has a Tile Menu, which holds 3 links that are displayed as images. For some reason, they're left-aligned, so the middle of the 3 images is to the left of the middle of the page.
I tried using the following CSS based on this documentation but I don't know how to select the proper element and its content.
.forceCommunityHeadline .headlineTitleText
    {
        text-align: center;
        align-content: center;
    }

A: I had the same issue with a tile menu where I only had 3 tiles. I was able to target them using the following in the CSS override:
.slds-large-size_1-of-4,
 .slds-large-size--1-of-4
{
    width: 33%;
}
Word of caution, this will target all tiles in your community indiscriminately if they are in a layout that allows for 4 to be visible at once. If only 3 are visible then the class will be.slds-large-size_1-of-3.

A: As of Feb 2020, the tile menu element looks like the HTML in this screenshot.

You need to apply your CSS to .tileMenuItemList class, but it's good to reference .forceCommunityTileMenu to make it more specific.
text-align doesn't work here, but justify-content does because display: flex is in use.  The following CSS works, I've tested it.
/* Center items in a Tile Menu component */
.forceCommunityTileMenu .tileMenuItemList {
    justify-content: center;
}


text:
Q: Hash Match and Nested Loops I have stored procedure which updates one table with data from another table, joind by some field. And that is super fast with no indexes on the first table. I see in execution plan that Hash Match is performed while joining tables. But when I add 3 indexes to the first table it becomes extremely slow and execution plan show that Nested loops is used instead of Hash Match. Why this happens? Why indexes make a problem? And is there a way to solve it without removing indexes?
Edit: When I put back 2 indexes, and remove the 3. one it is fast again. Third index is the problem, maybe because filed it is based on is nchar(255), too long maybe?


text:
Q: i want to display only those images according to the category_id selected i want to display only those images according to the category_id selected but iam not getting images here and and for all category_id the value showing is category_id=9
here is my controller
 public function men_clothing($p_id=null)
{
    $data['active_mn']='men_clothing';

    $data['men']=$this->roxmodel->get_category_by_parent($p_id=8);
    $data['kids']=$this->roxmodel->get_category_by_parent($p_id=9);

    $config['base_url'] = base_url().'roxcontrol/men_clothing';
    $config['per_page'] = 9;
    $config['uri_segment'] = 3;
    $config['total_rows'] = $this->roxmodel->count_gallery();
    $data['galllery']=$this->roxmodel->get_gallery_men_images($p_id,$config['per_page'],$this->uri->segment(3));

    var_dump($data['galllery']);
    $this->load->library('pagination',$config);
    $data['page_links'] = $this->pagination->create_links();

    $this->load->view('men_clothing',$data);
}

here is my model
public function get_gallery_men_images($p_id=null)
  {
    $this->db->where('gallery.category_id',$p_id);
    $this->db->select('gallery.*,category.category_name');
    $this->db->join('category','category.id=gallery.category_id');
    return $this->db->get('gallery')->result();

  }

here is my view page

<a href="<?php echo base_url();?>roxcontrol/men_clothing">View All

     <?php foreach($men as $row) {?>

<a href="<?php echo base_url();?>roxcontrol/men_clothing/<?php echo $row->id; ?>"><?php echo $row->category_name; ?>

     <?php } ?>

 <?php if( !empty($galllery) ) {
                                foreach($galllery as $row){?>

                                                        <img class="primary-image" ima="<?php echo base_url();?>images/<?php echo $row->image;?>" src="<?php echo base_url();?>images/<?php echo $row->image;?>" alt="" />
                                                        <img class="secondary-image" ima="<?php echo base_url();?>images/<?php echo $row->image;?>" src="<?php echo base_url();?>images/<?php echo $row->image;?>" alt="" />

                                                            <a href="<?php echo base_url()?>images/<?php echo $row->image ?>" data-toggle="modal-image"  title="Quick View">

<a href="<?php echo base_url();?>roxcontrol/product_details/<?php echo $row->id;?>/<?php echo $row->category_id;?>"><?php echo $row->title;?>

<?php echo $row->description;?>

                                    <?php }}?>

here the image is not displaying and getting like this
SELECT `gallery`.*, `category`.`category_name` FROM `gallery` JOIN `category` ON `category`.`id`=`gallery`.`category_id` WHERE `gallery`.`category_id` = 9

my table(gallery) looks like this
id     image                category_id
93   img1455604030.jpg       10
94   img1455605183.jpg       11
95   img1455616291.jpg       11
96   img1455617201.jpg       10
97   img1455617299.jpg       10
98   img1455681918.jpg       13
99   img1455681957.jpg       12

A: there is a problem in you join query
$this->db->select('*');
$this->db->from('gallery');
$this->db->where('category.id',$p_id);
$this->db->join('category', 'category.id = gallery.category_id');

$query = $this->db->get()->result();
return $query;

A: If what you want is to get or Filter result which has the same category_id: the query should be like this
public function get_gallery_men_images($p_id=null)
  {
    $img = $this->db->select('gallery.*')
         // why not add condition IF p_id = null
         // execute only if p_id not null otherwise it return error
         if($p_id != null):
         ->where('gallery.category_id',$p_id)
         endif;
          // we are using LEFT JOIN to fetch the category data's
         ->join('category','category.id=gallery.category_id', 'left')
         ->get('gallery');
    return $img->result();

  }


text:
Q: Failed asserting that 1 matches expected 6 i get this test, and i need to write code that pass.
But only what i can get is :
"Failed asserting that 1 matches expected 6 " if i return 6 i get " Too few arguments to function on line 18 and exactly 3 expected "
This is test :
    public function powerTest()
{
    $calculator = new Calculator();

    $this->assertEquals(6, $calculator->power(1,2,3));
    $this->assertEquals(0, $calculator->power());
}

That is my code :
    public function power(int $int, int $int1, int $int2)
{
    return 1;
}

A: Asserts by definition require the condition to be true; otherwise, they throw an exception. In this case, your first assert is requiring the result of $calculator->power(1, 2, 3) to equal 6, which it doesn't. It returns 1.
6 != 1, so it fails.
The second one provides no arguments to the power function $calculator->power(). Your power function has 3 arguments, and all are required. Not providing enough arguments will give you a too few arguments error.
You can make arguments optional by specifying a default value.
function foo($bar = true)


text:
Q: Tricks with transforming function plots I want to try a function graph trick and need some advice.
We have a function graph like this:

The trick is as follows:
We take an arbitrary interval $x∈[a;b]$ and the corresponding section of the function graph $f$. Further, we must introduce a new function F, such that for $t_0=0$ its value is equal $Y=y_a$, and for $t_k = b$ its value is equal $Y=y_b$. This can be graphically displayed as follows.

Sorry for the messy design. I was in a hurry. Can such a trick be done?

A: Let
$$
F(x) = \begin{cases}
f(a) & x \le 0 \\
f(\frac{b-a}{b}x + a) & 0 \le x \le b\\
f(b) & x \ge b
\end{cases}
$$
and you've got the function that the text under the right-hand graph indicates, although not what the picture in the right-hand graph indicates.

A: If i understand you correctly, the only thing you need is a linear parametrization mapping $$t=0 \mapsto b \mbox{ and } t=b \mapsto a $$
$$\Rightarrow x(t) = a + \frac{b-a}{b}(b-t)$$
As you can see: $x(0) = b$ and $x(b) = a$
So, plugging this into your function $f$ gives your desired function
$$F(t) = f\left(a + \frac{b-a}{b}(b-t)\right) \text{ on } [0,b]$$
Additional info after comment:
In order to "freeze" the maximum for $b>0$ and using an analytic expression you can do the following:
Assuming that $F(b) = f(a)$ is the (allowed) maximum you can do the following:
$$H(t) = \frac{F(t) + F(b)}{2} - \frac{|F(t) - F(b)|}{2} \text{ on } [0,+\infty)$$
This cuts off $F$ at $F(b)$ and continues with $F(b)$ for $t>b$, provided that $F$ would otherwise continue above the given threshold.


text:
Q: Running Scala Jar with Spark-Submit I've compiled a spark-scala script to a JAR and I want to run it with spark-submit. But I'm having this error:
2020-01-07 13:03:02,190 WARN util.Utils: Your hostname, nifi resolves to a loopback address: 127.0.1.1; using 10.0.2.15 instead (on interface enp0s3)
2020-01-07 13:03:02,192 WARN util.Utils: Set SPARK_LOCAL_IP if you need to bind to another address
2020-01-07 13:03:03,109 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
2020-01-07 13:03:03,826 WARN deploy.SparkSubmit$$anon$2: Failed to load hello.
java.lang.ClassNotFoundException: hello
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.util.Utils$.classForName(Utils.scala:238)
    at org.apache.spark.deploy.SparkSubmit.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:806)
    at org.apache.spark.deploy.SparkSubmit.doRunMain$1(SparkSubmit.scala:161)
    at org.apache.spark.deploy.SparkSubmit.submit(SparkSubmit.scala:184)
    at org.apache.spark.deploy.SparkSubmit.doSubmit(SparkSubmit.scala:86)
    at org.apache.spark.deploy.SparkSubmit$$anon$2.doSubmit(SparkSubmit.scala:920)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:929)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
2020-01-07 13:03:03,857 INFO util.ShutdownHookManager: Shutdown hook called
2020-01-07 13:03:03,858 INFO util.ShutdownHookManager: Deleting directory /tmp/spark-a8cc1ba6-3643-4646-82a3-4b44f4487105

This is my code:
import org.apache.spark.sql.SparkSession
import org.apache.spark.{SparkConf, SparkContext}

object hello {
  def main(args: Array[String]): Unit = {

    val conf = new SparkConf()
      .setMaster("local")
      .setAppName("quest9")

    val sc = new SparkContext(conf)
    val spark = SparkSession.builder().appName("quest9").master("local").getOrCreate()
    import spark.implicits._

    val zip_codes = spark.read.format("csv").option("header", "true").load("/home/hdfs/Documents/quest_9/doc/zip.csv")
    val census = spark.read.format("csv").option("header", "true").load("/home/hdfs/Documents/quest_9/doc/census.csv")

    census.createOrReplaceTempView("census")
    zip_codes.createOrReplaceTempView("zip")

    val query = census.as("census").join((zip_codes.where($"City" === "Inglewood").where($"County" === "Los Angeles").as("zip")),Seq("Zip_Code"),"inner").select($"census.Total_Males".as("male"),$"census.Total_Females".as("female")).distinct()
    query.show()
    val queryR = query.repartition(5)
    queryR.write.parquet("/home/hdfs/Documents/population/census/IDE/census.parquet")

    sc.stop()
  }
}

I think my problem is that im using scala object instead of a class, but I'm not sure.
I run the spark-submit like this
spark-submit \
--class hello \
/home/hdfs/IdeaProjects/untitled/out/artifacts/quest_jar/quest.jar

Anyone solved this error before?

A: I think you need to specify a package name for both spark-submit and your object.
For instance :
spark-submit \
--class com.my.package.hello \
/home/hdfs/IdeaProjects/untitled/out/artifacts/quest_jar/quest.jar

and
package com.my.package

import org.apache.spark.sql.SparkSession
import org.apache.spark.{SparkConf, SparkContext}

object hello {
    ...
}


text:
Q: css /smarty changing the size of a container on hover How can i change the size of a container on hover so that it looks like in the Picture. Is it possible with only css/Smarty?
Here is the Link to the Picture: http://www.bilder-upload.eu/upload/bc5052-1485274659.jpg

A: You can create that zoom effect that zooms over other elements using transform: scale(). Here's an example.

img {
  max-width: 200px;
  transition: transform .5s;
  transform-origin: 50% 0;
  background: #fff;
}

footer {
  background: #111;
  color: #fff;
  padding: 2em 0;
}

.shirts {
  text-align: center;
}

a:hover img {
  transform: scale(1.2);
}

footer


text:
Q: Add folders to specific compression archives SOURCE="/opt/gitlab/full
BACKUP_CONFIG="/etc/gitlab"
I have folder $SOURCE/ $date.tar
I want to add $BACKUP_CONFIG to $SOURCE/ $date.tar
Since this folder will generate $date.tar a weekly
How can i add $BACKUP_CONFIG to $SOURCE/$date.tar

A: You can append files to tar archive, from here:
tar --append --file=$SOURCE/$date.tar $BACKUP_CONFIG

You can replace the file in a tar archive, by deleting and append a file, from here:
tar --delete --file=$SOURCE/$date.tar $BACKUP_CONFIG
tar --append --file=$SOURCE/$date.tar $BACKUP_CONFIG


text:
Q: How is a modern digital oscilloscope calibrated? Old CRT type oscilloscopes were nothing but analog devices. They were filled with potentiometers. All this circuitry would drift over time. When they were calibrated, known waveforms were fed to the scope, the displayed wave form was then compared to the known and if the differences was within a given margin the pots would be adjusted to bring it back to the original spec. This procedure depends on that the scope has a predictable drift. If the difference between the known waveform and the displayed waveform was significantly greater than the expected drift, something was wrong with the scope and it needs repaired.
New digital oscilloscopes don't have potentiometers like the old CRT scopes. The verification process, I assume, is exactly the same. Feed the scope known waveforms and compare them with the displayed waveforms.
With no potentimeters how is the scope adjusted for drift over time?
Is the scope trimmed in software or if the scope is out of tolerance (but still within the excepted drift) it needs repaired?

A: The verification process, I assume, is exactly the same
That is a wrong assumption, to have a person sit down and calibrate a scope like this is too expensive. It can be automated ! I bet the manufacturers have an automated bench for this, just connect signals to the input and control the scope using a PC. Feed it +1.000 V DC, measure the "raw number" which the scope's ADC measures. Then feed it -1.000 VDC, measure again. Then program the scope such that +1.000 V gives +1.000V on the screen. After the ADC it is just numbers so the calibration can be done in software.
The same is done in a modern digital multimeter. All the pots are gone, calibration is done in software and stored in a flash ROM.
Time calibration is also not needed on digital scopes as they use a quartz crystal which will always be miles ahead regarding accuracy compared to analog scopes using an RC sawtooth generator circuit (for the horizontal deflection).
On an analog CRT based scope, the spot where the electron beam hits the screen must be calibrated (X, Y position). On a digital scope, there's a an LCD display, each pixel can be adressed individually by the application processor. No need to calibrate.


text:
Q: Django: Convert string of numbers to ip address in dynamic listview I have a django website containing a page with a listview. The list, created from a  object-list in a for loop {% for betr in object_list %} contains a field with ip addresses like <td>{{ betr.netmask }}</td>. The data in the object list is provided as a string of numbers like "123456789111".
What is the best way to display this as 123.456.789.111.
Tried lambda or normal functions imported as utils, but always ran into errors.

A: Try creating a custom template tag.
Ex:
from django import template
import ipaddress  #Python 3

register = template.Library()
def toIp(value):
    return ipaddress.ip_address(value)

In template
{{ betr.netmask |toIp }}

More Info

A: Python 3 has ipaddress module which features very simple conversion:
    a="123456789111"
    int(ipaddress.IPv4Address(a))

A: I don't think this is possible, because a number could translate to multiple valid IP-addresses.
For instance a number like 192168211 could be written as 192.168.2.11 or 192.168.21.1.
My advice is, either store the IP-address as a string, or as the actual decimal number representation. (An IP-address is after all just a 4 byte value. In that case 192.168.2.11 would translate to 3232236043, and 192.168.21.1 to 3232240897)


text:
Q: Help opening a file in Visual Studio 2008 I'm trying to use Visual Studio 2008 since I had problems opening a file in XCode.  I am new to VS, but these are the steps I took.  I created a new project, selected Win32 Console Application, empty project.  My code is:
// C_test.cpp : Defines the entry point for the console application.
//
#include <stdio.h>
#include <stdlib.h>

int main(void )
{
   printf("Hello");
   FILE *filePtr;

   filePtr = fopen( "test.txt", "r" );
   if (filePtr == NULL)
   {
      fprintf(stderr, "Can't open \"test\"\n");
      exit(EXIT_FAILURE);
   }
   else
   {
      int x;

      printf("File open successful\n");
      /* read one character at a time until EOF is reached */
      while ((x = fgetc(filePtr)) != EOF)
      {
         //printf("%c", x);
         fprintf(stderr, "%x\n",x);
      }
   }
   fclose(filePtr);
   system("pause");

   return 0;
}

Something doesn't seem to be correct since my error list is:
>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(9) : error C2275: 'FILE' : illegal use of this type as an expression
1>        c:\program files\microsoft visual studio 9.0\vc\include\stdio.h(69) : see declaration of 'FILE'
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(9) : error C2065: 'filePtr' : undeclared identifier
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(11) : error C2065: 'filePtr' : undeclared identifier
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(11) : warning C4047: '=' : 'int' differs in levels of indirection from 'FILE *'
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(12) : error C2065: 'filePtr' : undeclared identifier
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(12) : warning C4047: '==' : 'int' differs in levels of indirection from 'void *'
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(23) : error C2065: 'filePtr' : undeclared identifier
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(23) : warning C4047: 'function' : 'FILE *' differs in levels of indirection from 'int'
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(23) : warning C4024: 'fgetc' : different types for formal and actual parameter 1
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(29) : error C2065: 'filePtr' : undeclared identifier
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(29) : warning C4047: 'function' : 'FILE *' differs in levels of indirection from 'int'
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(29) : warning C4024: 'fclose' : different types for formal and actual parameter 1
1>Build log was saved at "file://c:\Documents and Settings\jon\My Documents\Visual Studio 2008\Projects\C_test\C_test\Debug\BuildLog.htm"
1>C_test - 6 error(s), 6 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Any thoughts?  Sorry if this is a>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(9) : error C2275: 'FILE' : illegal use of this type as an expression
1>        c:\program files\microsoft visual studio 9.0\vc\include\stdio.h(69) : see declaration of 'FILE'
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(9) : error C2065: 'filePtr' : undeclared identifier
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(11) : error C2065: 'filePtr' : undeclared identifier
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(11) : warning C4047: '=' : 'int' differs in levels of indirection from 'FILE *'
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(12) : error C2065: 'filePtr' : undeclared identifier
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(12) : warning C4047: '==' : 'int' differs in levels of indirection from 'void *'
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(23) : error C2065: 'filePtr' : undeclared identifier
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(23) : warning C4047: 'function' : 'FILE *' differs in levels of indirection from 'int'
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(23) : warning C4024: 'fgetc' : different types for formal and actual parameter 1
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(29) : error C2065: 'filePtr' : undeclared identifier
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(29) : warning C4047: 'function' : 'FILE *' differs in levels of indirection from 'int'
1>c:\documents and settings\jon\my documents\visual studio 2008\projects\c_test\c_test\main.c(29) : warning C4024: 'fclose' : different types for formal and actual parameter 1
1>Build log was saved at "file://c:\Documents and Settings\jon\My Documents\Visual Studio 2008\Projects\C_test\C_test\Debug\BuildLog.htm"
1>C_test - 6 error(s), 6 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Any thoughts?  Thanks!

A: You can only declare variables at the top of a scope {} before any code in C.
In C++ you can declare them anywhere.  So either change your filename to test.cpp or
move your first printf down below the declaration of FILE* fileptr.
int main(void )
{
   FILE *filePtr;
   printf("Hello");


text:
Q: Add images to ListView corresponding to its content, obtained from JSON response I am using JSON parser to parse JSON Response, where i am able to get item names in ListView but i am not able to get images corresponding to it. where image url's are present in JSON response. How can i parse response to get images corresponding to items. Following is the code, Any one who know how to do this kindly help me it would be very useful.
Note: images and items are NOT Fixed
public class AndroidJSONParsingActivity extends ListActivity {

// url to make request
private static String url = "website/?JSON=get_recent_post";

// JSON Node names
private static final String TAG_POSTS = "posts";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_DATE = "date";
private static final String TAG_CONTENT = "content";
private static final String TAG_AUTHOR = "author";
private static final String TAG_NAME = "name";

// contacts JSONArray
JSONArray posts = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);

    try {
        // Getting Array of Contacts
        posts = json.getJSONArray(TAG_POSTS);

        // looping through All Contacts
        for(int i = 0; i < posts.length(); i++){
            JSONObject c = posts.getJSONObject(i);

            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String title = c.getString(TAG_TITLE);
            String date = c.getString(TAG_DATE);
            String content = c.getString(TAG_CONTENT);

            // Phone number is agin  JSON Object
            JSONObject author = c.getJSONObject(TAG_AUTHOR);
            String name = author.getString(TAG_NAME);

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_ID, id);
            map.put(TAG_TITLE, title);
            map.put( TAG_DATE, date);
            map.put( TAG_NAME, name);
            map.put( TAG_CONTENT, content);
            // adding HashList to ArrayList
            contactList.add(map);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    /**
     * Updating parsed JSON data into ListView
     * */
    ListAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.list_item,
            new String[] { TAG_TITLE, TAG_DATE, TAG_NAME, TAG_CONTENT }, new int[] {
                    R.id.name, R.id.email,R.id.mobile, R.id.content });

    setListAdapter(adapter);

    // selecting single ListView item
    ListView lv = getListView();

    // Launching new screen on Selecting Single ListItem
    lv.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String title = ((TextView) view.findViewById(R.id.name)).getText().toString();
            String date = ((TextView) view.findViewById(R.id.email)).getText().toString();
            String name = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
            String content = ((TextView) view.findViewById(R.id.content)).getText().toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
            in.putExtra(TAG_TITLE, title);
            in.putExtra(TAG_DATE, date);
            in.putExtra(TAG_NAME, name);
            in.putExtra(TAG_CONTENT, content);
            startActivity(in);

        }
    });

}

}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

}
SingleMenuItem.java
public class SingleMenuItemActivity  extends Activity {

// JSON node keys
private static final String TAG_TITLE = "title";
private static final String TAG_DATE = "date";
private static final String TAG_NAME = "name";
private static final String TAG_CONTENT = "content";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_list_item);

    // getting intent data
    Intent in = getIntent();

    // Get JSON values from previous intent
    String title = in.getStringExtra(TAG_TITLE);
    String date = in.getStringExtra(TAG_DATE);
    String name = in.getStringExtra(TAG_NAME);
    String content = in.getStringExtra(TAG_CONTENT);

    // Displaying all values on the screen
    TextView lblName = (TextView) findViewById(R.id.name_label);
    TextView lblCost = (TextView) findViewById(R.id.email_label);
    TextView lblDesc = (TextView) findViewById(R.id.mobile_label);
    TextView lblCont = (TextView) findViewById(R.id.content_label);

    lblName.setText(title);
    lblCost.setText(date);
    lblDesc.setText(name);
    lblCont.setText(content);
}

}

A: You have to make your own adapter extending the BaseAdapter to have more freedom and flexibility...it's not too hard, you just have to bind the elements of the list row with the json data for the corresponding rows...on this binding you will also fetch the images, and assign to the ImageViews.
SimpleAdapter is meant for very simple stuff.


text:
Q: Prove that if $∀b>1$, $x,y>0$ and $x/yProve: if
$$
\forall \space b > 1 \space\space \space  x,y >0  \space   \space \text{and}  \space x/y < b
$$
then $x$ and $y$ satisfy the relation:
$$
x \leq y
$$
I understand the idea that $x$ has to be less than $y$ so the result is between $0$ and $1$ but I don't know how to express it with symbols.

A: Suppose $x>y$. Then $x/y>1$. But this contradicts $x/y<b$ for choice of $b=1+1/n$ where we choose integer $n$ so that $1/n<x/y-1$. So we have a contradiction for $x>y$. By the trichotomy property, That only leaves $x=y$ or $x<y$.
We know such an $n$ exists, because by the Archimedean property of the reals there is an $n$, $\frac{y}{x-y}<n$.

A: Suppose that $x > y$, then $b := \frac xy > 1$, thus $x < by$, i.e. $x < \frac xyy = x$, which is a contradiction.

A: How about this:
b $\in$ $(1, \infty)$
Then
$x/y < b \space => 1$ is supremum (it can be proved if necessary) of the set composed of $x/y$.
It follows that $x/y < 1$, hence $x < y$.


text:
Q: switch string with accent not matching I'm having trouble with a switch statement that is supposed to match a character with accent. The character string I want to match comes from a vector (data$ttx), himself coming from an excel sheet read with openxlsx.
> head(data$ttx)
[1] "Autorisé" "Autorisé" "Autorisé" "Autorisé" "Interdit" "Autorisé"

Here is the reproduction of my problem :
> x = data$ttx[1]
> switch(x, "oui" =, "Autorisé" = TRUE, "non" =, "Interdit" = FALSE, x)
#this doesn't work, it returns "Autorisé", the default statement

But if I do :
> x = "Autorisé"
> switch(x, "oui" =, "Autorisé" = TRUE, "non" =, "Interdit" = FALSE, x)
#this works, it returns TRUE

I'm guessing it is because of the accent in the string because for the other cases ("oui", "non", "Interdit") it works fine. My guess would be that the extraction from excel has given an invisible difference between the character strings in my vector, compared to strings written directly in R. The problem seems to be quite specific to the switch function because if I try :
> data$ttx[1] == "Autorisé"
#this returns TRUE

Do you know of this issue ? Do you have a way around it ?
EDIT : More informations :
> dput(head(data$ttx))
c("Autorisé", "Autorisé", "Autorisé", "Autorisé", "Interdit", "Autorisé")
> Encoding(head(data$ttx))
[1] "UTF-8"   "UTF-8"   "UTF-8"   "UTF-8"   "unknown" "UTF-8"


text:
Q: Prove that for every integer $n$, $n^3$mod$6$=$n$mod$6$ I will use induction to prove this.
Firstly for $n=1$,
$1^3\text{mod}6=1\text{mod}6$
Now we assume that this holds for some $n=k$ and prove that if it holds for $n=k$ it should also hold for $n=k+1$.
$(k+1)^3\text{mod}6=(k^3+3k^2+3k+1)\text{mod}6$
As for $n=k$ because it holds,
$k^3\text{mod}6=k\text{mod}6$
$k^3-6p(k)=k-6q(k)$
$k^3-k=6p(k)-6q(k)$
Consider $(k^3+3k^2+3k+1)-6a(k)=6p(k)-6q(k)+k+1+3k^2+3k$
Now we just need to prove that $3k^2+3k$ is always a multiple of 6.
For $k=1$ it holds.
Assume $k=j$ holds. Then for $k=j+1$,
$3(j+1)^2+3(j+1)=3(j^2+2j+1)+3j+3=3j^2+3j+6j+6$
So for $k=j+1$ it is also a multiple. As it holds for $k=1$, then it holds for all positive integers $k$.
Then this means that
$6p(k)-6q(k)+k+1+3k^2+3k=k+1-6b(k)$
And if $(k^3+3k^2+3k+1)-6a(k)=k+1-6b(k)$ this means $(k+1)^3\text{mod}6=(k+1)\text{mod}6$
Is this correct?

A: An easy approach:
$$n^3-n=(n-1)n(n+1)$$
As in any two consecutive integers, one is even, and in any three consecutive, one is multiple of three. So the product of three consecutive numbers is a multiple of $6$. $$\begin{split}n^3-n&\equiv0\pmod6\\n^3&\equiv n\pmod 6\end{split}$$ Done!

A: Why are you inducting in this case? I mean if we are working in $\mathbb Z/6\mathbb Z$, then there is no need to check it for all integers $n$. Anyways, this is just a special case of Euler's Theorem.


text:
Q: Runnig Ex-crawler Hi i am runnig  the jar of this open source Ex-Crawler
But i always receive this error :
og4j:WARN No appenders could be found for logger (eu.medsea.mimeutil.TextMimeDetector).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info

A: The application you're running uses log4j to produce log files. And log4j needs a configuration file, usually named log4j.properties, to be available in the application's class path, in order to start properly.
This is sample of default configuration you might start with:
log4j.rootLogger=WARN, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%5p [%t] (%F:%L) - %m%n


text:
Q: JavaScript appendChild() not working? (first time with appendChild()) I am trying to build a little resume builder. I want the user to be able to enter any number of phone numbers. However, the appendChild() is not working as expected. Actually, it's not working at all. It does nothing. Any ideas?
HTML:

    <?php
    if(isset($_SESSION['phoneNumber'])){
        for($i = 0; $i<sizeof($_SESSION['phoneNumber']); $i++){
            echo "<input type=\"text\" size=\"20\" name = \"phoneNumber[".$i."]\"
                    value=\"".$_SESSION['phoneNumber'][$i]."\" />

";
        }

    }
    else{
    ?>

    <input type="text" size="20" name = "phoneNumber[0]"
        value="" />

    <?php
    }
    ?>

<input type="button" value="Add another phone number" onclick="addPhoneNumber()">

Javascript:
var numberOfPhoneInputs = 1;

function addPhoneNumber()
{

// Found out the following doesn't work as expected...
//  var newPhoneNumberInput =  "<input type=\"text\" size=\"20\" name = \"phoneNumber[" +
//      numberOfPhoneInputs +"]\" value=\"\" />" +
//    "
"
//  document.getElementById("phoneNumbers").innerHTML += newPhoneNumberInput;

    var div = document.getElementByID("phoneNumbers");

    var newPhoneNumberInput = document.createElement('input');
    newPhoneNumberInput.setAttribute('type', 'text');
    newPhoneNumberInput.setAttribute('name', 'phoneNumber['+numberOfPhoneInputs+']');
    newPhoneNumberInput.setAttribute('size', '20');
    newPhoneNumberInput.setAttribute('value', '');
    div.appendChild(newPhoneNumberInput);

    numberOfPhoneInputs ++;
}

A: You need to return false; from the click handler to prevent the button's default action of submitting the page.

A: document.getElementByID needs to be  document.getElementById
This error should show in your console.

A: you need to make these changes ...

*

*change document.getElementByID("phoneNumbers"); to document.getElementById("phoneNumbers");

*(optional) It will be good if you change var div to var phoneNumbersDiv or something
fiddle example : http://jsfiddle.net/v8rF3/
Updated code:
var numberOfPhoneInputs = 1;

function addPhoneNumber(){
    var div1 = document.getElementById("phoneNumbers");
    var newPhoneNumberInput = document.createElement('input');
    newPhoneNumberInput.setAttribute('type', 'text');           newPhoneNumberInput.setAttribute('name', 'phoneNumber['+numberOfPhoneInputs+']');
    newPhoneNumberInput.setAttribute('size', '20');
    newPhoneNumberInput.setAttribute('value', '');
    div1.appendChild(newPhoneNumberInput);

    numberOfPhoneInputs ++;
}


text:
Q: Fast search in a large text file I'm trying to write a search program in C# which will search for a string in a large text file(5GB). I've done a simple code shown below but the search results are time consuming and can take about 30 mins to complete. This is how my code looks like-
public List<string> Search(string searchKey)
{
    List<string> results = new List<string>();
    StreamReader fileReader = new StreamReader("D:\Logs.txt");
    while ((line = fileReader.ReadLine()) != null)
    {
        if (line.Contains(searchKey)
        {
            results.Add(line);
        }
    }
}

Although the code works, it runs very slowly and takes about 30 mins to complete. Can we do something to bring the search time under a minute?

A: For string search in a really large file, you can use the Boyer Moore Search Algorithm, which is the standard benchmark for practical string-search literature.  For its implementation, links are given below:

*

*Boyer-Moore Practical in C#?

*Boyer Moore Algorithm for Pattern
Searching

A: File indexing is implemented in the library Bsa.Search.Core
You can implement your own version of reading from a file.
FileByLinesRowReader - read file by line and add documents with externalId equal line number.
FileDocumentIndex has been tested on wiki data json dictionary

*

*.Net Core

*.Net 472
     var selector = new IndexWordSelector();
     var morphology = new DefaultMorphology(new WordDictionary(), selector);
     var fileName = "D:\Logs.txt";

     // you can implement your own file reader, csv, json, or other
     var index = new FileDocumentIndex(fileName, new FileByLinesRowReader(null), morphology);

     // if index is already exist we skip file indexing
         if (!index.IsIndexed)
     index.Start();
     while (!index.IsReady)
     {
         Thread.Sleep(300);
     }

     var query = "("one" | two) ~50 ("error*")".Parse("*");
     var found = index.Search(new SearchQueryRequest()
     {
         Field = "*",
         Query = query,
         ShowHighlight = true,
     });
     // where ExternalId is line number from file
     //found.ShardResult.First().FoundDocs.FirstOrDefault().Value.ExternalId


text:
Q: swipe animation in layouts: android I know the animation effects and how to apply them to views(layouts) for onclicklistener, ontouchlistener etc. but which event occurs when i slide the layout to left or right.
previousButton.setOnClickListener(new OnClickListener()  {
      @Override
        publicvoid onClick(View v) {
              viewFlipper.setInAnimation(MainActivity.this,R.anim.view_transition_in_right);
               viewFlipper.setOutAnimation(MainActivity.this,R.anim.view_transition_out_right);
               viewFlipper.showPrevious();
      }
    });
}

i dont want onclicklistener. ie)if i touch and slide the current layout to left, it should go out and next layout should be in current view.how to do this?

A: Make your activity implement the onGestureListener.
then in you activity add
private GestureDetector gestureScanner;
gestureScanner = new GestureDetector(this);
private static final int SWIPE_MIN_DISTANCE = 100;
    private static final int SWIPE_THRESHOLD_VELOCITY = 100;

Then overrid the onTouchEvent(MotionEvent event) like below:
@Override
    public boolean onTouchEvent(MotionEvent event) {
        return gestureScanner.onTouchEvent(event);
    }

Also Finally you need to overide onFling method something like:
@Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY) {
        /* on scroll to the next page */
        if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY
                ) {
            //Ur code goes here
        }
        /* on scroll to the previous page  */
        else if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY
                ) {
            //ur code goes here.
        }
        return false;
    }

Hope this helps.

A: You should use Fragments for sliding between views. Use FragmentActivity and Fragment(for each view).android developers example
Or you can just use this opensource library

A: You need the View pager -
ViewPager
Very easy to implement too, you just provide an adapter in a similar way that you would with a ListView.


text:
Q: Run Java Threads On One CPU We Have a Multi-threaded Application in JAVA which has multiple threads running in parallel. Now  we want to run all these threads on a single core. Currently application is running on a system having more then one Cores.
We know there is a technique available ProcesAffinity in .Net Framework to set process affinity.
But we don't want to depend on .Net Framework, because our application is build in java.
Do we set Process affinity using Bat file and run our application executable jar file  through Bat file?
Currently our application is running on Window XP. So we need a solution that should be  working fine on XP platform.

A: EDIT:
It's possible: See Java thread affinity

Pure Java doesn't support running a thread on specific processor. Check the SO question linked above.

A: Personally, I don't think that the fact that this cannot be set in pure Java is a bad thing, as to me, how an app is run does very much depend on the OS, so therefore a OS-specific solution isn't a bad thing.
You can use the MS psexec utility to set the affinity:
psexec -a 1 java -jar myapplication.jar

Would instruct that all of the threads created by java would be run on the lowest CPU.
And this line would be your .BAT file...

A: You cannot do it in pure Java.  But on some versions of Windows, you can do it via operating system utilities; see https://superuser.com/questions/309617/how-to-limit-a-process-to-a-single-cpu-core ... and you might be able to do this by calling native libraries via JNI.


text:
Q: Bridge startup error connecting to Zookeeper Just getting the following error trying to setup the Bridge component using Zookeeper, according to the steps described in https://docs.corda.r3.com/website/releases/3.1/bridge-configuration-file.html?highlight=zookeeper.
> java -jar corda-bridgeserver-3.1.jar
BridgeSupervisorService: active = false
[ERROR] 20:59:31-0300 [main-EventThread] imps.EnsembleTracker.processConfigData - Invalid config event received: {server.1=10.102.32.104:2888:3888:participant, version=100000000, server.3=10.102.32.108:2888:3888:participant, server.2=10.102.32.107:2888:3888:participant}
[ERROR] 20:59:32-0300 [main-EventThread] imps.EnsembleTracker.processConfigData - Invalid config event received: {server.1=10.102.32.104:2888:3888:participant, version=100000000, server.3=10.102.32.108:2888:3888:participant, server.2=10.102.32.107:2888:3888:participant}

My bridge.conf:
bridgeMode = BridgeInner
outboundConfig {
    artemisBrokerAddress = "10.102.32.97:10010"
    alternateArtemisBrokerAddresses = [ "10.102.32.98:10010" ]
}
bridgeInnerConfig {
    floatAddresses = ["10.102.32.103:12005", "10.102.32.105:12005"]
    expectedCertificateSubject = "CN=Float Local,O=Local Only,L=London,C=GB"
    customSSLConfiguration {
           keyStorePassword = "bridgepass"
           trustStorePassword = "trustpass"
           sslKeystore = "./bridgecerts/bridge.jks"
           trustStoreFile = "./bridgecerts/trust.jks"
           crlCheckSoftFail = true
    }
}
haConfig {
    haConnectionString = "zk://10.102.32.104:2181,zk://10.102.32.107:2181,zk://10.102.32.108:2181"
}
networkParametersPath = ./network-parameters

Any thoughts?

A: This error is harmless. It indicates that the Dockerised Zookeeper has bad IP addresses, so when the Apache Curator is sent the dynamic topology, some checks fail. It does not invalidate the static configuration and everything should work fine.
Note that as of Corda Enterprise 3.2, you must use the Zookeeper version that is compatible with the Apache Curator library, which is 3.5.3-beta, and NOT the latest version.


text:
Q: Why does my unsigned byte need to be twice as big? I am in the process of disconnecting the rendering portion of my program from Qt and upgrading it to OpenGL 4.
I ran into an oddity concerning textures, I am getting a segfault for not supplying glTexImage with the right size data. Which is strange because I am pretty sure I am supplying it with the right size data.
int n = 1*g_windowHeight*g_windowHeight;
//int n = 2*g_windowHeight*g_windowHeight; Doesn't segfault but doesn't make sense to me
auto data = (GLbyte*) malloc(n*sizeof(GLbyte));
glBindTexture(GL_TEXTURE_2D,textures[i]);
glTexImage2D(GL_TEXTURE_2D,0,GL_R8,g_windowWidth,g_windowHeight,0,GL_RED,GL_UNSIGNED_BYTE,data); //

Unhandled exception at 0x0000000180012212 (ig4icd64.dll) in
  renderMan.exe: 0xC0000005: Access violation reading location
  0x0000007035F7C000.

Why does GL_R8 want a 2 bytes per pixel if I am using GL_R8?

A: It's a typo:
int n = 1*g_windowHeight*g_windowHeight;

Should be:
int n = 1*g_windowWidth*g_windowHeight;
//                ^^^^^


text:
Q: Entity Framework query loading a lot of related data in Web API throws timeout EntityCommandExecutionException I have a Web API that uses Entity Framework to load data from SQL Server 2012.
I have created a repository and using Ninject and an interface I use the concrete class in the Web API.
In some Get requests I will need to provide JSON data which is not so big as a graph but the relationships are pretty normalized.
I have mapped the entities to models that returned to the client in JSON format.
So, in the following query I need all this data.
var result = _dbContext.Quotes.Where(
                    quote => quote.UserId == user.MemberId)
                    .Include(quote => quote.AdditionalRequirements)
                    .Include(quote => quote.QuoteSpecialRequirements.Select(qsr => qsr.RequirementType))
                    .Include(quote => quote.City)
                    .Include(quote => quote.Country)
                    .Include(quote => quote.Area)
                    .Include(quote => quote.Rooms.Select(room => room.RoomType)).ToList();

If I call the service this will result to an EntityCommandExecutionException with InnerException a System.Data.SqlClient.SqlException and message "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.", which in turn have an InnerException System.ComponentModel.Win32Exception with message "The wait operation timed out".
Now I'm thinking what will happen when my data grows and how to consider handling this and make it efficient for the future.
Alternatives? Is the query needs restructuring?
I'm thinking, should I extend the timeout expiration value in the web api?
The operations is not yet awaitable, thinking if wrapping them in a Task.Run will improve the performance in a Web API call.
Another solution would be to go to SQL Server procedures.
[EDIT]
A diagram screenshot with the related tables in the database.
Diagram Screenshot
Here is the query that is created from Entity Framework, used a profiler and got it.
SQL Query
Thank you.


text:
Q: Star Trek: TNG novels that continue episodes? In the original series episode, "All Our Yesterdays", Spock goes back in time 4000 years into a particular planet's history.
Two sequels to this episode were written as novels. "Yesterday's Son" and "Time for Yesterday"  in which it is revealed, among other things, that:

 Spock had a son with that nice cave lady.

I am wondering which episodes of The Next Generation have similar sequels or prequels, and is there a comprehensive list of such things, perhaps including all the series?

A: There are quite a few TNG novels which reuse guest characters but I'm not going to list those since I don't really see those as sequels.
These are the novels that I feel are very strongly sequels to TNG episodes:

*

*Dyson Sphere: this novels revisits the Dyson Sphere seen in the episode Relics.

*Imzadi: this novel tells the story of Troi and Riker's relationship before TNG. The novel takes place before TNG as well as the episode All Good Things and the "future" seen in that episode.

These novels aren't really sequels but are fairly tightly woven into the TNG fabric:

*

*The Double Helix series: these books depict a series of biological weapons developed over a huge amount of time. The novels themselves span from the time of Jean Luc Picard's command of the Stargazer to the New Frontier era.

A: The Star Trek TOS episode Mirror, Mirror has a sequel novel set in the TNG universe called Dark Mirror, which I read many years ago and enjoyed at the time.

A: I haven't seen such a list on the web, but if I remember correctly the "The Q Continuum" books are interlaced with the episodes featuring Q.


text:
Q: How does Flutter calculate pixels for different resolutions? Flutter apps can run on a variety of hardware, operating systems, and form factors. How are "pixels" calculated for different resolutions?

A: From https://api.flutter.dev/flutter/dart-ui/FlutterView/devicePixelRatio.html :

The number of device pixels for each logical pixel. This number might
not be a power of two. Indeed, it might not even be an integer. For
example, the Nexus 6 has a device pixel ratio of 3.5.
Device pixels are also referred to as physical pixels. Logical pixels
are also referred to as device-independent or resolution-independent
pixels.
By definition, there are roughly 38 logical pixels per centimeter, or
about 96 logical pixels per inch, of the physical display. The value
returned by devicePixelRatio is ultimately obtained either from the
hardware itself, the device drivers, or a hard-coded value stored in
the operating system or firmware, and may be inaccurate, sometimes by
a significant margin.
The Flutter framework operates in logical pixels, so it is rarely
necessary to directly deal with this property.


text:
Q: displaying google map within a UIView Correctly I am using google maps with iOS.
this is my code:
import UIKit
import GoogleMaps

ViewController: UIViewController {

@IBOutlet weak var myMapView: GMSMapView!

override func viewDidLoad() {
    super.viewDidLoad()
}

override func viewDidAppear(_ animated: Bool) {
    // Create a GMSCameraPosition that tells the map to display the
    // coordinate -33.86,151.20 at zoom level 6.
    let camera = GMSCameraPosition.camera(withLatitude: +31.75097946, longitude: +35.23694368, zoom: 17.0)
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    //mapView.isMyLocationEnabled = true
    mapView.mapType =  .terrain

    self.view = mapView
    //self.myMapView = mapView

    // Creates a marker in the center of the map.
    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2D(latitude: +31.75097946, longitude: +35.23694368)
    marker.title = "Eden VidanPeled"

    //marker.snippet = "Australia"
    marker.map = mapView
    marker.opacity = 1.0
   }

In the Interface Builder I have a UIView with the class GMSMapView. When I attach my map to the UIViewController, I get my lat-long coords. When I try to attact the map to the UIView, I get a different map, zoom level etc,
as you can see in the photo below.

How do I get the UIView map to portray correctly?
p.s. I tried both viewDidLoad and viewDidAppear with same results.
Thanks

A: You are already creating an IBOutlet for GMSMapView
It will create a map instance for you. So no need to create one more instance of GMSMapView and assign it to the class variable.
override func viewDidAppear(_ animated: Bool) {
     // Create a GMSCameraPosition that tells the map to display the
     // coordinate -33.86,151.20 at zoom level 6.

     let camera = GMSCameraPosition.camera(withLatitude: +31.75097946, longitude: +35.23694368, zoom: 17.0)

     self.myMapView.mapType =  .terrain

     self.myMapView.camera = camera

    // Creates a marker in the center of the map.
    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2D(latitude: +31.75097946, longitude: +35.23694368)
    marker.title = "Eden VidanPeled"

    //marker.snippet = "Australia"
    marker.map = self.myMapView
    marker.opacity = 1.0
}


text:
Q: Rank of a matrix in Ellenberg/Gijswijt proof In a paper by Ellenberg and Gijswijt on the cap set problem, the proof of proposition 2 relies on the claim that certain matrices have rank 1. This is not obvious to me. Why?
https://arxiv.org/pdf/1605.09223v1.pdf
The matrices in question are indexed by a subset $A\subset \mathbb{F}_q^n$, with $a,b$ entry
$$m(a)F(b)$$
where $m$ is a monomial of degree at most $d\leq 2n$, and $F$ a polynomial of degree at most $2n-d$. Furthermore, each variable appears with degree at most $q-1$ in any term of $m(x)F(x)$


text:
Q: What is inverse Fourier transform of $\sin(3w)/w$? What is inverse fourier transform of $\displaystyle\,\,{\sin\left(3\omega\right) \over \omega}$ ?.
It says it's
$\displaystyle{1 \over 2}\left[\mathrm{u}\left(t + 3\right) - \mathrm{u}\left(t - 3\right)\right] = {1 \over 2}\quad\mbox{for}\quad\left\vert t\right\vert < 3\ \mbox{and}\ 0\ \mbox{for}\ \left\vert t\right\vert > 3$
I understand that applying the inverse fransform yields the periodic square wave but I'm not sure where $\displaystyle 1/2$ in the equation came from and why the answer is equal to $\displaystyle 1/2$ instead of $\displaystyle 1$.

A: Here I'm using the Fourier transform
$$
\mathcal{F}\{f(t)\} = \int_{-\infty}^{\infty} f(t) \, e^{-i\omega t} dt
.
$$
You should easily be able to confirm that
$$
\mathcal{F}\{\chi_{[-T,T]}(t)\} = 2\frac{\sin\omega T}{\omega}
$$
so the inverse transform you want to find is
$$
\mathcal{F}^{-1}\{\frac{\sin 3\omega}{\omega}\}
= \frac12 \mathcal{F}^{-1}\{2\frac{\sin 3\omega}{\omega}\}
= \frac12 \chi_{[-3,3]}(x)
.
$$


text:
Q: Scala play framework - completely offline environment Any idea if it's possible to use the Play framework, or akka, within a completely offline, non-internet connected environment?  I tried running, and it's connecting to maven central, etc...
Thoughts?

A: As long as you have all the dependencies you need for a successful build then you can do the following to stop the update check etc:
In plugins.sbt :
offline := true

A: You need to have Internet connection whenever you update your Play project such that the built tool (sbt/play/activator) can download all dependencies for the first time.
Since Play 2.3, dependencies/libraries locally go to ~/.ivy2/local and the cache of downloaded dependencies/libraries is under ~/.ivy2/cache.
Play 2.3 (and above) uses the default ivy cache and repository, in the .ivy2 folder in the users home directory. When you update (and hence compile or run) a Play 2.3.x project, the dependencies go to ~/.ivy2/cache.


text:
Q: HashMap and case construct For readability reasons I'm trying to avoid using Char based case constructs, using Java 6. I cannot switch to 7 jet...
Map<String, String> map = new HashMap<String, String>() {
    {
        put("foo", "--foo");
                put("bar), "--bar");
        ...
    }
    private static final long serialVersionUID = 1L; // java problem
};

The serialVersionUID - as far as I know, maybe part of the problem. Currently I'm working with if constructs:
if (!map.containsValue(args[0])) {
    logger.error("Unknown parameter:  " + args[0]);
        ...

I handle ~ 30 parameters. In any case a growing number.
Is it even possible to define switch constructs with enums or HashMaps In Java 6?

A: If you're handling over 30 parameters in the same way, then you need some kind of loop. For example:
for (int i=0; i<args.length; i++)
{
   String param = args[i];
   if (!map.containsValue(param))
      logger.error("Unknown parameter:  " + param);
   .. handle argument
}

It looks like you are parsing command line arguments. There are some good libraries available that offer flexible command line parsing, for example args4j. With args4j, you create your data model, and let it map fields in the data to command line arguments.

A: Using Strings in a switch statement will be available in Java 7.
For moderate or complex parsing of command line arguments I strongly recommend using Commons-CLI, it provides a great API to make this much easier for you to handle. An example of it's usage:
// create Options object
Options options = new Options();

// add t option
options.addOption("t", false, "display current time");
...

CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse( options, args);

if(cmd.hasOption("t")) {
    // print the date and time
}
else {
    // print the date
}


text:
Q: Bootstrap 4 Carousel how to get controls in slide and responsive I'm trying to figure out how to get the controls inside the slide and at the same time make it responsive. I have set that margin left and right to the appropriate pixels to have it at the perfect spot but when I check to see if it is responsive it ends up in different places depending on the resolution.
Here is my code
https://codepen.io/andysaurusrex/pen/roPmOq
HTML

            Previous

            Next

CSS
.carousel-inner img {
    margin: auto;
}
/* .carousel-control-prev {
    margin-left: 425px;
}

.carousel-control-next {
    margin-right: 425px;
} */

Is there anyway to work with this?
Thanks in advance

A:

.carousel-inner img {
  max-width: 100%;
}
.carousel {
  max-width: 800px;
  margin: 0 auto;
}

... will do it. Pen: https://codepen.io/andrei-gheorghiu/pen/JwxJKb


text:
Q: React-Native 0.60+ with linked libs not running despite "Dependency Graph" loading I have an ejected react-native app with multiple linked libraries which fails to run in Android (works in iOS).  The Dependency Graph loads to 100% and it shows the the splash screen on the emulator sometimes, but it immediately crashes when the emulator tries to load the js bundle.
Relevant packages in package.json
    "react": "16.8.6",
    "react-native": "0.60.5",
    "react-native-code-push": "^5.6.1",
    "rn-fetch-blob": "0.10.16",
    "react-native-firebase": "^5.5.5",
    "react-native-image-crop-picker": "^0.25.0",
    "react-native-linear-gradient": "^2.5.6",
    "react-native-splash-screen": "^3.2.0",
    "react-native-vector-icons": "^6.6.0",

android/build.gradle
buildscript {
  ext {
    buildToolsVersion = "27.0.0"
    minSdkVersion = 16
    compileSdkVersion = 28
    targetSdkVersion = 26
    supportLibVersion = "28.0.0"
    googlePlayServicesVersion = "16.1.0"
    firebaseVersion = "17.3.4"
  }
  repositories {
    google()
    jcenter()
    maven {
      url 'https://maven.fabric.io/public'
    }
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:3.5.0'
    classpath 'com.google.gms:google-services:4.2.0'
    classpath 'com.google.firebase:firebase-plugins:1.2.0'
    classpath 'io.fabric.tools:gradle:1.26.1'
  }
}

allprojects {
  repositories {
    mavenLocal()
    google()
    jcenter()
    maven {
      // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
      url "$rootDir/../node_modules/react-native/android"
    }
    maven { url "https://jitpack.io" } // required by react-native-image-crop-picker
  }
}

android/app/build.gradle
apply plugin: "com.android.application"
apply plugin: "com.google.firebase.firebase-perf"
apply plugin: 'io.fabric'

import com.android.build.OutputFile

project.ext.react = [
  entryFile: "index.js",
  enableHermes: false,
]

apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = false

android {
  lintOptions {
    disable 'GradleCompatible'
    disable 'InvalidPackage'
  }

  // because of firestore:
  dexOptions {
    javaMaxHeapSize "4g"
  }
  compileSdkVersion rootProject.ext.compileSdkVersion
  buildToolsVersion rootProject.ext.buildToolsVersion

  defaultConfig {
    applicationId "com.HIDDEN"
    minSdkVersion rootProject.ext.minSdkVersion
    targetSdkVersion rootProject.ext.targetSdkVersion
    versionCode 1
    versionName "1.0"
    ndk {
      abiFilters "armeabi-v7a", "x86"
    }
    // because of firestore:
    multiDexEnabled true
    vectorDrawables.useSupportLibrary = true
  }
  splits {
    abi {
      reset()
      enable enableSeparateBuildPerCPUArchitecture
      universalApk false  // If true, also generate a universal APK
      include "armeabi-v7a", "x86"
    }
  }
  buildTypes {
    release {
      minifyEnabled enableProguardInReleaseBuilds
      proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
    }
    debug {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }
  applicationVariants.all { variant ->
    variant.outputs.each { output ->
      // For each separate APK per architecture, set a unique version code as described here:
      // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
      def versionCodes = ["armeabi-v7a": 1, "x86": 2]
      def abi = output.getFilter(OutputFile.ABI)
      if (abi != null) {  // null for the universal-debug, universal-release variants
        output.versionCodeOverride =
          versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
      }
    }
  }
}

dependencies {
    implementation project(':rn-fetch-blob')
    implementation project(':react-native-image-crop-picker')
    implementation project(':@react-native-community_geolocation')
    implementation project(':react-native-vector-icons')
    implementation project(':react-native-splash-screen')
    implementation project(':react-native-linear-gradient')
    implementation project(':react-native-code-push')
    implementation project(':react-native-firebase')

  // RNFirebase required dependencies
  implementation "com.google.android.gms:play-services-base:16.0.1"
  implementation "com.google.firebase:firebase-core:16.0.9"
  // RNFirebase modules
  implementation "com.google.firebase:firebase-auth:17.0.0"
  implementation "com.google.firebase:firebase-analytics:16.5.0"
  implementation "com.google.firebase:firebase-perf:16.2.4"
  implementation "com.google.firebase:firebase-storage:17.0.0"
  implementation "com.google.firebase:firebase-dynamic-links:17.0.0"
  implementation "com.google.firebase:firebase-database:17.0.0"
  implementation "com.google.firebase:firebase-functions:17.0.0"
  implementation "com.google.firebase:firebase-firestore:19.0.0"
  implementation "com.google.firebase:firebase-messaging:18.0.0"
  implementation 'me.leolin:ShortcutBadger:1.1.21@aar'

  implementation "com.facebook.react:react-native:+"
  implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
  implementation "com.android.support:support-annotations:${rootProject.ext.supportLibVersion}"
  implementation fileTree(dir: "libs", include: ["*.jar"])
}

task copyDownloadableDepsToLibs(type: Copy) {
  from configurations.compile
  into 'libs'
}

apply plugin: 'com.google.gms.google-services'
com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true

MainApplication.java
package com.HIDDEN;

import android.annotation.SuppressLint;
import android.app.Application;

import com.facebook.react.ReactApplication;
import com.RNFetchBlob.RNFetchBlobPackage;
import com.reactnativecommunity.geolocation.GeolocationPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import org.devio.rn.splashscreen.SplashScreenReactPackage;
import org.devio.rn.splashscreen.SplashScreen;
import com.BV.LinearGradient.LinearGradientPackage;
import com.reactnative.ivpusic.imagepicker.PickerPackage;
import com.microsoft.codepush.react.CodePush;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

import io.invertase.firebase.RNFirebasePackage;
// optional packages - add/remove as appropriate
import io.invertase.firebase.analytics.RNFirebaseAnalyticsPackage;
import io.invertase.firebase.auth.RNFirebaseAuthPackage;
import io.invertase.firebase.database.RNFirebaseDatabasePackage;
import io.invertase.firebase.firestore.RNFirebaseFirestorePackage;
import io.invertase.firebase.functions.RNFirebaseFunctionsPackage;
import io.invertase.firebase.instanceid.RNFirebaseInstanceIdPackage;
import io.invertase.firebase.links.RNFirebaseLinksPackage;
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage;
import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage;
import io.invertase.firebase.perf.RNFirebasePerformancePackage;
import io.invertase.firebase.storage.RNFirebaseStoragePackage;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {

    @Override
    protected String getJSBundleFile() {
      return CodePush.getJSBundleFile();
    }

    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @SuppressLint("MissingPermission")
    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.asList(
        new MainReactPackage(),
        new RNFetchBlobPackage(),
        new GeolocationPackage(),
        new VectorIconsPackage(),
        new SplashScreenReactPackage(),
        new LinearGradientPackage(),
        new PickerPackage(),
        new CodePush("HIDDEN", getApplicationContext(), BuildConfig.DEBUG),
        new RNFirebasePackage(),
        // add/remove these packages as appropriate
        new RNFirebaseAnalyticsPackage(),
        new RNFirebaseAuthPackage(),
        new RNFirebaseDatabasePackage(),
        new RNFirebaseFirestorePackage(),
        new RNFirebaseFunctionsPackage(),
        new RNFirebaseInstanceIdPackage(),
        new RNFirebaseLinksPackage(),
        new RNFirebaseMessagingPackage(),
        new RNFirebaseNotificationsPackage(),
        new RNFirebasePerformancePackage(),
        new RNFirebaseStoragePackage()
      );
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, false);
  }
}

MainActivity.java
package com.HIDDEN;

import android.os.Bundle;
import com.facebook.react.ReactActivity;
import org.devio.rn.splashscreen.SplashScreen;

public class MainActivity extends ReactActivity {
    @Override
    protected String getMainComponentName() {
        return "CashoutSports";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        SplashScreen.show(this);  // here
        super.onCreate(savedInstanceState);
    }
}

A: I have never worked on React-native project. But I think there's something wrong in MainActivity.java.
In Android, normally we start initial UI code after  super.onCreate().
Maybe you can call SplashScreen.show after call super.onCreate
super.onCreate(savedInstanceState);
SplashScreen.show(this);  // here


text:
Q: Setting pointer to null creates runtime error I've been looking around and haven't seen a question with a problem as specific as this one.
I'm trying to create a linked list in this program, but I get a runtime error and no build errors when I run it.
Main:
#include <iostream>
#include "LinkedListInterface.h"
#include "LinkedList.h"
#include <fstream>

int main(int argc, char * argv[])
{
    ifstream in(argv[1]);

    LinkedList<int> myIntList;
}

LinkedList class:
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
#include <string>
#include <sstream>

using namespace std;

template<typename T>
class LinkedList : public LinkedListInterface<T>
{
public:
    LinkedList()
    {
        head->next = NULL;
    }
private:
    struct Node
    {
        T data;
        struct Node *next;
    };
    Node *head;
};

I have assured that the problem is not with an out-of-bounds error on argv[1], and removing any of the statements in LinkedList() or main() makes the program run smoothly.

A: You have to construct head before invoking head->next = NULL. But this would mean that there is an empty node in the list when you create it.
template<typename T>
class LinkedList : public LinkedListInterface<T>
{
public:
    LinkedList()
    {
        // At least do this
        head = new Node();
        head->next = NULL;

        // The best idea is to do below:
        // head = null;
    }
private:
    struct Node
    {
        T data;
        struct Node *next;
    };
    Node *head;
};


text:
Q: Operation timed out when connecting to Mailhog in Docker container I started mailhog in container: docker run --rm -ti -p 8025:8025 -p 1025:1025 mailhog/mailhog. Web UI works, but connection fails:
curl smtp://172.17.0.2:1025 --mail-from a@b.com --mail-rcpt c@d.com
curl: (28) Failed to connect to 172.17.0.2 port 1025 after 31641 ms: Operation timed out
172.17.0.2 is container IP address, i'm using Docker Desktop for Mac. Why connection is not established?

A: I solved this problem by connecting mailhog container to a network defined in docker-compose.yml.


text:
Q: how can i concatenate fields inside of my dataset? i have a dataset, dataset1:
i am trying to do:
select col1+col2, col3 from mytable

this does not work; however this is no problem:
select col1, col2, col3 from mytable

how can i concatenate fields inside of my dataset?
please note that col1, col2, col3 are all VARCHARS. i've tried the & operator as well.
please see the image below. i get the DEFINE QUERY PARAMETERS dialogue when it doesnt like my query:

A: Double quotes are not appropriate string delimiters in MS SQL.  Try:
SELECT ppl.FirstName + ' ' + ppl.LastName AS ReferredBy

Putting your actual query in the question may help you get a faster response next time, since the concatenation is actually a red herring here.


text:
Q: VB Forms don't recognize each other in the same project Hi everyone I need some help,
I am having a weird situation every time I try to call a window form I get this error

BC30469 Reference to a non-shared member requires an object reference.

I was originally working on Visual Studio 2010 when the first time contouring this problem so I thought that I may accidentally deleted or edited some code in the declaration of the form witch caused the problem so I closed the solution and created a new one to make sure that the problem is limited the solution not to VS. then I add window form "Form2" then created/added a button1 on Form1 to call Form2.Show()
simple code that should work fine but when I tape Form2.Show() it give that ERROR and red mark Form2
so I uninstalled VS2010 then Reset Windows 10 with option to wipe out all data on windows partition (I now that was extreme but I suspected that maybe the system was infected with some virus "prior action") so after that I checked the system with HitmanPro and found nothing then I installed VS2019 Community and get The some problem I searched on the web but did not found any similar case so here I am hoping that someone will resolve the mystery.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Form2.Show()
End Sub
End Class

Form2 is empty form I didn't make any change on it
Before this problem showing up everything work fine now even old project have the same issue
Thanks
Edit: Add project as simple
https://mega.nz/file/FgoXkCwA#ootxYrXGnR6sQR_Pifjvz617-r_Az1ozXWB49oGxqKU
the project dose not contain any executable file

A: I usually do something like this when calling a subform:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

' using a Using block:
    Using form2 as New Form2
        form2.ShowDialog(Me)
        form2.Close()
    End Using

' using a With block
    With New Form2
        .ShowDialog(Me)
        .Close()
    End With

End Sub

ShowDialog(Me) keeps the subform open until a DialogResult is provided by the user (OK or Cancel usually).


text:
Q: Can't get Ubuntu, but customised with LiveCDCustomisation, to boot from USB without Universal USB Installer on Windows I'm following the steps on Ubuntu's LiveCDCustomisation Wiki to make feren OS, but, when I get to booting it, it doesn't boot according to testers, except if using Universal USB Installer on Windows, and it's not just me, but also my buddies making Trenta OS are also getting the same problem when using this wiki, don't get me wrong, everything else works just fine, but that issue...
...it drives me so crazy and I just cannot find a way to fix it, it's a real pain in the bum though.

A: In the end, this is what I did to make the ISO work these days, plus it gives the ISO UEFI Support too:
cd "$LIVECDTMP"
cd ./extract-cd
sudo dd if=$UBUNTUBASEISOLOCATION bs=512 count=1 of=./isolinux/isohdpfx.bin
sudo xorriso -as mkisofs -isohybrid-mbr isolinux/isohdpfx.bin \
-V "$CDLABEL" -c isolinux/boot.cat -b isolinux/isolinux.bin -no-emul-boot -boot-load-size 4 \
-boot-info-table -eltorito-alt-boot -e boot/grub/efi.img -no-emul-boot \
-isohybrid-gpt-basdat -o "$PRODUCTISOTARGETLOCATION" .

DD is there to get a working isohdpfx.bin from the Original Ubuntu ISO File used for the base, so that it can be used for the MBR image part of the ISO, and then Xorriso is used instead of mkisofs because of it has the ability to also add EFI Booting Support to the ISO.
This is personally what works now for me, and so to aid others, I might as well put the answer I found in the end for this, and to also make it so the question is then 'answered' and is no longer pending an answer...
By the way, assign UBUNTUBASEISOLOCATION to be the full path of the Ubuntu ISO file, CDLABEL to be the string name of what the ISO should be labeled when flashed or burned onto a drive, and PRODUCTISOTARGETLOCATION as the full path location of where the Created ISO should be at, for this to work properly. Also, make sure your base Ubuntu ISO has all of these files before attempting this. As far as I know, the x32 Ubuntu ISO might lack some of these files, so be sure to make sure they all exist in the base ISO first...


text:
Q: NHibernate LINQ Where and Any throwing exception I have the following code that is throwing a "Specified method is not supported" error:
var list = securityRepository.Query<IsAuthorized>().Where(
    ia => ia.SecurableObjectName == objectName
    && ia.PermittedActionName == permittedActionName
    && ia.ScopeName == scopeName).ToList();

var prins = repository.Query<Principal>().Where(
    p => list.Any(l => l.PrincipalId == p.Id)).ToList();

The second query with the Any is what is throwing.
I need to select a list of Principal whose id's are in the list<IsAuthorized>.

A: I would say, that the best what we can do with that type of query, is to move it to DB Server. Of course, only in case, that this is possible, that the first query is not returning results from external source. Then we have to use a bit different technique.. but let's assume, that both tables are inside the DB.
The second query, would be the OUTER Select, the first will be the INNER Select. To combine them, we will use the IN statement.
What we have to do is:
Firstly, let's adjust the first query, to return the One property/column, to be used later:
var list = securityRepository
    .Query<IsAuthorized>()
    .Where(
      ia => ia.SecurableObjectName == objectName
      && ia.PermittedActionName == permittedActionName
      && ia.ScopeName == scopeName)
    // .ToList();
    .Select(ia => ia.PrincipalId);

So, what we've done, is deferring the query execution (no ToList() call). Instead, we created a SELECT clause with projection containing only one property/column.
Let's adjust what we have and need for the second query:
var prins = repository
    .Query<Principal>()
    //.Where(p => list.Any(l => l.PrincipalId == p.Id))
    .Where(p => list.Contains(p.Id)) // our subQuery
    .ToList();

And this, will produce something like this:
SELECT ...
 FROM Pincipal p
 WHERE p.Id IN (SELECT ia.PrincipalId FROM IsAuthorized ia......


text:
Q: Can't call setState in componentWillMount() multiple times, what is workaround React Native So I have fetch() which gets me an array. So I store that array in state, and after that I do some function and when it's done I want to set state again so I stop loading. Here is code that will explain it better(all this code is in componentWillMount() btw):

// before this is just simple unimportant get request
.then(responseJson => {
            // loading here is 1
            this.setState(function (prevState, props) {
                return {questions: responseJson}
            })

            this.makeAnswers(responseJson)

            // loading needs to be 0 here

        })

If you need more info please comment.
Thanks!

A: Why don't you put the this.setState({loading: 0}) inside your makeAnswers() function?
Just check if you need to do that:
makeAnswers = (response) => {
  ...
  if (this.state.loading !== 0) this.setState({loading: 0})
}

A: You probably just need to await the promise of the first setState before calling your makeAnswers function.
.then(async response => {
        // This will ensure questions is set in the state before calling makeAnswers
        await this.setState({questions: response.questions})

        this.makeAnswers(response.questions)

        this.setState({ loading: false })

    })

If you set the state inside makeAnswers also, you can just set the loading state there. Like
    componentDidMount = () => {
        fetch()
        .then(async response => {
            // This will ensure questions is set in the state before calling makeAnswers
            await this.setState({questions: response.questions})
            this.makeAnswers(response.questions)

        })
    }

    makeAnswers = questions => {
        //...do something
        this.setState({ answers: something, loading: false })
    }


text:
Q: ReSharper overwrites VS shortcut no matter what I'm experimenting with ReSharper and really want to love it but ran into a major issue.
I like to use " CTRL + ," to open files without mousing to the solution explorer. ReSharper has an alternative use for this button combo. It politely asks my preference and I select the visual studio option.

It works once, then switches to the ReSharper option for all subsequent uses.
I can go into ReSharper settings to reverse this but then it asks the polite question again, accepts my answer and ignores my preference again!
This is bad on its own but I'm guessing I'll run into other similar issues as I experiment further. How can I convince ReSharper that I really do like the "Navigate To" better than the "GoToRecentFiles"?

A: You can try this :
In VS Tools - > Options -> Environment -> Keyboard


text:
Q: Can JMS resources be targeted to multiple managed servers in weblogic? I have following kind of a scenario:
I have two managed servers -> Managed_BridgeServer & Managed_ApplicationServer ,
3 JMS resources -> Requestqueue , Responsequeue , ConnFac
1 Subdeployment -> JMSSubDep
1 JMS Server -> JMSServer1

Targeting is as follows:
JMS resources -> JMSSubDep -> JMSServer1 -> Managed_BridgeServer

There's a Bridge that's hosted on this server for which Destination is my Requestqueue and Source is an another queue hosted on different application.
On my Managed_ApplicationServer, there's an MDB that listens to the Requestqueue ( mentioned above )
However , the MDB is not able to pick up the message from the queue as it's not able to recognise the queue since its JNDI is not registered with this Managed_ApplicationServer. ( Note: requestqueue is targeted to Managed_BridgeServer )
My requirement is, that I should be able to target my JMS resources to both these managed servers so that my bridge and application both can access them and function properly.
Is there a way I can implement this? I tried exploring uniform distributed queues as an option but I am not sure if that's the perfect choice here.

A: You should be able to do so. You can have 2 JMS servers, each having their own persistence store and 1 JMS module which is targeted to the Managed servers. Of course this can only be done if the managed servers are clustered so if you set up a cluster, the Uniform Queues and Topics can be shared across them.


text:
Q: R Shiny + Future + Plumber Preamble
Inspired by the presentation by Barret Schloerke at studio::global(2021) (I will add the link as soon as it becomes available), I tried to implement an app to see the differences between using {future}, {plumber}, both or none into a Shiny app running a sequence of fast-slow-slow-fast computations (both on distinct output and in a sequence within the same one).
Gist
You can find here my attempt, including the app.R Shiny app and the plumber.R APIs.
Results

execution selected (5 s for "slow")
result
expectation
comments

Standard run
~20 seconds before anything appear, next everything appears in the same moment
~20 seconds, appearing sequentially somehow
Why did not appear sequentially?

{future} only
~5 seconds before anything appear, next everything appears in the same moment
~20 with "first fast" and "second fast" appearing almost immediatly and next (~5) "first slow" or "second slow," next (~10) the other, and finally (~20) "Sequential")
I would expect that something similar to what happened here for the combined type of run... how is possible that "sequential" completed in 5 seconds???

{plumber} only
same as the standard run (r should remain busy until each API call would be resolved, right?)
same time (~20) but appearing sequentially some how
why shiny rendered everything the same time?

{future} and {plumber}
same as the standard run
I do not expect this at all!, What I expected here is to have "_fast"s appearing immediately, "_slow"s quite the same time after ~5 seconds, and "sequential" after ~10 seconds from the start (i.e., ~10 seconds overall)
I am totally confused here :-(

Doubts
One of the main things I did not understand is why when activating {future} (both with or without {plumber}), "first fast" does not appear immediately. And in general, why the output does not appear in a single sequence when {future} is not involved. And how is it possible that with {future} alone, "sequential" stay ~5 seconds?
So, clearly, I made something the wrong way, and I do not understand something correctly.
Questions
Can someone help me understand where/what (and maybe try to infer "why") I made the app wrong, and/or the API wrong, or their interaction wrong?
Thank you,
Corrado.


text:
Q: How to generate Code_products in Codeigniter? How to create invoice number as below required?
Invoice format DP1411-0001 it contain three piece.

*

*DP = type of invoice

*14 = year of create invoice

*11 = month of creating invoice

*0001 = number of invoice that generate by invoice amount

Example

*

*DP1411-0001

*DP1411-0002

*DP1411-0003

*...........

*DP1411-000n

But I have not any idea or logic to create.

A: Concat everything,
When generating Invoice get the information about whether it is DP or something store it into some variable.
Get the year and month and store it some variable and finally concat everything...
if you want something else please be specific.


text:
Q: Looping through an Array of objects in Javascript sent by socket.emit So I am making a blockchain in Node.js and am trying to print generated blocks in html. I am using socket. io to emit data to html, but am having issues with sending an object array of blocks that are in the blockchain.
So far my code looks like this:
Client.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const myArgs = process.argv.slice(2);
const port = myArgs[0];
const SHA256 = require("crypto-js/sha256");

class Block {
    constructor(index, timestamp, data, previousHash) {
        this.index = index;
        this.timestamp = timestamp;
        this.data = data;
        this.previousHash = previousHash;
        this.hash = this.generateHash();
    }
    generateHash() {
        return SHA256(this.index + this.timestamp + this.previousHash + JSON.stringify(this.data)).toString();
    }
}

class Blockchain {
    constructor() {
        this.blockchain = [this.createGenesisBlock()];
    }

    createGenesisBlock() {
        return new Block(0, Date.now(), "prvi blok verige", "0");
    }

    getTheLatestBlock() {
        return this.blockchain[this.blockchain.length - 1];
    }

    addNewBlock(newBlock) {
        newBlock.previousHash = this.getTheLatestBlock().hash;
        newBlock.hash = newBlock.generateHash();
        this.blockchain.push(newBlock);
    }

    validateBlock(newBlock) {
        const latestBlock = this.getTheLatestBlock();
        if (newBlock.previousHash !== latestBlock.hash)
            return false;
        if (newBlock.index <= latestBlock.index)
            return false;
        if (newBlock.hash !== newBlock.generateHash())
            return false;
        return true;
    }

    validateChain() {
        for (let i = 1; i < this.blockchain.length; i++) {
            const currentBlock = this.blockchain[i];
            const previousBlock = this.blockchain[i - 1];
            if (currentBlock.hash !== currentBlock.generateHash()) {
                return false;
            }
            if (currentBlock.previousHash !== previousBlock.hash) {
                return false;
            }
            if (currentBlock.index <= previousBlock.index)
                return false;
            return true;

        }
    }
}
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
    console.log('GUI connected on port: ' + port);
    socket.emit('onConnection', port);

    let logCoin = new Blockchain();
    console.log("mining logcoin in progress...");
    logCoin.addNewBlock(
        new Block(1, Date.now(),"Block 1")
    );

    logCoin.addNewBlock(
        new Block(2, Date.now(), "Block 2")
    );

    logCoin.addNewBlock(
        new Block(3, Date.now(),"Block 3")
    );
    console.log(logCoin);
    socket.emit('blockLedger', JSON.stringify(logCoin,null));

    socket.on('disconnect', () => {
        console.log("Client has disconnected");
    });
});

server.listen(port, () => {
    console.log('listening on port ' + port + ':');
});

index.html

<!DOCTYPE html>

Blockchain

Status: Offline

            <form id="form" action="">
                <button id="mine">Mine</button>
            </form>

            <form id="form" action="">

                    <input id="portInput" autocomplete="off" /><button>Connect port</button>

            </form>

Blockchain ledger

Mining...

I am trying to add all block indexes to a list, but nothing is added to the list. I dont think the forEach loop even works.
The array looks like this
And like this when i send it to html stringified
What am I doing wrong?
Edit
I used the solution from @ZackNewsham and it works, thanks!


text:
Q: PHP error_log & includes not working So, my problem is as follows. This code works fine when I load the page via the web browser. But when I run the script from the command line like so: "php script.php" it bombs.
script.php is:
<?php
include_once('class.WebsiteScraper.php');
$ws = new WebsiteScraper();
$ws->test();
...
?>

class.WebsiteScraper.php is:
<?php
echo 'test';
class WebsiteScraper {
    public function test() {
        echo 'test2';
    }
}
?>

This returns the error:

PHP Fatal error:  Call to undefined
  method WebsiteScraper::test()
  in
  ...
  on line 4

Only when called via the command line does this happen.
Another thing to note, when I append an
error_log('hey there');

To script.php, it throws the error to the standard out, rather than in my error log. But when called from the web browser it puts it in the error log. Any ideas?

A: Use the command line option --ini to check if the command line is loading the same configuration file as apache:
php --ini

You could also call phpinfo().
It seems likely your file isn't being included - probably due to include paths.
Edit:
Try adding
error_reporting(E_ALL);


text:
Q: ValueError: setting an array element with a sequence when array is not a sequence Hello this code  is intended to store the coordinates of rectangles drawn with open cv and compile the results into a single image.
import numpy as np
import cv2

im = cv2.imread('1.jpg')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

squares = []

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)

        if  h>28 and h<34:
            rect = (cv2.rectangle(im,(x,y),(x+w,y+h),(255,255,255),3))
            squares.append(cv2.boundingRect(cnt))
            cv2.imwrite('norm1.jpg',im)

crop_img = [[255 for x in xrange(377)] for x in xrange(377) ]

for s in squares:
    s = squares[0]
    x = s[0]
    y = s[1]
    w = s[2]
    h = s[3]
    img = im[y:y+h,x:x+w]
    for col in range(y,y+h):
        for row in range(x,x+w):
            if img[col - y][row - x].tolist() == [0,0,0]:
                crop_img[col][row] = [0,0,0]

cv2.imwrite("cropped.jpg", np.array(crop_img))

However, it throws this error message
File "C:\Users\Program\Desktop\new  1.py", line 43, in <module>
    cv2.imwrite("cropped.jpg", np.array(crop_img))
ValueError: setting an array element with a sequence

I have read that this can be caused by an "uneven" matrix but after several rounds of testing I have confirmed that it is indeed a square 377 x 377 matrix
For reference: "1.jpg" is the image shown below

Any leads as to how to fix this error would be greatly appreciated!

A: Each "pixel" here have one value. crop_img = [[255 for x in xrange(377)] for x in xrange(377) ]
But later you're setting some of them to a list of 3 values. That's the problem.
This should fix it i think:
crop_img = [[[255, 255, 255] for x in xrange(377)] for x in xrange(377) ]
Although you might as well start off with a numpy array with shape 377,377, 3 instead of converting it afterwards.

A:                 crop_img[col][row] = [0,0,0]

Is this supposed to be an RGB value? crop_img starts as a list of 377 elements, each of which is a list of 377 elements, each element of which is the integer 255. This line replaces a 255 with a list. It's not clear whether you want 2-dimensional nesting, which is the way you're initializing crop_img, or 3-dimensional nesting, which is what this line would suggest. Pick the one that's correct for your application and stick with it.