text:
Q: Access nodejs with web javascript but hitting XSS? I have a nodejs app that runs a web server and works as a web API. Simple GETs to interact with it. My goal is to be as accessible as possible by any language or programmatic scenario. My biggest problem is that javascript run in the browser can't hit it because the browser (specifically chrome) prevent cross site scripting. I'm open to any ideas that allow this. I want any site to be able to make requests against the url, sort of like how twitter has a javascript API.
I've tried using jQuery's ajax with JSONP but I was having all sorts of problems. Either it wouldn't go through or if it did go through I wouldn't get the response.
If there's a pure javascript way, I'd prefer that because of it having fewer dependencies.


text:
Q: SQL - Delete row based on number of rows in another table How would I go about deleting a row from the table 'subjects' that has a primary id 'subject_id' based on the number of rows in another table named 'replies' that uses a 'subject_id' column as a reference.
Example in pseudo code:
If ('subject' has less than 1 reply){
delete 'subject'}
I don't know much about SQL triggers so I have no clue if I would be able to incorporate this directly in the database or if I'd have to write some PHP code to handle this...

A: To delete any subjects that have had no replies, this query should do the trick:
DELETE s.* FROM subjects AS s
WHERE NOT EXISTS
    (
    SELECT r.subject_id
    FROM replies AS r
    WHERE r.subject_id = s.subject_id
    );

Demo: DB Fiddle Example

A: One of the MySQL gurus will need to weigh in on whether or not you can do this directly, but in PHP you could...
$query = "SELECT subject_id FROM subjects WHERE subject='test'";
$return = mysqli_query($mysqli, $query);
$id = mysqli_fetch_assoc($return);

$query = "SELECT reply_id FROM replies WHERE subject_id='".$id[0]."'";
$return = mysqli_query($mysqli, $query);

if(mysqli_num_rows($return) < 1){
    $query = "DELETE FROM subjects WHERE subject_id='1'";
    $return = mysqli_query($mysqli, $query);
}

This example assumes the "subject" is unique.  In other words, SELECTing WHERE subject='test' will only ever return one subject_id.  If you were doing this as a periodic cleaning, you would grab all the subject_id values (no WHERE clause) and loop through them to remove them if no replies.

A: You can achieve this in one query by selecting all (unique) subject-ids from the replies table, and delete all subjects that doesn't have a reply in there. Using SELECT DISTINCT, you don't get the IDs more than once (if a subject has more than one reply), so you don't get unnecessary data.
DELETE FROM subjects
WHERE subject_id NOT IN (SELECT DISTINCT subject_id FROM replies)

Any subject that doesn't have a reply should be deleted!

A: So you want to delete all subjects with no replies:
DELETE FROM subjects WHERE subject_id NOT IN
(SELECT subject_id FROM replies);

I think this is what you want...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot get Method from assembly at runtime I'm using the following code to load an assembly at runtime and then get a reference to a specific method and obviously execute it at the end:
var assemblyLoaded = Assembly.LoadFile(absolutePath);
var type = assemblyLoaded.GetType("CreateContactPlugin.Plugin");

var instance = Activator.CreateInstance(type);

var methodInfo = type.GetMethod("Execute", new Type[] { typeof(System.String)});
if (methodInfo == null)
{
    throw new Exception("No such method exists.");
}

Here is the assembly that I'm calling
namespace CreateContactPlugin
{
   public class Plugin
   {

    static bool Execute(string contactName){
        bool contactCreated = false;
        if (!String.IsNullOrWhiteSpace(contactName))
        {
            //process
        }
        return contactCreated;
    }

  }
 }

I can succesfully load the Assembly, the Type. When I highlight the type variable, I see the method listed in the DeclaredMethods array. But when I try to get the Method, it returns always null.
Does somebody see what I might be doing wrong here ?

A: There's a couple of problems here. First of all the Execute method is static and not public so you need to specify the correct binding flags to get at it.
var methodInfo = type.GetMethod("Execute", BindingFlags.Static | BindingFlags.NonPublic);

However, an alternative (and preferable in my opinion) solution using less reflection and strong typing would be to make your plugin class implement a common interface, that way you can strongly type your instance object. First make a class library with the relevant interfaces in it, for example:
public interface IContactPlugin
{
    bool Execute(string contactName);
}

Now your plugin can also reference the same library and becomes this:
namespace CreateContactPlugin
{
    public class Plugin : IContactPlugin
    {
        public bool Execute(string contactName)
        {
            //snip
        }
    }
}

And your calling code would now be this:
var assemblyLoaded = Assembly.LoadFile(absolutePath);
var type = assemblyLoaded.GetType("CreateContactPlugin.Plugin");

var instance = Activator.CreateInstance(type) as IContactPlugin;

if (instance == null)
{
    //That type wasn't an IContactPlugin, do something here...
}

instance.Execute("name of contact");

A: The problem is "static" of
static bool Execute(string contactName)

put it as
public bool Execute(string contactName)


text:
Q: Selenium Python Slow character speed is there a way to make my send key goes slower when it types the character.
Having a hard time to slowdown how fast it types.
I tried using Sleep method, but that doesn't work.
A('Starting up browser...')
e=l()
e.add_argument('disable-infobars')
B=k.Chrome(options=e)
B.implicitly_wait(5)
n=[0.02,0.04,0.03]
o=[F,J]
def f(word):
        A=word;A=list(A);C=[]
        for E in i(10):C.append([G(U),d.BACKSPACE])
        F=G(o)
        if F:
                I=G([1,2,3])
                for E in i(I):A.insert(G(i(j(A))),G(C))
                A=[C for B in A for C in B]
        D=B.find_element_by_css_selector('.selfTurn input')
        for J in A:K=G(n);D.send_keys(J);H(K)
        H(0.2);D.send_keys(d.ENTER)
A('Navigating to the JKLM website...')
B.get(m)
g=J

A: You can send keys to the element with action_chains send_keys method instead of using the selenium driver send_keys method.
I would show that on your code, but it appears to be too abnormal, so I will give you the general example.
You need to add import
from selenium.webdriver.common.action_chains import ActionChains

then to initialize the actions object with
actions = ActionChains(driver)

then to send text with actions to method located by .selfTurn input css_selector
element = driver.find_element_by_css_selector('.selfTurn input')
action.click(element)
action.send_keys("your_text")
action.perform()

A: I understand that you want to send keys like people typing because there is any detection if type speed is fast than normal, is right?
At selenium you can use send_keys, but there's no time interval arguments associated with type. See Selenium Document
So use custom send_keys with some edit like below.
def send_keys(self, *keys_to_send, time_interval):
    """
    Sends keys to current focused element.

    :Args:
     - keys_to_send: The keys to send.  Modifier keys constants can be found in the
       'Keys' class.
    """
    typing = keys_to_typing(keys_to_send)

    for key in typing:
        self.key_down(key)
        self.key_up(key)
        time.sleep(time_interval)  # what I insert to delay input time

    return self


text:
Q: Android - SMS Popup, wont open over itself I have made an app that opens a popup, everything is working fine getting the SMS content, sender name and picture.
When a SMS is received it opens a popup shows all the details. But if the popup is already open it wont open another popup showing the content of the second SMS.
The thing that bothers me alot is that, I have PreferenceActivity for this app. When this activity is open then the app is able to open multiple popups, else it doesnt.
I would like to ask
1. How can I make my app to open multiple popups?
2. Why is it when PreferenceActivity is open, the app can make multiple popups
Some details:
For case 1, log is NOT giving me any sort of warning or error.
I have tried to use  FLAG_ACTIVITY_NEW_TASK FLAG_ACTIVITY_NO_HISTORY FLAG_ACTIVITY_MULTIPLE_TASK and android:launchMode= "standard"
I have this AlertDialog in an activity, starting this activity from a broadcastreveiver
Thank you.

A: You are only allowed one popup window at a time and in this case you can treat Dialog like a Popup Window. I'm skeptical that you are able to see more than one popup window in your Preference Activity, but you may be seeing something that looks like it but isn't really more than one. This can be easily checked by using the hierarchy viewer to see what is actually layered.
If you want to have something like layered messages, like in a carousel, card edges, or use some other visual indication you would have use/build a custom view.


text:
Q: Download msv file in js We try to download msv file in js.
Our code:
var link = document.createElement("a");
                                   link.download = 'SampleReport.msv';
                                   link.href = "C:/Mcf/16-02-2016.msv";
                                   link.click();

But it doesn't work.What do we do wrong?
Thanks!


text:
Q: Generic way to convert String to Object I am implementing a Utility method that accept String as parameter and convert to object with generic. I can achieve with the code below but the weak point is every object that need to parse must have a string constructor. There is no way of defining that the object must have String constructor. Is there any other better way to achieve this by Using polymorphism or generic?
AAA.java
public class AAA {
    private String id;
    private String description;

    public AAA(String str) {
        // Do parsing...
    }

Utility method.
public static <T extends Base> List<T> readFile(File file, Class<T> type) {
    List<T> collection = new ArrayList<T>();
    // Read file line by line and convert to Instance

    Constructor<T> ctor = type.getConstructor(String.class);
    T newInstance = ctor.newInstance(line);
    if (newInstance != null) {
        collection.add(newInstance);
    }
    return collection;
}

Usage:
List<AAA> list = FileUtil.readFile(file, AAA.class);

A: I assume that your POJO classes (the one which actually contain the data) are usually in the format you have in your example. Meaning all the fields are String values. If this is not the case my solution needs a little bit of refinement.
My suggestion is to use reflection for the use case you describe. I have been very successful with this in the past. Although reflection can pose severe performance penalties if applied badly.
Parsing code could look roughly like the following. I omit a method header since the one you provide already looks good. The code I provide will assume that in the String[] variable line we find an already parsed line of your CSV file. Each element of the array containing one column of the CSV line.
String[] line; // initialised as explained above
T newInstance = T.newInstance(); // invoke default constructor
Field[] fields = newInstance.getClass().getDeclaredFields(); // use reflection to read all fields
int count = 0;
for(Fields f : fields) {
    f.set(newInstance, line[count]);
    count++;
}

Disclaimer: The above code does not do any boundary checks! The assumption is that the CSV lines and the number of fields in a class have the same length!
On the Field objects what I usually do is to also call getAnnotation to check whether or not a certain annotation is set on the field. This allows you to write classes like that:
public class AAAAnnotated {

    @MyCSVAnnotation
    String field1;

    @MyCSVAnnotation
    String field2;

