text:
Q: Can you bind the default network interface of the host into the container to read network stats? I have a project where I read system information from the host inside a container. Right now I got CPU, RAM and Storage to work, but Network turns out to be a little harder. I am using the Node.js library https://systeminformation.io/network.html, which reads the network stats from /sys/class/net/.
The only solution that I found right now, is to use --network host, but that does not seem like the best way, because it breaks a lot of other networking related stuff and I cannot make the assumption that everybody who uses my project is fine with that.
I have tried --add-host=host.docker.internal:host-gateway as well, but while it does show up in /etc/hosts, it does not add a network interface to /sys/class/net/.
My knowledge on Docker and Linux is very limited, so does someone know if there is any other way?

My workaround for now is, to use readlink -f /sys/class/net/$(ip addr show | awk '/inet.*brd/{print $NF; exit}') to get the final path to the network statistics of the default interface and mount it to a imaginary path in the container. Therefore I don't use the mentioned systeminformation library for that right now. I would still like to have something that is a bit more reliable and in the best case officially supported by docker. I am fine with something that is not compatible with systeminformation, though.

A: There is a way to enter the host network namespace after starting the container. This can be used to run one process in the container in the container network namespace and another process in the host network namespace. Communication between the processes can be done using a unix domain socket.
Alternatively you can just mount a new instance of the sysfs which points to the host network namespace. If I understood correctly this is what you really need.
For this to work you need access to the host net namespace (I mount /proc/1/ns/net to the container for this purpose). Additionally the capabilities CAP_SYS_PTRACE and CAP_SYS_ADMIN are needed.
# /proc/1 is the 'init' process of the host which is always running in host network namespace
$ docker run -it --rm --cap-add CAP_SYS_PTRACE --cap-add CAP_SYS_ADMIN -v /proc/1/ns/net:/host_ns_net:ro debian:bullseye-slim bash
root@8b40f2f48808:/ ls -l /sys/class/net
lrwxrwxrwx 1 root root 0 Jun  2 21:09 eth0 -> ../../devices/virtual/net/eth0
lrwxrwxrwx 1 root root 0 Jun  2 21:09 lo -> ../../devices/virtual/net/lo

# enter the host network namespace
root@8b40f2f48808:/ nsenter --net=/host_ns_net bash

# now we are in the host network namespace and can see the host network interfaces
root@8b40f2f48808:/ mkdir /sys2
root@8b40f2f48808:/ mount -t sysfs nodevice /sys2
root@8b40f2f48808:/ ls -l /sys2/class/net/
lrwxrwxrwx 1 root root 0 Oct 25  2021 enp2s0 -> ../../devices/pci0000:00/0000:00:1c.1/0000:02:00.0/net/enp2s0
lrwxrwxrwx 1 root root 0 Oct 25  2021 enp3s0 -> ../../devices/pci0000:00/0000:00:1c.2/0000:03:00.0/net/enp3s0
[...]

root@8b40f2f48808:/ ls -l /sys2/class/net/enp2s0/
-r--r--r--  1 root root 4096 Oct 25  2021 addr_assign_type
-r--r--r--  1 root root 4096 Oct 25  2021 addr_len
-r--r--r--  1 root root 4096 Oct 25  2021 address
-r--r--r--  1 root root 4096 Oct 25  2021 broadcast
[...]

# Now you can switch back to the original network namespace
# of the container; the dir "/sys2" is still accessible
root@8b40f2f48808:/ exit

Putting this together for non-interactive usage:
Use the docker run with the following parameters:
docker run -it --rm --cap-add CAP_SYS_PTRACE --cap-add CAP_SYS_ADMIN -v /proc/1/ns/net:/host_ns_net:ro debian:bullseye-slim bash
Execute these commands in the container before starting your node app:
mkdir /sys2
nsenter --net=/host_ns_net mount -t sysfs nodevice /sys2

After nsenter (and mount) exits, you are back in the network namespace of the container. In theory you could drop the extended capabilities now.
Now you can access the network devices under /sys2/class/net.

A: You could mount the host's /sys/class/net/ directory as a volume in your container and patch the systeminformation package to read the contents of your custom path instead of the default path. The changes would need to be made in lib/network.js. You can see in that file how the directory is hardcoded throughout, just do a find/replace in your local copy to change all instances of the default path.

A: An easy way is to mount the whole "/sys" filesystem of the host into the container. Either mount them to a new location (e.g. /sys_host) or over-mount the original "/sys" in the container:
# docker run -it --rm -v /sys:/sys:ro debian:bullseye-slim bash
root@b84df3184dce:/# ls -l /sys/class/net/
lrwxrwxrwx 1 root root 0 Oct 25  2021 enp2s0 -> ../../devices/pci0000:00/0000:00:1c.1/0000:02:00.0/net/enp2s0
lrwxrwxrwx 1 root root 0 Oct 25  2021 enp3s0 -> ../../devices/pci0000:00/0000:00:1c.2/0000:03:00.0/net/enp3s0
[...]

root@b84df3184dce:/# ls -l /sys/class/net/enp2s0/
-r--r--r--  1 root root 4096 Oct 25  2021 addr_assign_type
-r--r--r--  1 root root 4096 Oct 25  2021 addr_len
-r--r--r--  1 root root 4096 Oct 25  2021 address
-r--r--r--  1 root root 4096 Oct 25  2021 broadcast
[...]

Please be aware that this way the container has access to the whole "/sys" filesystem of the host. The relative links from the network interface to the pci device still work.
If you don't need to write you should mount it read-only by appending ":ro" to the mounted path.


text:
Q: Scala - Passing a Seq/Map of derived class's class in place of base class's class This is a follow up question on my previous question:
Scala - Passing Class of derived type in place of Class of supertype
Following is my use case:
I have a class called MultiplePredictionTester with the following implementation...
class MultiplePredictionTester[T <: SurvivalPredictor](predictorClasses: Seq[Class[T]],
                                                       restOfConstructorParams: Map[Class[T], Seq[Object]],
                                                       dataSplitter: DataSplitter,
                                                       titanic: DataFrame) extends PredictionTester {

  import titanic.sqlContext.implicits._

  override def test: Map[SurvivalPredictor, Double] = ???
}

The idea is to be able to take a sequence of classes derived from SurvivalPredictor and instantiate them inside, using a constructor where first argument is fetched from DataSplitter while the rest of the arguments come from the Map[Class[T], Seq[Object]]
I plan to invoke this class as:
object MultiQuickRunner extends App with ResourceGetter {
  val conf: SparkConf = new SparkConf().setAppName("TitanicSurvivalPredictor").setMaster("local[4]")
  val sc: SparkContext = new SparkContext(conf)
  val sqlContext: SQLContext = new SQLContext(sc)
  val test: Map[SurvivalPredictor, Double] =
    new MultiplePredictionTester(Seq(classOf[SexBasedPredictor], classOf[TotallyRandomPredictor]),
      Map[Class[SurvivalPredictor],Seq[Object]](),
      new DataSplitter {},
      new DataFrameLoader {}.load(getPathForResource("train.csv"),
        sqlContext)).test
  test.foreach { case (survivalPredictorInstance, accuracy) =>
    println("Accuracy for " + survivalPredictorInstance.getClass.getName + " is " + accuracy)
  }
}

However trying to compile something like that throws me the exception:
Error:(27, 5) no type parameters for constructor MultiplePredictionTester: (predictorClasses: Seq[Class[T]], restOfConstructorParams: Map[Class[T],Seq[Object]], dataSplitter: com.dhruvk.kaggle.DataSplitter, titanic: org.apache.spark.sql.DataFrame)com.dhruvk.kaggle.predictiontesters.implementations.MultiplePredictionTester[T] exist so that it can be applied to arguments (Seq[Class[_ >: com.dhruvk.kaggle.predictors.implementations.TotallyRandomPredictor with com.dhruvk.kaggle.predictors.implementations.SexBasedPredictor <: com.dhruvk.kaggle.predictors.SurvivalPredictor]], scala.collection.immutable.Map[Class[com.dhruvk.kaggle.predictors.SurvivalPredictor],Seq[Object]], com.dhruvk.kaggle.DataSplitter, org.apache.spark.sql.DataFrame)
 --- because ---
