text:
Q: Time domain representation of a waveform from an accelerating source (doppler effect) Consider the scenario where a stationary observer observes a source moving in 3 dimensions, emitting a signal $s(t)$.  I would assume only the distance between the source and the observer, $x(t)$, has any effect on the frequency scaling.
The only thing I have ever learned (or been able to find online) is the frequency scaling equation $f=(1+\frac{\Delta v}{c})f_0$.  Is there a more general formulation that, using $s(t)$ and $x(t)$, would allow me to model the signal recieved at the observer?
I would imagine that a model exists for radar, but I haven't been able to find it.  I expect it can be solved with the Fourier transform but I don't know where to begin.

A:
I would assume only the distance between the source and the observer, $x(t)$, has any effect on the frequency scaling.

Wave Dispersion
There are multiple effects that matter here if the medium is dispersive (i.e., the wave frequency depends upon the wave number or another way of stating this is that the phase speed depends upon the wave frequency and/or wavenumber).  For the example of radar, the Earth's atmosphere is not dispersive until one reaches large altitudes (i.e., few to several 10s of km) and only for specific ranges of frequencies.  So we can ignore dispersion for the moment.
Time of Flight
Since the observer is at a finite distance, $\mathbf{x}\left(t\right)$, from the reflecting object that is moving at a velocity, $\mathbf{v}\left(t\right)$, relative to the observer, one may naively expect that some signals would arrive at different times than others.  Since radar is a free mode of electromagnetic radiation, mostly radio waves, and the medium is not dispersive nor ionized, all frequencies propagate at the same speed, the speed of light, $c$.  If you are far away from the reflecting object (i.e., $\lvert \mathbf{x}\left(t\right) \rvert \gg L$, where $L$ is the size of the reflecting object), then there should be no noticeable time of flight effects.  Meaning, you should not receive frequency one at a different time than frequency two since they both share the same propagation distance.
Doppler Effect
The effect that can give you information about the objects velocity is known as the Doppler effect, which is mathematically defined as (assuming a constant source frequency/wavenumber):
$$
\omega_{obs}\left(t\right) = \gamma \left( \omega_{src} + \mathbf{k}_{src} \cdot \mathbf{v}\left(t\right) \right) \tag{1}
$$
where $\omega_{obs(src)}$ is the frequency in the observer's(source's) rest frame, $\mathbf{k}_{src}$ is the wavenumber of the source, $\gamma$ is the relativistic Lorentz factor (one can assume $\gamma \approx 1$ for most cases in Earth's atmosphere), and $\mathbf{v}\left(t\right)$ is the velocity of the source relative to the observer.  Note that $\mathbf{k}_{src}$ and $\mathbf{v}\left(t\right)$ are both represented here as 3-vectors, not scalars.
Answer

Is there a more general formulation that, using $s(t)$ and $x(t)$, would allow me to model the signal recieved at the observer?

Yes, you can use the Doppler effect in Equation 1 to determine the velocity of the source if you know $\omega_{src}$ and $\mathbf{k}_{src}$, which you would if this were the radar example to which you elude at the end of your question.  Using multiple radar source stations (and/or multiple observations over a given time interval), one could derive a numerical estimate for $\mathbf{v}\left(t\right)$.
Again, in the case of the radar example, you know when a signal was emitted and you know the speed at which it was emitted (i.e., $c$), then you can determine the magnitude of the distance to the source using the delay time, $\Delta \tau\left(t\right)$, between the emitted and received signal.  This would be given by:
$$
\lvert \mathbf{x}\left(t\right) \rvert = \frac{c \Delta \tau\left(t\right)}{2} \tag{2}
$$
Most radar systems send a beamed signal (i.e., narrow angular focus) in one direction at a given time and rotate the emitter to sweep across the entire sky.  This provides directional information, since you know the azimuthal angles, $\phi$, during which you observed the reflecting source.  Thus, you could use this information to define a 2D direction for the magnitude calculated from Equation 2.  The third directional component could be estimated if the radar system had finite poloidal receiving bins or if one used multiple radar transmitters to triangulate the signal.  This would all be integrated with the estimate for $\mathbf{v}\left(t\right)$ (may be a 2D or 3D estimate, depending on the radar system) to determine the full 3-vector distance, $\mathbf{x}\left(t\right)$.  Numerical derivatives can be used to determine full 3-vector velocity of the reflecting object, $\mathbf{v}\left(t\right)$.
Update
I forgot to mention that if $\omega_{obs}\left(t\right)$ increased/decreased in time, it would represent an acceleration of the source, i.e., $\mathbf{v} = \mathbf{v}\left(t\right)$.

A: I believe I found the solution for my question, it was actually fairly simple (no calculus or explicit use of the Doppler effect!).  In the received signal $r(t)$, the value at any time $t$ is equal to the sum of the perturbations that would reach the observer at time $t$.  Assuming that the speed of the source is significantly lower than the speed of a wave in the medium, there is only one single perturbation that reaches the observer at time $t$.  This perturbation occurred some time $\tau$ before $t$.  The value of $\tau$ at any time $t$ is solved by:
$\tau(t) = \frac{x(t-\tau(t))}{v} \tag{1}$
where $x(t)$ is the distance of the source from the observer at time $t$, and $v$ is the speed of a wave in the medium.
Therefore, $r(t)$ can be described by:
$r(t) = s(t - \tau(t))  \text{  where  } \frac{x(t-\tau(t))}{v} - \tau(t) = 0 \tag{2}$


text:
Q: Почему не видит значение? $token = $_GET["token"];
$stmt = $pdo->prepare("SELECT token FROM Tokens WHERE token =? LIMIT 1");
$stmt->execute(array($token));
echo $stmt->fetchColumn(PDO::FETCH_ASSOC);

Ответ от сервера пустой.
В чем может быть проблема?

A: $token = $_GET["token"];
$stmt = $pdo->prepare("SELECT token FROM Tokens WHERE token =? LIMIT 1");
$stmt->execute(array($token));

if($stmt->rowCount() == 1) {
    echo $stmt->fetchColumn(0);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bash: executing a command stored in a variable I am writing a script, and one part of it is not working as I would expect.
I have broken out this part in a simple example for simplicity:
echo 'echo "" > tmp' | while read cmd; do  $cmd ; done

Here I would expect the full command, "echo "" > tmp" to be executed by $cmd.
But this happens:
"" > tmp

The command executed echoes out "" > tmp literally. Instead of echoing out "" and redirecting it to the file tmp. Obviously something is wrong when storing the command in $cmd and then later trying to execute it.
The result is the same even if I simplify it further:
cmd="echo "" > tmp"
$cmd
> tmp

I have tried to experiment with different usages of '' and "", but not solved it yet.

A: Use eval to execute the command stored in the variable:
echo 'echo "" > tmp' | while read cmd; do eval "$cmd" ; done

The value of cmd will be echo "" > tmp. Then when Bash resolves the parameter substitution as a command, the part "" > tmp will be the string arguments of echo, not be recognized as >(redirection). So it will just output the arguments part.
The same as: $(echo 'echo "" > tmp')

A: Change
do  $cmd ;

to
do  eval  "$cmd" ;


text:
Q: Syntax error when I put DISTINCT Keyword in join query I am getting syntax error when I put DISTINCT Keyword  in join query
I use DISTINCT for the user id using join query
SELECT  `dev_test_team`. *,
        DISTINCT `dev_user`.`user_id` as athlete_id,
        `dev_user`.`user_type`
FROM `dev_test_team`,`dev_user`
JOIN `dev_test_teams_athlete` as `tt` ON  `dev_user`.`user_id` = `tt`.`user_id`

SQL Syntex error is
   #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'DISTINCT dev_user.user_id as athlete_id, dev_user.user_type FROM `dev_te' at line 1

I am always getting this values using this query
SELECT `dev_test_team`.*,`dev_user`.`user_id` as `athlete_id`,
        `dev_user`.`user_type`
FROM `dev_test_team`,`dev_user`
JOIN `dev_test_teams_athlete` as `tt` ON `dev_user`.`user_id` = `tt`.`user_id`

team_id |team_name| user_id |athlete_id | user_type
 1          team1     480       380         4
 2          team2     472       380         4
 1          team1     480       379         4
 2          team2     472       379         4
 3          team3     478       360         4
 4          team3     478       390         4

I want value like that values:-
team_id |team_name| user_id |athlete_id | user_type
 1          team1     480       380         4
 2          team2     472       379         4
 3          team3     478       360,369     4

A: looking to your expected  result  you should not use DISTINCT Clause but
semms you are looking for group_concat distinct
SELECT dev_test_tean.id, dev_test_team.name, dev_test_team.user_id, group_concat( distinct `dev_user`.`user_id`) as `athlete_id`,
        `dev_user`.`user_type`
FROM `dev_test_team`
CROSS JOIN `dev_user`
INNER JOIN `dev_test_teams_athlete` as `tt` ON `dev_user`.`user_id` = `tt`.`user_id`
GROUP BY dev_test_tean.id, dev_test_team.name, dev_test_team.user_id, `dev_user`.`user_type`


text:
Q: Simplifying and Factoring Formulae I'm am doing an 8th grade math text book, and I came across this simple problem:
$8l^3 - 36l^2m + 54lm^2 - 27m^3$ simplifies to?
I immediately got to know that it is $(2l - 3m)^3$ ,
but how do you Factor it (step by step)?
Basically how do you factor expressions which has more than 3 or 4 terms.
Please help.
The variables here and l[l for last] and m. (I don't know how to type symbols, italics { it would be nice if someone includes that also })

A: For classwork, there will always be a simple answer.  A slightly less "out of the blue" solution is to take the cube roots of the first and last terms, put the proper sign between, and see if it works.  Here you win.  A second approach is like the rational root theorem-take $l$ as a constant and find the list of roots in $m$.  Now for each root $r$, divide by $m-r$ and see if it comes out.  You can do it from the other end as well.  If it works, you are down to a quadratic, and the quadratic formula or factoring techniques will suffice.

A: Hint: substitute $x=2l$ and $y=3m$ into your expression that you want to simplify. Recognize anything yet?

A: As a general rule, you can't really factor it. Imagine if you had a 5th degree polynomial? Galois pretty much proved that there is no general way to factor it (or even extract one factor).
For second degree polynomials, you can always complete the squares.
For third and higher you have to guess by looking at the coefficients.
Fixing $m$ and solving for $l$ is too painful!


text:
Q: C double holds 0 no matter what I input #include<stdio.h>
int main()
{
    double a,b;
    scanf("%lf%lf",&a,&b);
    printf("%lf %lf",a,b);
    return 0;
}

The result I'm getting from printf here is 0.000000 no matter the input. What should I do to remedy this? It seems it's some compiler or system related issue, but I have no idea what could it be.. Thanks in advance

A: %lf is not a valid format specifier. You should use %f for a double, or %Lf for long double (where supported).

A: You code works fine on Ubuntu 64bit with gcc4.8.2
Please give more info about you compiler/arch/ etc..

A: I think what you're doing is to input a number with a decimal point(,)!
Something like this:
0,4565 0,345

But you have to use a dot(.)! Like this:
0.4565 0.345

Then it should work fine! There is no error/mistake in the program


text:
Q: How to derive the variation of parameters formula I have the initial value problem $\dot x(t)=Ax(t)+f(t)$ , $x(t_0)=x^0$ , $t \ge t_0$ where $t_0 \in  \mathbb{R}$ , $f:[t_0,\infty) \to \mathbb{R}^n$ is piecewise continuous, $A \in \mathbb{R}^{n x n} $ and $x^0 \in \mathbb{R}$.
I know that a unique solution to this inivitial value problem is:
$x(t) = e^{A(t-t_0)}x^0 + \int_{t_0}^t  e^{A(t-\tau)}f(\tau) d\tau $
I need to proof why this is a solution.  So basically I need to proof the variation of paraters formula.
Any suggestion on how to do that?

A: Look for a particular solution of the form $e^{A(t-t_0)}C(t)$. Substituting in the equation leads to
$$
e^{A(t-t_0)}C'(t)=f(t)\implies C'(t)=e^{-A(t-t_0)}f(t).
$$


text:
Q: deploying data from google cloud spanner database I'm trying to get data from my google cloud spanner into a web page. But i'm not familiar with cloud spanner. I created some tables and add data into them. Now i want to get them to my own web page

A: Please follow this tutorial, where it is explained step by step the process of working with cloud spanner with php.
1.Create a Cloud Spanner instance and database.
2.Write, read, and execute SQL queries on data in the database.
3.Update the database schema.
4.Update data using a read-write transaction.
5.Add a secondary index to the database.
6.Use the index to read and execute SQL queries on data.
7.Retrieve data using a read-only transaction.


text:
Q: After if statment nothing will fire in javascript There is very strange. It looks like after the If statement, the script it stop. The page has a javascript function is called by clicking the button. If the browser on IE, I will do something. Otherwise I close the page. I put alert statement to test it. However the alert has never fired. Would someone tell me what's wrong will my code.
There is my button call the function:
  <input class="btn" id="btnClose" onclick="javascript:openFile();" type="button" value="Close" name="btnClose" />

There is the javascript function:
 function openFile() {

            var url = 'file://' + document.getElementById("hdURL").value;
            //alert('Open File' + url);
            var location = document.getElementById("hdURL").value;

            ////http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
             if ((/*@cc_on!@*/false || !!document.documentMode) ||(!isIE && !!window.StyleMedia))
             {
                 alert('IE');
                //do something
                window.self.close();
             }
             alert('test');  //never fire

             closeWindow();

        }

A: First off, going to give credit to Amy in the comments on the question for realizing that your isIE is not defined.

Take a look at the accepted answer to the question you referenced in your code. It says the following: (I've added an arrow to show the use of isIE)
// Internet Explorer 6-11
var isIE = /*@cc_on!@*/false || !!document.documentMode;
//    |________
//             |
// Edge 20+    V
var isEdge = !isIE && !!window.StyleMedia;

Notice how their example for detecting edge references the variable for detecting IE, isIE. In your example, you don't have var isIE, and so this is coming back as undefined - the code fails.

Why does it work in IE but not Firefox/Chrome?

JavaScript will not evaluate the second condition of an OR if the first is true - this is known as Short Circuit Evaluation.
When using IE, the first condition evaluates to true. This means that the second condition (and the syntax error therein) is ignored.
However, Chrome and Firefox get false for the first condition, and must evaluate the second. Once they get to the undefined variable, an error will be thrown.

Solution:
// Internet Explorer 6-11
var isIE = /*@cc_on!@*/false || !!document.documentMode;

// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;

if (isIE || isEdge) {
    //DO STUFF
}

A: it is always helpful to prepare jsifddle, so you can immediately test your solution and see errors.
It is also good to check browser console which shows errors
see working example
https://jsbin.com/sipukovono/edit?html,css,js,console,output
function openFile() {

var isIE=false; // temporary definition

var url = 'file://' + document.getElementById("hdURL").value;
        //alert('Open File' + url);
        var location = document.getElementById("hdURL").value;

         if ((false || !!document.documentMode) ||(!isIE && !!window.StyleMedia))
         {
             alert('IE');
            window.self.close();
         }
         alert('test');  //never fire

         closeWindow();

    }


text:
Q: Laravel 4: redirect users after login I have page that not allowed for guests, so if guest visit it automatically redirect to login page,
the question is, Is there any simple way (included in Laravel) to return him back to first page after logged in successfully?
I know I can use with() in first redirection:
Redirect::action('UserController@login')->with('url', $_SERVER['REQUEST_URI']);
or
Redirect::action('UserController@login')->withUrl($_SERVER['REQUEST_URI']);

then store and use it in login page,
but is there something already built in Laravel,
thanks,

A: Yes, when your user first enters your site, Laravel stores the entry page in the Session, so, as soon as a login is successful, you can:
return Redirect::intended();

Note that this probably only work if keep using
return Redirect::guest('login');

In your filtered Route. This is the original Laravel code (filters.php) that provides this:
Route::filter('auth', function()
{
    if (Auth::guest()) return Redirect::guest('login');
});

You can also set a default page (just in case the intended is not available at the moment) using:
return Redirect::intended('dashboard');

And you can change the original intended by setting a new one using Session:
Session::put('url.intended', $newUrl);

A: As Antonio's answer states, you can use:
return Redirect::intended();

and it will redirect the user to the page the originally intended to go to, but you can pass an optional 'defualt' paramter so if they login at the login page with no intended location, it will redirect them to the default.
i.e. return Redirect::intended('dashboard');


text:
Q: NameError: name 'final_error_code' is not defined I tried to assign final_error_code as a global variable but still the problem persists.
File "C:\Ujjwal\sample_python_proj - Copy\fetch_array.py", line 154, in get_error_code_array
print("Lemon Squeeze", final_error_code)
NameError: name 'final_error_code' is not defined

def get_error_code_array():
    array_pt_failed_current = []
    # global final_error_code
    for loop in files:
        # print("This is get error code first loop", loop)
        with open(loop, 'w+') as file:
            # print("This is get error code second loop", loop)
            lines = file.readlines()
            error_str = json.dumps(lines)
            print("This is get error code of ",error_str)
            for pt_found in re.finditer('PT-', error_str):
                i = pt_found.end() + 1
                pt_failed_current = error_str[pt_found.end()] + error_str[i] + error_str[i+1]
                array_pt_failed_current.append(pt_failed_current)
                final_error_code = ["PT-"+ls for ls in array_pt_failed_current]
                # show_error_code_array.append(final_error_code)
    print("Lemon Squeeze", final_error_code)
    return (final_error_code)

A: final_error_code is defined in your loop.
If it is not defined, that means that your loop didn't loop at all.
Your for loop condition is: re.finditer('PT-', error_str), so I assume that re.finditer(...) didn't find anything.


text:
Q: Is there some sort of ASLR protection on Android? I want to know if someone could access libraries with function addresses that would be the same from one instance of the program to the other?

A: The address space layout will be pretty consistent from run to run on the same device.  A lot of the major system libraries are preloaded by zygote, and so inherited as shared mappings by the children it forks off to differentiate into applications.  I suppose remapping them at the virtual memory level would be possible, but would incur a sort of dynamic-re-linking penalty and would be fairly tricky to implement.


text:
Q: Trouble finding source of a designer exception in VS2010 When loading the mainform of a WinForms app I'm working on, I encountered a familiar exception: a "To prevent possible data loss before loading the designer, the following errors must be resolved" error. The stacktrace is as follows:
Object reference not set to an instance of an object.

Instances of this error (4)

1.   Hide Call Stack

at System.ComponentModel.ReflectPropertyDescriptor.SetValue(Object component, Object value)
at Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkPropertyDescriptor.SetValue(Object component, Object value)
at System.Windows.Forms.Design.ControlDesigner.CanResetSizePropertyDescriptor.SetValue(Object component, Object value)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializePropertyAssignStatement(IDesignerSerializationManager manager, CodeAssignStatement statement, CodePropertyReferenceExpression propertyReferenceEx, Boolean reportError)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeAssignStatement(IDesignerSerializationManager manager, CodeAssignStatement statement)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement)

I know what's causing this error -- there are four lines buried somewhere in the MainForm that make reference to an image object that doesn't exist at design time. I even have an idea of how to fix the error, thanks to this post at MSDN. The trouble is, I can't find the lines from which the exception is thrown. Normally I would navigate to the exception using the Error List window, but it says that there are zero errors. Any ideas as to how I can locate the offending lines?

A: I usually find that this relates to a user control hosted on the form that relies on a DI container or similar, but as you say it is sometimes difficult to determine the source from the call stack the designer provides. If you're hosting a lot of controls, to figure out which controls are causing the issue without diving into each one you could:

*

*Make a list of the user controls that are directly hosted on the form, then

*Create a new temporary form, then

*Drop each user control in your list onto the form to see which one kills the designer


text:
Q: What is the name of the quick open completion setting in VS Code I want to change the theme color for this particular element (the bright white letter when searching in quick open, ex: tabCompletion in the screenshot).
I cannot find it in the settings. Does someone know its setting name ?
Thanks

A: That highlighted foreground color for the found typed letters is:
editorSuggestWidget.highlightForeground
editorSuggestWidget.focusHighlightForeground  // when that line is selected

From theme colors: editor widgets


text:
Q: Bootstrap 5 select data-live-search not working I am using bootstrap 5 and I try to add live search to a form select.
In Bootstrap 3 I can just do it like following:
<select class="selectpicker" data-live-search="true">
   <option>A</option>
   <option>B</option>
   <option>C</option>
</select>

I have tried the same for bootstrap 5 but it does not work.
After some research I have found the datalist, where I can search:
<input class="form-control" list="datalistOptions" placeholder="Type to search...">
<datalist id="datalistOptions">
    <option>A</option>
    <option>B</option>
    <option>C</option>
</datalist>

The live search works but it is not the same.
Is there any way to make it just like in bootstrap 3?
Thank you very much!


text:
Q: Java - Should private instance variables be accessed in constructors through getters and setters method? I know that private instance variables are accessed through their public getters and setters method.
But when I generate constructors with the help of IDE, it initializes instance variables directly instead of initializing them through their setter methods.
Q1. So should I change the IDE generated code for constructors to initialize those instance variables through their setter methods.
Q2. If yes, then why IDE don't generate constructors code in that way?
============================= EDITED =======================================

*

*I use Eclipse and Netbeans IDE

*It's a general question. But as asked by @Lords would the answer depends on whether our constructor is public or protected or package private or private?

A: Constructors are for initialization. Initialize private instance variables directly in the constructor. Methods define an object's behavior. Behavior occurs after instantiation/initialization. Manipulate the state of your instance variables with your setter methods. That's classic OOP thinking and probably why your IDE is generating the code it does.

A: You should never call a non-final method from a constructor. A class constructor is used to initialize an object, and the object is not in a consistent state until the constructor returns. If your constructor calls a non-final method which is later overridden by a subclass, you can get strange, unexpected results because the object is not fully initialized when the overridden method is called.
Consider this contrived example:
class A {
    private int x;

    public A() {
        setX(2);
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getX() {
        return x;
    }
}

class B extends A {
    private int number = 10;

    @Override
    public void setX(int x) {
        // set x to the value of number: 10
        super.setX(number);
    }
}

public class Test {
    public static void main(String[] args) {
        B b = new B();
        // b.getX() should be 10, right?
        System.out.println("B.getX() = " + b.getX());
    }
}

The output of this program is:
B.getX() = 0

The reason is that B's number member is not initialized at the time setX is called, so its default value of 0 is used.
This article has a more thorough explanation, as does Effective Java.

A: That depends. If your setters/getters are simply accessing the members you should access them directly. If you also have some code along with it, use setters.

A: You should decide which fields you will initialise with the constructor and which to initalise with a setter. (both is possible) I prefer to use the constructor only as much as possible and often have no setters.
This should be configurable/selectable in IDE. Without knowing your IDE there is no way to know why it works the way it does.

A: Good answers. Only want to add that Eclipse (the one I use often) has templates, which you can modify in order to generate your code the way you want. It could help to adjust the code to your needs.
PS. I rather use setters and getters. Just as an habit, keeps the code coherent, I feel like it will be easier to read for someone else if I keep the habits all over the code.

A: First of all initialization != setters (at least not always)
But IDEs are just playing nice with once revered JavaBean design pattern
Assuming property changes should happen via setters.
So, it is a matter of design. If your classes represent pure value objects, no harm in initializing via =
But if your classes have a potential of becoming a JavaBean whose property change is more than just init or assignment, go with set* calls.

A: Private instance variables of a class should be (I believe need to be) declared outside of any class constructor.  If I could break part of your question down into two parts:
Q1) If instance variables are initialized when a class is instantiated, unlike local variables, why bother doing the extra work within a given class constructor (?).
A1) Although you do not need to initialize instance variables (private string someString; defaults to null and is legal), one reason for doing so is that the default assigned by the compiler may not be the value you want, or worse, incorrect (which the compiler should catch).
Q2) Assuming the part above, what is the significance of get; set; properties?
A2) Aside from the fact they are easy and more elegant that a method equivalent, properties can be used at anytime within your class (obviously), they can be used as simple assignments or contain additional code (someone already stated this for validating information), and finally the data is self contained within the class and therefore easier to debug.
All this being said, you may have a perfectly valid reason for doing things differently than what a book or someone else says.  There are always acceptions to the "rule(s)", and you should code accordingly.