    String field3;
}

If your code checks whether or not fields are annotated with your annotations you can even control in the POJO classes which fields to load form CSV and which to leave untouched.


text:
Q: Deleting a function defined in GHCI I'm starting to learn haskell and find myself having to restart the repl again and again because I defined incorrect specialization for a function and I don't know how to delete them.
For example, let's say I made the error of putting the base case of n == 0 after the general case for a factorial function:
fact n = n * fact(n-1)
fact 0 = 1

This is obviously wrong, now if I repeat the general case, it will be added to the current list, giving me 3 overloads for fact.
How do I delete the first case that I defined, or all the definitions of fact if possible. Is it possible to delete a function I defined in GHCI? If yes, how?

A: Prelude> fact n = n * fact (n-1)
Prelude> fact 0 = 1
Prelude> fact 3
*** Exception: <interactive>:6:1-10: Non-exhaustive patterns in function fact
Prelude> :q
Leaving GHCi.
bash> ghci
Prelude> fact 0 = 1
Prelude> fact n = n * fact (n-1)
Prelude> fact 3
*** Exception: stack overflow

What's going on?
With GHC, the first definition would result in a stack overflow, and the second one would be correct.
But in GHCi each binding shadows the previous one with the same name. In the example above, in each of the sessions each line that contains an equation for fact is a complete definition. When fact 3 is called, only the second line is in effect, and the first one is invisible.
So you cannot define functions the same way you do in normal GHC.
To define the factorial function correctly you can use one of these three methods.

*

*A braced definition with no layout.
Prelude> let { fact 0 = 1; fact n = n * fact(n-1) }

*A multiline definition with special GHCi braces.
Prelude> :{
Prelude| let fact 0 = 1
Prelude|     fact n = n * fact (n-1)
Prelude| :}

*A multiline definition with no special braces (needs :set +m which can be added to your ~/.ghci)
Prelude> let fact 0 = 1
Ptelude|     fact n = n * fact (n-1)
Prelude|
Prelude>

See the manual for more imformation.
Note I have used let in these definitions, because I'm used to them, but they are in fact not necessary in newer versions of GHCi.


text:
Q: Why do I see random ActionFailed after condition block in logic app Every so often I have ActionFailed. An action failed. No dependent actions succeeded. after condition block. This seems pretty random and goes away if I resubmit the run, as if there was some sort of race condition.
I know that an empty condition branch taken would cause a Skipped result and I know I can handle that by setting Configure run after to include Skipped (which for whatever stupid reason is not a default) but I've tried an alternative solution of putting a "no-op" block into empty branch (just a useless compose block) in order to always have success outcome going out of condition as seen below.
Is this because both branches of condition are actually executed in parallel and the not taken branch, if faster, will cause the outcome of condition to be skipped? It's a very counterintuitive behavior (like most of Flows sadly).

A:
Is this because both branches of condition are actually executed in parallel and the not taken branch, if faster, will cause the outcome of condition to be skipped

For the question above, I don't think it was caused by both branches of condition are actually executed in parallel because we can see the expression result of "Switch" action show with updated. The outcome of condition will not affect "Switch" action.
According to some test, the error may be related to the cases under the "Switch". If any case under "Switch" fails, it will show this error. So please check the cases under "Switch" action. As we can see the "Switch" spent 5 minutes, so please check if there is a case under "Switch" needs much time to do the job and failed with time out.


text:
Q: "Your project does not explicitly specify the CocoaPods master specs repo" warning when running pod install After I ran pod install, I got a warning that said:

[!] Your project does not explicitly specify the CocoaPods master specs repo. Since CDN is now used as the default, you may safely remove it from your repos directory via pod repo remove master.
To suppress this warning please add warn_for_unused_master_specs_repo => false to your Podfile.

Why did I get this warning? Previously, I was able to ran pod install without any warnings.
Here's another detail if that's helpful: I wasn't able to use sudo gem install to install/upgrade CocoaPods, so I used this command instead:
sudo gem install -n /usr/local/bin cocoapods

A: It has relation to this change which removes git repo and makes trunk default repository  I have solved the problem by listing repos pod repo list and then removing master using the command pod repo remove leaving only trunk

A: Run the command pod repo remove master

A: You should now use the CocoaPods CDN as the default source:
source 'https://cdn.cocoapods.org/'

and if so, you can safely delete the master repo from your machine, with the suggested command pod repo remove master.
Original Answer
I resolved this warning by adding a source to the top of my Podfile:
source 'https://github.com/CocoaPods/Specs.git'

A: When running the 'pod repo remove master' I was greeted with:
[!] repo master does not exist

I did a ....
pod repo list

cocoapods
- Type: git (master)
- URL:  https://github.com/CocoaPods/Specs.git
- Path: /Users/plasma/.cocoapods/repos/cocoapods

trunk
- Type: CDN
- URL:  https://cdn.cocoapods.org/
- Path: /Users/plasma/.cocoapods/repos/trunk

Noticed the 'master' is actually called 'cocoapods' so then I did a..
pod repo remove cocoapods

One that had completed I was able to do update and install without any errors.

A: I would recommend following Plasma's answer. However, if you don't want to delete the master repo, just mute the warning by adding the warn_for_unused_master_specs_repo setting to your Podfile by changing this:
install! 'cocoapods'

to this:
install! 'cocoapods', :warn_for_unused_master_specs_repo => false

If you already have an option after install! 'cocoapods', append the new setting with a comma:
install! 'cocoapods', :deterministic_uuids => false, :warn_for_unused_master_specs_repo => false

A: If you have the error:
[!] repo master does not exist

It's will work if you try this:
pod repo remove cocoapods

Don't worry it's will not remove your pods :)

A: # pod version > 1.7.2
# Step 1
pod repo list

# pod repo list result:
# cocoapods
# - Type: git (remotes/origin/master)
# - URL:  https://github.com/CocoaPods/Specs.git
# - Path: /Users/apple/.cocoapods/repos/cocoapods

# trunk
# - Type: CDN
# - URL:  https://cdn.cocoapods.org/
# - Path: /Users/apple/.cocoapods/repos/trunk

# Step 2
pod repo remove cocoapods

# result
# Removing spec repo `cocoapods`

It's working for me.


text:
Q: The coordinate system of ARKit unstable I load a model in the AR environment and add an ARAnchor to stabilize the model. When I place the device on the desktop and picked up later. The model's position is not changed, but it will fly away soon. The coordinate system of ARKit will fly and be unstable.
How to avoid or deal with this situation

A:
ARKit/RealityKit world tracking system is based on a combination of five sensors:

*

*Rear RGB Camera

*LiDAR Scanner

*Gyroscope

*Accelerometer

*Magnetometer

Three latter ones are known as Inertial Measurement Unit (IMU) that operates at 1000 fps. But what sees your RGB Camera (running at 60 fps) and LiDAR (also at 60 fps) is very important too.
Hence, a stability of world tracking greatly depends on camera image.

Here are some recommendations for high-quality tracking:

*

*Track only well-lit environment (if you don't have LiDAR)

*Track only static objects (not moving)

*Don't track poor-textured surfaces like white walls (if you don't have LiDAR)

*Don't track surfaces with repetitive texture pattern (like Polka Dots)

*Don't track mirrors, chrome and glass objects (reflective and refractive)

*Move your iPhone slowly when tracking

*Don't shake iPhone when tracking

*Track as much environment as possible