argument expression's type is not compatible with formal parameter type;
 found   : Seq[Class[_ >: com.dhruvk.kaggle.predictors.implementations.TotallyRandomPredictor with com.dhruvk.kaggle.predictors.implementations.SexBasedPredictor <: com.dhruvk.kaggle.predictors.SurvivalPredictor]]
 required: Seq[Class[?T]]
    new MultiplePredictionTester(Seq(classOf[SexBasedPredictor], classOf[TotallyRandomPredictor]),
    ^

Any help is appreciated.

A: java.lang.Class is invariant. During class declaration you are telling compiler that it is some T which has a upper bound such that T <: SurvivalPredictor. But when initializing you are saying T could SexBasedPredictor, TotallyRandomPredictor or SurvivalPredictor. This is not possible.
Consider
class A
class B extends A

class Test[T <: A](x: Seq[Class[T]], m: Map[Class[T], Seq[T]])

Here I have a class Test with type parameter T with upper bound A. Now I can initialize Test with
new Test(Seq(classOf[A], classOf[A]), Map(classOf[A] -> Seq(new B)))

As java.lang.Class is invariant, once I state T as A. I cant change it. If I change to B, compiler will yell at me. On the other hand as Seq is covariant I can say new B there.

A: As my comment to Till Rohrman's answer to the linked question mentions, there is just one Class[T] for any specific class or trait T: classOf[T]. So your predictorClasses can have length at most 1, and restOfConstructorParams can have size of most one. This is not what you want. The correct signature would use existential types:
class MultiplePredictionTester(predictorClasses: Seq[Class[_ <: SurvivalPredictor]],
                               ...

Class[_ <: SurvivalPredictor] is short for Class[T <: SurvivalPredictor] forSome { type T } and is the common type for all Class objects of subtypes of SurvivalPredictor.
It isn't clear what you want to use restOfConstructorParams for, but the type you gave is also wrong. It might be Seq[Any], for example.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Configure CSP in an Ember CLI application which uses http-mock I'm using http-mock with Ember CLI as suggested on http://www.ember-cli.com/#ember-data. I understand the basic concept of CSP but I don't understand the configuration of it within an Ember CLI application.
How can I configure my application to either accept requests to localhost:4200/api/ to avoid this during development:
Content Security Policy violation: {
    "csp-report": {
        "document-uri":"http://localhost:4200/products",
        "referrer":"",
        "violated-directive":"style-src 'self'",
        "effective-directive":"style-src",
        "original-policy":"default-src 'none'; script-src 'self' 'unsafe-eval' localhost:35729 0.0.0.0:35729; font-src 'self'; connect-src 'self' ws://localhost:35729 ws://0.0.0.0:35729 http://0.0.0.0:4200/csp-report; img-src 'self'; style-src 'self'; media-src 'self'; report-uri http://0.0.0.0:4200/csp-report;",
        "blocked-uri":"",
        "source-file":"chrome-extension://alelhddbbhepgpmgidjdcjakblofbmce",
        "line-number":1,"column-number":20481,"status-code":200
    }
}

A: You can adjust your content security policy by editing config/environment.js.  I believe in your case, the connect-src is relevant to the error being thrown (edit: looks like style-src is being violated, possibly by Chrome Extension Awesome Screenshot).  Adding * will allow it to connect to anything.
var ENV = {

  ...

  contentSecurityPolicy: {
    'default-src': "'none'",
    'script-src': "'self'",
    'font-src': "'self'",
    'connect-src': "'self' *",
    'img-src': "'self'",
    'style-src': "'self' *",
    'media-src': "'self'"
  }
}

Or more specifically, you could add:
...
'connect-src': "'self' 'localhost:4200'",
...

Furthermore, if you only wanted to add this to your dev environment, put it in:
if (environment === 'development') {
  ENV.contentSecurityPolicy = {
    ...(policies)...
  }
}

More information available about CSP in ember-cli: https://www.npmjs.com/package/ember-cli-content-security-policy.
More information about CSP in general: http://content-security-policy.com/


text:
Q: Manipulate Model Binding in MVC 4 This is easier to explain with an example. Suppose I have a person class
Public Person
{
string firstName;
string SocialSecurityNumber;
}

When some changes are made by the user in a web page, the Person object is posted back to a controller that accepts Person as the input parameter. The SocialSecurity number is encrypted. We have many pages that post back objects (Not Necessarily Person class) that have encrypted Social security as a parameter. Now I want to modify the model binding, so that if the posted object has SocialSecurityNumber as a property, it should be automatically decrypted. How can I do this?

A: You could use a custom model binder. Some examples:

*

*http://www.dotnetcurry.com/ShowArticle.aspx?ID=584

*http://odetocode.com/blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx

*http://www.markeverard.com/blog/2011/07/18/creating-a-custom-modelbinder-allowing-validation-of-injected-composite-models/
This is an example of a simple one I've used before that you could modify for your needs:
public class FormatterModelBinder : DefaultModelBinder
{
    internal static string TrimValue([CanBeNull] string value, [CanBeNull] FormatAttribute formatter)
    {
        if (string.IsNullOrEmpty(value)) return value;
        return ((formatter == null) || formatter.Trim) ? value.Trim() : value;
    }

    protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
    {
        if ((propertyDescriptor != null) && (propertyDescriptor.PropertyType == typeof(string)))
        {
            var stringValue = value as string;
            var formatter = propertyDescriptor.Attributes.OfType<FormatAttribute>().FirstOrDefault();
            stringValue = TrimValue(stringValue, formatter);
            value = stringValue;
        }

        base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
    }
}

You could then create an attribute to decorate the property as required:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class FormatAttribute : Attribute
{
    public FormatAttribute()
    {
        Trim = true;
    }

    public bool Trim { get; set; }
}

This is "activated" by an attribute on the property in the ViewModel
Public Person
{
    string firstName;
    [Format(Trim = true)]
    string SocialSecurityNumber;
}

It should be fairly simple to modify this to allow for encryption.

A: Perhaps you should store it in its own class
public class Person
{
 public string firstName { get; set; }
 public SocialSecurityNumber SSN { get; set; }
}

public class SocialSecurityNumber
{
 public string SSN { get; set; }
}

Perhaps the class could have its own decrypt method as well.
public class SocialSecurityNumber
{
 public string SSN { get; set; }

 public string Decrypt()
 {
  //TODO: Decrypt SSN
  return decrypted ssn
 }
}

Now in your controller
[HttpPost]
public ActionResult PostedPerson (Person person)
{
 string PersonName = person.firstName;
 string SocialSecurityNumber = person.SSN.SSN;//or person.SSN.Decrypt();
 //TODO: decrypt SocialSecurity number
}

In the case where you are using FormCollection for model binding, then you would have to set some sort of flag or use an abstraction to mark that the field was encrypted
public class Person
{
 public string firstName { get; set; }
 public SocialSecurityNumber SSN { get; set; }
}

public class SocialSecurityNumber
{
 public string SSN { get; set; }
 public string Encrypted { get; set; }//set this to "EncryptedTrue" or something
                                      //similar in order to handle it in the post
}

And then with your form collection
[HttpPost]
public ActionResult PostedPerson (FormCollection fc)
{
 for( var val in fc )
 {
  if( val is InnerList ){
  {
   if( val.Contains("EncryptedTrue") )
   {
    //then val.SSN would be an encryped social security number
   }
  }
 }
}


text:
Q: Solving 5 variables Karnaugh map - grouping Welcome. I would like to ask about solving Karnaugh Maps, especially grouping 5-variables map. I am not sure if I made this good way, so if you could, please let me know what is wrong. It seems to me everything is fine.
Actually, is there any good Karnaugh map solver which work with 5 variables as well?
Here is map:

A: This answer is correct ?
Your answer is NOT correct; This is not the proper way to group a 5 variables K-map
Lets first look why a K-map is not practical for functions with more than 4 variables
The way the K-Map works is by grouping the numbers that their binary representation has a Hamming distance = 1 [Only 1 bit difference]
In the image you posted

This doesnt seem like the only way to arrange the values of inputs C,D,E since '011' is not next to '111'. We cant put all the values of a HD=1 of 3-bits on a line [1-D]
Having 2-bits guarantees that you can arrange the values of the 2 inputs in a 1-D [Line] such that all the binary values are surrounded by all the other values of hamming distance = 1 bit, but more than 2 bits require a 2-D or more in order to make sure that all the binary values are surrounded by all the possible values of a hamming distance = 1 bit
Thats why the way you are taking the groups is not correct
You might want to check This PDF
What is the correct answer?
According to my Python script which uses Quine–McCluskey algorithm, the correct answer is

What tools can i use to solve K-Map or to reduce a Boolean equation

*

*You can use my python script i provided above [Its a terrible code BUT works]

*You can use This tool to solve up to 8 variables K-Map

*You can use Logic Friday

A: Can check out this k-map solver. It can solve more than 9-bit k-maps too!!
Minterm and Don't care terms input, and output of SOP, VHDL & Verilog code snippets.
It has a great representation of the matrix too.
https://www.charlie-coleman.com/experiments/kmap/


text:
Q: Finding surface of the set in $\mathbb{R}^3$ Given set
$$M \equiv x^2 + y^2 \leq 2z,~z \in [0, 1]$$
find it's surface.
Using cylindrical coordinates I'm finding that
$$r^2 = 2z \implies z = \frac{r^2}{2}.$$
Now my transformation is of the form $x = r\cos\phi$, $y = r\sin\phi$ and $z = r^2/2$. Taking my transformation as a vector $\Psi := (x, y, z) = (r\cos\phi, r\sin\phi, r^2/2)$ norm of the normal vector is then $||\partial_r \Psi \times \partial_\phi \Psi|| = ||\mathbf{n}|| = r\sqrt{1 + r^2}$. Hence the surface of the set is
$$S = \int_M 1~dS  =  \int_{0}^{2\pi}d\phi\int_{0}^{1}dr~r\sqrt{1 + r^2} = \frac{2\pi}{3}\left(2\sqrt{2} - 1\right).$$
Is my approach correct or did I made any mistake?

A: Your norm of normal vector approach is correct.
However to check by the usual axial cut shells for a surface of revolution along arc I took
$$ dA= 2 \pi r ds = \frac{2 \pi r dr }{\cos \varphi} $$
when by differentiation
$$ \tan \varphi= 1/r $$
$$ A = 2 \pi \int \sqrt{1+r^2} dr $$
upper limit should be $r=\sqrt2$

A: I know this doesn't answer your question, but ...

Mathematica: ImplicitRegion[x^2 + y^2 <= 2 z && 0 <= z && z <= 1, {x, y, z}]


text:
Q: How does a standing wave decay? This question refers to standing waves in general rather than any particular type of standing wave. It may have nodes only at the ends, or it may have multiple nodes. It may be subject to damping, resistance, or absorption, or not. I assume that when the source of vibration or disturbance that causes the standing wave is removed, the standing wave does not instantly pass out of existence. I would like to know the manner in which the standing wave decays. I assume that something happens to it as a function of time. What equations describe the behavior of a standing wave when the energy source that causes it is removed? I am not looking for an answer involving a secondary effect like reverberation, I want to know the fate of the original standing wave itself.

A: Practically all energy transporting waves have damping mechanisms either related to the material they are propagating in or to the boundaries. This usually leads to an exponential decay in time of a free standing wave oscillation which could also be expressed as complex eigenfrequencies of the standing waves.


text:
Q: Exciton elements and exciton chemistry An exciton is a bound state of an electron and a hole, much like a hydrogen atom is a bound state of a proton and an electron.
Can a "helium" exciton be created, such that two electrons are bound to two holes? How about other exciton "elements"?
If these elements can be created (and momentarily stabilized), can they interact with each other if they exist within a quantum dot? If they are somehow independent? Can we expect the "exciton chemistry" to be the same as normal chemistry, with "exciton elements" replacing atom elements (with much shorter stability times, of course)? Or is there a theoretical model that suggests otherwise?
Thank you!

A: The exitonic molecule composed of two electrons and two holes was seen by J.R. Haynes in 1966 in silicon. Since electron-electron or hole-hole binding would be very different from nucleon binding, it does not qualify as 'helium'.


text:
Q: Right adjoint preserves products Given two additive categories $\mathcal{C}$ and $\mathcal{D}$ and a functor $F \colon \mathcal{C} \rightarrow \mathcal{D}$, then:
Definition: $F$ is additive if and only if $F$ turns product diagrams into product diagrams.
I saw an argument using the Yoneda Lemma that if I have an adjunction $F \dashv G$ then I have the following sequence of natural isomorphisms:
\begin{align*}
  \mathrm{Hom}(A, G(B \times C))
  &\simeq \mathrm{Hom}(F(A), B \times C) \\
  &\simeq \mathrm{Hom}(F(A), B) \times \mathrm{Hom}(F(A), C) \\
  &\simeq \mathrm{Hom}(A, G(B)) \times \mathrm{Hom}(A, G(C)) \\
  &\simeq \mathrm{Hom}(A, G(B) \times G(C)) \,.
\end{align*}
This implies that $G(B \times C) \simeq G(B) \times G(C)$.
But, here I'm just saying that the objects are isomorphic not that $G$ preserves product diagrams. What am I missing here?

A: Given objects $B^{\prime}, C^{\prime}\in{\mathcal C}$, endowing an object $X\in{\mathcal C}$ with the structure of a product of $B^{\prime}$ and $C^{\prime}$ is the same as providing an isomorphism $\text{Hom}_{\mathcal C}(-,X)\cong\text{Hom}_{\mathcal C}(-,B^{\prime})\times\text{Hom}_{\mathcal C}(-,C^{\prime})$ of functors ${\mathcal C}^{\text{op}}\to\text{Set}$. In your situation, $B^{\prime} = G(B)$, $C^{\prime} = G(C)$ and $X = G(B\times C)$, and at the fourth stage of your chain of isomorphisms you are done.
Note that you do not have to assume that ${\mathcal C}$ has products for that.

A: I think you are missing that the product is determined only up to isomorphism, moreover if $P$ is a product of objects $B$ and $C$ (i.e. the following diagram is universal),
$$\begin{matrix}
P&\overset{\pi_B}\longrightarrow\  B \\
 & \searrow{\scriptstyle{\pi_C} } \\
& \ \ \ C
\end{matrix}$$
 and $f:P\to Q$ is an isomorphism, then composing both legs of the product diagram with $P$ by $f^{-1}$ we get again a product diagram, where $Q$ plays the role of the product object.
Put it in other words, assume that products in $\mathcal C$ are not yet 'prepared', then still the first 3 isomorphisms of hom sets make sense and are valid, so
$$\hom(A,G(P))\ \simeq\ \hom(A,G(B))\times\hom(A,G(C)) $$
which proves that $G(P)$ is a product object. If you put $A=G(P)$ and take element $1_{G(P)}$ from left side, check that the above isomorphisms will naturally evaluate $(G(\pi_B),G(\pi_C))$ as the corresponding element on the right side.


text:
Q: C Bus Error with mmap, what is the problem For a homework assignment my prof wants us to read a file using mmap. Then copy it to another file using memcpy after mmap-ing the destination file.
I think i am doing this correctly, but C disagrees.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h> // for sleep
#include <time.h> // for the timeing of execution

// for reading and writing the files:
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <assert.h>

#include <string.h>

// create status struct for passing arguments to the threads
typedef struct threadComms{
    char* source;
    char* destination;

    double total_time;
    clock_t start;
    clock_t end;

    // to use the timeing functions,
    // when the thread starts, 'start = clock();'
    // when the thread ends, 'end = clock();'
    // 'total_time = end - start;'
} ThreadComms;

size_t getFileSize(char* filePath){

    struct stat st;
    stat(filePath, &st);

    return st.st_size;
}

void copyFile(void* arg){ // this needs to be a void* for the pthread library

    ThreadComms* comms = (ThreadComms*) arg;
    // start the counter
    comms->start = clock();

    size_t fileSize = getFileSize(comms->source);

    int sfd = open(comms->source, O_RDONLY, 0);

    assert(sfd != -1); // failed to open the file

    void* content = mmap(NULL, fileSize, PROT_READ, MAP_PRIVATE | MAP_FILE, sfd, 0); // map the file into the address space

    assert(content != MAP_FAILED);
    printf("data: %s\n", (char*) content);

    int dfd = open(comms->destination, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    assert(dfd != -1); // failed to create the file

    printf("fileSize: %d\n", (int) fileSize);

    printf("1\n");
    void* destination = mmap(NULL, fileSize, PROT_READ | PROT_WRITE, MAP_PRIVATE,  dfd, 0);
    printf("2 destination is: %p\n", destination);

    memcpy(destination, content, fileSize);
    printf("3\n");

    comms->end = clock();
    comms->total_time = ((double) (comms->end - comms->start)) / CLOCKS_PER_SEC;
}

int main(int argc, char *argv[]) {

    ThreadComms t1;
    char* filePath = "/home/csis/tempFile";
    char* newFile =  "/home/csis/tempFile2";

    t1.source = filePath;
    t1.destination = newFile;
    copyFile(&t1);

//  printf("Start: %f, End: %f, Run Time: %f \n", (double)t1.start, (double)t1.end , (double)t1.total_time);
}

I am guessing that i am using my file descriptor for the destination incorrectly or giving it the wrong permissions.
Wondering if you have any guess as to what is wrong?

A: You can't write to a non-existent portion of a file via mmap().
This truncates the file:
int dfd = open(comms->destination, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

This mmap()'s the truncated file:
void* destination = mmap(NULL, fileSize, PROT_READ | PROT_WRITE, MAP_PRIVATE,  dfd, 0);

This tries to copy to a non-existent part of the file:
memcpy(destination, content, fileSize);

Per the Linux mmap() man page ERRORS:

ERRORS
...
Use of a mapped region can result in these signals:
...
SIGBUS Attempted access to a portion of the buffer that does not
                correspond to the file (for example, beyond the end of the
                file, including the case where another process has truncated
                the file).

Per the POSIX mmap() specification:

... References within the address range starting at pa and continuing for len bytes to whole pages following the end of an object shall result in delivery of a SIGBUS signal.
An implementation may generate SIGBUS signals when a reference would cause an error in the mapped object, such as out-of-space condition.

The fix is to call ftruncate() to set the file length on the output file:
ftruncate( dfd, fileSize );
void* destination = mmap(NULL, fileSize, PROT_READ | PROT_WRITE, MAP_SHARED,  dfd, 0);

Note that you also have to replace the MAP_PRIVATE flag with MAP_SHARED.  Per POSIX again (bolding mine):

MAP_SHARED and MAP_PRIVATE describe the disposition of write references to the memory object. If MAP_SHARED is specified, write references shall change the underlying object. If MAP_PRIVATE is specified, modifications to the mapped data by the calling process shall be visible only to the calling process and shall not change the underlying object. It is unspecified whether modifications to the underlying object done after the MAP_PRIVATE mapping is established are visible through the MAP_PRIVATE mapping. Either MAP_SHARED or MAP_PRIVATE can be specified, but not both. The mapping type is retained across fork().


text:
Q: Deselecting a data with different column value Hi guys I've got this table structure
 field 1                  field 2
---------------------------------------------
    1                        1
    1                        2
    2                        1

Then I want it to be like this when selecting Key Field2 = 1
 field 1                  field 2
---------------------------------------------
   2                         1

I don't want to return field1 = 1 because It contains different values field1 IN (1,2)
Thanks you so much.

A: Your post seems unclear because I think you mixed up column names in certain parts of your description. However, judging by your sample output, I'm going to assume you mean the following:

Select rows from the table where field2 contains identical values for the same field1.

If you only need to output field1 and field2, you could do the following:
SELECT field1, MAX(field2) AS field2
FROM atable
GROUP BY field1
HAVING COUNT(DISTINCT field2) = 1

You can omit DISTINCT if your table cannot hold duplicate pairs of (field1, field2).
However, if there are more columns in the table and some or all of them need to be returned too, you could first just get the field1 values like above, then join that row set back to atable to get complete rows, like this:
SELECT t.*  /* or specify the necessary columns explicitly */
FROM atable AS t
  INNER JOIN (
    SELECT field1
    FROM atable
    GROUP BY field1
    HAVING COUNT(DISTINCT field2) = 1
  ) s ON t.field1 = s.field1

Again, DISTINCT can be omitted, as explained above.
Since you are using SQL Server 2008, you could also use windowed aggregating. If your table doesn't contain duplicates of (field1, field2), you could use the following:
;
WITH counted AS (
  SELECT
    *,
    cnt = COUNT(*) OVER (PARTITION BY field1)
  FROM atable
)
SELECT
  field1,
  field2,
  …
FROM counted
WHERE cnt = 1

But if the duplicates are allowed, you'll need to use a slightly different approach, because there's no windowing counterpart for COUNT(DISTINCT …). Here's what you could try:
;
WITH counted AS (
  SELECT
    *,
    f2min = MIN(field2) OVER (PARTITION BY field1),
    f2max = MAX(field2) OVER (PARTITION BY field1)
  FROM atable
)
SELECT
  field1,
  field2,
  …
FROM minmaxed
WHERE f2min = f2max

That is, you are getting the minimum and the maximum value of field2 for every field1 value. Then you are filtering out rows where f2min is not the same as f2max, because that would imply that there are different field2 values in the group.

A: SELECT * FROM table WHERE field_2 = 1 AND field_1 <> 1


text:
Q: PHP/MySQL not returning number of rows in database I'm attempting to count the number of rows in my database for a pagination script. My entire script works until it comes down to counting the rows.
This is the code that should be counting my rows[$conn is a variable set with my database login - it is used throughout this code and works, except for this bit].
$limit = 2;
$rows = mysql_num_rows(mysqli_query($conn, "SELECT count(*) FROM pilotOperators"));
$total=ceil($rows/$limit);

To test my code I added this to the end of my page:
echo "Total:" . $total . "
";
echo "Rows:" . $rows . "
";
echo "Limit:" . $limit . "
";

And this is the result taken from my source code:
Total:0
Rows:
Limit:2

I've tried several variations and such, but nothing is returning a number.

SOLVED: Thanks to two different answers(apparently I had two mistakes).
One of my lines was changed to:
$rows = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM pilotOperators"));

And it works like a charm now.
Thanks Mureinik, and EyasSH

A: This line is your problem:
$rows = mysql_num_rows(mysqli_query($conn, "SELECT count(*) FROM pilotOperators"));

You are asking for _num_rows() of a COUNT query. If oyu loo kat the result of
mysqli_query($conn, "SELECT count(*) FROM pilotOoperators");

You'll find out that you will get one row and one column:
|----------|
| count(*) |
|----------|
| 233      | etc
|----------|

What you want is:
$rows_result = mysqli_query($conn, "SELECT count(*) FROM pilotOoperators")->fetch_row();
$rows = $rows_result[0];

It is generally always better to use a COUNT aggregate query than num_rows. When is the right time to use mysqli_num_rows? Well, if you are actually using the query for something else, but need to know the number of rows in advance, then its best not to make two separate queries here.

A: Don't mix mysql and mysqli functions. If you're performing the query with mysqli_query, you should use mysqli_num_rows to get the number of rows:
$limit = 2;
$rows = mysqli_num_rows(mysqli_query($conn, "SELECT count(*) FROM pilotOperators"));
$total=ceil($rows/$limit);


text:
Q: Why am I getting OAuth errors when using the SoundCloud API? I have created an iPhone test application. Also I have integrated SoundCloud with the test application.
Also I got consumer key and consumer secret. When I tried to run my application, I am getting following messages.

2010-11-03 15:49:11.420 iPhoneTestApp[883:207] No CallbackURL supplied
2010-11-03 15:49:11.510 iPhoneTestApp[883:207] OAuth is not initialized with all 3 URLs
2010-11-03 15:49:11.511 iPhoneTestApp[883:207] OAuth is not initialized with all 3 URLs
2010-11-03 15:49:11.512 iPhoneTestApp[883:207] API is not configured with base URL

What could be causing this?

A: I have resolved it.
Again I registered with SoundCloud.com. I got the consumer key and consumer secret, I have used that key in my application. Then it is working fine.


text:
Q: Treat Symbolic Links as Folders in Nautilus FTP I have a Pure-FTPd server running with the virtualchroot-enabled binary. When I connect to the server with FileZilla, FileZilla shows a link overlay for symbolic links that point to folders, but I can navigate to those folders successfully.
However, when I connect to the server with GNOME Files (Nautilus), GNOME Files shows a generic document icon for the link and gives the error This link cannot be used because its target "../relative/path/to/target" doesn't exist. when I try to navigate to it.
It seems that FileZilla is letting the server handle the link while GNOME Files is trying to interpret the link itself. Can I change GNOME Files to treat the link as a normal directory?


text:
Q: How to write a perspective of log function in cvxpy? In cvxpy, I want to express a perspective of log function, which has the form: x*log(1 + y/x). This can be easily implemented in cvx by using rel_entr(). But I found that rel_entr() is not supported in cvxpy. Is there any way to write this perspective?

A: I have figured it out. We can use kl_div() in cvxpy to transform, i.e., -kl_div(x, x+y) + y.


text:
Q: Mysql IF IN (Select) no esta sirviendo tengo un problema, tengo esta consulta
select if (id in (
                  select valor
                  from tabla_variable
                  where nombre = 'no_id'),null,id) as id
from tabla_id

tabla_id

id
1
2
3
4
5
6
7

tabla_variable
id_variable | nombre | valor |
1             no_id    4,5

esperaba que me devolviera esto
id
1
2
3
null
null
6
7

pero me esta devolviendo esto
id
1
2
3
null
5
6
7

me esta tomando solo el primer numero y necesito que lo tome como si la consulta como tal fuera asi
select if(id in (4,5),null,id) as id
from tabla_id

A: En el caso de que siempre tengas dos valores en el campo valor puedes hacer uso de la  función SUBSTRING_INDEX() que te permite extraer los números separados por la coma, entonces la consulta quedaría de la siguiente manera:
select if (t1.id in (SUBSTRING_INDEX(t2.valor,',',1),
SUBSTRING_INDEX(t2.valor,',',-1)),null,t1.id) as ID
from tabla_id t1, tabla_variable  t2 where t2.nombre='no_id'

La sintaxis de la función es: SUBSTRING_INDEX(cadena,delimitador,contador).
La cadena vendría a ser tu campo valor, el delimitador en este caso sería la coma y
el contador se debe especificar. Si es positivo te va a devolver los valores de la izquierda de la coma contando desde la izquierda. Si es negativo te va a devolver los valores de la derecha de la coma contando desde la derecha.
Como "siempre" va a tener dos valores tu campo, el contador sería 1 para capturar el número de la izquierda (4) y -1 para el número de la derecha (5).
Pero si tu campo tuviera mas de dos valores por ejemplo '4,5,6,7...' los valores que retornarías sería 4 y 7. Si tu ingresas en el contador -2 te retornaría 6,7 o si ingresas 2 te retornaría 4,5.
Como mencionabas que incluso puede tener mas valores tu campo. En tu consulta al usar IN éste no te toma como una cadena lo que tienes en tu campo "valor", en lugar de usar IN podrías usar la función FIND_IN_SET() que sí te devuelve todos los valores en el que está presente el id dentro una cadena quedando la consulta de la siguiente manera:
select if (find_in_set (t1.id,t2.valor),null,t1.id) as ID from tabla_id t1,
tabla_variable  t2 where t2.nombre='no_id'

A: Me cuesta un poco trabajo saber que deseas hacer, pero lo que observo que quieres validar de la tabla tabla_id  hacia la tabla tabla_variable por la llave id si la columna nombre contiene el campo 'no_id':
select if((select nombre from tabla_variable AS tb2 where tb2.id = tb1.id) = 'no_id',null,id) as id from tabla_id AS tb1

Te sugiero que uses Alias a tus tablas para no tener ambigüedades al intentar devolver datos.


text:
Q: Excel VBA to change background image of shape by clicking on shape first time posting for some help that I can't find after exhaustive search. I'm sure this is easy for someone who know what they are doing.
I'm looking for VBA that will cycle through background images (saved on my computer) within in a shape by clicking on the shape. I'm pasting 2 sets of code below that I found that gives me a good start but I can't figure out how to merge the code to get the result I'm looking for.
Ultimately, I want each click on a shape to keep cycling through the following command:

*

*Initial Shape: transparent background

*Single Click on Shape: Transparent background replaced with BackgroundImage1

*Another Single Click on Shape: BackgroundImage1 replaced with BackgroundImage2

*Another Single Click on Shape: BackgroundImage2 replaced with transparent background

I've found this code that works well to change color of the shape by clicking:
Sub trafficlight()
Dim WhoAmI As String, sh As Shape
    WhoAmI = Application.Caller
    With ActiveSheet.Shapes(WhoAmI).Fill.ForeColor
        Select Case .RGB
            Case vbRed
                .RGB = vbGreen
            Case vbGreen
                .RGB = vbYellow
            Case Else
                .RGB = vbRed
        End Select
    End With
End Sub

And then this code to change the shape with a image saved on my computer:
Sub Rectangle9_Click()
Dim WhoAmI As String, sh As Shape
    WhoAmI = Application.Caller
    With ActiveSheet.Shapes(WhoAmI).Fill
        .Visible = msoTrue
        .UserPicture "C:\Users\username\Desktop\BackgroundImage1.png"
        .TextureTile = msoFalse
    End With
End Sub

Hope that was easy to understand. Thanks in advance for the help!!!

A: You need to keep track of what image is currently displayed. You could set an integer for each time the image changes.
Option Explicit

Sub ChangeShapePic()
Static i As Integer

With ActiveSheet.Shapes(Application.Caller).Fill
    Select Case i
        Case 0
            .UserPicture ("C:\Users\username\Desktop\BackgroundImage1.png")
            i = 1
        Case 1
            .UserPicture ("C:\Users\username\Desktop\BackgroundImage2.png")
            i = 2
        Case 2
            .UserPicture ("C:\Users\username\Desktop\BackgroundImage3.png")
            i = 3
        Case 3
           .Solid
           .Transparency = 0#
            i = 0
    End Select
End With
End Sub


text:
Q: Pod update has fatally altered app My perfectly working app used to have an Xcode Project Navigator as shown below.

iOS 10 requirements meant I had to upgrade Xcode to 8.1, which meant upgrading the entire Mac OS to Sierra and also translating the whole app to Swift 2.3.
Needless to say, this caused errors, one of which was an issue with PubNub. However, apart from this new build error the app structure was the same and everything seemed ok after dealing with all the layout issues.
I was requested to run the following steps to try to solve the PubNub pod error despite me warning that previous attempts to deal with the pod file caused fatal errors that were ultimately unrecoverable.

*

*Install all iOS simulators after Xcode update

*Open Xcode preferences (Cmd+,) and navigate to "Locations" tab where will be shown path to "DerivedData" folder

*Click on small circle with arrow on the right side of shown "DerivedData" path to open it in Finder

*Quit Xcode

*Remove "DerivedData" folder

*Clean up CocoaPods (if integrated with it) caches by entering this in Terminal:
rm -rf ~/Library/Caches/CocoaPods

*From project root (where Podfile is located) run this in Terminal:
pod deintegrate MyApp.xcodeproj

*Remove from project root (where Podfile is located) Podfile.lock file

*From project root (where Podfile is located) run this in Terminal: pod update

*Launch Xcode (hit Shift + Cmd + K just in case)

*Try build project

After doing all this my Project Navigator now looks like this.

As you can see, I've lost a load of stuff including the pod file etc. As suspected, my app is now fatally wounded.
My bridging header is red, Restkit.h is red and all pod references gone.
My project root in Finder has the Pods folder and pod file etc, however if I try to drag folders into the project from Finder they do not show as they used to - e.g., folders are blue color not yellow.
I'm on Xcode 8.1 and Cocoapods 1.1.1.
How can I recover my app?
EDIT: If it helps, here is the link to my unsolved question in January which was the last time I dared touch the pod file at all until now. The consequences of this situation are the same as before - the difference is that in January I was ditching 2 weeks work, now I'm looking at ditching 10 months' work.
RestKit.h never found in Xcode project
Podfile:
pod 'RestKit', '~> 0.24.0'
pod 'SimpleKeychain'
pod 'AWSS3'
pod 'VideoCore'
pod 'SDWebImage', '~>3.7'
pod 'SVPullToRefresh'
pod 'PubNub', '~> 3.7.11'
pod 'MZFormSheetController'

Result of pod update in Terminal:
Update all pods
Updating local specs repositories
Performing a deep fetch of the master specs repo to improve future performance
warning: inexact rename detection was skipped due to too many files.
CocoaPods 1.2.0.beta.1 is available.
To update use: sudo gem install cocoapods --pre
[!] This is a test version we'd love you to try.
For more information, see https://blog.cocoapods.org and the CHANGELOG for this version at https://github.com/CocoaPods/CocoaPods/releases/tag/1.2.0.beta.1
Analyzing dependencies
[!] The dependency RestKit (~> 0.24.0) is not used in any concrete target.
The dependency SimpleKeychain is not used in any concrete target.
The dependency AWSS3 is not used in any concrete target.
The dependency VideoCore is not used in any concrete target.
The dependency SDWebImage (~> 3.7) is not used in any concrete target.
The dependency SVPullToRefresh is not used in any concrete target.
The dependency PubNub (~> 3.7.11) is not used in any concrete target.
The dependency MZFormSheetController is not used in any concrete target.

A: From the pod update logs seems like CocoaPods can't find any target where the libraries have to be applied.
Can you try something like this in  your Podfile?
target 'YOUR_TARGET_NAME' do
    pod 'RestKit', '~> 0.24.0'
    pod 'SimpleKeychain'
    pod 'AWSS3'
    pod 'VideoCore'
    pod 'SDWebImage', '~>3.7'
    pod 'SVPullToRefresh'
    pod 'PubNub', '~> 3.7.11'
    pod 'MZFormSheetController'
end

Not sure if it will fix the error you have.


text:
Q: How do I prepend a proxy url to all requests on an HTML page I would like to prepend a proxy url to every HTTP request a page makes
I am unable to use Service Workers because they would load after the page loads, while I need it to load before the page loads.

A: I suggest you look into burp suite for a robust solution.
Another easier option is the Resource Override browser extension.

A: You can try a <base> tag. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base


text:
Q: DLL Injection with CreateRemoteThread If you take a look at the following working code of a simple DLL injection:
  //Open the target process with read , write and execute priviledges
   Process = OpenProcess(PROCESS_CREATE_THREAD|PROCESS_QUERY_INFORMATION|PROCESS_VM_READ|PROCESS_VM_WRITE|PROCESS_VM_OPERATION, FALSE, ID);

   //Get the address of LoadLibraryA
   LoadLibrary = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");

   // Allocate space in the process for our DLL
   Memory = (LPVOID)VirtualAllocEx(Process, NULL, strlen(dll)+1, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);

   // Write the string name of our DLL in the memory allocated
   WriteProcessMemory(Process, (LPVOID)Memory, dll, strlen(dll)+1, NULL);

   // Load our DLL
   CreateRemoteThread(Process, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibrary, (LPVOID)Memory, NULL, NULL);

   //Let the program regain control of itself
   CloseHandle(Process);

The thing confuses me is that GetProcAddress returns the LoadLibraryA fucntion address of the current process, how can you pass it as a parameter to CreateRemoteThread and expect the target process to run it?

A: Address Space Layout Randomisation (ASLR) is an anti-exploit mitigation feature handled by Windows, and it allows address relocation to help prevent attackers from determining the address for exploitation of something in memory (stops hard-coding of addresses/offsets). However, Windows modules only change their addresses per session.
If you have a process which uses kernel32.dll (not all processes use kernel32.dll and I'll explain this further in a few minutes), the address to a routine might be 55AA1122 as an example (that's an invalid example address). Now, the next process with kernel32.dll, will have the same address for 55AA1122 for the same routine as the previous.... Only if the processes are both of the same architecture.
32-bit processes will have the same addresses for kernel32.dll exports, among other Windows module exports too (e.g. NTDLL, USER32, etc.). 64-bit processes will have different addresses to the 32-bit processes, however the 64-bit processes will all have the same addresses for the Windows modules, too!
Remote thread creation was not an "accident", Microsoft intentionally implemented it. Why? Microsoft use it a lot during Windows themselves, also for Asynchronous Procedure Calls. Microsoft also hot-patch things often for their own routines as an anti-reversing trick, or if they lose the source code to their own projects, haha.
Now regarding kernel32.dll being loaded into a process, it is only loaded into processes which use the Win32 API. This includes 99% of programs in the world, however it is possible to compile a native process which will not use it. This will however force you to use Native API and no Win32 API completely, and a Windows process called smss.exe does exactly this. You can also compile Native DLLs which don't even have a normal Win32 API DLL Entry routine.
To put it short, the addresses for Windows module routines change once per boot. It'll maintain the same until the next reboot, and so on. 32-bit processes have their own shared addresses of Windows modules for each process, as does 64-bit processes. Therefore, you cannot use LoadLibraryA address of a 64-bit process whilst targeting DLL injection for a 32-bit process, unless you use the 32-bit Kernel32.dll LoadLibraryA address. A better idea would be to use LdrLoadDll anyway, or just shell-code injection of a reflective DLL loader stub.

A: It works by accident.  It is a very common accident, Microsoft makes a great deal of effort to ensure that the operating system DLLs, like kernel32.dll, have a base address that doesn't conflict with any other DLLs.  Further enhanced by kernel32.dll getting loaded very early at process initialization so low odds that it has to fight to get its preferred base address.
You'll get away with easily.  It is notable that this has gone wrong in the past, there was an XP security update oops that caused gdi32.dll to get relocated and made lots of machines fall over at boot.  The correct way is fairly painful, CreateToolhelp32Snapshot() + Module32First/Next() to find the relocation offset isn't great joy.  Frankly, you probably ought to not do this at all if the operating system is "weird" like that.

A: LoadLibraryA lives in kernel32.dll, a module that is always loaded into every process and happens to also be loaded at the same address in every process.

A: If you launch Visual Studio, create an empty project, add new main.cpp file, write down:
#include <windows.h>
void main()
{
}

And then compile this program, don't expect that the created executable does nothing, it doesn't.
Maybe the Visual C++ compiler didn't write down any command in the object file, because there is no command in the source code, but the linker did write down in the beginning of the main procedure of the executable LoadLibrary calls to user32.dll, kernel32.dll, gdi32.dll and etc.
So every application that is written in Visual Studio C++ initially make many and the same calls to LoadLibrary in the same order, no matter what was the source code of this executable.
The source code only determines the commands that should come after the LoadLibrary calls.
So every Visual Studio C++ application loads LoadLibrary of kernel32.dll in the beginning of the execution and so LoadLibrary has the same entry point or address in all processes relative to the process address.
Theoretically you can make the injector, the malicious program that attempts to inject your program, fail if you link some kernel32.lib that doesn't load kernel32.dll's LoadLibrary procedure into the memory of your program.
The injector cannot cause your program to dynamically during execution loads some dll if your program cannot dynamically during execution load dll, because the procedure that supposes to do this, LoadLibrary, does not present in the process memory.
Therefore the remote thread created by the injector cannot execute LoadLibrary that doesn't exist in the victim's memory.
But this is possible that the attacker will VirtualAllocEx to create some block in the victim's memory, WriteProcessMemory some executable code and then CreateRemoteThread to execute it.


text:
Q: How to hide a discard button in openerp 7? I need to hide the discard button from a page in openerp. Is it possible?

A: You have to inherit the form buttons template and hide the button from the form.
<templates id="template" xml:space="preserve">
   <t t-extend="FormView.buttons">
        <t t-jquery="div[class=oe_form_button_cancel]" t-operation="replace">
            Discard
        </t>
   </t>
</templates>

Hope this help
Regards,

A: This would seem pointless as you can't stop them using the back button on the browser (or just closing the browser).
Apologies if this seems silly but do you mean you want to stop them deleting the object?


text:
Q: TFS 2012 team build, How to specify package location when specified these parameters in the msbuild commandline args in the build definition,
/p:Configuration=Release /p:VisualStudioVersion=11.0 /P:UsePublishProfile=True /p:PublishProfile=CI /p:DeployOnBuild=true /p:DesktopBuildPackageLocation=..\Deployment\Files\Package\SubcontractGenerator.zip
it seems like msbuild ignore all of the parameters except /p:DeployOnBuild=true, so it just create the package in the droplocation_publishedWebsites\blah blah blah.
my question is how to get the build process to just create the package? because the CI publish profile specified there just to create the package.

A: I suggest you to install Visual Studio 2012 on your build server for execute Ms Build with these arguments


text:
Q: To find minimal polynomial of a matrix I am asked to find the minimal polynomial of the matrix
\begin{bmatrix}
4&-2&2\\
6&-3&4\\
3&-2&3\end{bmatrix}
I've calculated the characteristic polynomial is $\Delta(x)=(x-2)(x-1)^2$.
As we know that the minimal polynomial $m(x)$ must divide $\Delta(x)$, so the possibilities of being $m(x)$ are $(x-2),(x-1),(x-1)^2,(x-2)(x-1),(x-2)(x-1)^2$.
Among these, by Cayley-Hamilton theorem, for which least degree factor $\Delta(A)=O$ is satisfied will be the minimal polynomial.
But for some reason, the first three above mentioned factors were ignored in my book. What can be the possible reason for this?

A: Because every root of the characteristic polynomial is always a root of the minimal polynomial. In the case, for instance, of $x-1$, $2$ is not a root, but it is a root of that characteristic polynomial.


text:
Q: Javascript Checking array value always return -1 I have the following route in my AngularJS app, where I save permission level for each route in an array as shown in the code below. Then I check if the current logged in user has permission level matching that of the route to be loaded, using the code below, but I always get result -1 even if the logged user permission is matching one of those in the plevel array. Can someone please check my code and tell me what exactly I am doing wrong and how to fix it? Thanks.
       $routeProvider.when('/clients/new-invoice',
        {     templateUrl: 'templates/new-invoice.html',
              controller: 'InvoicesController',
              title: 'New Invoice',
              data: {
                 auth: true,
                 plevel: [5, 6, 8]
              }
        });

 $rootScope.$on("$routeChangeStart", function(event, next, current) {

      var CContent = $.cookie('UCookie');

      console.log('User - permission match : ' + $.inArray(CContent, next.data. plevel) );
  });

A: $.inArray uses strict equality and you are comparing a string to ints which are not strictly equal (5 === "5" //returns false) thus the -1. You should first convert CContent to an int like this:
CContent = parseInt($.cookie('UCookie'), 10);


text:
Q: How to add multiple markers on the google map, at a certain meta_key and meta_value I have over 200 customposts and each has customfields (add_city, add_state, add_location) in each custompost is googlmap with customfield (geo_longitude geo_latitude) Help please, display in googlmap  multiple markers, depending on more meta_key meta_value.
To sort kustomposts I use this beautiful code :
<?php $args = array(
'meta_query'=> array(
    array(
        'key' => 'add_state',
        'value'=> 'ill'
    ),
           array(
                    'key' => 'add_city',
                    'value' => 'chicago'
     ))); $posts = query_posts($args); ?>

On the details page, I use this code for googlmap:
<?php
        $add_arr = array();
        if(get_post_meta($post->ID,'address',true))
        {
            $add_arr[] = get_post_meta($post->ID,'address',true);
        }
        if(get_post_meta($post->ID,'add_city',true))
        {
            $add_arr[] = get_post_meta($post->ID,'add_city',true);
        }
        if(get_post_meta($post->ID,'add_state',true))
        {
            $add_arr[] = get_post_meta($post->ID,'add_state',true);
        }

        $add_str = '';
        if($add_arr)
        {
            $add_str = implode(',',$add_arr);
        }
        if($add_str)
        {
            $geo_longitude = get_post_meta($post->ID,'geo_longitude',true);
            $geo_latitude = get_post_meta($post->ID,'geo_latitude',true);
        ?>

             <?php if($geo_longitude &&  $geo_latitude){

                    require_once (TEMPLATEPATH . '/library/map/preview_map.php');
                    preview_address_google_map($geo_latitude,$geo_longitude,$add_str);
            }else{?>
            <iframe src="http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=<?php echo $add_str;?>&ie=UTF8&z=14&iwloc=A&output=embed" height="358" width="239" scrolling="no" frameborder="0" >
            <?php }?>

Then I created a page and a lot of time trying to string any of these codes.
He received only a white screen.
Please help me solve this puzzle !!!

A: The only way to get multiple markers on a map is to use the Google Maps API.
https://developers.google.com/maps/documentation/javascript/tutorial.
The way you are referencing through an iframe only allows one marker(one location).

A: Well there are other ways how to get multiple markers on the map that do not involve any programming.. You can use http://www.copypastemap.com or google fussion tables. Sorry, can't help you if you insist on programming solution.

A: I found this awesome solution multiple locations, php, mysql, custom marker, fullscreen option, NO Google API key needed. Take a look
» SachingShare.com Blog Article


text:
Q: monitor which process modified a file under FreeBSD/Linux From time to time, a file that I'm interested in is modified by some process.  I need to find out which process is modifying this file.  Using lsof will not work, nor does kqueue.  Is this possible under FreeBSD and Linux?

A: On Linux, there's a kernel patch floating around for inotify. However, some have said this is rarely useful and that it can be a security risk. In any case, here's the patch.
Apart from that, I'm not sure there's any way to get the PID, either with inotify or dnotify. You could investigate further (e.g. search for pid dnotify or pid inotify), but I believe it isn't likely.

A: On FreeBSD, perhaps it should be best if you check its auditing features.

A: Linux has an audit daemon http://www.cyberciti.biz/tips/linux-audit-files-to-see-who-made-changes-to-a-file.html
See also auditd homepage

A: You can see which processes opened a file just installing and using lsof (LiSt Open Files) command.


text:
Q: WebDriver not detecting the buttom element for click after dismssing the permission dialog alert I am using WdAndroid to run automation test on appium for Android. The part where I am getting stuck is that when the app is installed first time, it pops up permission dialog (location permission). I am using below code to accept the permission.
driver.elementById('com.android.packageinstaller:id/permission_allow_button').click()

Once the dialog is gone, I want to click the button of the activity to perform the desired action, using below snippet to achieve that.
const intervalObj = setInterval(() => {

  driver.elementById('com.testpackage.testapp:id/testClickButton').click();

  clearInterval(intervalObj);
}, 3000);

But above action does not work and I am getting following error in the appium log

[debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Finding
  'com.testpackage.testapp:id/testClickButton' using 'ID' with the
  contextId: '' multiple: false [debug] [AndroidBootstrap] [BOOTSTRAP
  LOG] [debug] Using: UiSelector[INSTANCE=0,
  RESOURCE_ID=com.testpackage.testapp:id/testClickButton] [debug]
  [AndroidBootstrap] Received command result from bootstrap [HTTP] <--
  POST /wd/hub/session/88f58979-f7ff-4d52-b840-e930d4a04804/element 500
  116 ms - 164  [debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug]
  Returning result: {"status":7,"value":"No element found"}

The automation flow is to accept permission and wait for 3 secs to perform click on button. But this is not happening.
However if I remove the permission alert dialog and then use above snippet to get click on button it works fine. Issue is only happening when dialog is dismissed and automation is not finding the button.

I am writing the automation source code in Node.JS.

A: Can you try sending your app to background just after accepting the dialog? With this you will get focus back for your app
driver.elementById('com.android.packageinstaller:id/permission_allow_button').click()
driver.runAppInBackground(0)

After this you could search again for an element.
There is also a capability for your driver that will auto accept your permissions
capabilities.setCapability("autoGrantPermissions", "true");

Another capability I want to suggest is 'noReset' so those permissions won't be asked everytime you launch the app, just the first time:
capabilities.setCapability("noReset", "true");


text:
Q: Can I access a local variable of a function without outputting it? I have a function in MATALB that looks like the following:
function [a, b] = SumIt(I1, I2)

    a = sum(I1);
    b = sum(I2);
    c = sum(I1/I2);

end

In the command window, I run the function but I cannot access the c variable. I know that I can do something like this [a, b, c] = SumIt(I1, I2) and access c variable. Can I access the variable c without outputting it?
The issue is that I have many outputs that are useless but I need to access them. How can I do this?
I tried with global but I got the same error.
function [a, b] = SumIt(I1, I2)
    global c;

    a = sum(I1);
    b = sum(I2);
    c = sum(I1/I2);

end
>> [a, b] = SumIt([1 4 6], [1 2 3]);
>> c
Undefined function or variable 'c'.

A: The only way that this can be done is to have a function script that also declares SumIt as an additional function and also declaring c to be global outside of the scope of SumIt.  Consider the following test function shown below:
function [] = test_func()

global c;

function [a, b] = SumIt(I1, I2)
    a = sum(I1);
    b = sum(I2);
    c = sum(I1/I2);
end

[t1, t2] = SumIt(6, 3);
disp(['t1 = ' num2str(t1)]);
disp(['t2 = ' num2str(t2)]);
disp(['c = ' num2str(c)]);

end

I have created a test function called test_func where we declare c to be global, but it is outside of the scope of SumIt.  After, I declare SumIt as a nested function, then try and call it with some example numbers.  I then display the outputs of SumIt as well as c.  Since I1 = 6, I2 = 3, we should get c = 2.
This is what I get when I run test_func:
>> test_func

t1 = 6
t2 = 3
c = 2

Minor note
It looks like I1 and I2 are vectors judging from the context of your use with sum.  As such, you should probably consider using the element-by-element division operator ./ if what I am interpreting is correct.  Are you trying to divide each element of I1 by I2 and then summing the result?  If that's the case, you need to change your function such that it becomes:
function [a, b] = SumIt(I1, I2)
    a = sum(I1);
    b = sum(I2);
    c = sum(I1./I2);
end


text:
Q: change SSIS package protection level before deployment I'm developing SSIS project locally using project deployment model. I use SQL Server Authentication to connect to remote server. During this period Protection level is set to EncryptSensitiveWithUserKey.
However, upon deployment this package will be executed in a completely different environment, using SSPI security context and with environment variables from SSIS catalog.
This means that right now, before deployment I have to manually change Protection level to DontSaveSensitive inside a project and every package in it. Only after that tedious procedure I deploy the project to remote server.
I cannot keep DontSaveSensitive locally because every time I run a package it will ask me for a password. I cannot deploy with EncryptSensitiveWithUserKey either, because it gives error saying it cannot decrypt some of the values (passwords).
My question is how can skip changes of protection level manually every time I deploy a package? How can I automate this?

A: Since you're in project deployment mode, which means you are deploying to the SSISDB, there's no need for what you're doing ;)
When you deploy, the isdeploymentwizard.exe is handling all that for your

As part of the deployment, the "Changing protection level" step switches the packages to ServerStorage level


text:
Q: GridBooleanColumn with data first by 0 and 1 but no true and false In my db I have a column Actif with values 0 and 1 (false and true)
I tried to use a column. Boolean with my db values 0 and 1 ... but it doesn't work.
{
    xtype: 'booleancolumn',
    dataIndex: 'Actif',
    text: 'MyBooleanColumn',
    falseText: 'Non',
    trueText: 'Oui'
}

Help me please :)
My Model
Ext.define('ModuleGestion.model.UtilisateursApplicatifs', {
extend: 'Ext.data.Model',

fields: [
    {
        name: 'Nom'
    },
    {
        name: 'Prenom'
    },
    {
        name: 'Identification'
    },
    {
        name: 'MotDePasse'
    },
    {
        name: 'IUtilisateurApplicatif'
    },
    {
        name: 'FonctionRepertoire'
    },
    {
        name: 'FonctionAnimation'
    },
    {
        name: 'FonctionFormation'
    },
    {
        name: 'FonctionAdministration'
    },
    {
        name: 'Actif'
    }
]});

the solution is delete the double quote of the return of the values :
$resultat = json_encode($resultat );
$resultat = str_replace('"Actif":"0"', '"Actif":0', $resultat);
$resultat = str_replace('"Actif":"1"', '"Actif":1', $resultat);

A: I have similar situation and for work with 0 and 1 from db I use not boolean column. From db I send 0 and 1, in my column renderer I check this and make some conversions. Check my example(here's actioncolumn - it's for show icons in cells). It's one way to decision your situation.
My view:
xtype: 'actioncolumn',
width: 55,
align: 'center',
dataIndex: 'Actif',
menuDisabled: 'true'
text: '',
sortable: false,
fixed: 'true',
renderer: function (value, metadata, record) {
    if (value == '0') {
        //some code
    }
    else {
        //some code
    }
},
getTip: function (value, metadata, record) {
    if (value == '0') {
        return 'here 0';
    } else {
        return 'here 1';
    }
}

You don't need to change model.
In your example I think you should add type of you'r field in model.
here's example
  { name: 'Actif', type: 'boolean' }


text:
Q: Cap touch measurement using digital pin? I have previously used dedicated touch pins and connected them across an electrode and been able to easily detect touch. Usually in such a case one wire directly from the pad to the dedicated touch pin would work.
I would like to do the same except the micro I am using is doing a few things and I've only got two digital pins available. Is there a way to do captouch sensing using digital pins?
I only need one pad detection. I can make it fairly big for better sensitivity etc.
Is this possible?
I ask as everything I could find online seems to need analog comparators and relaxation oscillators to make the measurement ( analogue pin on micro).

A: You don't say which microcontroller but some manufacturers offer a software library for capacitive sensing. Essentially they perform measurement similar to Qtouch technology. Library or not, yes this should be possible, but if you do it yourself you are basically replicating patented technology.

A: I am not promoting the product but just to give you a hint. I have been using touch controllers and this is one smallest and just enough for the need.
MBR3102 from Cypress
It needs no extra pins. No software. It can be used to sense two touch buttons and is the cheapest in the family. If you can accomodate this in the design, give a try. I have also explored similar IC solution from QTouch family but this IC is better in terms of performance

A: With two pins you could create a software I2C interface and interface an IC (e.g. QTouch)


text:
Q: "Uncaught TypeError: 5 is not a function" при присваивании 5 в переменную Почему данный код приводит к возникновению ошибки?

var a = 5

(function() {
  // ...
})();

A: Если не ставить ; там, где это требуется, то в некоторых ситуациях точки с запятой будут подставлены автоматически. Однако есть ситуации, в которых ; подставлена не будет, и в итоге код будет обработан совсем не так, как планировалось.
В спецификации в разделе 7.9.2 есть пример, в котором ; не будет подставлена, и который похож на пример из вопроса:

a = b + c
(d + e).print()
is not transformed by automatic semicolon insertion, because the parenthesised expression that begins the second line can be interpreted as an argument list for a function call:
a = b + c(d + e).print()

В примере из вопроса суть сводится к тому, что конструкция 5(function() {...}) воспринимается как вызов функции 5 и передача ей в качестве аргумента функции. () же в конце воспринимается как вызов результата выполнения 5 как функции
Пример того как это выполняется (5 заменено на f, потому что не очень-то получится объявить функцию с именем в виде числа):

function f(func) {
  func();
  return function(number) {
    console.log(number);
  };
}

var a = f

(function() {
  console.log("func");
})(10);


text:
Q: How to have rounded corners with repeat? I am trying for repeat for buttons. I am able to get repeat for regular background type. But i was not able to find right, left and center using the repeat xml file.
If you know some solution with the xml file please help me.
Thanks in advance
The repeat xml file i have used is
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
        <bitmap
            android:src="@drawable/barslice"
            android:tileMode="repeat"
            android:dither="true"/>
</item>

The button i require is:

A: you may get round-corner gradient buttons without even using images.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#449def" />
            <stroke
                android:width="1dp"
                android:color="#2f6699" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#449def"
                android:endColor="#2f6699"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#2f6699" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

and simply set it as background to your button, textview or whatever you want

A: This will be nicely handled by  9 patch image.
you will have an image like this

and android will handle it automatically.
Just set it as background of any button.
Note: image for other states like pressed, focused and disabled should also be provided otherwise it will not change buttons state.

A: You can use 9-patch images. Check the following links.
http://developer.android.com/guide/topics/resources/drawable-resource.html#NinePatch
http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch


text:
Q: Android Button To Another Screen i have a simple problem but it is giving me a big problem im sure it is something simple i am just missing.
I am trying to cerate a splash screen with a button that will go to the next screen at the moment the java code below creates a list of all the activitys in the manifest.
I am using the KanKan Wheel project BTW.
I want my java file to just have a simple button java command that links to one button on the xml file like so:
   Button bEnter = (Button) findViewById(R.id.enter);
    bEnter.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            startActivity(new Intent("??????????????????"));

        }
    });

Usually where the "???" are you would just place the package name then .MATCHMANIFESTNAME but i cant seem to get this to work i think the java code below is adding something as it is making the links automatcilly.
At the moment the java file is:
public class WheelDemo extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = getIntent();
    String path = intent.getStringExtra("com.example.android.apis.Path");

    if (path == null) {
        path = "";
    }

    setListAdapter(new SimpleAdapter(this, getData(path),
            android.R.layout.simple_list_item_1, new String[] { "title" },
            new int[] { android.R.id.text1 }));
}

protected List getData(String prefix) {
    List<Map> myData = new ArrayList<Map>();

    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory("kankan.wheel.WHEEL_SAMPLE");

    PackageManager pm = getPackageManager();
    List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);

    if (null == list)
        return myData;

    String[] prefixPath;

    if (prefix.equals("")) {
        prefixPath = null;
    } else {
        prefixPath = prefix.split("/");
    }

    int len = list.size();

    Map<String, Boolean> entries = new HashMap<String, Boolean>();

    for (int i = 0; i < len; i++) {
        ResolveInfo info = list.get(i);
        CharSequence labelSeq = info.loadLabel(pm);
        String label = labelSeq != null
                ? labelSeq.toString()
                : info.activityInfo.name;

        if (prefix.length() == 0 || label.startsWith(prefix)) {

            String[] labelPath = label.split("/");

            String nextLabel = prefixPath == null ? labelPath[0] : labelPath[prefixPath.length];

            if ((prefixPath != null ? prefixPath.length : 0) == labelPath.length - 1) {
                addItem(myData, nextLabel, activityIntent(
                        info.activityInfo.applicationInfo.packageName,
                        info.activityInfo.name));
            } else {
                if (entries.get(nextLabel) == null) {
                    addItem(myData, nextLabel, browseIntent(prefix.equals("") ? nextLabel : prefix + "/" + nextLabel));
                    entries.put(nextLabel, true);
                }
            }
        }
    }

    Collections.sort(myData, sDisplayNameComparator);

    return myData;
}

private final static Comparator<Map> sDisplayNameComparator = new Comparator<Map>() {
    private final Collator collator = Collator.getInstance();

    public int compare(Map map1, Map map2) {
        return collator.compare(map1.get("title"), map2.get("title"));
    }
};

protected Intent activityIntent(String pkg, String componentName) {
    Intent result = new Intent();
    result.setClassName(pkg, componentName);
    return result;
}

protected Intent browseIntent(String path) {
    Intent result = new Intent();
    result.setClass(this, WheelDemo.class);
    result.putExtra("com.example.android.apis.Path", path);
    return result;
}

protected void addItem(List<Map> data, String name, Intent intent) {
    Map<String, Object> temp = new HashMap<String, Object>();
    temp.put("title", name);
    temp.put("intent", intent);
    data.add(temp);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    Map map = (Map) l.getItemAtPosition(position);

    Intent intent = (Intent) map.get("intent");
    startActivity(intent);
}
}

And the screen i want to link to in the manifest is defined as:
<activity android:name="kankan.wheel.demo.PasswActivity" android:label="Password" android:screenOrientation="landscape">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="kankan.wheel.WHEEL_SAMPLE"/>
        </intent-filter>
    </activity>

A: In the intent, you need pass in which class is calling it and also what class you will be starting with that intent.. new Intent should be like this;
startActivity(new Intent(this, className.class);

this only works if you are in the activity, so that "this" is pointing to the active activity class.. And for the second variable you don't need package names.. Just use the className.class (and you will need to import the class into the activity obviously) and make sure that the className is an activity..
Also noe that className.class is NOT in quotes.

A: in my experience, simply put:
Button bEnter = (Button) findViewById(R.id.enter);
bEnter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub

startActivity(new Intent("nameofthisclass.this, nameofotherclass.class"));

}
});