text:
Q: Replace objects inside an array with array key I am not sure if this is a bug from my application, but I have an array like this:
var arr = [{name: 'John'}, {name: 'Jane'}, {name: 'Smith'}, {name: 'George'}];

I am trying to replace {name: 'Jane'} with {name: 'Simon'} so, I am doing
arr.splice(1, 0, {name:'Simon'})

But Jane isn't removed. Just Simon is added to the list.
I thought the splice's first arg was where to place the new array, and 0 was to replace the existing array

var arr = [{
  name: 'John'
}, {
  name: 'Jane'
}, {
  name: 'Smith'
}, {
  name: 'George'
}];

arr.splice(1, 0, {
  name: 'Simon'
})
console.log(arr)

A: Array#splice is the wrong tool, because it deletes and/or inserts elements.
You could use the index directly and replace the item.

var array = [{ name: 'John' }, { name: 'Jane' }, { name: 'Smith' }, { name: 'George' }];

array[1] = { name: 'Simon' };

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Edit, nearly, you could remove the actual item and add a new one, but this is in this case not advisable, because you take some array oreations, which are not necessay, like removing and inserting of an item.
arr.splice(1, 1, { name:'Simon' })
//            ^                    take one element out at index 1 and insert a new object

var array = [{ name: 'John' }, { name: 'Jane' }, { name: 'Smith' }, { name: 'George' }];