*Track high-contrast objects in environment (if you don't have LiDAR)

If you follow these recommendations, coordinate system in ARKit will be stable.
And look at the picture in this SO post – there are a good example for tracking and a bad one.


text:
Q: no visualiza valor correcto de campo booleano en flask-wtform Hice un simple abm con flask wtform y sqalchemy (sqlite3). Los datos en la base me los almacena bien, pero al momento de visualizar un registro existente, en la vista me muestra todo, salvo los campos booleanos, que me los muestra como false y en realidad en la base tiene un valor true. Si me pueden ayudar desde ya lo agradezco porque esto no me deja avanzar.
En el form lo defini así
class FormOt(FlaskForm):
 ...
    internet_adsl = BooleanField('Internet Adsl', default=False)
 ...

En la base de datos el campo esta definido así
 ...
    internet_adsl = db.Column(db.Boolean, default=False)
 ...

Desde ya muchas gracias

A: por suerte pude solucionarlo. Comparto solución por si a alguno le sirve, ya que hace tiempo que vengo lidiando con esto.
En la vista, cuando valido si el campo del form es booleano, pregunto si el valor del campo es 1 o 0, dependiendo de esto en la mascara paso checked=True o checked=False
Copio macro resumida, en donde se compara la parte booleana
{% if field.type == 'BooleanField' %}
    {% if field() == 1 %}

            {{ field(checked=True, class='form-check-input') }}
            {{ field.label.text|safe }}

    {% else %}

            {{ field(checked=False, class='form-check-input') }}
            {{ field.label.text|safe }}

    {% endif %}

Saludos


text:
Q: Can a vector boson carry cosmic acceleration? Clifton, Ferreira, Padilla and Skordis discuss ghosts arising from dark energy:

To get cosmic acceleration we need an additional repulsive force to
  act between massive objects at large distances. If this force is to be
  mediated by a particle of even spin, such as a scalar (spin 0) or a
  tensor (spin 2), then the kinetic term describing this must have the
  "wrong" sign, that is, it must be a ghost.

Is there any reason a spin-1 boson cannot mediate dark energy? (Note that the carrier need not match the cosmological parameter's spin, as $\Lambda$ being a scalar does not preclude spin-2 mediation of cosmic acceleration.)


text:
Q: About embedded firmware development In the past few days I found how important is RTOS layer on the top of the embedded hardware.
My question is :
Is there any bifurcation between device driver (written in C directly burned over the microcontroller)
And the Linux Device driver ?

A: This question is a little broad, but an answer, a little broad itself, can be given.
The broadness comes from the fact that "embedded hardware" is not a precise term. That hardware ranges from 4 bit microcontrollers, or 8 pins ones, up to big CPUs which have many points in common with typical processors used tipically on linux machines (desktop and servers). Linux itself can be tailored up to the point it does not resemble a normal operating system anymore.
Anyway, a few things, generally acceptable, can be the following. Linux is not, in its "plain" version, a real time operating system - with the term RTOS instead, the "real time" part is implied. So, this can be one bifurcation. But the most important thing, I think, is that embedded firmware tries to address the hardware and the task to be done without anything else added. Linux O.S. instead is general purpose - it means that it offers a lot of services and functionalities that, in many cases, are not needed and only give more cost, less performances, more complication.
Often, in a small or medium embedded system, there is not even a "driver": the hardware and the application talk directly to each other. Of course, when the hardware is (more or less) standard (like a USB port, a ethernet controller, a serial port), the programming framework can provide ready-to-use software that sometimes is called "driver" - but very often it is not a driver, but simply a library with a set of functions to initialize the device, and exchange data. The application uses those library routines to directly manage the device. The O.S. layer is not present or, if the programmer wants to use an RTOS, he must check that there are no problems.
A Linux driver is not targeted to the application, but to the kernel. And the application seldom talks to the driver - it uses instead a uniform language (tipically "file system idiom") to talk to the kernel, which in turns calls the driver on behalf of the application.
A simple example I know very well is a serial port. Under Linux you open a file (may be /dev/ttyS0), use some IOCTL and alike to set it up, and then start to read and write to the file. You don't even care that there is a driver in the middle, and the driver was written without knowledge of the application - the driver only interacts with the kernel.
In many embedded cases instead, you set up the serial port writing directly to the hardware registers; you then write two interrupt routines which read and write to the serial port, getting and putting data from/into ram buffers. The application reads and writes data directly to those buffers. Special events (or not so special ones) can be signaled directly from the interrupt handlers to the application. Sometimes I implement the serial protocol (checksum, packets, sequences) directly in the interrupt routine. It is faster, and simpler, and uses less resources. But clearly this piece of software is no more a "driver" in the common sense.
Hope this answer explains at least a part of the whole picture, which is very large.


text:
Q: Reverse engineering algebra question - why is it not working? So I have the curve $y=(x-4)(x-2)(x+1) = x^3 -5x^2 + 2x + 8$.
Note here $\int_{-1}^0 y dx = \frac{61}{20}$.
The question I propose to create is as follows:

A curve has the equation $y=f(x)$, where $f(x) = x^3 + ax^2 + bx + 8$, where $a, b$ are constants. The curve meets the $x$ axis at $(-1, 0)$ and the integral $\int_{-1}^0 f(x) dx = \frac{61}{20}$.

If all checks out, they should get $a=-5$ and $b=2$.
But this is not the case.
$(-1, 0)$ being a point on the curve gives $b-a = 7$.
The integral condition gives $a/3 - b/2 + 47/10 = 0$.
These two simultaneous equations do not give $a=-5$ and $b=2$.
What is going on here?

A: Your integral is wrong. $\int_{-1}^0f(x)dx=\frac{61}{12}$, not $\frac{61}{20}$. Therefore, the second equation should actually be $\frac{a}{3}-\frac{b}{2}=-\frac{32}{12}$, which does indeed give $a=-5$ and $b=2$.


text:
Q: Is binding to 0.0.0.0 in Java guaranteed to bind to all network interfaces? I've found empirically that
Endpoint endpoint1 = Endpoint.create(new Ping());
endpoint1.publish("http://0.0.0.0:8080/ws/ping");

binds to all network interfaces on the current computer (instead of just localhost - 127.0.0.1 or the hostname), but I have not been able to locate the documentation which says that this is guaranteed.
Question:  Where is it defined that binding to 0.0.0.0 in Java will always bind to all network interfaces?

A: It has nothing to do with Java. 0.0.0.0 is INADDR_ANY, which is is a special address that is guaranteed to receive from any  network interface by the C sockets API, which is called by Java.

A: It seems to be a special reserved IP address of sorts. This link probably has more information Is 0.0.0.0 a valid IP address?. So I suspect it is not documented in Java as it is more related to the actual network specification.
And as some others have mentioned it appears that it is the Chuck Norris IP address :D
HTH

A: Using 0.0.0.0 will only bind to IPv4-enabled interfaces. However, if you bind to ::, that should cover all IPv4 and IPv6 interfaces, assuming your TCP/IP stack (and Java) have IPv4-compatible IPv6 sockets enabled.
You'll need to look to the kernel (or socket libraries, if you're on Windows) for an explanation of "why". On my OS X system, the man pages explain it.
From man 4 inet`:

Sockets may be created with the local address INADDR_ANY to effect
'wildcard' matching on incoming messages.  The address in a connect(2)
or sendto(2) call may be given as INADDR_ANY to mean 'this host'.  The
distinguished address INADDR_BROADCAST is allowed as a shorthand for the
broadcast address on the primary network if the first network configured
supports broadcast.

From man 4 inet6:

Sockets may be created with the local address :: (which is equal to
IPv6 address 0:0:0:0:0:0:0:0) to affect 'wildcard' matching on incoming
messages.


text:
Q: Customize login page of ASP.NET web page without Visual Studio How can I create a new scaffold item with terminal commands, without using visual studio? I would need it for the same reason requested here:
Customize Login Page design for Authentication type : Individual User account ASP.NET core 2.1, MVC, c#
but finding myself on linux I can only use dotnet commands. Thank you

A: Run the following commands in your project directory
dotnet tool install -g dotnet-aspnet-codegenerator
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet restore

after that

Run the following command to list the Identity scaffolder options:

dotnet aspnet-codegenerator identity -h

In the project folder, run the Identity scaffolder with the options you want. For example, to setup identity with the default UI and the minimum number of files, run the following command. Use the correct fully qualified name for your DB context:

dotnet aspnet-codegenerator identity -dc MyApplication.Data.ApplicationDbContext --files "Account.Register;Account.Login"

More information can be found at Microsoft Docs


text:
Q: What are the permutation matrices that satisfy $P^2 = I$? I am struggling to come up with a "general" answer to this question. I found a permutation matrix $$P = \begin{bmatrix} 0 & 1 & 0 \\ 1 & 0 & 0 \\ 0 & 0 & 1 \end{bmatrix}$$ where its square is equal to the identity matrix. But how would I generalize this?

A: The proper question should be what permutations $\sigma$ satisfy $\sigma^2=1$. And the answer is those with $1$-cycles and $2$-cycles. Translating this into permutation matrices, the answer should be the matrices $P$ that are obtaine from the identity matrix by swapping some pairs of rows.


text:
Q: How can I route my angular child pages without error? I cannot route my angular child pages.
Please help me to solve this. I have attached my routing module down BELOW FOR more details.
its submodule of app.module
import { NgModule } from '@angular/core';
  import { Routes, RouterModule } from '@angular/router';
     import { BillingSetupComponent } from './Setup/billing-setup/billing-setup.component';
     import { NewBillingMasterComponent } from './Master Billing/new-billing-master/new-billing-
              master.component';
  import { NewBillingSubMasterComponent } from './Master Billing/new-billing-sub-master/new-billing-
   sub-master.component';

      export const routes: Routes = [
         {
         path: '', component: BillingSetupComponent,

      children: [

    { path: 'Setup', component: BillingSetupComponent },
    { path: 'Master', component: NewBillingMasterComponent },
    { path: 'SubMaster', component: NewBillingSubMasterComponent },

           ]
         }
          ]

         @NgModule({
            imports: [RouterModule.forChild(routes)],
          exports: [RouterModule]
             })

             export class ConfigurationRoutingModule { }

A: Your config only work when there a router-outlet in BillingSetupComponent. We cannot help you to find the problem with your code posted. Please provide more code or you can check example for child route here:
https://stackblitz.com/edit/angular-routing-child-routes?file=app%2Fapp-routing.module.ts

A: try to delete export from this line export const routes: Routes and add path before children like my example that worked for me


text:
Q: Replace string between "variabletext[" and "]" with javascript I'm trying to build an html form that generates structured JSON code from the input values. This form uses repeat fields.
I have to modify name attributes in cloned fields.
In Javascript I have a string 'menu-item[0][offers][0][price]'.
I would like to replace 'menu-item[0]' with 'menu-item[1]', as in example at http://regexr.com/3gpnt
I'm using RegExp, but is not required.
This is my experiment, but it doesn't work.
var string = 'menu-item[0][offers][price]';
var itemName = 'menu-item';
var regExp = new RegExp(itemName + '\[(.*?)\]', "");
var newString = string.replace(regExp, itemName + '[1]');
console.log(newString);
alert(newString);

Returns 'menu-item[0][offers][price]'.
Test on jsfiddle https://jsfiddle.net/lorenzodetomasi/dmnd7f9L/
Thank you.


text:
Q: Ubuntu 11.10 Oneiric Low Disk Space I started to receive "Low Disk Space" message on my Ubuntu Oneiric 11.04 few days ago.
With GParted I see that my /dev/sda1 where is system is only 1,17 Gb! and this is obviously not enough. I have 3 more (needed) partitions with enough space and about 28 Gb of unalocated disk space on this phisical disk.
Now I can't turn on terminal with root privileges "Failed to run /usr/bin/x-terminal-emulator as user root." anymore because linux is "Unable to copy the user's Xauthorization file".
Question is: Can I increase my /dev/sda1 by adding this unallocated space and how to do this?
Preffered with GParted if possible.
I try to do this by myself but unsuccessfuly. This partition is of ntfs type and here is also system files for windows booting what I choose with grub at startup.
I am not linux guru so please explanation on "simple way".
Edit
The output of df -T is:

Filesystem    Type   1K-blocks      Used Available Use% Mounted on
/dev/sda7     ext4   113036984 107296076         0 100% /
udev      devtmpfs     1987968         4   1987964   1% /dev
tmpfs        tmpfs      798356      1184    797172   1% /run
none         tmpfs        5120         0      5120   0% /run/lock
none         tmpfs     1995888      3736   1992152   1% /run/shm
/dev/sda3  fuseblk    16383996   9103384   7280612  56% /media/sda3
/dev/sdc1     vfat   312492320  49250336 263241984  16% /media/usb0

Additionally, this thead is not duplicate of any other thread in ask ubuntu!
Sorry, I am new here and dont know with this forum yet!
I emptyed trash already!
Then get some more access to my root... thank you!
But I see GParted LiveCD is for x86 machines.
Forgot to say I use 64bit machine and OS.
Is this OK for me?
Sure, I get useful and nice answers here and I will vote as soon I register.
Someone put me here automatically from "stack-overflow" and I am forbidden to give votes unregistered. Sorry.

A: *

*To gain access to the root-reserved space, change the size from 5% to 0,5%. As you are not on a server, it won't hurt anybody.
sudo tune2fs -m 0.5 /dev/sda7

*Resize with an ubuntu liveCD/liveUSB or with Gparted LiveCD. It can move, shrink, grow partitions. But keep in mind, that you must one task at a time (eg. first shrink, then move ...).

A: You can empty the Trash. Open Nautilus, go to Trash and choose "Empty Trash".

A: You have 113036984 1K blocks in /dev/sda7 and this makes around 100 G if I'm not too rusty in math. You are out of disk space, however that's not because your root file system is too small. 100 G should be sufficient for a standart installation where you do not store much stuff.
You can do some partition magic with gparted to enlarge /dev/sda7 (not /dev/sda1 !!!) However I believe you can just clean up some space. Most probably you do not want to store 100 G data, since it seems you are not aware of it.


text:
Q: How to apply Tailwind UI animation in plain HTML/JS I am trying to use sample tailwindui.com components.
They have the animation part defined in the comments, but I am not able to make out how I should those in my code. I am using plain html/js and would prefer to not use any framework/lib for this.
Here I am trying to show/hide a modal dialog.
The animation doe for the background overlay is given as

I have no idea how to encode this information to the background overlay div.

Here is what I have tried so far;

<button class="border border-red-500" onclick="toggleModal()">Toggle modal</button>

            <svg class="h-6 w-6 text-red-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>

Deactivate account

Are you sure you want to deactivate your account? All of your data will be permanently removed. This action cannot be undone.

        <button onclick="toggleModal()" type="button" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm">Deactivate</button>
        <button onclick="toggleModal()" type="button" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">Cancel</button>

I have put the same in a codepen for the ease of testing.
https://codepen.io/rishavs/pen/BadMQaN?editors=1000

A: i`m using jquery on a legacy php project, perhaps you could get the idea from that.
First add an id to slide-over-title, and suggested animations.

then create simple "toggle" function to use anywhere
function toggleSlider() {
    if($("#slide-over-title").hasClass("translate-x-full")) {
    $("#slide-over-title").removeClass("translate-x-full");
    $("#slide-over-title").addClass("translate-x-0");
    } else  {
    $("#slide-over-title").addClass("translate-x-full");
    $("#slide-over-title").removeClass("translate-x-0");
    }
}

On the snippet i am using the tailwind cdn, but for production you should use the tailwind preprocesor or cli to generate an optimized css file

function toggleSlider() {
        if($("#slide-over-title").hasClass("translate-x-full")) {
        $("#slide-over-title").removeClass("translate-x-full");
        $("#slide-over-title").addClass("translate-x-0");
        } else  {
        $("#slide-over-title").addClass("translate-x-full");
        $("#slide-over-title").removeClass("translate-x-0");
        }
    }
<button onclick="toggleSlider()">Toggle Slider</button>

Panel title

                <button type="button" class="rounded-md bg-white text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2" onclick="toggleSlider()">
                  Close panel

                  <svg class="h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>

A: The easiest way to apply the transition effects without using Vue/React on tailwindui is to use Alpine.js, as explained in the docs:

If you want to write it by yourself, then you need to make sure that you first change the display (block/hidden) then you need to wait a frame before you apply the actual transition class. This is required, as changing the status from display:none to display:block does not trigger css transition animations (see Transitions on the CSS display property). Also you need to make sure that you hide your element after the transition has taken place (so ona duration-200 class, you would need to wait 200ms). Otherwise it would be hidden immediately without transition animation.
You could use "visibility" instead of "display", but that would not be a good option for the module, as the background goes over your entire page and makes other buttons unclickable.
To wait one frame before next repaint, you may use the window.requestAnimationFrame() method. Another possibility to implement it is using the setTimeout method, as done at https://stackoverflow.com/a/40447192
I actually found a github repository which implements only this x-transition from alpine with the aim to be used for tailwind-ui transitions https://github.com/CaptainCodeman/x-transition and its ~1kb gzipped, but alpine.js is ~7kb gzipped with a ton of other functionality, so I think it makes sense to go directly with alpine.js
In addition, when you implement it by your own, or use alpine.js, you still need to make sure that you meet the wai aria practices.


text:
Q: How do I remove an invitation request notification? I'm using FB.ui({method: 'apprequests', ... }) to invite a user but when the user accepts and logs into the app, the app icon still has a little red 1 on it.  How do I remove this notification or even get a list of notifications?  I've tried querying the graph explorer with manage_notifications permissions but I always end up with an empty data array.
I'd like to do as much as possible using the graph API and php if that's an option.

A: This is covered thoroughily in the requests documentation. You would just need to issue a HTTP DELETE command to https://graph.facebook.com/requestID?access_token=...  The id's come as part of the querystring when the user clicks on the notification: https://apps.facebook.com/[app_name]/?request_ids=[request_ids]


text:
Q: How prove this polynomials inequality Let $f=a_0x^n+a_1x^{n-1}+\ldots+a_{n-1}x+a_n\in \mathbb{R}[X]$ a polynomial which has the roots contained in $(-1,1)$. Prove that:
$$\left|\frac{a_1+a_3+a_5+\ldots}{a_0+a_2+a_4+\ldots}\right|<1$$
Thank you .

A: Without loss of generality I will assume $a_0 > 0$.  Let $p = a_1 + a_3 + \dotsc$ and $q = a_0 + a_2 +\dotsc$.  If $n$ is even then
$$0 < f(-1) = q - p$$
$$0 < f(1) = q + p$$
and combining these equations we get $q > 0$ and $\left|\tfrac{p}{q}\right|<1$.  If $n$ is odd then
$$0 < -f(-1) = q - p$$
$$0 < f(1) = q + p$$
and again $q > 0$ and $\left|\tfrac{p}{q}\right| < 1$.


text:
Q: dojo1.8 - populate dijit/select with data from mysql Hi how do I populate the records from gathertests.php into dijit/select?
I do not think that I should use innerHTML as that would build not the dijit/select. Maybe I should use the function. But how?
request.post('gathertests.php',{
    data:{testx : selectX.value},
}).then
    {
    function(response){   dom.byId('line4').innerHTML=response;
},
function(error){
    alert(error);
});

Please advise
Thanks
Clement

A: Create dojo/store/Memory or ideally dojo/store/JsonRest and assign the store to the dijit/Select.
Do not manipulate the DOM directly, mutate data in dojo/store (i.e. the model), dijits observe it and update the DOM accordingly.
Please see my answer to Dojo declarative vs. programmatic creation of Select elements with stores and the related jsFiddle.
Bonus: a bit more complex example: http://jsfiddle.net/phusick/N8DqG/


text:
Q: Ember uglify breaks rainbow.js I am trying to add rainbow code samples to my ember project. I installed rainbow through bower and it works locally. However when I build and deploy to staging I am getting JS console errors.

As far as I can tell this is the minified version of this. It appears to me that for some reason the Prism class is not being included when it is minified. I am importing
    'rainbow/dist/rainbow.min.js',
    'rainbow/src/language/generic.js',
    'rainbow/src/language/r.js',
    'rainbow/src/language/python.js',
    'rainbow/src/language/json.js',
    'rainbow/src/language/html.js'

in my ember-cli-build.js using
bowerDependencies.forEach(function(path) { app.import(app.bowerDirectory + '/' + path); });.
If I build with minify off it works wonderfully, but I would like to minify the JS. I am currently at a loss of why these files are not being included.

A: Use ./rainbow/dist/rainbow.min.js for al the file inclusion.
Refer :
https://github.com/ember-cli/ember-cli/issues/6829


text:
Q: No math.h include - sqrt function return value? i have following C code:
#include <stdio.h>

main()
{
    double wurzelZwei;
    wurzelZwei = sqrt(2.0);
    printf("Wurzel 2: %lf\n", wurzelZwei);
}

Why is the return value of sqrt "1073742463" and the compiler/linker does only show a warning and no fatal error when the "math.h" libary is not included?

A: In C89 and earlier it is allowed to call a function that has not been declared. When doing so, that function is assumed to have return type int. This is called an implicit declaration.
When you call a function that way, but it has been defined with a return type other than int, you invoke undefined behavior just as if you had explicitly declared the function with a different return type than you defined it with.
So in your case what happens is that you implicitly declare sqrt with the default return type int, so the return value you get from sqrt is (falsely) interpreted as an int and that int is then converted to double when you store it in wurzelZwei.


text:
Q: Are these in passives? I learned English autodidactically by reading books , watching movies , video games , etc.... But, there are some things in english that confused me , such as passive forms. What's the difference between 'x cannot be stolen' and 'x cannot be steal'? . Are both in passive forms and have the same meaning ?

A: Only the first one is grammatically correct. The second one has no meaning. When something is stolen, it means that someone has stolen it. So, to answer your question, the first one is in passive form.


text:
Q: Cannot find libxml2 in android ndk project Good day Everyone. I have wasted almost a week now figuring what's wrong when i try adding libxml2 to my android ndk project.
 LOCAL_PATH     := $(call my-dir)
    #BUILDING LIBXML2
     include $(CLEAR_VARS)
LOCAL_MODULE := xml2
LOCAL_SRC_FILES :=  $(LOCAL_PATH)/libxml2/libxml2.a
LOCAL_C_INCLUDES := $(LOCAL_PATH)/libxml2/include
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/libxml2/include
LOCAL_DISABLE_FORMAT_STRING_CHECKS := true
include $(BUILD_SHARED_LIBRARY)
#BUILDING SOME SPICE CODES
include $(CLEAR_VARS)

LIB_PATH := $(LOCAL_PATH)/../../libs/armeabi

SPICE_CLIENT_ANDROID_DEPS   := $(LOCAL_PATH)/../libs/deps

spice_objs := \
                   $(SPICE_CLIENT_ANDROID_DEPS)/lib/libssl.a \
                   $(SPICE_CLIENT_ANDROID_DEPS)/lib/libcrypto.a \
                   $(SPICE_CLIENT_ANDROID_DEPS)/lib/libcelt051.a

LOCAL_MODULE    := spice

LOCAL_SRC_FILES := channel-record.c channel-playback.c channel-cursor.c \
                   spice-cmdline.c coroutine_gthread.c spice-util.c \
                   spice-session.c spice-channel.c spice-marshal.c spice-glib-enums.c \
                   common/generated_client_demarshallers.c common/generated_client_demarshallers1.c \
                   common/generated_client_marshallers.c common/generated_client_marshallers1.c \
                   gio-coroutine.c channel-base.c channel-main.c spice-proxy.c bio-gsocket.c glib-compat.c \
                   channel-display.c channel-display-mjpeg.c channel-inputs.c decode-glz.c \
                   decode-jpeg.c decode-zlib.c wocky-http-proxy.c channel-port.c spice-client.c spice-audio.c \
                   common/mem.c common/marshaller.c common/canvas_utils.c common/backtrace.c \
                   common/sw_canvas.c common/pixman_utils.c common/lines.c common/rop3.c common/quic.c \
                   common/lz.c common/region.c common/ssl_verify.c common/log.c spice-gstaudio.c

LOCAL_LDLIBS    += $(spice_objs) \
                   -ljnigraphics -llog -ldl -lstdc++ -lz -lc \
                   -malign-double -malign-loops
LOCAL_LDLIBS    += -L$(LIB_PATH) -lgstreamer_android

LOCAL_CPPFLAGS  += -DG_LOG_DOMAIN=\"GSpice\" \
                   -DSW_CANVAS_CACHE \
                   -DSPICE_GTK_LOCALEDIR=\"/usr/local/share/locale\" \
                   -DHAVE_CONFIG_H -UHAVE_SYS_SHM_H -DSW_CANVAS_CACHE  \
                   -D_REENTRANT -DWITH_GSTAUDIO

LOCAL_C_INCLUDES += $(LOCAL_PATH)/common \
                    $(SPICE_CLIENT_ANDROID_DEPS)/include

LOCAL_CFLAGS    :=  $(LOCAL_CPPFLAGS) \
                   -std=gnu99 -Wall -Wno-sign-compare -Wno-deprecated-declarations -Wl,--no-undefined \
                   -fPIC -DPIC -O3 -funroll-loops -ffast-math

LOCAL_EXPORT_CFLAGS += $(LOCAL_CFLAGS)
LOCAL_EXPORT_LDLIBS += $(LOCAL_LDLIBS)
LOCAL_SHARED_LIBRARIES := gstreamer_android
LOCAL_ARM_MODE := arm
include $(BUILD_STATIC_LIBRARY)
#BUILDING SOME MINE C CODE   --------Here i add Mine C file and xml2 for it
include $(CLEAR_VARS)
LOCAL_MODULE    := start-spice
LOCAL_SRC_FILES := start-spice.c
LOCAL_SHARED_LIBRARIES= xml2
include $(BUILD_SHARED_LIBRARY)
#BUILDING SPICE ANDROID
include $(CLEAR_VARS)
LOCAL_MODULE    := spice-android
LOCAL_SRC_FILES := android/android-service.c android/android-spicy.c android/android-spice-widget.c \
                   android/android-io.c
LOCAL_STATIC_LIBRARIES := spice
include $(BUILD_SHARED_LIBRARY)
include $(CLEAR_VARS)
ifndef GSTREAMER_SDK_ROOT
ifndef GSTREAMER_SDK_ROOT_ANDROID
$(error GSTREAMER_SDK_ROOT_ANDROID is not defined!)
endif
GSTREAMER_SDK_ROOT        := $(GSTREAMER_SDK_ROOT_ANDROID)
endif
GSTREAMER_NDK_BUILD_PATH  := $(GSTREAMER_SDK_ROOT)/share/gst-android/ndk-build/
include $(GSTREAMER_NDK_BUILD_PATH)/plugins.mk
GSTREAMER_PLUGINS         := $(GSTREAMER_PLUGINS_CORE) $(GSTREAMER_PLUGINS_SYS) jpeg
GSTREAMER_EXTRA_DEPS      := glib-2.0 gthread-2.0 pixman-1 gstreamer-app-0.10

include $(GSTREAMER_NDK_BUILD_PATH)/gstreamer.mk

So even after I add xml2.so as shared library to my project - nothing happens. It strill cannot find libs  and gives me tons of this
[armeabi] SharedLibrary  : libstart-spice.so
/opt/android-ndk-r9c/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: /opt/Test6/bVNC/eclipse_projects/bVNC/obj/local/armeabi/objs/start-spice/start-spice.o: in function create_request:/opt/Test6/bVNC/eclipse_projects/bVNC/jni/src/start-spice.c:251: error: undefined reference to 'xmlNewDoc'
/opt/android-ndk-r9c/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: /opt/Test6/bVNC/eclipse_projects/bVNC/obj/local/armeabi/objs/start-spice/start-spice.o: in function create_request:/opt/Test6/bVNC/eclipse_projects/bVNC/jni/src/start-spice.c:252: error: undefined reference to 'xmlNewNode'
/opt/android-ndk-r9c/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: /opt/Test6/bVNC/eclipse_projects/bVNC/obj/local/armeabi/objs/start-spice/start-spice.o: in function create_request:/opt/Test6/bVNC/eclipse_projects/bVNC/jni/src/start-spice.c:253: error: undefined reference to 'xmlNodeSetContent'
/opt/android-ndk-r9c/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: /opt/Test6/bVNC/eclipse_projects/bVNC/obj/local/armeabi/objs/start-spice/start-spice.o: in function create_request:/opt/Test6/bVNC/eclipse_projects/bVNC/jni/src/start-spice.c:254: error: undefined reference to 'xmlDocSetRootElement'
/opt/android-ndk-r9c/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: /opt/Test6/bVNC/eclipse_projects/bVNC/obj/local/armeabi/objs/start-spice/start-spice.o: in function create_request:/opt/Test6/bVNC/eclipse_projects/bVNC/jni/src/start-spice.c:255: error: undefined reference to 'xmlDocDumpFormatMemory'
/opt/android-ndk-r9c/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: /opt/Test6/bVNC/eclipse_projects/bVNC/obj/local/armeabi/objs/start-spice/start-spice.o: in function create_request:/opt/Test6/bVNC/eclipse_projects/bVNC/jni/src/start-spice.c:256: error: undefined reference to 'xmlFreeDoc'
/opt/android-ndk-r9c/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: /opt/Test6/bVNC/eclipse_projects/bVNC/obj/local/armeabi/objs/start-spice/start-spice.o: in function Java_com_iiordanov_bVNC_NativeCalls_getPortAndPassword:/opt/Test6/bVNC/eclipse_projects/bVNC/jni/src/start-spice.c:144: error: undefined reference to 'xmlReadMemory'
/opt/android-ndk-r9c/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: /opt/Test6/bVNC/eclipse_projects/bVNC/obj/local/armeabi/objs/start-spice/start-spice.o: in function Java_com_iiordanov_bVNC_NativeCalls_getPortAndPassword:/opt/Test6/bVNC/eclipse_projects/bVNC/jni/src/start-spice.c:153: error: undefined reference to 'xmlDocGetRootElement'
/opt/android-ndk-r9c/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: /opt/Test6/bVNC/eclipse_projects/bVNC/obj/local/armeabi/objs/start-spice/start-spice.o: in function Java_com_iiordanov_bVNC_NativeCalls_getPortAndPassword:/opt/Test6/bVNC/eclipse_projects/bVNC/jni/src/start-spice.c:163: error: undefined reference to 'xmlHasProp'
/opt/android-ndk-r9c/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: /opt/Test6/bVNC/eclipse_projects/bVNC/obj/local/armeabi/objs/start-spice/start-spice.o: in function Java_com_iiordanov_bVNC_NativeCalls_getPortAndPassword:/opt/Test6/bVNC/eclipse_projects/bVNC/jni/src/start-spice.c:170: error: undefined reference to 'xmlHasProp'
/opt/android-ndk-r9c/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: /opt/Test6/bVNC/eclipse_projects/bVNC/obj/local/armeabi/objs/start-spice/start-spice.o: in function Java_com_iiordanov_bVNC_NativeCalls_getPortAndPassword:/opt/Test6/bVNC/eclipse_projects/bVNC/jni/src/start-spice.c:172: error: undefined reference to 'xmlGetProp'
/opt/android-ndk-r9c/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: /opt/Test6/bVNC/eclipse_projects/bVNC/obj/local/armeabi/objs/start-spice/start-spice.o: in function Java_com_iiordanov_bVNC_NativeCalls_getPortAndPassword:/opt/Test6/bVNC/eclipse_projects/bVNC/jni/src/start-spice.c:182: error: undefined reference to 'xmlHasProp'
/opt/android-ndk-r9c/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: /opt/Test6/bVNC/eclipse_projects/bVNC/obj/local/armeabi/objs/start-spice/start-spice.o: in function Java_com_iiordanov_bVNC_NativeCalls_getPortAndPassword:/opt/Test6/bVNC/eclipse_projects/bVNC/jni/src/start-spice.c:184: error: undefined reference to 'xmlGetProp'
/opt/android-ndk-r9c/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: /opt/Test6/bVNC/eclipse_projects/bVNC/obj/local/armeabi/objs/start-spice/start-spice.o: in function Java_com_iiordanov_bVNC_NativeCalls_getPortAndPassword:/opt/Test6/bVNC/eclipse_projects/bVNC/jni/src/start-spice.c:221: error: undefined reference to 'xmlFreeDoc'
/opt/android-ndk-r9c/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: /opt/Test6/bVNC/eclipse_projects/bVNC/obj/local/armeabi/objs/start-spice/start-spice.o: in function Java_com_iiordanov_bVNC_NativeCalls_getPortAndPassword:/opt/Test6/bVNC/eclipse_projects/bVNC/jni/src/start-spice.c:234: error: undefined reference to 'xmlFreeDoc'
collect2: ld returned 1 exit status
make: *** [/opt/Test6/bVNC/eclipse_projects/bVNC/obj/local/armeabi/libstart-spice.so] Error 1

С code header in start-spice looks something like this:
#include <jni.h>
#include <android/log.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <libxml/parser.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <libxml/parser.h>
#include <libxml/tree.h>

And i in java code i add:
 static
    {
       System.loadLibrary("start-spice");
    }

Would be really really gratefull if someone helped!

A: If you have the prebuilt static library for Android in $(LOCAL_PATH)/libxml2/libxml2.a, you can use it as is in your spice-android project,
LOCAL_STATIC_LIBRARIES += xml2

Instead of include $(BUILD_SHARED_LIBRARY) for xml2, use
LOCAL_SRC_FILES :=  libxml2/libxml2.a
include $(PREBUILT_STATIC_LIBRARY)

If you have a strong reason to use xml2 as a separate shared library, you need to add call
System.loadLibrary("xml2");

to your Java code (before loading libspice-android.so) and replace LOCAL_SRC_FILES :=  $(LOCAL_PATH)/libxml2/libxml2.a with
LOCAL_WHOLE_STATIC_LIBRARIES :=  $(LOCAL_PATH)/libxml2/libxml2.a

A: This is issue of linking shared libraries, you need to add LOCAL_LDLIBS += $(LIB_PATH) -lxm2 just before LOCAL_SHARED_LIBRARIES= xml2 .


text:
Q: Cannot convert byte to byte[] I tried to make a function to get a string but didn't actually worked. Please notice I'm not good at c#
static byte[] getString(byte testok)
{
   return UTF8Encoding.UTF8.GetString(testok);
}

What I'm actually trying to do:
https://prnt.sc/uvfs53

A: You are convert TO string, so need the function to return a String. Also - ReadAllBytes returns a byte array (byte[]) not a single byte, so you also need to change that in the parameters. This should work:
static String getString(byte[] testok)
{
   return UTF8Encoding.UTF8.GetString(testok);
}


text:
Q: Color a list of 2D points continuously I have a list of 3-tuples. First 2 positions are coordinates in $R^2$, the third specifies concentration of a chemical at that point, which I want to render in color.  Here's what the list looks like:
list={{0.1, 0.1, 0.000100686}, {0.1, 0.2, 0.000139706}, {0.1, 0.3,0.000158851}... {0.2, 0.1, 0.000149521}...{4,4,0.00151234}}

I've tried
 BubbleChart[list, ColorFunction -> (Hue[#3] &)]

Which doesn't look all that bad, but I was thinking of something more smooth that blends over values continuously.
For example, Mathematica interpolates (I guess) over a list of points for ListPlot3D to give you a (hopefully) smooth surface, as opposed to ListPointPlot3D where the points are explicitly shown, I'm looking for the equivalent of that in color.
Any help is appreciated!

A: I would do something like the following:
    ListDensityPlot[list, PlotLegends->True, ColorFunction->"Rainbow"]


text:
Q: por que no se modifica el array inicial con este programa? estaba haciendo un programa en el que parto de un array random y quiero modificar ese array.pero cuando corro el siguiente programa,mi array de arranque no cambia.
B=np.random.randn(4,4,10)

N=4
J=4
T=10

for t in range (T-1):
for i in range (N-1):
    for j in range (J-1):
        B[i,j,t+1]=B[i,j,t]-( B[i+1,j,t]+B[i,j+1,t] -2*B[i,j,t]-2*B[i,j,t]+B[i-1,j,t]+B[i,j-1,t] )

print(B)

alguna idea? grcias!


text:
Q: how to unmount a function in useEffect (react js) test function dose not unmount and wen i click on correectAnswer the last function (test) is steal running and again test function will run and then when the last test function achieve to 0 we go to loser page.
const [state, setState] = useState({
    haveTime: 10
})

const [states] = useState({
    correct: "question",
    step: "loser"
})

const test = (timer) => {
    let haveTime = 10
    let time = setInterval(() => {
        haveTime -= 1;
        setState({ haveTime })
        // console.log(state.haveTime)
    }, 1000);
    setTimeout(() => {
        clearInterval(time)
        dispatch(getNameStep(states.step))
    }, timer);
}

const correectAnswer = () => {
    if (index === 9) {
        dispatch(getNameStep(stateForWinner.step))
    }
    else {
        dispatch({
            type: "indexIncrease"
        })
        test(10000)
    }

}

let { question, correct_answer } = details.question[index];

useEffect(() => {
    test(10000)
}, [])

A: There are a few things wrong with your code.
First you are combining setInterval with setTimeout which is not a good idea just because of the amount of coordination that needs to happen.
Second to clear an interval or a timeout you need to do it from within the useEffect by returning a function.
Third you have no "dependencies" in your useEffect.
Look at this code that use in one my apps:
 useEffect(() => {
    const delayDebounceFn = setTimeout(() => {
        SetSearchFilter(SearchLocal, State.Reversed);
    }, 250)

    // this is how you clear a timeout from within a use effect
    // by returning a function that does the disposing
    return () => clearTimeout(delayDebounceFn);
}, [SearchLocal]);//here you need to add the actual dependencies of your useEffect

Lastly you need to breakdown your useEffect to perform a "single effect". Combining "too much stuff" into a single use effect is not good because then it is very difficult to debug and to achieve what you want.
You need to break down your useEffect into smaller useEffects.
You need to tell the useEffect when you want it to run by adding the dependencies.  This way you know that a particular useEffect will run for ecxample if the "nextStep" has changed or if the test has reached the end.


text:
Q: Socket.IO Scoping Issue (Node.JS) I am working on a node.js project that I am leveraging Socket.IO in, and am having an issue getting my head around a scoping issue. Here is what I am trying to do:
var io = require('socket.io').listen(80);
session_manager = require('./includes/session_manager');

// client joins the socket server
io.sockets.on('connection', function(client) {
    client.on('X.Session.join', function(session_id, client) {
        session_manager.joinSession(session_id, function(err, session) {
            // do whatever
        });
    });
    // BRING IN MORE LISTENERS/EMITTERS?
    require('someModuleIBuild');
});

As you can see I am basically setting up the initial connection, joining a session via a managing class (so I know who to emit to for which session) and then I am trying to dynamically bring in some custom stuff that ALSO is going to be emitting and listening via the socket connection.
So how do I reference this current connection from within the confines of my custom modules? All the examples I have seen have all the "on" and "emit" functions in one file, which seems like it could get out of control pretty quickly.
I am possibly over-thinking/over-complicating this (this is my first node.js project, first socket-based project, first mostly-javascript project....etc) but any help would be appreciated.

A: create your modules like this and you can pass the client into the module
module.exports = function(client) {
    client.on("whatever", function () {

    });

    client.on("whenever", function (data) {

    });
};

and then do the require like this
require('someModuleIBuild')(client);


text:
Q: Unexpected T_ELSE error in PHP I am working on an example from a php book and am getting an error on line 8 with this code
<?php

$agent = getenv("HTTP_USER_AGENT");
if (preg_match("/MSIE/i", "$agent"));
{
    $result = "You are using Microsoft Internet Explorer";
}
else if (preg_match("/Mozilla/i", "$agent"));
{
    $result = "You are using Mozilla firefox";
}
else {$result = "you are using $agent"; }

echo $result;

?>

A: Try:
$agent = getenv("HTTP_USER_AGENT");
if (preg_match("/MSIE/i", $agent)) {
  $result = "You are using Microsoft Internet Explorer";
} else if (preg_match("/Mozilla/i", $agent)) {
  $result = "You are using Mozilla firefox";
} else {
  $result = "you are using $agent";
}

echo $result;

Two things:

*

*You had a semi-colon at the end of your if clauses. That means the subsequent opening brace was a local block that is always executed. That caused a problem because later you had an else statement that wasn't attached to an if statement; and

*Doing "$agent" is unnecessary and not recommended. Simply pass in $agent.

A: remove the semi-colons from the end of the lines with "if" in them.

A: There are ; at the end of if statements.
Cause of error:
if(...) ;
{
...
}

Will not cause any syntax error as the body of if is empty and the following block always gets executed. But
if(...) ;
{
  // blk A
} else {
...
}

will cause Unexpected else syntax error because the if as before has empty body and is followed by another block blk A which is not if's body. Now when an else if found after the block it cannot be matched with any if causing this error. The same would happen if we'd statement(s) in place of a block:
if(...) ;
 do_something;
else {
...
}

A: Why do you have a semicolon here? if (preg_match("/MSIE/i", "$agent")); and here else if (preg_match("/Mozilla/i", "$agent"));


text:
Q: Automatically click segmentControl with index 0 on ViewDidAppear I am hoping to "automate" a click on the segmentController with the index of 0.
My tabBar-based app has multiple segmentControllers in a tab in the ViewDidAppear method, I would like to automatically have it "click" the first segmented controller.
if (segmentController.selectedSegmentIndex == 0) {
    //stuff here
}

if (segmentController.selectedSegmentIndex == 1) {
    //stuff here
}

Does anyone know how I might accomplish this? Thank you!

A: Set the selectedSegmentIndex property on your UISegmentedControl in your viewDidAppear (or viewDidLoad) method.
self.segmentedController.selectedSegemntIndex = 1;
UISegmentedControl Reference

A: If you're creating it programmatically, you could lazy load it like this:
@interface ExampleViewController : UIViewController
@property (nonatomic, strong) UISegmentedControl *segmentedControl;
- (void)segmentedControlClicked:(UISegmentedControl *)segmentedControl;
@end

@implementation ExampleViewController

- (UISegmentedControl *)segmentedControl
{
    if (!_segmentedControl)
    {
        NSArray *items = @[@"First", @"Second", @"Third"];
        _segmentedControl = [[UISegmentedControl alloc] initWithItems:items];
        [_segmentedControl addTarget:self
                           action:@selector(segmentedControlClicked:)
                           forControlEvents:UIControlEventValueChanged];

        [_segmentedControl setSelectedSegmentIndex:0];   // Set Default selection

        CGRect frame = _segmentedControl.frame;
        frame.origin = CGPointMake(0.0f, 0.0f);     // Move to wherever you need it
        [self.view addSubview:_segmentedControl];
    }
    return _segmentedControl;
}

- (void)segmentedControlClicked:(UISegmentedControl *)segmentedControl
{

    // Whatever your code is goes here...

}
@end

If you're wanting a method to be called also initially, you can call it within your viewDidLoad: method as such:
- (void)viewDidLoad
{
    [self.segmentedControl setSelectedSegmentIndex:0];  // Set desired default index (optional if set in lazy load as shown above)
    [self segmentedControlClicked:self.segmentedControl];
}

This would hence simulate a click on desired default index.
Be careful putting the above into viewDidAppear: (you could if you really wanted to) because anytime the view comes to the front, this method will be called (in example, if this view controller presents a modal view controller, once the modal is dismissed, this view controller's viewDidAppear: method will be called).
Cheers!


text:
Q: Laptop stuck at boot menu screen My lenovo laptop is stuck at boot menu. On starting the laptop the boot menu loads up and shows various boot options but on selecting a particular option , the boot menu load again .
How can this be fixed ?

A: It would seem to me that the boot process is unable to find a bootable partition.  If you plug in a bootable USB disk (eg Linux rescue disk), does it boot off that?
If you are certain there is a useable OS on the hard drive, you may want to go into BIOS and toggle between UEFI and MBR booting.


text:
Q: Can I know the best way to render template Client side Vs Server side using Express? And performance? It's getting difficult day by day to choose server side Vs client side rendering, can some one post ur thoughts or references on this??
Which one will give better performance ??

A: *

*Bandwidth:  In my mind, the less data you have to push to the client the faster everything will seem to your users, assuming that you've scaled the server-side appropriately.  This tends to suggest server-side rendering.

*Security:  I tend to "keep my cards close to my chest" when playing poker and in design terms that means that the less API you expose to the browser's View -> Source, the better, IMHO.  Again, I like to render things on the server if I can.

*Third-party:  If I'm exercising a well-known third-party API like Google Maps then it doesn't matter to me if I'm doing that client- or server-side with the exception of exposing a Google API key, for example.  There may be some advantages to pushing this client-side when Google is tracking the hits-per-second or whatever; you'd be using the client's IP address instead of your own.

*Moving Target:  If you're pushing a lot of code to the browser, to include modules, then you can never guarantee what browser the client will have.  What's to prevent a new browser version from coming out tomorrow?  How will your new stack work on that until you've tested it?  Server-side, I control that platform, usually at least.

In a nutshell, I do server when I can.  AngularJS is pretty cool, though.  Things may change up as a result of it.  That's my take on it.


text:
Q: Documentum xCP - Failed to start webby at port 8888 I am using xCPDesigner 2.1 in order to build Documentum xCP 2.1 application. It seems that it uses Maven Eclipse m2e-webby plugin.
I am unable to start Preview mode. Nothing happens within UI of the designer. In logs I can find
ERROR [TWorker-4] [internal.com.emc.xcp.builder.ui.util.PreviewStartJob:115] Failed to start webby at port 8888
org.eclipse.core.runtime.CoreException: Exception occurred executing command line.
    at org.eclipse.debug.core.DebugPlugin.exec(DebugPlugin.java:842)
    at org.eclipse.jdt.launching.AbstractVMRunner.exec(AbstractVMRunner.java:86)
    at org.eclipse.jdt.internal.launching.StandardVMRunner.run(StandardVMRunner.java:323)
    at org.sonatype.m2e.webby.internal.launch.WebbyLaunchDelegate.launchEmbedded(WebbyLaunchDelegate.java:310)
    at org.sonatype.m2e.webby.internal.launch.WebbyLaunchDelegate.launch(WebbyLaunchDelegate.java:157)
    at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:855)
    at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:704)
    at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:697)
    at internal.com.emc.xcp.builder.ui.util.PreviewStartJob.startWebby(PreviewStartJob.java:107)
    at internal.com.emc.xcp.builder.ui.util.PreviewStartJob.run(PreviewStartJob.java:45)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
Caused by: java.io.IOException: Cannot run program "C:\XCPDocumentum\xCPDesigner\jre\bin\javaw.exe" (in directory "C:\XCPDocumentum\xCPDesigner\Applications\test_two\test_two\target\m2e-webby"): CreateProcess error=206, The filename or extension is too long
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:460)
    at java.lang.Runtime.exec(Runtime.java:593)
    at org.eclipse.debug.core.DebugPlugin.exec(DebugPlugin.java:838)
    ... 10 more
Caused by: java.io.IOException: CreateProcess error=206, The filename or extension is too long
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(ProcessImpl.java:81)
    at java.lang.ProcessImpl.start(ProcessImpl.java:30)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:453)
    ... 12 more