A: What I would do is type:
Button bEnter = (Button) findViewById(R.id.enter);
bEnter.setOnClickListener(SetOnClickListener(this)
public void onClick(View v) {
  // TODO Auto-generated method stub
  switch (v.getId()){
    case R.id.Button Id:
      startActivity(new Intent("package.PUT_WHATEVER_YOU_WANT_HERE"));
  }
}

Also, you have to go in the manifest and type this up:
<activity android:name="package.Java_Class_Name" android:label="@string/app_name">
  <intent-filter>
    <action android:name="package.PUT_WHATEVER_YOU_WANT_HERE"/>
    <category android:name="android.intent.category.DEFAULT"/>
  </intent-filter>
</activity>

remember that the PUT_WHATEVER_YOU_WANT_HERE thing has to be the same thing in the manifest and the java class.


text:
Q: valores en matplotlib Tengo el siguiente código en python:
import matplotlib.pyplot as plt
x_values = range(1, 1001)
y_values = [x ** 2 for x in x_values]
plt.style.use('seaborn-v0_8')
fig, ax = plt.subplots()
ax.scatter(x_values, y_values, s = 10)
ax.set_title("Square Numbers", fontsize = 24)
ax.set_xlabel("Value", fontsize = 10)
ax.set_ylabel("Square of value", fontsize = 10)
ax.tick_params(axis = 'both', labelsize = 10)
ax.axis([0, 1000, 0, 1000000])
plt.show()

El resultado es el siguiente:

El problema es que en el eje Y siempre aparecen los valores en notación exponencial, como se ve. Como puedo hacer para que aparezcan "normales" (200000, 400000, etc)?

A: Buen día,
Puedes indicar que el formato de las etiquetas es "plano" utilizando ax.ticklabel_format(style='plain')
Ejemplo:
import matplotlib.pyplot as plt

x_values = range(1, 1001)
y_values = [x ** 2 for x in x_values]
plt.style.use('seaborn-v0_8')
fig, ax = plt.subplots()
ax.scatter(x_values, y_values, s = 10)
ax.set_title("Square Numbers", fontsize = 24)
ax.set_xlabel("Value", fontsize = 10)
ax.set_ylabel("Square of value", fontsize = 10)
ax.tick_params(axis = 'both', labelsize = 10)
ax.axis([0, 1000, 0, 1000000])
ax.ticklabel_format(style='plain')
plt.show()

Esto produce:


text:
Q: How to reduce code using es6 destructuring syntax? I'm using urql with Svelte and I'm delighted.
There is one thing I would like to improve but I don't know how.
Many times I have code like this:
<script lang="ts">
  import { operationStore, query } from "@urql/svelte";
  import { EntertainmentPlayerDocument } from "generated/queries";

  const entertainmentPlayer = operationStore(EntertainmentPlayerDocument, { id });

  query(entertainmentPlayer);
</script>

{#if $entertainmentPlayer.fetching}
  Loading...
{:else if $entertainmentPlayer.error}
  {$entertainmentPlayer.error}
{:else}
  <Button disabled={
      $entertainmentPlayer.data.entertainmentPlayer.state == EntertainmentPlayerStateEnum.Finish ||
      $entertainmentPlayer.data.entertainmentPlayer.state == EntertainmentPlayerStateEnum.Making
    }
  >
    MyButton
  </Button>
{/if}

I use many, many and many times $entertainmentPlayer.data.entertainmentPlayer in my code.
Is ther a way to reduce this?
I tried this code instead:
<script lang="ts">
  import { operationStore, query } from "@urql/svelte";
  import { EntertainmentPlayerDocument } from "generated/queries";

  const {data: {entertainmentPlayer}, fetching, error} = operationStore(EntertainmentPlayerDocument,{ id });

  // query(entertainmentPlayer); HOW TO USE THIS NOW?
</script>

But as you can see from the code I don't know how to call query(entertainmentPlayer) now.
If I use the below code I lose the typescript definitions on entertainmentPlayer:
const entertainmentPlayerStore = operationStore(EntertainmentPlayerDocument, { id });

query(entertainmentPlayerStore);

$: ({
  data: { entertainmentPlayer } = { entertainmentPlayer: {} },
  fetching,
  error
} = $entertainmentPlayerStore);

// Here `entertainmentPlayer` is no more typed.

Can you help me?

A: Nothing stops you from just introducing extra variables in your code:
<script lang="ts">
  import { operationStore, query } from "@urql/svelte";
  import { EntertainmentPlayerDocument } from "generated/queries";

  const queryOperation = operationStore(EntertainmentPlayerDocument, { id });

  query(entertainmentPlayer);

  const { entertainmentPlayer } = queryOperation.data ?? {};
</script>

{#if $queryOperation.fetching}
  Loading...
{:else if $queryOperation.error}
  {$queryOperation.error}
{:else}
  <Button disabled={
      $entertainmentPlayer.state == EntertainmentPlayerStateEnum.Finish ||
      $entertainmentPlayer.state == EntertainmentPlayerStateEnum.Making
    }
  >
    MyButton
  </Button>
{/if}


text:
Q: Undefined Symbol for Architecture i386 "_CloseZStream", "_CreateZStream" etc I have build the Unity project on my mac and it opens in XCode, it tries to build it straight away. Then it tells me it fails with 201 errors all linker errors.
Error is:

Undefined symbols for architecture i386: "_CloseZStream", referenced from: _DeflateStream_CloseZStream_m4_604 in Bulk_System_0.o (maybe you meant: _DeflateStream_CloseZStream_m4_604)

Has anyone got any ideas on how this problem can be fixed?


text:
Q: Vertical icon button navigation without font awesome I am trying to create a vertical left navigation menu.  It has 8 icons with text right beneath the icons.  I cannot use any icon font toolkit or libraries.  I was given the 8 icons in png format so that is what I have to work with.  I have been reading online the do and don't and arguments against using "i" tag but I'm not sure where to begin/end with this.  I went to W3schools and even the article there on vertical menu is using font awesome.
How can I replicate this https://www.w3schools.com/howto/howto_css_icon_bar.asp without font awesome and text beneath the icon of the button?
Based on the respone I feel the need to include the link I am trying to referring to about the  tag.
Should I use  tag for icons instead of ?

A: This is a working code snippet, all explanations are in the css. I hope this gives you the answer you needed, I know you wanted to know if you should use  or  but this should work.
As for SEO (Search Engine Optimization) this should be fine since you have an a tag.

/*This is a vertical nav bar that will take the whole height, the width of it isn't fixed since the text might take space so it has to expand as needed*/
*{
  padding:0;
  margin:0;
  box-sizing: border-box;
}

html,body{
  height:100%;
  width:100%;
}

/*The vertical nav bar*/
.container {
  height:100%;
  border-right: 1px solid black;
  position: fixed;
  left:0;
  top:0;
}

/*put it as  to link it to somewhere else, this wraps the image and the text together*/
a.wrapper{
  color: black;
  text-decoration: none;

  /*Flex column to align the image and the text underneath each other*/
  display:flex;
  flex-direction: column;
  align-items: center;
  padding:5px;
  margin-bottom:15px;
}

a.wrapper:hover{
  background: green;
}

.container .wrapper .img-wrapper{
  /*Having an image container with a fixed width and the image itself at 100% width is the best thing you could do for images, because the image will take the needed height to not lose any img clarity*/
  width:30px;

  margin-bottom:5px;
}
.container .wrapper img {
  width:100%;
}

.container .wrapper p {
  font-family: helvetica;
  font-size: 0.9em;
}

Item 1

Item 1

Item 2929292


text:
Q: Using translations of Behat predefined steps (Phar install) I've run some tests with the predefined step definitions of Mink Extension. They work as long as they're in english language.
Now I've tried the following scenario with german steps:
# language: de
Funktionalität: Demo

  @javascript
  Szenario: Test 1
    Angenommen I am on "/"
    Angenommen ich bin auf "/"
    ...

Behat now tells me that the german step definition is undefined, while the english version works.
According to the CLI help, behat --lang de -dl should display the translated definitions, but it only shows me the english ones ...
What am I doing wrong here?
Edit:
Here's a script to rebuild the scenario. It follows the install steps from the docs (http://extensions.behat.org/mink/#through-phar) in a temporary directory and runs the test feature file.
#!/bin/bash

set -e

TEMPDIR=/tmp/behat-$$
mkdir $TEMPDIR
cd $TEMPDIR

curl http://behat.org/downloads/behat.phar >behat.phar
curl http://behat.org/downloads/mink.phar >mink.phar
curl http://behat.org/downloads/mink_extension.phar >mink_extension.phar

cat >behat.yml <<EOF
default:
  extensions:
    mink_extension.phar:
      mink_loader: 'mink.phar'
      base_url:    'http://behat.org'
      goutte:      ~
EOF

mkdir features
cat >features/test.feature <<EOF
# language: de
Funktionalität: Demo

  Szenario: Öffne Startseite DE + EN
    Angenommen I am on "/"
    Angenommen ich bin auf "/"
EOF

php behat.phar

A: Basically you didn't do anything wrong.
Although the translation of Behat/Gherkin itself is included in the behat.phar file, the translations of the step definitions from MinkExtension are missing in the mink_extension.phar archive.
This seems to be the case because the build script only includes the files in MinkExtension/src/ without MinkExtension/i18n/. You could open an issue for MinkExtension at to get this fixed.
As a workaround I suggest to install Behat/Mink using composer instead of working with phar archives.
Create the following composer.json file:
{
    "require": {
        "behat/behat": "2.4.*@stable",
        "behat/mink": "1.4.*@stable",
        "behat/mink-extension": "*",
        "behat/mink-goutte-driver": "*",
        "behat/mink-selenium2-driver": "*"
    },
    "minimum-stability": "dev",
    "config": {
        "bin-dir": "bin/"
    }
}

and then install it with:
curl http://getcomposer.org/installer | php
php composer.phar install


text:
Q: quotients of vector spaces by linear isomorphic vectors spaces Let $Y$ be a vector space. Let $Z$ be a linear subspace of $Y$. Suppose that $Y/Z$ is finite dimensional. Does it follows that $Y/W$ is finite dimensional if $W$ is isomorphic to $Z$ as a vector space?

A: No. Take a vector space $Y$ with basis $e_1,e_2,e_3,\ldots$ and let $W=\textrm{span}(e_2,e_4,e_6,\ldots)$ and $Z=Y$. Clearly, $W$ is isomorphic to $Z$ as a vector space, but $Y/Z$ is trivial while $Y/W$ is infinite-dimensional.


text:
Q: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error: failed to open database with message 'not an error'.' I am making an app with many database operations. Since SQLite caches data, in my applicationDidReceiveMemoryWarning method, I am closing the database and opening it again to delete the cached data.
When the do this, I get this error

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error: failed to open database with message 'not an error'.'

Here's the code I am using to close the database and open again where database is of type sqlite3*
     [MySQLInter finalizeStatements];
 if(sqlite3_close(database) == SQLITE_OK){

//open again
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *path = [documentsDirectory stringByAppendingPathComponent:@"mydb.sql"];

    if(sqlite3_open([path UTF8String], &database) != SQLITE_OK){

         NSAssert1(0, @"Error: failed to open database with message '%s'.", sqlite3_errmsg(database));

}

 }

 else{

NSAssert1(0, @"Error: failed to close database on memwarning with message '%s'.", sqlite3_errmsg(database));

 }

How to avoid this?

A: Are you sure you don't mean "!= SQLITE_OK" on the sqlite3_open call?

A: sqlite3_open returns an error code.  You're just checking it for SQLITE_OK - it'd be interesting to see exactly what it's returning.  If it doesn't open, it's not valid to call sqlite3_errmsg on database because it didn't open the database, so that object may not be populated properly.
In your error catching conditional, print out the value of the return of sqlite3_open instead, and we'll be able to help better.


text:
Q: Force PC to Output 4k 60hz Ok so I have a bit of a strange setup that I'm trying to get working.
I bought a brand new LG C8 OLED 4K TV and put it in my livingroom. I own a new gaming PC that's in my office (on a different floor and far from TV) which is hooked up to a 2k monitor. I would like to stream my desktop to my TV and play 4k 60fps games.
I've been doing this for about a year with my old 1080p TV. I was using Nvidia Moonlight to stream from my PC to a laptop that was next to the TV and connected through HDMI. This worked flawlessly, and also supports 4k streams.
Issue 1:
I was able to get my laptop to display 4k by displaying only on the TV, and setting the resolution to 4k.
However on my gaming PC Windows 10 will only let me increase my resolution to 2k, because that's what the connected monitor supports. And I can't extend the display or anything because there's technically just the one display connected.
Is there a way I can force my PC to stream 4k content without having a 4k displaying physically connected?
Issue 2:
When I set my laptop to 4k, the highest refresh rate that it would allow was 30hz. I'm using HDMI 2.0 so I'm not sure why this is happening. As far as I understand, if I get my PC streaming in 4k but leave my laptop in 1080p, it will downsample the 4k to 1080p on my TV, correct? I haven't been able to test this yet because I need issue 1 resolved first, but it's a big concern of mine. Anyone know if this will be an issue or if there's a work around?
EDIT:
The laptop connected to the TV has an 850m in it, which is not strong enough to run 4k games at 60fps. This is why I'm only using it as an intermediary device.
My gaming PC has a ROG Strix 1070ti. This is the computer in my office and the one I want to stream from.


text:
Q: Wordpress rebuild - 301 redirect old pages (*.php) to pretty permalinks Here is what I need to do:
old pages are mydomain.com/something.php
new pages are rebuilt in Wordpress identified using pretty permalinks so they are mydomain.com/something/
I need to figure out what the rewrite rule should look like.  I have crawled the web and can't find anything exactly like it.

A: Something like:
RewriteEngine On
RewriteRule   ^(.*)\.php$ $1/ [R=permanent]

The (.*) is a "group" of characters before the .php, and $1 refers to that group of characters.  So just add a slash to the group and send the browser to the new URL with an HTTP code 301 (permanent redirect)

A: Try this:
RewriteEngine On
RewriteBase /

#Ignore index.php
RewriteCond %{REQUEST_URI} !index\.php
RewriteCond %{REQUEST_URI} !(wp-login|wp-admin|wp-includes)
RewriteCond %{REQUEST_URI} ^(.*)\.php$
RewriteRule ^(.*)\.php$ $1/ [R=301,L]

#"Standard" Wordpress Rewrite Stuff
RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !/catalog
RewriteRule . /index.php [L]


text:
Q: I get this error when trying to display a static image on blazor C#? //this is the error: Not allowed to load local resource: file:///C:/Users/Rus/source/repos/TestProj/wwwroot/logoPng/test.png im not sure how to solve this issue..

@imgName

@img

    @code {
        string img = Directory.GetCurrentDirectory() + @"\wwwroot\logoPng\test.png";
    }

A: To access the file(s) from wwwroot folder,
string img = "//logoPng//test.png";

References
Serve static files


text:
Q: How can I safely change states between state objects? I posted a question recently, and it was pointed out to me that I am going horribly wrong!
In main() I am making a state and then passing in integers to processState() and based on the integer it will changes state (by destroying the state and creating a new instance of a new state), or stay in the same state.
The main issue pointed out to me is in function void state_t::changeState(state_t * new_state). I am deleting this and then pointing the deleted _state pointer to point to the new state.  Now that it is pointed out to me, it is obviously a bad thing to do.
So the question is:  what is the best way to achieve this kind of state switching using different states?  Maybe _state needs to be a global pointer to the current state or some such?
Main.cpp:
#include <QCoreApplication>
#include <QDebug>
#include "statemachine.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    state_t *myState = new testState1();

    myState = myState->processState(1);
    myState = myState->processState(2);
    myState = myState->processState(3);
    myState = myState->processState(1);

    return a.exec();
}

Base type:
#include "state_t.h"

state_t::state_t(QByteArray stateName) :
    name(stateName),
    _state(this)
{
    qDebug() << this->name << ": Creating state";
}

state_t::~state_t()
{
    qDebug() << this->name << ": Deleting state";
    qDebug() << endl;
}

void state_t::changeState(state_t * new_state)
{
    // Check if the state has changed
    if (this != new_state)
    {
        qDebug() << this->name << ": State changed to: " << new_state->name;
        delete this;
        _state = new_state;
    }
    else
    {
        qDebug() << this->name << ": State un-changed";
    }
}

void state_t::unknownStateEventHandler(int event)
{
    qWarning() << this->name << ": Unknown event " << event;
}

A state class (there can be many of these):
#include "teststate1.h"

testState1::testState1() :
    state_t("state1")
{
}

state_t *testState1::processState(int event)
{
    qDebug() << name << ": event" << event;
    switch (event)
    {
        case 2:
        {
            changeState(new testState2());
            //changeState_t(testState2);
            break;
        }
        default:
        {
            unknownStateEventHandler(event);
            break;
        }
    }

    return _state;
}

A: I think the problem you've got is that you're mixing-up the behaviour of a state with the behaviour of the state machine; i.e. executing state behaviour, vs. managing state changes. Those should be kept separate.
You could have a class which represents your state machine as a whole. It doesn't have any state-specific functionality inside. Rather, it will contain a pointer to the current state object. (I'm assuming all your individual state classes are derived from a common base class.)
When you want to change state, the state machine class will delete the old state and create and/or store the new one. The individual state classes shouldn't be doing that directly, although they could call a function on the state machine to initiate the change.
As a side note, it's best to avoid using delete this. It technically works, but it's usually not a good idea.

A: In your case, you should not do
delete this;
_state = new_state;

You should just assign the value of new_state to this by:
*this = *new_state

But I don't think this is a good design. Please check this example.

A: I am trying to implement it too and I have some doubts too but as far as I understand you are committing some design mistakes.
This design pattern defines the following partecipants:

*

*context defines the interface of interest to clients and maintains an instance of a
ConcreteState subclass that defines the current state.

*State defines an interface for encapsulating the behaviour associated with a a particular state.

*ConcreteState subclasses: each subclass implementing a behaviour associated with a state of the context.

The goal is that the context does not have to worry about which state it is in: it uses the general interface delegating the specific operations to the ConcreteState subclasses. Plus you can extend your program by adding a new state without having to modify the context and the rest of the code.
The state in C++ is represented by a member variable in the Context, your "machine", of type State which is a base class, possibly abstract. Defining a pointer of parent class type exploits polymorphism, allowing you to reference the ConcreteState subclasses.
For example let me define the following State class (note it has a reference to the Context class) defining the interface for all the ConcreteState subclasses. (I defined the methods as virtual it is not mandatory):
#ifndef INPUTSTATE_H
#define INPUTSTATE_H
#include "Context.hpp"

using namespace std;
class Context;

class State
{
public:
  State(Context* context);
  virtual void method1(int x, int y);
  virtual void method2();

protected:
  Context* _context;
};

#endif

Then the Context will be something like (note State* state;):
#ifndef INPUTESTATECONTEXT_H
#define INPUTESTATECONTEXT_H

#include "State.hpp"

class State;

class Context
{
private:
  State* state;
public:
  Context();
  void setState(State* new_state);
};

#endif

The implementation of the function to change the state is the following and it will be called from the concrete implementation of the State classes:
void Context::setState(InputState* new_state)
{
  state = new_state;
}

The constructor must initialize the state member:
Context::Context()
{
  state = new State(this);
}
We are passing this because all the State classes need a reference to the Context.
Then we have the concrete implementation of the base State
#include "State.hpp"

class ConcreteState1 : public State
{
public:
  ConcreteState1(Context* context);
  void method1(int x, int y);
  void method2();

};

#include "State.hpp"

class ConcreteState2 : public State
{
public:
  ConcreteState1(Context* context);
  void method1(int x, int y);
  void method2();

};

These two classes will differ for the implementation of their member functions.
From the Context class you will call this methods with state->method2() without worrying which state is currently active (state is the pointer to the current state).
To finally answer your question Suppose in ConcreteState1::method1(int int) you find a condition for which you need to change the state to ConcreteState2. This can be achieved with the following:
_context->setState( new ConcreteState2(_context) );

After changing the state you must clean the memory from the ConcreteState subclass since it is not needed anymore. Many people do this with delete (somebody correct me if there is a more elegant way):
_context->setState( new ConcreteState2(_context) );
delete this;

Also note that all classes need also a proper destructor method to delete the pointer initialized with new.
One problem in your code was also that you were doing:
delete this;
_state = new_state;

this delete the object but then you are assigning a value to one of its member. I do not think this works.
I tried to be concise but if something is not clear let me know.