array.splice(1, 1, { name: 'Simon' });

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: Or if you just want to change the name:
arr[1].name = "Simon";

A: You can access elements directly by using sqaure brackets.
arr[0] will access the first element in the array so you need arr[1].
You can simply say  arr[1] = {name:'Simon'}; to do this
The splice() method adds/removes items to/from an array, and returns the removed item(s).


text:
Q: Globally Replace Old School $PHP_SELF with $SERVER['PHP_SELF'] using sed Not being an sed expert, I need to replace all instances of the string $PHP_SELF with $_SERVER['PHP_SELF'] globally in a directory.
This is an "old school" osCommerce application that I need to resurrect temporarily for a showcase.

A: sed doesn't recurse on it's own so you'll need to use another tool for that, find is generally the right answer.
Run this in the top-level directory.  sed will make a backup of each file it reads with a .bak extension (regardless if it actually does a replacement). If you don't want the backup behavior, use -i instead of -i.bak
I recommend you first try this on a test directory to make sure it meets expectations.
#!/bin/bash

while IFS= read -r -d $'\0' file; do
   sed -i.bak $'s/$PHP_SELF/$_SERVER[\'PHP_SELF\']/g' "$file"
done < <(find . -type f -name "*.php" -print0)


text:
Q: How to install security updates after "Upgrade to Windows 10" hijacks Windows Update? EDIT: Future visitors - the cited duplicate is not a duplicate. Ignore Ramhound's (and other's) claims. This is not a question about removing Get Windows 10 malware because it keeps returning. Instead, its a question about installing the security updates after  Get Windows 10 malware hijacks the update process.

Patch Tuesday was yesterday. My Windows 7 machine took about 10 or 15 security updates. I attempted to install the updates on my mother's Windows 7 machine, but it appears GWX.exe has returned. The malware has gotten more aggressive, and it has hijacked the Windows Update process. (I've already removed it completely twice).

I visited Show all available updates and selected all the updates. But when I clicked Ok and returned to install screen, the malware was still controlling the screen, and there was no Install updates like I am used to seeing.
I also clicked the Get Started button (with an immediate exit) hoping I could dismiss the malware, but it did not return control of the update process to me.
How do I install the outstanding Windows Updates?

A:
How do I install outstanding Windows Updates?

In the main Windows Update window
left click the blue Show all available updates.

Left click on Optional () on far left side of the Windows Update window.

That should reveal a check-marked selection for the Windows 10 Upgrade (which is the cause of your anguish).
Uncheck that selection (to disable the upgrade).
Proceed to select any optional updates.
Left click on Important () on far left side of the Windows Update window.
Select the Important updates.
Resume the normal update procedure (e.g. click the OK button on the bottom right, then at the main screen click the Install updates button).

After you reboot and start Windows Update again, the Upgrade WIndows 10 will self-activate again.
Right-clicking the update line for Win10 and hiding it does not seem to disable this update.
ADDENDUM
As of this moment, the Windows 10 Upgrade no longer appears in the list of available updates on my PCs.  No patches, registry edits or removed updates have been made.  The icon for the upgrade is still in the system tray.
IOW the removal must be on the MS server end.


text:
Q: A sequences problem The first 3 terms of an infinite geometric sequence are a, b, 1 and the first 3 terms of an arithmetic sequence are a, 1, b - 4. The sum of the infinite geometric sequence is 27/4
and the sum of the first 3 terms of the arithmetic sequence is 3. Find all possible pairs of values of a and b.
I think I've gotten two pairs(correct me if I'm wrong)
a=4, b=2
a=9, b=-3
However I didn't involve either sum formulas, making me think I did something wrong, or that there are more pairs.
Any help is greatly appreciated!

A: You were going in the right direction, but you stopped before the finish.
Given that $a, b, 1$ make a geometric sequence, you know $a/b = b/1,$ hence $a=b^2.$
Given that $a, 1, b-4$ make an arithmetic sequence, you know $1-a = (b-4)-1,$ hence $a+b-6=0.$ This is equivalent to $b^2+b-6 = 0,$ which resolves as $b=-3$ or $b=2.$
That makes $a=b^2=9$ or $a=4,$ respectively.
You can easily check, that both resulting arithmetic sequences: $(9,1,-7)$ and $(4,1,-2)$ give a sum of the three terms equal $3.$
Now the last step, missing in your attempt: checking the sum of an infinite geometric sequence.
The sum exists, if the quotient is small enough: $|q|<1.$ This is satisfied in both cases: the quotient is $1/b,$ which is $-1/3$ in the sequence $(9,-3,1,\dots)$ or $1/2$ in the sequence $(4,2,1,\dots).$
The sum is $\frac{\text{the first term}}{1-\text{quotient}},$ which results in $\frac9{1-(-1/3)}=\frac9{4/3}=\frac{27}4$ or in $\frac4{1-1/2}=\frac3{1/2}=6.$
The latter gets discarded and we get a result: $a=9, b=-3.$


text:
Q: Power BI - "The key didn't match any rows in the table" - Appended PBI dataflow table to Folder CSV table Good evening!
We are currently having an issue with the below error being thrown when trying to refresh a dataset via the on-premises gateway. Refreshing direct through Power BI desktop does not provide any errors and seems to refresh fine.
Data source error: {"error":{"code":"DM_GWPipeline_Gateway_MashupDataAccessError",
"pbi.error":{"code":"DM_GWPipeline_Gateway_MashupDataAccessError",
"parameters":{},"details":[{"code":"DM_ErrorDetailNameCode_UnderlyingErrorCode",
"detail":{"type":1,"value":"-2147467259"}},{"code":"DM_ErrorDetailNameCode_UnderlyingErrorMessage",
"detail":{"type":1,"value":"The key didn't match any rows in the table."}},{"code":"DM_ErrorDetailNameCode_UnderlyingHResult",
"detail":{"type":1,"value":"-2147467259"}},{"code":"Microsoft.Data.Mashup.ValueError.Key",
"detail":{"type":1,"value":"[entity = \"Forecast\"]"}},{"code":"Microsoft.Data.Mashup.ValueError.Reason",
"detail":{"type":1,"value":"Expression.Error"}}],"exceptionCulprit":1}}} Table: FACT - Cost Forecast Tool.
Cluster URI: WABI-EUROPE-NORTH-B-redirect.analysis.windows.net
Activity ID: f4b629a6-a9bc-4966-954c-ae37139737a4
Request ID: db16cb6d-a765-1e0e-f9f5-b8803c8baa6e
Time: 2020-11-25 17:20:30Z