There is some discussion in support forum but with no updates for a month now.
I don't have any experience with this plugin.
Any clue with configuration options for this plugin and hints with this specific error message is highly appreciated.

A: I migrated xCPDesigner to another environment and I didn't face this issue. Environment is pretty much the same, OS is Win 7. EMC /o\

A: The issue is due to a bug when handling non-English Windows operating systems.
Make sure that English is set as the language for your operating system in the regional settings. Afterwards, restart your operating system and try again.
This issue is reproducible when setting the language to Turkish as per my tests.

A: I think, The problem with lengthy directory, so move forward your xCP designer, this might be the solution. simply D:/xCPdesigner , also try to give short names to any artifacts


text:
Q: How to enter a fraction in formula editor of Word? How can I enter the following fraction in Word for Mac (with the keyboard, clicking twice every time I need it is obviously not a solution)?

A: In Word 2010 for PC while in an equation you can just type 1/2 and it should convert it to a fraction. Other notable shortcuts include x^n for xn and x_n for xn.
Here's a more elaborate list of such shortcuts.

turns into

This should be the same for World for Mac 2011!


text:
Q: how to start page-scraping technique I'm new to page scraping, and i don't know where to start.
What is easiest way to do page scraping? What are your opinions for that, what web technologies are best for that?
Can anyone help me, thanks.

A: Look into html aglity pack;
Example:
Well, it depends. If, for example, one tag has a class and it is unique- it is one function, but if there are multiple tags, you need to think and create your function based on tag location, another situation when there are no tags and you would have to count html elements; you might also need to loop over tabe rows for example.
Example below does similar what you need. (not sure if it still works, since if there was a change in the page layout, it might fail.) But it gives the idea and you can go from there.
PS - when asking questions please give exact problem, not the vague question.
C# Example:
                String openUrl = @"http://www.ebay.com/sch/-/11724/i.html?_nkw=" + some_part_number + "&_armrs=1&LH_Complete=1";

                HtmlWeb hw = new HtmlWeb();
                hw.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
                HtmlAgilityPack.HtmlDocument doc = hw.Load(openUrl);

                foreach (HtmlNode nd in doc.DocumentNode.SelectNodes("//tr[@itemprop='offers']"))
                {
                    String title = "";
                    title = Regex.Split(nd.InnerHtml.ToString(), ("title='"))[1].Trim();
                    title = Regex.Split(title, "'")[0].Trim();
                }

A: Well probably best and easiset way would be with yahoo query language YQL.
It's simple to use. U can also use yahoo pipes with yql. Google it.
You can begin here:
http://ijaar.com/basic-yql-tutorials/
Also there are some question about screen scraping here on stack so check it out.
And yes, yql is not the only technique for that, you can also use php, xquery, even python for that, but in my opinion it's the easiest - and it works really fine.