From reading previous posts, I'm not sure any of the normal responses apply in this scenario, as they tend to relate to either pulling data from SQL Server, or Excel files (where the sheet name causes an issue).
The table throwing the error (FACT - Cost Forecast Tool) is made by appending two other tables - one comes from a Power BI dataflow (Forecast), and one from a folder import of CSV files (Forecast Tool Adjustments).
Publishing a model with just the two individual tables (Forecast and Forecast Tool Adjustments) works and refreshes fine.
The above error only occurs where a third table is added combining these two tables via a one liner in Power Query:
= Table.Combine({#"Forecast Tool Adjustments", Forecast})
Oddly the value being flagged in the error, "[entity = "Forecast"]", is one of the first steps in Power Query for the 'Forecast' table. So while that table refreshes fine if it's on it's own, it seems to throw an error when refreshed through the combined table?
Any thoughts would be greatly appreciated.


text:
Q: va_start error on x64 arhitecture? I am having a hard time compiling my program in x64.
Whilst I was able to fix everything and compile, my program crashes at the logging:
void TLog::VLogAddFormat(COLORREF colorText, const char *& AddressOfFmt, ...)
{
    m_Sync.Lock();
    // ----
    PrepareLogBuff();
    // ----
    //setter(&AddressOfFmt, -32L);
    va_start(m_pArguments, AddressOfFmt);       // the real address of fmt. m_pArguments = (va_list)_ADDRESSOF(v) + _INTSIZEOF(v)
    vsprintf(m_LogTempBuff, AddressOfFmt, m_pArguments);
    va_end(m_pArguments); < BREAK HERE !
    // ----
    LogAddStr(colorText, m_LogTempBuff);
    // ----
    m_Sync.Unlock();
}

Notice that I have added the "..." because it would not compile otherwise.
Break occurs at: "va_end(m_pArguments); < BREAK HERE !"
And the strange problem is that in "m_pArguments" I get very strange characters...
Can somebody tell me how should I use va_start in x64? Many thanks.

A: You can't pass a reference parameter to va_start. It's undefined behaviour.


text:
Q: How to parse multiple dates from a block of text in Python (or another language) I have a string that has several date values in it, and I want to parse them all out. The string is natural language, so the best thing I've found so far is dateutil.
Unfortunately, if a string has multiple date values in it, dateutil throws an error:
>>> s = "I like peas on 2011-04-23, and I also like them on easter and my birthday, the 29th of July, 1928"
>>> parse(s, fuzzy=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/pymodules/python2.7/dateutil/parser.py", line 697, in parse
    return DEFAULTPARSER.parse(timestr, **kwargs)
  File "/usr/lib/pymodules/python2.7/dateutil/parser.py", line 303, in parse
    raise ValueError, "unknown string format"
ValueError: unknown string format

Any thoughts on how to parse all dates from a long string? Ideally, a list would be created, but I can handle that myself if I need to.
I'm using Python, but at this point, other languages are probably OK, if they get the job done.
PS - I guess I could recursively split the input file in the middle and try, try again until it works, but it's a hell of a hack.

A: While I was offline, I was bothered by the answer I posted here yesterday. Yes it did the job, but it was unnecessarily complicated and extremely inefficient.
Here's the back-of-the-envelope edition that should do a much better job!
import itertools
from dateutil import parser

jumpwords = set(parser.parserinfo.JUMP)
keywords = set(kw.lower() for kw in itertools.chain(
    parser.parserinfo.UTCZONE,
    parser.parserinfo.PERTAIN,
    (x for s in parser.parserinfo.WEEKDAYS for x in s),
    (x for s in parser.parserinfo.MONTHS for x in s),
    (x for s in parser.parserinfo.HMS for x in s),
    (x for s in parser.parserinfo.AMPM for x in s),
))

def parse_multiple(s):
    def is_valid_kw(s):
        try:  # is it a number?
            float(s)
            return True
        except ValueError:
            return s.lower() in keywords

    def _split(s):
        kw_found = False
        tokens = parser._timelex.split(s)
        for i in xrange(len(tokens)):
            if tokens[i] in jumpwords:
                continue
            if not kw_found and is_valid_kw(tokens[i]):
                kw_found = True
                start = i
            elif kw_found and not is_valid_kw(tokens[i]):
                kw_found = False
                yield "".join(tokens[start:i])
        # handle date at end of input str
        if kw_found:
            yield "".join(tokens[start:])

    return [parser.parse(x) for x in _split(s)]

Example usage:
>>> parse_multiple("I like peas on 2011-04-23, and I also like them on easter and my birthday, the 29th of July, 1928")
[datetime.datetime(2011, 4, 23, 0, 0), datetime.datetime(1928, 7, 29, 0, 0)]

It's probably worth noting that its behaviour deviates slightly from dateutil.parser.parse when dealing with empty/unknown strings. Dateutil will return the current day, while parse_multiple returns an empty list which, IMHO, is what one would expect.
>>> from dateutil import parser
>>> parser.parse("")
datetime.datetime(2011, 8, 12, 0, 0)
>>> parse_multiple("")
[]

P.S. Just spotted MattH's updated answer which does something very similar.

A: Looking at it, the least hacky way would be to modify dateutil parser to have a fuzzy-multiple option.
parser._parse takes your string, tokenizes it with _timelex and then compares the tokens with data defined in parserinfo.
Here, if a token doesn't match anything in parserinfo, the parse will fail unless fuzzy is True.
What I suggest you allow non-matches while you don't have any processed time tokens, then when you hit a non-match, process the parsed data at that point and start looking for time tokens again.
Shouldn't take too much effort.

Update
While you're waiting for your patch to get rolled in...
This is a little hacky, uses non-public functions in the library, but doesn't require modifying the library and is not trial-and-error. You might have false positives if you have any lone tokens that can be turned into floats. You might need to filter the results some more.
from dateutil.parser import _timelex, parser

a = "I like peas on 2011-04-23, and I also like them on easter and my birthday, the 29th of July, 1928"

p = parser()
info = p.info

def timetoken(token):
  try:
    float(token)
    return True
  except ValueError:
    pass
  return any(f(token) for f in (info.jump,info.weekday,info.month,info.hms,info.ampm,info.pertain,info.utczone,info.tzoffset))

def timesplit(input_string):
  batch = []
  for token in _timelex(input_string):
    if timetoken(token):
      if info.jump(token):
        continue
      batch.append(token)
    else:
      if batch:
        yield " ".join(batch)
        batch = []
  if batch:
    yield " ".join(batch)

for item in timesplit(a):
  print "Found:", item
  print "Parsed:", p.parse(item)

Yields:
Found: 2011 04 23
Parsed: 2011-04-23 00:00:00
Found: 29 July 1928
Parsed: 1928-07-29 00:00:00

Update for Dieter
Dateutil 2.1 appears to be written for compatibility with python3 and uses a "compatability" library called six. Something isn't right with it and it's not treating str objects as text.
This solution works with dateutil 2.1 if you pass strings as unicode or as file-like objects:
from cStringIO import StringIO
for item in timesplit(StringIO(a)):
  print "Found:", item
  print "Parsed:", p.parse(StringIO(item))

If you want to set option on the parserinfo, instantiate a parserinfo and pass it to the parser object. E.g:
from dateutil.parser import _timelex, parser, parserinfo
info = parserinfo(dayfirst=True)
p = parser(info)

A: I think if you put the "words" in an array, it should do the trick. With that you can verify if it is a date or no, and put in a variable.
Once you have the date you should use datetime library library.

A: Why not writing a regex pattern covering all the possible forms in which a date can appear, and then launching the regex to explore the text ? I presume that there are not dozen of dozens of manners to express a date in a string.
The only problem is to gather the maximum of date's expressions

A: I see that there are some good answers already but adding this one as it worked better in a use case of mine while the above answers didn't.
Using this library: https://datefinder.readthedocs.io/en/latest/index.html#module-datefinder

import datefinder

def DatesToList(x):

    dates = datefinder.find_dates(x)

    lists = []

    for date in dates:

        lists.append(date)

    return (lists)

dates = DateToList(s)

Output:
[datetime.datetime(2011, 4, 23, 0, 0), datetime.datetime(1928, 7, 29, 0, 0)]


text:
Q: Finding a contour of constant density in a joint distribution I would appreciate any help to find the solution for the following problem. In short the problem is explained below:
What I need: I need to find a contour of constant density in joint distribution of d random variables. The distribution may or may not be Gaussian. If the distribution is not Gaussian, this counter may no longer be an ellipsoid (I am not sure about it).
What I have:

*

*Option $1$: I have $N$ numbers of $d$-dimensional points from a joint distribution (only these points are available, we do not access the closed form of distribution but $N$ can be large enough). I need to find ellipsoidal (or whatever is called instead of ellipsoid) uncertainty sets which covers $X$ % of these points. This should represent a contour of constant density in their joint distribution.

*Option $2$: The joint distribution (non Gaussian) of d random variables is available. The question is how to find a contour of constant density in this joint distribution. I know the formulation for the Gaussian distribution based on chi-square distribution.


text:
Q: ImageIcon in JLabel not working I've been struggling with this problem for weeks to no avail. Other Java forums have not been able to help me with this so I'm hoping I can find someone here with new eyes. I have a JFrame in which, among other things, I am trying to insert an image. I have put together an SSCCE that reproduces the problem.
    public class ImageTest {
   public static void main(String[] args) {
    SplashScreen.ShowWindow();
   }
    }

    public class SplashScreen {

private JFrame frmKcbsEventsSearch;

public SplashScreen() {
    initialize();
}

public static void ShowWindow() {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                SplashScreen window = new SplashScreen();
                window.frmKcbsEventsSearch.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public void initialize() {
    frmKcbsEventsSearch=new JFrame();
    frmKcbsEventsSearch.getContentPane().setBounds(new Rectangle(200, 200, 520, 450));
    frmKcbsEventsSearch.getContentPane().setFont(new Font("Times New Roman", Font.PLAIN, 16));
    frmKcbsEventsSearch.setTitle("KCBS Events Search");
    frmKcbsEventsSearch.setBounds(200,200,520,450);
    frmKcbsEventsSearch.getContentPane().setLayout(new FlowLayout());
    frmKcbsEventsSearch.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    JLabel logo;
    java.net.URL logoURL=getClass().getResource("KCBSLogo.jpg");
    if (logoURL!=null) {
        try {
            logo = new JLabel();
            logo.setIcon(new ImageIcon(logoURL));
        }
        catch (Exception e) {
            logo = new JLabel("KCBS Logo");
        }
    }
    else {
        logo = new JLabel("KCBS Logo missing");
    }
    logo.setHorizontalAlignment(SwingConstants.CENTER);
    logo.setVerticalAlignment(SwingConstants.CENTER);
    frmKcbsEventsSearch.getContentPane().add(logo);
}
    }

It has been mentioned elsewhere that the layout is important to make this work. I've not had much luck getting layout managers to do what I want but in this case I just want to get the image displayed. Once I have that I'll work through getting it formatted the way I want.

A: This code works perfectly fine!
I changed the KCBSLogo.jpg to a source that I had named tile.png.
When I ran it displayed perfectly.
Make sure the KCBSLogo.jpg is in your SRC folder in the project.
http://i.stack.imgur.com/sYfYF.png
As you can see the tile image was shown.


text:
Q: Using `@Transactional` with Spring's `@Retriable` I'm using spring data jpa with @EnableJpaRepositories and spring retry with @EnableRetry.
I want to retry a transactional method that calls another transactional method that acquires an Oracle DBMS_LOCK using a wrapper stored proc: MY_PROC_THAT_CALLS_ORACLE_DBMS_LOCK.
The lock acquired is set up to be released upon transaction commit and that is what I want.
But despite successfully acquiring the lock on, say, the second attempt, my transaction is getting marked as rollback_only and is failing.
I suspect the @Transactional annotation on my acquireDbmsLock method in my Repository is seeing the SQLException and setting the transaction to roll back only.
From my understanding of the transaction propogation semantics, I think I don't want @Transactional(propogation = Propogation.REQUIRES_NEW) on the acquireDbmsLock interface method. Looks like Hibernate doesn't support Propogation.NESTED.
So, what is a good solution for this problem?
I'm resisting setting noRollbackFor = SQLException.class.
Here's my code:
@Retriable(SQLException.class)
@Transactional
public MyThing myService(String thingId) {
  MyThing myThing = myRepository.findMyThing(thingId);

  if(myThing == null) {
    myLockRepository.acquireDbmsLock(thingId);
    myRepository.createMyThing(thingId);
  } else {
    return myThing;
  }
}

public interface MyLockRepository extends Repository<XXX, YY> {

  @Procedure(procedureName = "MY_PROC_THAT_CALLS_ORACLE_DBMS_LOCK")
  void acquireDbmsLock(String lockName);
}

I've tried overriding the default retry configuration as shown below as well (after removing the @EnableRetry annotation):
@Bean
  RetryConfiguration retryConfiguration() {
    // Need retries to happen before transaction is set to rollback only: https://stackoverflow.com/a/53654301/499635
    return new RetryConfiguration() {
      @Override
      public int getOrder() {
       return Ordered.HIGHEST_PRECEDENCE;
      }
    };
  }


text:
Q: highcharts 3d scatter chart: displaying categories I am using Highcharts and I would like this chart to display categories on axis z. This is what I have now: JSFiddle
zAxis: {
            min: 1,
            max: 3,
            categories: ['Apples', 'Bananas', 'Oranges'],
            minorTickInterval: 1,
            title: 'source'
        },

As you can see I have 3 categories. I would like them to be displayed in the same way as the numbers on the x and y axes. Any ideas?

A: Just get set categories for every axis in your config and get it from chart.zAxis[0].options.categories for z axis. Then you can get indexes which are in this.point.x this.point.y and this.point.z and return a formatted tooltip containing categories names.
Code:
tooltip: {
  formatter: function() {
    const chart = this.point.series.chart,
      catsX = chart.xAxis[0].categories,
      catsY = chart.yAxis[0].categories,
      catsZ = chart.zAxis[0].options.categories;
    return `X: ${catsX[this.point.x]}

        Y: ${catsY[this.point.y]}

        Z: ${catsZ[this.point.z]}`;
  }
},

Live example:
https://jsfiddle.net/p86a7y0g/
Api reference:
http://api.highcharts.com/highcharts/tooltip.formatter
Output:


text:
Q: Installing a product as a feature through emdebbed msi The Problem
Currently I have a legacy product that installs a service as a feature using a Merge Module (.msm). However the same service may be installed as a standalone Product via an MSI package (.msi) that basically embeds the Merge Module (.msm).
This leads to a necessity of complex workarounds on updates, since the Service can be installed on the same machine either as a standalone Product (that has its own Product Code GUID) or as a feature (which doesn't have its own Product Code GUID).
More over, the Service's msi and msm are configured via Wix, but the main product's installer is created via InstallShield 2010.
Also the Custom Action tables are merged upon the Main product installer's generation. And there are some custom actions within the Service's installation that require a particular order.
Possible solution
I know that I can basically run the Service's .msi installer as a Main product's Custom Action.
But there are several concerns:

*

*Is it possible to show space requirements for a feature that installs the Service? As a subprocess it would not take part in the main installer sequence...

*Is it possible to show progress information in the main installation process?

*What is a safe way to migrate msm to msi during an Upgrade, if a new Service as a Product must be installed in the same subfolder by default?


text:
Q: Uncaught TypeError: Cannot read property 'src' of undefined at displayFull I am having trouble with this homework assignment and I have been stuck on it for a while. I am getting an error message saying

Uncaught TypeError: Cannot read property 'src' of undefined at
  displayFull

Any idea to fix this?
The image folders and files are in the same folder, so the src is right.
HTML
<!DOCTYPE html>

      <meta charset = "utf-8">
      <title>Deitel Book Cover Viewer</title>
      <link rel = "stylesheet" type = "text/css" href = "style.css">

 // I AM GETTING THE ERROR MESSAGE HERE FOR EACH IMAGE ON CLICK AT WITH THE ONCLICK ATTRIBUTE

JAVASCRIPT
var fullpic = new Array(6);

//define each array element as an image
for (var i=0;i<fullpic.length;i++)
    fullpic[i] = new Image(289,373);

//give the path to the src properties of the array elements
fullpic[0].src = "fullsize/jhtp.jpg";
fullpic[0].alt = "Java How to Program";
fullpic[1].src = "fullsize/iw3htp.jpg";
fullpic[2].src = "fullsize/cpphtp.jpg";
fullpic[3].src = "fullsize/jhtplov.jpg";
fullpic[4].src = "fullsize/cpphtplov.jpg";
fullpic[5].src = "fullsize/vcsharphtp.jpg";

/*function displayFull(title){
    document.getElementById("imgCover").src="fullsize/"+title+".jpg";

}*/

function displayFull(i){
    document.getElementById("imgCover").src=fullpic[i].src; // I AM GETTING THE ERROR MESSAGE HERE

}

A: To make it cleaner and readable, You can just do something like this as mentioned below. All you need is , have all the images under in your markup.

window.onload = function() {
  document.querySelector("#thumbs").addEventListener("click", function(event) {

    if (event.target.tagName.toLowerCase() === "img") {
      var title = event.target.getAttribute("id"),
        imgSrc = "fullsize/" + title + ".jpg",
        imgElement = document.querySelector("#imgCover");

      imgElement.src = imgSrc;
      imgElement.alt = imgSrc;
    }
  });
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Deitel Book Cover Viewer</title>
  <link rel="stylesheet" type="text/css" href="style.css">

// I AM GETTING THE ERROR MESSAGE HERE FOR EACH IMAGE ON CLICK AT WITH THE ONCLICK ATTRIBUTE


text:
Q: Windows task scheduler and python logging module I have a program which is running on daily basis. I would like to have a log created for each run of it. Here is the snip of code responsible for logging:
logging.basicConfig(filename = 'log.txt', level = logging.DEBUG, format = '%(asctime)s - %(levelname)s - %(message)s')

logging.debug('Start of program') # example logging

Everything runs perfectly fine as long as I launch it by .py file or .bat file (mouse clicking in file explorer). Unfortunately, when I put it on the schedule the program runs fine but log file doesn't get created.
I have tried multiple scheduler settings but the problem seems to be located in the code of the script.
Thanks for feedback!

A: I wanted to add the solution as an answer too, since this seems to be a somewhat common problem which has caused me some grief in the past.
When executing something from the Windows Task Scheduler the working directory of that process is not by default the path of the executable but some other directory. E.g. when your Scheduler action calls C:\sample.py this is not executed in C:\ but C:\Windows\system32 (in my case).
You can verify this by adding a Scheduled Task calling a simple Python/Batch script which saves the active working directory to some file, such as this
import os

with open("C:\\cwd.txt", "w") as fh:
    fh.write(os.getcwd())

or this
echo %cd% >> C:\cwd.txt

This messes with any relative paths your program may contain and, I  suspect, it has some more subtle issues that I have not been able to pin down yet.
Problems can be avoided by explicitly setting the optional 'Start in' path for your action:


text:
Q: Simplifying rspec unit tests A lot of times in unit test in rspec having to specify both a context and a let is somewhat cumbersome and seems unnecessary.  For example:
context 'type = :invalid' do
  let(:type) { :invalid }

  it { expect { subject }.to raise_error(ArgumentError) }
end

It would be nicer (in aggregate over lots of tests) if I could do something like:
let_context type: :invalid do
  it { expect { subject }.to raise_error(ArgumentError) }
end

The method would define a context and let(s) for me and the context's argument would be something like type = :invalid or let(:type) { :invalid } because I don't have anything else to say other that the fact that this variable has changed.

A:

A lot of times in unit test in rspec having to specify both a context and a let is somewhat cumbersome

Sounds like you might want to use a RSpec shared context.
UPDATE
RSpec provides a DSL for the syntax you're suggesting: a shared example. For example:
RSpec.shared_examples "some thang" do |type|
 it { expect { subject }.to raise_error(ArgumentError) }
end

RSpec.shared_examples "a thang" do
  include_examples "some thang", :invalid
  # Or whatever is more appropriate for your domain
  # I.e., If you're testing subclass behavior use it_should_behave_like()
end

A: actually you could get less lines by following some http://betterspecs.org recommendations:
context 'type = :invalid' do
  let(:type) { :invalid }
  it { expect{ subject }.to raise_error(ArgumentError)
end

Your variant could be read as

it raises an error expect subject to raise error

While this is much cleaner

it expect subject to raise_error

Nevertheless it is pretty off topic :)
UPD
Oh. Really you can't pass two blocks to method, so below example is not valid Ruby :)
context(:type) { :invalid } do
  it{ expect{ subject }.to raise_error(ArgumentError)
end

While your example
let_context type: :invalid do
  ...
end

Won't do lazy execution, like let does


text:
Q: firefox URL autocomplete: how to suppress autocomplete for the first few characters? Firefox's "awesomebar" goes into autocomplete mode as soon as you type in 1 character. That seems silly to me, and it hangs for a few seconds when I first start the program up, as it does its thinking + database queries / caching / whatever.
Is there a way I can suppress autocomplete until at least 3 or 4 characters have been typed?

A: Besides the 'search.timeout' configuration (in Sean's answer),
a few more suggestions here and here might make your experience better.
You may want to look at,

*

*'browser.urlbar.default.behavior'

*'browser.urlbar.matchBehavior'

A: You may also want to "vacuum" the database Firefox uses to store your history - believe it or not, it greatly improves the speed of the awesome bar.
There are two ways to do this - manually, or through an extension.
Manually:

*

*Open the Error Console - Tools->Error Console (on a Windows computer, you can press Ctrl + Shift + J)

*In the Code box, paste the following line (it's one line):
Components.classes["@mozilla.org/browser/nav-history-service;1"].getService(Components.interfaces.nsPIPlacesDatabase).DBConnection.executeSimpleSQL("VACUUM");

*Press the Evaluate button. Firefox will seem to "hang" as it cleans up the database.

*You're done!

Extension: Vacuum Places - after it's installed, just click on the little vacuum in the status bar, and it cleans everything up!

A: I don't see a setting to set the minimum characters required to launch a search, but you can try increasing the searchTimeout setting to, say, 700 (ms) from the default of 100. This will give you a chance to type a few more characters before the thrashing begins.

A: I'm not sure how to configure autocomplete in the Firefox 3 AwesomeBar.
However, I find that the oldbar extension works great.  It restores the old the Location Bar functionality of Firefox 2 to Firefox 3


text:
Q: how to fetch data when user comes to the footerView in table(iphone) I have made an uitableView and I am fetching data from json from a webservice
now i want that I get first 20 object first and load it in my tableView. it is happening properly
Now I want that when user scroll to the footer ..next 20 data should be fetched and it should be shown in tableView..
I am stuck here ..can anyone give me any idea how to proceed next?

A: You can use a ready made implementation of a UITableView with pull-to-refresh functionality.
Have a look at EGOTableViewPullRefresh or for a simpler implementation to PullToRefresh.
If you are interested in implementing this yourself, one approach is to add a subview to your UITableView (e.g., UILabel showing the "pull to refresh" message); then "intercept" the delegate methods when the user scrolls down (or up) and calculate whether the subview came into the viewable frame. Then issue the reload.
Another approach would be adding a last row to your table; then when the tableView:cellForRowAtIndexPath: method of your data source is called, return a cell with the "pull to refresh" message and do the refresh.
But you will be better off using one of the suggested implementations.

A: May be you can put Load more button in footerview and by tapping that you can load another 20 records from server ?
Another method is to implement Pull To Refresh and modify it as per your need.

A: To know if you reached the button of the table (aka: seeing the footer) I think you could use this:
How to know when UITableView did scroll to bottom in iPhone


text:
Q: How to display a length into minutes and seconds with a leading zero using printf() I am working on my second java program. I am creating a class called Song and a main class to test the Song class. My issue is in my method public void songDisplay() located in the Song class. The assignment calls for me to calculate length into min and sec using / and % operators and to output using printf()  while displaying a leading zero for seconds less than 10. I have tried to search how to do this and have failed. Any help would be appreciated!
An example of what I am looking to do would be for my method in the main class file my method testdisplaymethod(title3) the output should appear as follows  "Blue Canadian Rockies" (The Byrds) 2:02.
Song Class
public class Song {

    //declares private variables
    private String title;
    private String artist;
    private int length;

    public Song(String songTitle,String songArtist,int songMin,int songSec){
        this.title = songTitle;
        this.artist = songArtist;
        this.length = (songMin * 60) + songSec;
        }
     public Song(){
        title = "untitled";
        artist = "unknown";
        length= 0;
     }

    //accessors
    public String getTitle(){
        return this.title;
    }
    public String getArtist(){
        return this.artist;
    }
    public int getLength(){
        return this.length;
    }

    //mutatators
    public void setTitle(String songTitle){
        this.title = songTitle;
    }
    public void setArtist(String songArtist){
        this.artist = songArtist;
    }
    public void setLength(int songLength){
        this.length = songLength;
    }
    public void songdisplay(){
        System.out.printf("\"%s\",(%s),", title, artist, length);
        System.out.println();
    }
}

Main Class file to test Song class
public static void main(String[] args) {

        // creates a default object to test default constructor
        Song title1 = new Song();
        testdefaultconstructor(title1);

        // creates a an object to test accessor/mutator methods
        Song title2 = new Song("For What It's Worth", "Buffalo Springfield",2,37
        );
        testfourparamconstructor(title2);

        //tests the display method
        Song title3 = new Song("Blue Canadian Rockies", "The Byrds", 2,2);
        testdisplaymethod(title3);
    }
    // tests the defaul constructor
    public static void testdefaultconstructor(Song title1){
        System.out.println("Testing default constructor");
        System.out.println("Title: "+ title1.getTitle());
        System.out.println("Artist: " + title1.getArtist());
        System.out.println("Length "+ title1.getLength());
        System.out.println();
    }
    public static void testfourparamconstructor(Song title2){
        System.out.println("Testing four-paramameter constructor");
        System.out.println("Title: "+ title2.getTitle());
        System.out.println("Artist: " + title2.getArtist());
        System.out.println("Length "+ title2.getLength());
        System.out.println();
    }
    public static void testdisplaymethod(Song title3){
        System.out.println("Testing Display Method");
        title3.songdisplay();
    }
}

A: To specify two digits with leading zeros the format specified is %02d. Change
System.out.printf("\"%s\",(%s),", title, artist, length); // <-- missing a format
System.out.println();

to
System.out.printf("\"%s\", (%s), %d:%02d%n", title, artist,
        length / 60, length % 60);


text:
Q: How to redirect all network traffic to a VM or docker image? I have a problem. I am running a wifi network. I would like to redirect ALL traffic on this network to a server. It would be nice if it was possible to use a docker container. It is not a problem to have a router connected directly to the host via the ethernet jack as I in that case can bridge the network.
So my question is:
Is it possible for all network traffic on a network (internal) to go to a VM or docker image? The VM or docker container will run either apache or Nginx.
And if so, How do I do this? preferably a kinda detailed guide.
I appreciate all answers!


text:
Q: Is a Windows Timer as accurate as Sleep()? Sleep() is very accurate, so for example if I want to sleep for 10 hours:
Sleep(36000000); // sleep for 10 hours

My thread will wait for exactly 10 hours (plus the time that Windows needs to wake up my thread, which is negligible).
However, since Sleep() will block my UI thread, I which to use Windows Timers instead. So is a Windows Timer as accurate as Sleep()? that is, will it wait for exactly 10 hours (plus the time it needs for my Window Procedure to receive the WM_TIMER message)?

A: Yes, the basic plumbing underneath Sleep() and SetTimer() is the same.  Something you can see by calling timeBeginPeriod(), it affects the accuracy of both.  It is the clock tick interrupt handler that counts sleeps and timers down and gets the thread scheduled when it gets ready to run again.  Their sleep/wait time is adjusted when the system clock gets re-calibrated by a time server.


text:
Q: Symfony2 How to check in action or template that i18n is switch off for current action (route)? I would like to switch off the language switcher for actions that has i18n disabled in route.
I do not want to hardcode actions identifiers anywhere, instead I would like to get information about status of i18n for current template/action.
/**
 * @Route("/path", name="route_name", options={"i18n" = false})
 * @Template("someAppBundle:Frontend/Home:something.html.twig")
 */
public function somethingAction()
{
    //How to check here if i18n is switch off?
    //How to check it directly in twig template?
    return array();
}

A: you can access route options via
$request->attributes->get('i18n')

or (in twig):
app.request.attributes.get('i18n')


text:
Q: Managing a large 3D array that is worked with often I'm trying to make a videogame. A randomly generated world made of 3D blocks, and with various creatures inhabiting it. Simple 2D graphics, tick-based time. I tried to generate a simple testing world like this:
        World currentWorld = new World(24576, 24576, 150);

    for (int ix = 0; ix < currentWorld.worldArray.length; ix++) {
        for (int iy = 0; iy < currentWorld.worldArray[0].length; iy++) {
            for (int iz = 0; iz < currentWorld.worldArray[0][0].length; iz++) {
                currentWorld.worldArray[ix][iy][iz] = new Element(random.nextInt(10));
                System.out.println(currentWorld.worldArray[ix][iy][iz].ID);
            }
        }
    }

And I got this error:
Exception in thread "Display" java.lang.OutOfMemoryError: Java heap space
 at cz.sargon.realms.world.World.<init>(World.java:11)
I understand that the error means that I ran out of Java's 'working' memory, intended for tempopary storage of data that is currently being worked with. Now, how do I go around storing this world somehow and working with it later? I will need to read from it every time I want to render something and also check the AIs of some of the creatures every few ticks (I plan for every creature in the world to check it's surroundings every few ticks and react in an appropriate way to its circumstances).


text:
Q: How to generate the API key or token for a service account? Being a beginner for JFROG Artifactory, I have clarification on a specific use case. Checking if I can get any solutions or directions before hitting the vendor support.
I am using the Artifactory pro v.7.31.10. Is it possible to generate the API Key or Access token by a non-admin individual using JFROG APIs for a service account instead of a human ID at Artifactory?
How can I generate an API key or an access token using Postman? Do I need to pass any parameters (such as for which user) other than having basic authentication at Postman? I couldn't find from the samples in the knowledge documentation.
For the Artifactory HA application which has SAML authentication enabled, I want to restrict users to download artifacts via their scripts using their service account (generic ids), which should be a local account at Artifactory. I am checking for the possibility of obtaining the API key or Access token as an individual developer for their service account at runtime rather than the admin generate a key or token for them.
I have seen samples for admin creates the access token which can be used as a bearer token in curl. Is it possible to achieve the same by a non-admin? Trying to remove the dependency over here.

A: You can use the below REST APIs to generate the API key and the access token,

*

*Create API key -

*Create Access tokens
Note, an admin can create access tokens for any user and a user who is not an admin can only create api keys and access tokens for himself.
Again, non-admin users cannot create api keys and tokens for other users but for himself.

A: Based on my experience, the access token created via UI will not work in DR mode when app is running at a different data center than where it was created, though the circle of trust is enabled for access federation. This seems to be a bug which will be fixed in 7.37, per support.
The only other option to make it work is by calling the api using curl or Postman as admin. Non-admins cannot create an access token for others. However, I couldn't create the access token for myself as an non-admin. This seems to be an issue. While SAML is enabled,  I tried to create the access token via browser and couldn't able to proceed. Was getting issue while trying to create via Postman.
At the end, only admin was able to create.


text:
Q: Breaking time of Burgers equation I am studying Burgers equation
$$
u_t+uu_x=0, \qquad u(x,0) = u_0(x) ,
$$
and I am trying to prove the expression for the breaking time $t_c$. I obtain that
$$
t_c=-\dfrac{1}{\min\limits_{x_1,x_2\in\mathbb{R}}\dfrac{1}{x_2-x_1}\int_{x_1}^{x_2}u_0'(x)dx},
$$
but I do not know why this is equal to
$$
t_c=-\dfrac{1}{\min\limits_{x\in\mathbb{R}}u_0'(x)}
$$
Thanks a lot!

A: This is slightly sloppy notation. You're missing a condition that $x_1\ne x_2$; otherwise the denominator is not defined. Also, in the first result the minimum should be the infimum, since for general $u_0$ the infimum may not actually be attained.
If you correct these two inaccuracies, the result follows naturally: If you take $x_1=x_0-\epsilon$ and $x_2=x_0+\epsilon$, where $x_0=\operatorname{argmin}\limits_{x\in\mathbb{R}}u_0'(x)$, the quotient goes to $x_0=\min\limits_{x\in\mathbb{R}}u_0'(x)$ for $\epsilon\to0$, and on the other hand
$$
\frac1{x_2-x_1}\int_{x_1}^{x_2}u_0'(x)\mathrm dx\ge\frac1{x_2-x_1}\int_{x_1}^{x_2}\min\limits_{x\in\mathbb{R}}u_0'(x)\mathrm dx=\min\limits_{x\in\mathbb{R}}u_0'(x)\;.
$$
Thus $\min\limits_{x\in\mathbb{R}}u_0'(x)$ is the infimum of the quotient.


text:
Q: How to pull dynamic data from a javascript-based website? I would like to pull the data from a site like this. The idea is to build a Google Chrome extension that can pull the data and maybe inject some javascript into the browser with statistics of each players action frequencies while the table is open.
I have noticed that if you use the Google devtools and 'inspect' a table while it is running, that the data changes with every players action. This is the data that would be useful to retrieve. What is the best way to do accomplish this task? Would it be to build a Javascript Chrome extension? Is this project too complicated for someone beginning in Javascript but has a few months in Python?
Thanks in advance!


text:
Q: having trouble making a function to find the determinant of a matrix Probably a simple fix, but I keep getting 0 as the determinate when I should be getting 22, I have to use dynamic memory allocation as well. Might be some problem with using floats as I am not completely familiar with how they work with pointers. Honestly don't know what could be causing the function to output a zero.
cpp.sh link to test: http://cpp.sh/5bu2v
#include <iostream>
#include <math.h>
using namespace std;

float determinant(float *mat1, int &rows1)
{
    float s = 1, D = 0;
    float *temp = new float[rows1 * rows1];
    int i, j, m, n, c;
    if (rows1 == 1)
    {
        return (*(mat1 + 0 * rows1 + 0));
    }
    else
    {
        D = 0;
        for (c = 0; c < rows1; c++)
        {
            m = 0;
            n = 0;
            for (i = 0; i < rows1; i++)
            {
                for (j = 0; j < rows1; j++)
                {
                    *(temp + i * rows1 + j) = 0;
                    if (i != 0 && j != c)
                    {
                        *(temp + m * rows1 + n) = *(mat1 + i * rows1 + j);
                        if (n < (rows1 - 2))
                            n++;
                        else
                        {
                            n = 0;
                            m++;
                        }
                    }
                }
            }
            int V1 = rows1 - 1;
            D = D + s * (*(mat1 + 0 * rows1 + c) * determinant(temp, V1));
            s = -1 * s;
        }
    }
    return (D);
}

int main()
{
    int i, j;
    int n = 3;

    int matrix[10][10] = {{1, 2, 3},
                          {0, 4, 5},
                          {1, 0, 6}};
    float *mat1 = new float[n * n];
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            *(mat1 + i * n + j) = matrix[i][j];
        }
    }
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
            cout << matrix[i][j] << " ";

        cout << endl;
    }

    cout << "Determinant of the matrix is " << determinant(mat1, n);
    return 0;
}

A: Your first call into determinant, mat is a 3x3 matrix stored in a 1 dimensional array.  Visualize it like this:
A B C
D E F
G H I

You create another 3x3 matrix, temp.
You series of loops to fill the temp matrix exclude the first row and column c, so it ends up looking like this the first time thru:
D E 0
G H 0
0 0 0

This gets passed to determinant, which is expecting a 2x2 matrix.  Since you've passed it something else, what the recursive call sees is
D E
0 G

When you construct temp you need to do it with the smaller matrix size, not the source size.


text:
Q: Multiple POST request issues in Node JS so I have been building a web app and I have already implemented a POST request to request some JSON data to be sent to the Node JS server however when I try to add a second post for a different set of data now as an HTML form I receive a Cannot POST /x/ page, however, if I use the previous POST URL for the first set of data the data is sent correctly. Is there some issue with sending multiple POST requests? I have added some code below so you can see my working /foo/ JSON data request vs my non-working /basket/ HTML form request. Thanks a lot in advance.
Working Code:
    app.post("/foo/", function(req, res) {

    var myObject = req.body;

    console.log(myObject);

    for(var i = 0; i < myObject.length; i++){
        var parsed = JSON.parse(myObject[i])
        console.log(parsed.Item.ProductNo);
        console.log(parsed.Item.Quantity);
    }

    var transporter = nodemailer.createTransport({
  service: '*****',
  auth: {
    user: '*****',
    pass: '*****'
  }
});

Not working request:
    app.post("/basket/"), function(req, res){
    var body = req.body;
    console.log(body);
}

Working foo request JS:
function sendBasket(){

    fetch('/foo/', {
  method: 'post',
  headers: {
    'Accept': 'application/json, text/plain, */*',
    'Content-Type': 'application/json'
  },
  body: localStorage.getItem('basket')
}).then(res=>res.json())
  .then(res => console.log(res));

    console.log('Sending' + basketList + 'To email');
    //console.log(localStorage.getItem('basket'));
    //$.post("/foo/", localStorage.getItem('basket'), function(temp) {
    // temp === "I am done";
//});

}

Not working HTML form request:
form#customerForm(method = 'post' action = '/basket/')
            input(class='input' id='email' name='email' type='email' value='')
            ul#listForBasket.listForBasket
            input#butSubmit(type = 'submit' value = 'submit')

A: Answer: I'm still somewhat unsure how I fixed it but the issue has now been resolved, I believe it was due to the incorrect use of the Action attribute in the HTML form along with a badly structured fetch request in the JS file and also a badly structured server.js file. Huge thanks to u/fastidious-magician for being a great help in diagnosing my issues. Here is my final working second fetch request in JS:
function sendData(e){
    e.preventDefault();
    const email = document.getElementById("email").value;
    const bodyToSubmit = { "email": email }
    console.log(JSON.stringify(bodyToSubmit))
    fetch('/foo2/', {
          method: 'post',
          headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/json'
              },
          body: JSON.stringify(bodyToSubmit)
            }).then(res=>res.json())
              .then(res => console.log(res));
}


text:
Q: How to use continue with Task in C# in If condition I have implemented wcf client in my .NET application. My question is how I can ensure that if condition is call after Task> is completed?
  private List<MarketingCampaign> _GetAllCampaignTypeList()
    {
        List<MarketingCampaign> _MarketingCampaignList = null;

        Task<List<MarketingCampaignTypeData>> _MarketingCampaignTypeDataList = _MarketingCampaignTypeClientObject.GetAllCampaignTypes();

        ??? // how can I use continue with or Task.wait all in following if condition

        if(_MarketingCampaignTypeDataList!=null)
        {
           // code
        }

        return _MarketingCampaignList;
    }

above code is calling following class
  public async Task<List<App.Client.Proxies.MarketingCampaignTypeServiceRef.MarketingCampaignTypeData>> GetAllCampaignTypes()
    {

        var task  = Task<List<App.Client.Proxies.MarketingCampaignTypeServiceRef.MarketingCampaignTypeData>>.Factory.StartNew(() => {
                                            return _MarketingCampaignTypeClient.GetAllCampaignTypes();
                                      });

        return await task.ConfigureAwait(false);

    }

A: I believe you need something like this:
async Task<List<MarketingCampaign>> GetAllCampaignTypeList()
{
    List<MarketingCampaign> campaignList = null;

    List<MarketingCampaignTypeData> campaignTypeList = await _MarketingCampaignTypeClientObject.GetAllCampaignTypes();

    if(campaignTypeList != null)
    {
       // do whatever you need to convert campaignTypeList to campaignList
    }

    return campaignList;
}

Also, you don't need await in GetAllCampaignTypes method, just return task. And I would suggest you to not use Task.Factory.StartNew without proper reason. Use Task.Run instead: http://blog.stephencleary.com/2013/08/startnew-is-dangerous.html


text:
Q: Quick and dirty GridView not working I need to make a simple asp.net MVC project, which contains a GridView. I managed to get the gridview working, and showing actual data (I have an MS Access database set up), but it seems somehow I got something wrong: although everything shows up just fine, any buttons/links (like page updating, delete, edit, etc) don't do nothing. They just submit the form and refresh the page, but nothing is different.
Could you point me in the right direction? (although I couldn't find anything on google, I'm pretty sure this is a common newbie mistake)
Note: I know I didn't post any code, but I don't know exactly what code to post. If you need further information, please ask.

A: When you talk about GridView I hope you are not referring to GridView because that's not something you should be using in an MVC application.
If you are running MVC 3 you could use the WebGrid helper (which has some limitations) or MVCContrib Grid. There is also the Telerik Grid which is nice and worth looking at. You also have the possibility of a full client side javascript driven grid such as the jqGrid jquery Grid plugin.

A: The ASP.Net GridView will probably work much better for you in a conventional ASP.Net Web Site or Web Application project, which is different from an MVC application.
You have mixed the two kinds of web projects. You have to use MVC techniques in an MVC application, as Darin suggests.
If you are in a hurry and you don't mind changing from MVC to classic ASP.Net, you will probably be able to copy your code onto a new WebForm and get it working as you wish fairly quickly.
Otherwise, you will have to start over with a control intended for MVC.

A: I would recommend a jQuery Gridview. You can see one example here and you can see a blog post about it here.


text:
Q: How to create font preview image from font file on Linux? I am wondering if there is any easy / possible way to create a "font preview image" file for a given font file on the Linux command line.
You know, like when you click on a font file in Linux or Windows file explorer and you get a little font preview window with "The quick brown fox jumps overs the lazy dog" in different sizes etc.
The input font file would be .PFB (Adobe type 1 font) or .TTF (TrueType font).
So, for example:

createfontpreviewimage somefont.pfb

[which creates somefontpreview.png or whatever]
Any thoughts? Or will I have to go down the hard work route of embedding the font file in a PDF document and generating the preview as a PDF document with PDFLib or some such?

A: Use fontimage: http://fontforge.sourceforge.net/fontimage.html

A: Write simple PHP script and use
imagettftext()
function to generate your images


text:
Q: restfullyii Defining Custom Routes i bulit api using yii restful extension  http://www.yiiframework.com/extension/restfullyii/
i want create api  for login which accept username and password then  return all user
information i think the correct way to do that is to create custom router after checking
extension documentation section Defining Custom Routes  the author say i must create http verb combination (event name = 'req..\.render')
[POST] api/login/login
to create url i do this
main.php

 array('<controller>/req.post.login', 'pattern'=>'api/<controller:\w+>', 'verb'=>'POST'),

login Controller :
public function restEvents()
    {
        $this->onRest('req.post.login.render', function() {
            echo "sss";
            //Custom logic for this route.
            //Should output results.
            $this->emitRest('req.render.json', [
                    [
                    'type'=>'raw',
                    'data'=>['active'=>true]
                    ]
                    ])
        });
    }

  restEvents  didn't fire any help ??

A: to create custom routing add this to  controler and url will be http://css.local.com/index.php/api/controlername/test
    $this->onRest('req.post.test.render',function() {

        $this->emitRest('req.render.json', [
                [
                'type'=>'raw',
                'data'=>data
                ]
                ]);
    });


text:
Q: How to call activity Android from button HTML? I want to ask how to call activity on Android Studio from my buttom HTML.
This my button html code:
<button id="button" class="buttonHome" style="background:url(assets/scan.png)"></button>

and this is my java.activity:
@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    this.architectView.onPostCreate();
    try {

 this.architectView.load("file:///android_asset/cobarealobjek/index.html");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

and this my .xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.geowikitudes.RealObjectActivity">
    <com.wikitude.architect.ArchitectView
        android:id="@+id/architectView_real"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    </com.wikitude.architect.ArchitectView>
</FrameLayout>

A: If using a WebView instead of ArchitectView is an option for you, you may want to try using a JavascriptInterface.
You would have to define a class for your interface, which you would then bind to your WebViewClient, for example, AppInterface.
import android.webkit.JavascriptInterface;
import android.content.Context;
import android.content.Intent;

public class AppInterface {
    Context mContext;
    public AppInterface(Context context) {
        mContext = context;
    }

    // This is where you define the methods you want to be able to call from your web app
    // You have to annotate such methods with @JavascriptInterface
    @JavascriptInterface
    public void startMyActivity() {
        Intent intent = new Intent();
        intent.setClass(mContext, SecondActivity.class);  // Assuming SecondActivity is the name of activity you want to open
        mContext.startActivity(intent);
    }
}

In your main activity file, you could have something like this:
import android.webkit.WebView;
import android.webkit.WebViewClient;

Webview webView;
WebViewClient webVC;
// ...
@Override
public void onCreate(Bundle savedInstanceState) {
    // ...
    webView = (WebView) findViewById(R.id.webview);  // Assuming you have a webview with the id of "webview" defined in your layout
    webVC = WebViewClient();

    webView.setWebViewClient(webVC);
    webView.getSettings().setJavascriptEnabled(true);
    webView.addJavascriptInterface(new AppInterface(this), "Android");  // You can set the second parameter to any other string, just make sure that you change it accordingly in your javascript
    webView.loadUrl("yourURL");
    // ...

}

Finally, in your HTML/javascript code, you need to call the function via the provided javascript interface:
<button id="button" class="buttonHome" style="background:url(assets/scan.png)" onclick="Android.startMyActivity();"></button>
I hope this helps.


text:
Q: Drupal 7 db_query The perfect little module for what I am looking to do was made for drupal 6 but to my dismay it doesn't work on drupal 7. I've have learned that drupal 7 has a new api for the database. I have tried to get it to work but I am admittedly out of my league here. I am hoping some one could give me a little guidance. Specifically with the db_query.
function webform_image_validation_webform_validation_validate($validator_name, $items,
$components, $rule) {
$errors = array();
if ($items) {
switch ($validator_name) {
  case 'max_image_size':
    $dimensions = explode('x', $rule['data']);
    foreach ($items as $key => $val) {
      if (is_numeric($val['_fid'])) {
        $result = db_query("select * from {files} where fid = %d", $val['_fid']);
        while ($data = db_fetch_object($result)) {
          $thefile = $data;
        }
        $image_info = image_get_info($thefile->filepath);
        if (webform_image_validation_validate_image($image_info, $dimensions[0], $dimensions[1], FALSE) === FALSE) {
          $errors[$key] = t('Your image did not match the required width and/or height. (') . $dimensions[0] . t(' x ') . $dimensions[1] . t(')');
        }
      }
    }

This is the error I receive.
Argument 2 passed to db_query() must be an array, string given, called in
/home/designco/public_html/dev/sites/all/modules/webform_image_validation/
webform_image_validation.module on line 69 and defined in
/home/designco/public_html/dev/includes/database/database.inc on line 2310

It appears I need to add an array but I get lost there. Any help would be appreciated. I'm just trying to find out if I'm the right track.

A: db_query works differently in Drupal7.

$result = db_query("select * from {files} where fid = %d", $val['_fid']);
while ($data = db_fetch_object($result)) {
  $thefile = $data;
}

becomes

$results = db_query("select * from {files} where fid = :fid", array(':fid' => $val['_fid']));
foreach($results as $result) {
  // Do your thing for each result.
}

A: Try changing
$result = db_query("select * from {files} where fid = %d", $val['_fid']);
while ($data = db_fetch_object($result)) {
  $thefile = $data;
}

to
$query = db_select('files', 'f')
  ->fields('f')
  ->condition('fid', $val['_fid']);
$thefile = $query->execute()->fetchObject();

The Drupal 7 database API docs http://drupal.org/node/310069

A: thanks JurgenR for the answer.
Just to add one more thing: In drupal 6, we use '%s' for strings. In drupal 7, it is same for all.
For example:
$results = db_query("select * from {files}
where filename = :fname", array(':fname' => $filename));

If you want to search for records starting with a pattern then query will be:
$results = db_query("select * from {files}
where filename = :fname", array(':fname' => $filename.'%'));

Hope this is useful.


text:
Q: What are each of the separate mongodb-org packages for ubuntu? I am installing mongodb on a local ubuntu vm and I'm using the official Mongo supported packages per the official instructions. However, I don't know what each of these packages contain. I know this is a merely informational question, but I've googled and not found the answer.
mongodb-org
mongodb-org-server
mongodb-org-shell
mongodb-org-mongos
mongodb-org-tools
What do each of these packages provide? Thanks!

A: Please find below the details of each item from MongoDB official documentation.


text:
Q: Determining the type of isometry I am working on a problem that says:
Classify and discuss the isometry $F: \mathbb{E}^3 \to \mathbb{E}^3: (p_1,p_2,p_3)\mapsto (p_2-2,p_3+1,8-p_1)$.
I really don't know where to begin on problems like this. Can someone give me some hints to get me going? I think that I can write $F$ as
$$\begin{pmatrix}p_1 \\ p_2 \\ p_3 \end{pmatrix} \mapsto \begin{pmatrix}0 & 1 & 0 \\ 0 & 0 & 1 \\ -1 & 0 & 0 \end{pmatrix} \begin{pmatrix}p_1 \\ p_2 \\ p_3 \end{pmatrix} +\begin{pmatrix}-2 \\ 1 \\ 8 \end{pmatrix} $$
At this point I don't really know what to do. How would I go on to find out what kind of isometry it is and any additional information that can be given about the isometry?

A: I will expand on the hints I gave in the comments, and use them to work through the solution. If you want to stop reading at any point and try and finish off the question yourself, I recommend doing this. As a warning, writing $F$ as an affine transformation in the way you did in the question is a bit of a red Herring.
Hint 1: Find the fixed points of $F$.
Suppose $F(a,b,c)=(b-2,c+1,8-a)=(a,b,c)$, then $$a=b-2=(c+1)-2=((8-a)+1)-2=7-a$$  which implies $a=7/2$, and consequently $c=8-a=9/2$ and $b=c+1=11/2$, so $F$ has a unique fixed point, $(7/2,11/2,9/2)$.
Hint 2: What types of isometries of $\mathbb{E}^3$ have a unique fixed point? Can you relate these isometries to isometries of $\mathbb{S}^2$?
For simplicity, let's conjugate $F$ by the translation $T$ which sends $(0,0,0)\mapsto (7/2,11/2,9/2)$ to get a new isometry $F'=T^{-1}\circ F\circ T$ which fixes the origin. You can check $$F'(p_1,p_2,p_3)=(p_2,p_3,-p_1).$$ Since $F'$ is an isometry which fixes the origin, it is actually a linear isometry of $\mathbb{E}^3=\mathbb{R}^3$ thought of as a vector space. Because it doesn't change distances, the set of points a distance 1 from the origin is invariant, or put another way, it induces an isometry of the unit sphere $\mathbb{S}^2$.
There is a simple description of the isometries of the sphere, they are either 1) the identity, 2) a reflection in a great circle, 3) a rotation along a great circle, or 4) a glide reflection (rotation along a great circle followed by a reflection in that same circle.
Hint 3: Which type of isometry could $F'$ be, based on the description of fixed points we found?
Thought of as an isometry of the sphere, $F'$ has no fixed points, and hence must be a glide reflection, since the other types all do have fixed points: 1) all points of $\mathbb{S}^2$, 2) all points on the great circle, and 3) the poles of $\mathbb{S}^2$ relative to the great circle.
Hint 4: What is the invariant plane of $F'$?
Since $F'=S\circ R$ where $R$ is a rotation, and $S$ is a reflection we can ask what is the plane of reflection of $S$, which is also the invariant plane under the rotation $R$. Notice that $$F'(1,-1,1)=-(1,-1,1),$$
so the invariant plane is orthogonal to the vector $(1,-1,1)$.
Hint 5: What is the angle of rotation in this invariant plane by $R$?
Extend $(1/\sqrt{3})(1,-1,1)$ to an orthonormal basis of $\mathbb{R}^3$, eg $$\left\{e_1=\frac{1}{\sqrt{3}}(1,-1,1),e_2=\frac{1}{\sqrt{2}}(1,1,0),e_3=\frac{1}{\sqrt{6}}(-1,1,2)\right\}.$$ Then, since the reflection $S$ fixes $e_2$ and $e_3$ by definition, $$R(e_2)=F'(e_2)=\frac{1}{\sqrt{2}}(1,0,-1)=\frac{1}{2}e_2-\frac{\sqrt{3}}{2}e_3,\;\textrm{and}$$ $$R(e_3)=F'(e_3)=\frac{1}{\sqrt{6}}(1,2,1)=\frac{\sqrt{3}}{2}e_2+\frac{1}{2}e_3.$$
So as a rotation in the $(e_2,e_3)$ plane, $R$ is given by the matrix $$\begin{pmatrix}\frac{1}{2} & -\frac{\sqrt{3}}{2}\\\frac{\sqrt{3}}{2} & \frac{1}{2}\end{pmatrix}$$
and hence is a rotation by $\pi/3$.
Hint 6: Put it all together.
$F$ is the isometry which is a glide reflection of a sphere, centred on the point $(7/2,11/2,9/2)$, which rotates the affine plane through this point and orthogonal to $(1,-1,1)$ through an angle of $\pi/3$.
I have no doubt that there are more "direct" ways to compute this, but I hope working through the problem in a detailed geometric way gives you an intuitive understanding of what is going on.