text:
Q: looping through object property names in actionscript I have a dynamic class that I have created
public dynamic class SiteZoneFileUploadVO
{
    public var destination:String = "sitezone";
    public var siteZoneId:uint;
    public var fileType:String;
    public var fileContents:String;

    public function SiteZoneFileUploadVO()
    {
    }

}

when I try to iterate over this object's property names it only iterates the dynamically added properties.
        parameters.dynVar= "value";

        for(var name:String in parameters)
        {
            trace(name);
        }

Even though the object has all the properties equal to a value (ive checked this in the debugger) the only property name that will be traced is dynVar.
How can I iterate over all the property names and not just the dynamically added ones?

A: You can use describeType() to get an XML with all methods and variables of your class and then filter out the properties you want to iterate over (e.g. all variables) and store them in an XMLList.
As the next step you would then iterate over the XMLList and use square bracket notation on your object to access the filtered properties by their names. However, you can only access public properties this way because describeType() won't look at private properties.

A: If you're running flex:
Looked at a few posts, ObjectUtil.toString was the most promising, then looked at the flex source code for it, it uses another method ObjectUtil.getClassInfo which is exactly what you need. If you just want property names:
ObjectUtil.getClassInfo(myClass).properties

returns an Array of QName objects, each has a localName property which will give you a string for each property name

A: Just use trace(ObjectUtil.toString(parameters)); That should give you your entire object.


text:
Q: Proof for a prime number equation Let x and n be positive integers such that $$1 + x + x^2 + x^3 ... + x^{n-1}$$ is a prime number. Then show that n is a prime number.
So I have summed up the GP and equated it to y which is a prime number. I have no clue how I should proceed forward. Can you please help me out ?

A: Say $n=ab$ where $a,b>1$. Since $$1 + x + x^2 + x^3 ... + x^{n-1} ={x^n-1\over x-1}$$
$$={x^{ab}-1\over x-1}={(x^a-1)((x^a)^{b-1}+...(x^a)^2+x^a+1)\over x-1}$$
$$ = \underbrace{(x^{a-1}+...+x^2+x+1)}_{>1}\cdot \underbrace{((x^a)^{b-1}+...(x^a)^2+x^a+1)}_{>1}$$
a contradiction.

A: Hint: Show that if $n$ is not a prime, the expression can be factored. For instance, for $n=4$, we have
$$
1+x+x^2+x^3=(1+x^2)(1+x)
$$
(It may be easier to show that $x^n-1$ can be factored differently than $(x-1)(1+x+\cdots+x^{n-1})$)


text:
Q: Не работает конструктор в yii2 Добрый день! Есть стандартный класс для авторизации User. В нём мне надо сделать так, чтобы данные о пользователях брались из баз данных. Прописал следующий код:
    use app\models\GetUsers;

    class User extends \yii\base\BaseObject implements
    \yii\web\IdentityInterface
   {
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
//public $usersArray = GetUsers::getUsersArray();

private static $users; //= User::$usersArray;

public function __construct(){
    User::$users = GetUsers::getUsersArray();
    var_dump(User::$users);

}

Здесь я написал конструктор, чтобы свойству $users присваивался массив, который берётся из отдельной модели GetUsers. Далее ничего не менял. В результате выдаётся ошибка Invalid argument supplied for foreach(). Попробовал вывести свойство $users через var_dump - пишет NULL, то есть конструктор не работает, следовательно, пустое свойство отдаётся foreach - в результате ошибка. При этом массив из модели GetUsers однозначно получается (Проверял через var_dump). Где ошибка? Я только начинаю изучать yii2, поэтому прошу не кидать помидоры.


text:
Q: Update TWiki or Migrate to Foswiki? In my company, we have a big old TWiki portal. The installed version is 4.1.1 from 2007. And we want to update it now, but our problem is:
Should we update to the a newer TWiki version or, instead, migrate to Foswiki?
Our concerns are:

*

*Today, they are equivalent in features?

*Which one will do better in the future?

A: 1 - It's quite difficult to feel the difference in features for basic
installations of both TWiki and Foswiki. I'd say that they are the
same.
Also Foswiki already have included compatibility level for stuff
migrating from TWiki such as plugins, etc.
2 - As per news from official Foswiki blog, the most active
contributors have joined Foswiki already. All my recent wiki
installations based on Foswiki and I'm quite happy with them. Let it
be the way I support Foswiki community.
Read the Foswiki documentation - it should help you to make the right
decision.
Good luck!

A: I've upgraded 7 TWiki installations to Foswiki.
As of now (November 2009) it looks as if about 200 bugs are present in TWiki
which have been fixed in Foswiki.  Not surprising as Foswiki now has about 15
active developers -- to 1.5 for TWiki after the great corporate lockout.
So the featureset is currently with Foswiki -- and the future is clearly with them.
Besides, the switchover is no more difficult than doing a version-to-version
upgrade (they are the same codebase).  And the new Foswiki way of doing future
upgrades is a snap.  Unpack a special tarball and you're done.  After previous
painful TWiki upgrades, it's a snap (they copied this technique, by the way,
recently-- but who knows how long they'll be around to keep it up -- or if
they'll ever find the manpower or community to make the backlog of bugs go down).
Big companies are switching or have switched.  Yahoo, which has the world's largest TWiki installation, has a hiring opportunity open for a Foswiki developer to spearhead their migration and continued customization.  Why Foswiki?  Because that's where the features and bugfixes are coming from -- it's the only active community driving innovation.


text:
Q: How can I set the image to move at the given speed? I have an image of a man that moves in x-axis. Now I want to move the man with its corresponding speed of 5 meter/s with delta time which is in nanoseconds and that is my problem. Could you give me some idea on how to do it?
Any help would be much appreciated...
Here's the code :
public class Board extends Canvas

{
 public double meter;//PIXEL

private final java.util.List<Sprite> sprites = new ArrayList<Sprite>();

private final java.util.List<Sprite> z_sorted_sprites = new ArrayList<Sprite>();

private BufferStrategy strategy;

int x0_pixel;
int y0_pixel;

int x1_pixel;
int y1_pixel;

double x1_world;
double y1_world;

public Board(double meter)
{
    this.setIgnoreRepaint(true);

    this.meter = meter;

    init();

    addComponentListener(new ComponentAdapter()
    {
        @Override
        public void componentResized(ComponentEvent e)
        {
            render();
        }
    });
}
public void init()
{
    HumanBeing humanBeing = new HumanBeing(this, 2, 2, 0);

           sprites.add(humanBeing);

    z_sorted_sprites.add(humanBeing);
       }

@Override
public void paint(Graphics g)
{
}

public void render()
{
    setupStrategy();

    x0_pixel = 0;
    y0_pixel = 0;

    x1_pixel = getWidth();
    y1_pixel = getHeight();

    x1_world = x1_pixel / meter;
    y1_world = y1_pixel / meter;

    Graphics2D g2d = (Graphics2D) strategy.getDrawGraphics();

    g2d.setBackground(Color.lightGray);
    g2d.clearRect(0, 0, x1_pixel, y1_pixel);

    g2d.setColor(Color.BLACK);

    for (double x = 0; x < x1_world; x++)
    {
        for (double y = 0; y < y1_world; y++)
        {
            int xx = convertToPixelX(x);
            int yy = convertToPixelY(y);

            g2d.drawOval(xx, yy, 2, 2);
        }
    }

    for (Sprite z_sorted_sprite : z_sorted_sprites)
    {
        z_sorted_sprite.render(g2d);
    }

    g2d.dispose();
    strategy.show();

    Toolkit.getDefaultToolkit().sync();
}

public int convertToPixelX(double distance)
{
    return (int) (distance * meter);
}

public int convertToPixelY(double y_world)
{
    return (int) (y1_pixel - (y_world * meter));
}

public void onZoomUpdated(int value)
{
    meter = value;
    render();
}

private void setupStrategy()
{
    if (strategy == null)
    {
        this.createBufferStrategy(2);
        strategy = this.getBufferStrategy();
    }
}

public void start() throws InterruptedException
{
    long previousTime = System.nanoTime();

    while (true)
    {
        long now = System.nanoTime();
        long dt = now - previousTime;

        for (Sprite sprite : sprites)
        {
            sprite.move(0);
        }
        render();

        Thread.sleep(1);
        previousTime = now;

    }
 }
}

for Human Class
public class HumanBeing extends Sprite  implements ImageObserver
{
private java.awt.Image humanImage;
private final Board board;
private double x;

private double y;

private int speed;

private java.util.List<Sprite> objects = new ArrayList<Sprite>();
private int cImage;

public HumanBeing(Board board, int x, int y, int speed)
{
    this.board = board;

    this.x = x;
    this.y = y;
    this.speed = speed;

    URL iU = this.getClass().getResource("human.jpg");
    ImageIcon icon = new ImageIcon(iU);
    humanImage = icon.getImage();

    objects.add(this);

}
public Image getImage()
{
    return humanImage;
}

@Override
public void move(long ns)
{
    x += 0.001;

}

@Override
public void render(Graphics2D g2d)
{
    AffineTransform t = g2d.getTransform();

    final double humanHeight = 1.6;// meter
    final double humanWidth = 1.8;  //meter

    final double foot_position_x = humanHeight / 2;
    final double foot_position_y = humanWidth;

    int xx = board.convertToPixelX(x - foot_position_x); // to find the upper-left corner
    int yy = board.convertToPixelY(y + foot_position_y); // to find the upper-left corner

    g2d.translate(xx, yy);

    // ratio for actual Image size

    double x_expected_pixels = humanHeight * board.meter;
    double y_expected_pixels = humanWidth * board.meter;

    double w = ((ToolkitImage) humanImage).getWidth();
    double h = ((ToolkitImage) humanImage).getHeight();

    double x_s = x_expected_pixels / w;
    double y_s = y_expected_pixels / h;

    g2d.scale(x_s, y_s);

    g2d.drawImage(getImage(), 0, 0, this); // upper left corner

    g2d.setColor(Color.BLACK);

    g2d.setTransform(t);
}
@Override
public void moveAt(double distance_x, double distance_y)
{
    this.x = distance_x;
    this.y = distance_y;
}

@Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height)
{
    return false;
}
}

A: Here's an idea for architecting your solution.  I'm going to assume you have figured out how many pixels the image has to move every second to be the speed you want.  Let's say that for your game or simulation, that means 10 pixels every second.  You have a starting location and an ending location.  So you know when you need to move the image.  Use the class ScheduledThreadPoolExecutor and its method scheduleWithFixedRate to set up a periodic update of your image's position, issuing a call to draw the image once every second, at an updated location.  Remember that your call to position your image could be delayed briefly as the Swing thread is servicing other GUI requests.  But your scheduled thread is not affected.  Say the scheduled thread says to Swing to put your image at position x and time 1.0 seconds.  In fact, Swing gets to it a touch later at time 1.1 seconds.  But you don't want that delta to screw up your timing.  It doesn't because scheduleWithFixedRate will issue the next Swing call at the correct time 2.0 seconds, not at 2.1 seconds.  The second image update is at exactly the right spot at the right time (or close enough depending on how busy the GUI thread is).


text:
Q: Ajax cross application on same machine I have 2 applications running on the same machine:

*

*node.js app running on port 15000

*a full javascript application running on port 15001

Both are served through nginx front end (each app defined as a virtual host)
Ajax requests from the javascript app (requesting resources from the node.js app) are not working.
Is this linked to restriction of Ajax for cross domain ? The domain is the same (only the port are differents).
Any idea ?

A: Different ports are seen as a different domains.
MDC Same Origin Policy

A: Yes, limiting requests on same domain to different port
Same origin policy
https://developer.mozilla.org/en/Same_origin_policy_for_JavaScript
http://en.wikipedia.org/wiki/Same_origin_policy


text:
Q: Is there a command to flag and clean different messages that have the same translation in a po file? Is there a command to flag and clean different messages that have the same translation in a GetText po file ?
#: templates/translations.html:7161
msgid "Straightedges"
msgstr "Règles de précision"

#: templates/translations.html:11697
msgid "Straight hemostats"
msgstr "Règles de précision"

Is there a way to wipe all the translations in that case ?

A: You can use the following Perl script for that task:
#! /usr/bin/env perl

use strict;

use Locale::PO;

die "usage: $0 POFILE\n" unless $ARGV[0];

binmode 'STDOUT', ':utf8';
my $entries = Locale::PO->load_file_asarray($ARGV[0], 'UTF-8')
    or die "$ARGV[0]: $!\n";

my %seen;

foreach my $entry (@$entries) {
    ++$seen{$entry->dequote($entry->msgstr)};
}
foreach my $entry (@$entries) {
    my $msgstr = $entry->dequote($entry->msgstr);
    #next if $seen{$msgstr} > 1;
    $entry->msgstr("") if $seen{$msgstr} > 1;
    print $entry->dump;
}

You need the Perl library Locale-PO for that.  You can install it with one the command sudo perl -MCPAN -e 'install Locale::PO'. Omit the sudo if you don't need it.
If you really want to delete the entries with duplicate translations, then uncomment the line with next.  My version just discards the translation which is most probably what you really want.
The solution oversimplifies a little bit. It does not support entries with plural forms or message contexts but you probably don't need them anyway.


text:
Q: Problems with $_POST["var"] in Yii Controller i am having problems with $_POST["var"] on controller. It seems to be empty. How can i receive the string being typed on my textFiled?
View
<?php Yii::app()->clientScript->registerCoreScript("jquery"); ?>
                <script type="text/javascript">
                $(document).ready(function(){
                        $("#hhmm").change(function(){
                        $.ajax({
                      url: "<?php echo CController::createUrl('reqTest01Loading'); ?>",
                                data: $(this).serialize(),
                                type: "post",
                                dataType: "json",
                                success: function(data) {
                                      if (data.status === 'failure') {
                                            $('#impatto').val('Error request failed.');
                                         } else {
                                                 $("#impatto").html(data.total);
                                         }

                                }
                        });
                        });

                });
                </script>

Controller
public function actionReqTest01Loading() {

    $result = array("total" => $_POST['hhmm'], "status"=>"OK");
            echo CJSON::encode($result);
}

rules on Controller
array('allow',  // allow all users to perform 'index' and 'view' actions
            'actions'=>array('reqTest01Loading','index','view','admin'),
            'users'=>array('@'),
        ),

thanks in advance

A: This is because you dont tell ajax call to send parameters.
Try:
    $.ajax({
    url: "<?php echo CController::createUrl('reqTest01Loading'); ?>",
       data: {data:$(this).serialize()},
       type: "post",
       dataType: "json",
       success: function(data) {
           if (data.status === 'failure') {
              $('#impatto').val('Error request failed.');
           } else {
              $("#impatto").html(data.total);
           }

        }
   });

And it controller:
public function actionReqTest01Loading() {
    // var_dump(Yii::app()->request->getPost('data'));
    $result = array("total" => Yii::app()->request->getPost('data'), "status"=>"OK");
    echo CJSON::encode($result);
}


text:
Q: .hgignore doesn't work I created .hgignore file, but before that I sent project structure to server. Now hgignore doesn't work for those files which was sent earlier. I read somewhere that I need to remove those files and dirs from tracking list or add it in some "private" way but I cannot figure out how I need to do that. Problem is even more complicated because I wrote sh script which is copying part of this structure to other place (project consists of some client apps and www server, those server files are being copied to other place after each hg push command). So I want to ignore some files (but want that those files exists on server, just pushed once with some configuration) and I want to copy those ignored files with my sh script (the most important thing in this script is fact that I am using 'hg archive' to handle what I want to copy). I hope this is understandable for someone:)

A: .hgignore only ignores files that haven't been added to the repository yet.  Use hg forget to stop tracking an already added file.
You can't check in a file and ignore changes afterward.  For configuration files, a best practice is to check in a template file, and ignore the actual local configuration file.  Someone pulling the repo can then copy the template file and make their local changes.  You sh script could automate that.

A: Basically, Mark Tolonen already said everything important in his answer.
I just wanted to add an example for this part of his answer:

For configuration files, a best practice is to check in a template file, and ignore the actual local configuration file.  Someone pulling the repo can then copy the template file and make their local changes.  You sh script could automate that.

I answered a similar question some time ago with a detailed example:
how to ignore files in kiln/mercurial using tortoise hg "that are part of the repository"
My answer is for Visual Studio though (which you apparently don't use, according to the questions you've asked until now), but it can help you to get the basic idea, so you should be able to adopt it easily to any other environment.


text:
Q: How can use SSIS to run command delete with bind variable in Vertica target I tried to use SSIS to transfer CDC data from SQL Server to Vertica.
but I'm stuck at the step for delete data on target.
For SQL server --> SQL Server : when the source sent date for delete or update, I will use "OLE DB Command" to run delete from targetTB where ID=? first then insert the row update.
but when I tried to change target to Vertica, It cannot use "OLE DB Command".
So I tried to  use the "Execute SQL Task" to select the ID from the update rows and keep result in the Full Resultset. Then use another "Execute SQL Task" for use command  delete from targetTB where ID=? but I'm not sure how to mapping the parameter with the resultset. it error about the variable type.
Could anyone advise me the solution that I can send sql command to the Vertica database.
Thank you

A: I would avoid firing UPDATE/DELETE/INSERT commands with single rows .
I would rather build a staging table with the same structure, and then, for example:
MERGE /*+DIRECT*/
INTO d_cust_scd t
USING stg_d_cust_scd s
  ON s.cust_key=t.cust_key
WHEN MATCHED THEN UPDATE SET
  cust_key     = s.cust_key
, cust_id      = s.cust_id
, cust_from_dt = s.cust_from_dt
, cust_to_dt   = s.cust_to_dt
, cust_is_curr = s.cust_is_curr
, cust_cre_ts  = s.cust_cre_ts
, cust_udt_ts  = s.cust_udt_ts
, cust_fname   = s.cust_fname
, cust_lname   = s.cust_lname
, cust_phoneno = s.cust_phoneno
, cust_loy_lvl = s.cust_loy_lvl
, cust_org_id  = s.cust_org_id
WHEN NOT MATCHED THEN INSERT (
  cust_key
, cust_id
, cust_from_dt
, cust_to_dt
, cust_is_curr
, cust_cre_ts
, cust_udt_ts
, cust_fname
, cust_lname
, cust_phoneno
, cust_loy_lvl
, cust_org_id
) VALUES (
  s.cust_key
, s.cust_id
, s.cust_from_dt
, s.cust_to_dt
, s.cust_is_curr
, s.cust_cre_ts
, s.cust_udt_ts
, s.cust_fname
, s.cust_lname
, s.cust_phoneno
, s.cust_loy_lvl
, s.cust_org_id
);