text:
Q: Modal Window When Clicking Link Button I have a LinkButton inside a data list. When I click on this LinkButton, I want to open a modal window and load another html page in it.
Can you guys please help me with this?

A: You should check out a jQuery plugin like Thickbox, which I've used to do exactly what you've described.

A: check ModalPopupExtender....It's a component of Ajax Control toolkit.
First download it from from CodePlex ....and when you add reference the *Binary.dll to your project...you can use it within your pages.

A: I have always been a big fan of YUI, they have great documentation and Examples showing how to set things up. [ i love jQuery too ].
Look at YUI's Container Objects. They have very slick skinable Modal Panels:
http://developer.yahoo.com/yui/container/panel/
Here is a simple example:
http://developer.yahoo.com/yui/examples/container/panel-loading.html
Server Side
button.Attributes.Add("click", "popModal");

Client Side
<script>
    function popModal(e) {
        // Initialize the temporary Panel to display while waiting for external content to load
        var SavingPanel =
                        new YAHOO.widget.Panel("wait",
                            { width: "240px",
                                fixedcenter: true,
                                close: false,
                                draggable: false,
                                zindex: 1000,
                                modal: true,
                                visible: true
                            }
                        );

        SavingPanel.setHeader("Saving, please wait...");
        SavingPanel.setBody('<img src="http://l.yimg.com/a/i/us/per/gr/gp/rel_interstitial_loading.gif"  />');
        SavingPanel.render(document.body);

    }
</script>


text:
Q: How to run JavaScript functions in order (React) I have created a small react App that presents documents from a SharePoint site.
To make the App work correctly I am having to add setTimeouts, but I know there must be a better way using callbacks or promises or something >.<
My knowledge is lacking, so could somebody please point me in the right direction?
  // Handles what runs when the drop down is changed
  public handleDropdownChange(e) {

    // Updates dropdown select
    this.setState({ selectedOption: e.target.value, isLoading: true });

    // Checks security permissions - MAKES A GET REQUEST
    setTimeout(() => {
      this.getSecurityGroupUsers();
    }, 1000);

   // Ghecks if user can access docs
    setTimeout(() => {
      this.checkForDocAccess();
    }, 2000);

    // Gets documents - MAKES A GET REQUEST
    setTimeout(() => {
      this.getDocuments();
    }, 4000);

    // Delete Mark as Reviewed property THEN displays docs
    setTimeout(() => {
      this.hideMarkAsReviewed();
    }, 8000);

  }

One of the functions:
  // Grabs the documents
  public getDocuments() {

    axios
      .get("https://bpk.sharepoint.com/_api/search/query?querytext='owstaxIdDocumentx0020Owner:" + this.state.selectedOption + "'&trimduplicates=true&rowsperpage=100&rowlimit=1000&selectproperties='LastReviewDateOWSDATE,ScheduledReviewDateOWSDATE,Path'",
        { params:{},
          headers: { 'accept': 'application/json;odata=verbose' }
        })
      .then(response =>
          response.data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results.map(document => ({
            Type: this.checkFile(document),
            Name: document.Cells.results[6].Value.split("/").pop(),
            'Scheduled Review Date': document.Cells.results[8].Value.slice(0,-11),
            Path: document.Cells.results[6].Value.replace('https://bpkintelogydev.sharepoint.com', ''),
            Site: document.Cells.results[6].Value.split('/').slice(4).slice(0,1),
            'Last Review Date': document.Cells.results[7].Value.slice(0,-11),
            View: window.open(document.Cells.results[6].Value + '?web=1&action=edit')}>View,
            'Mark as Reviewed': Mark
        }))
      )
      .then(documents => {
        this.setState({documents, isLoading: true});
      })
      .catch(error => {
        //console.log(error);
      });

  }

A: Yes, callbacks or promises are what you do here. Promises would be the more modern way (not least so you can use async/await with them). setState provides a callback for when the state is set if you want that (it's an optional second argument to setState). Then your various functions (getSecurityGroupUsers, etc.) would return promises that they fulfill or reject.
In your getDocuments, for instance, you want to:

*

*return the result of calling then, and

*Don't have an error handler, leave that to handleDropdownChange
...and similar in the others. For any that don't already have a promise to chain on (getDocuments has the one from axios) because they use a callback-style API you can create a promise and fulfill/reject it yourself (see this question's answers for details there).
Doing that, handleDropdownChange might look something like:
// Handles what runs when the drop down is changed
public handleDropdownChange(e) {
    // Updates dropdown select
    this.setState({ selectedOption: e.target.value, isLoading: true });

    this.getSecurityGroupUsers()
    .then(() => this.checkForDocAccess())
    .then(() => this.getDocuments())
    .then(() => this.hideMarkAsReviewed())
    .catch(error => {
        // ...handle/report error...
    });
}

or if you didn't want to start those until the state had been changed initially:
// Handles what runs when the drop down is changed
public handleDropdownChange(e) {
    // Updates dropdown select
    this.setState(
        { selectedOption: e.target.value, isLoading: true },
        () => {
            this.getSecurityGroupUsers()
            .then(() => this.checkForDocAccess())
            .then(() => this.getDocuments())
            .then(() => this.hideMarkAsReviewed())
            .catch(error => {
                // ...handle/report error...
            });
        }
    );
}

In this particular case, async/await doesn't help much, but perhaps some. I assume handleDropdownChange shouldn't be async since it's an event handler and so nothing would handle the promise it would return, so:
// Handles what runs when the drop down is changed
public handleDropdownChange(e) {
    // Updates dropdown select
    this.setState({ selectedOption: e.target.value, isLoading: true });

    (async () => {
        try {
            await this.getSecurityGroupUsers();
            await this.checkForDocAccess();
            await this.getDocuments();
            await this.hideMarkAsReviewed();
        } catch (error) {
            // ...handle/report error...
        }
    })();
}

Notice how the entire body of the async function is in a try/catch, because nothing hooks its promise, so it's important we handle errors directly. (Ensure that "handle/report error" doesn't throw an error. :-) )

A: You can use Async await for waiting promise to resolve
public handleDropdownChange = async e => {

   this.setState({ selectedOption: e.target.value, isLoading: true });

   await this.getSecurityGroupUsers();

   await this.checkForDocAccess();

   await this.getDocuments();

   await this.hideMarkAsReviewed();
}

A: You need a function call back!
function functionOne(x) { return x; };

function functionTwo(var1) {
    // some code
}

functionTwo(functionOne);

A: Use async await and a simple sleep function to wait between them if it is required

const sleep = time => new Promise(res => {
  setTimeout(res, time);
});

async handleDropdownChange(e) {

    // Updates dropdown select
    this.setState({ selectedOption: e.target.value, isLoading: true });

    // Checks security permissions - MAKES A GET REQUEST
    await sleep(1000);
    await this.getSecurityGroupUsers();

    await sleep(1000);

   // Ghecks if user can access docs
   await this.checkForDocAccess();

   await sleep(1000);
    // Gets documents - MAKES A GET REQUEST
    await this.getDocuments();

    await sleep(1000);
    // Delete Mark as Reviewed property THEN displays docs
    await this.hideMarkAsReviewed();
  }

  // But you methods should return a promise like this

  getDocuments = () => {
     return fetch('some url').then(res => res.json());
  }

  // Or something like
  getSecurityGroupUsers = async () => {
    const data = await axios('some url');
    return data.message;
  }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it good to avoid macro in this example? I read that data > functions > macros
Say you want to evaluate code in a postfix fashion.
Which approach would be better?
;; Macro

(defmacro reverse-fn [expression]
  (conj (butlast expression) (last expression)))

(reverse-fn ("hello world" println))
; => "hello world"

;; Function and data

(def data ["hello world" println])

(defn reverse-fn [data]
  (apply (eval (last data)) (butlast data)))

(reverse-fn ["hello world" println])
; => "hello world"

Thanks!

A: If you require different evaluation behavior for any kind of data in your code macros are your best choice because they can transform unevaluated data at compile time to the code you'd like to be evaluated instead.

Clojure has a programmatic macro system which allows the compiler to be extended by user code. Macros can be used to define syntactic constructs which would require primitives or built-in support in other languages. (http://clojure.org/macros)

The example you provide has specifically that requirement ("evaluate code in a postfix fashion") which is why a macro is the correct choice.

A: In general:
Macros have their use however; macros expand at the point they are encountered so you will have one or more code blocks being inlined in the resulting byte code. They are ideal for encapsulating High Order DSL terminologies.
Functions, on the other hand, are wonderful for reuse where you localize the purity of the function and it can be called from multiple other functions without increasing the code footprint. They are ideal for localized or global usage.
REPL behavior consideration: A single function is easier to rework without worrying about fully evaluating the entire source file(s) to ensure all macro reference expansions get updated.
Hope this helps

A: Simple rules are the best: Use a function if you can, a macro if you must.

A: Your macro is better than your function: a macro is better than a function employing eval.
However, the function need not employ eval. You could write it
(defn reverse-fn [data]
  (apply (last data) (butlast data)))

Then, for example, as before,
(reverse-fn [3 inc])
=> 4

On a related topic, you might find this explanation of transducers interesting.

Edit:
Notice that functions are literals, in the sense that a function evaluates to itself:
((eval +) 1 1)
=>  2


text:
Q: Refactor class that has multiple methods with the same signature I have a class with multiple methods that have the same signature:
string MethodA(int id);
string MethodB(int id);
string MethodC(int id);

The implementation of these methods differs obviously, but I'm trying to make this more SOLID. I got a long way with Composite pattern, where a Composite class would implement the IDoSomething interface below:
public Interface IDoSomething
{
   string DoSomething(int id);
}

public class CompositeClass : IDoSomething
{
    private readonly IEnumerable<IDoSomething> somethings;
    public CompositeClass(IEnumerable<IDoSomething> somethings)
    {
        this.somethings = somethings;
    }

    public string DoSomething(int id)
    {
        foreach (var s in somethings)
        {
            return s.DoSomething(id);
        }
    }
}

Problem is the result to return. This is different for each call. I could change the signature to string[] but that seems like a hack. Any ideas?

A: I don't see what you are trying to achive, the class and method looks good. You can use a Decorator pattern to chain methods, but it seems you need several results as well?
If you want the same method name and signature, you can use explicit interface implementation, which is not really a good practice.
You can even go the really dirty way and use an interface with your Methodname and signature. Derive markup interfaces (which is an ANTI pattern!). Implement the derived interfaces explicitly. Implement the base interface by using reflection on yourself and invoking all the "other" interface methods... but don't do that for sake of... well everything!

A:
Problem is the result to return. This is different for each call.

This seems to be an improper use of the Composite pattern. The general idea behind the Composite is that you don't care whether you work with a Composite or any of its constituents, because they are logically interchangeable.

To illustrate, say you have an abstraction
interface IPainter
{
    double PaintedArea(double hours);
}

You have a bunch of implementations --
class DiligentPainter : IPainter
{
    double PaintedArea(double hours) => hours * 100;
}

class LazyPainter : IPainter
{
    double PaintedArea(double hours) => hours * 20;
}

And here is a key part -- come to think of it, your clients may not care whether they hire a single painter or a crew. They only care that all their walls are painted.
So your can make a composite PainterCrew and make it work as a single painter --
class PainterCrew : IPainter
{
    readonly IEnumerable<IPainter> painters;

    PainterCrew(IEnumerable<IPainter> painters)
    {
        this.painters = painters;
    }

    double PaintedArea(double hours)
    {
        return this.painters.Sum(p => p.PaintedArea(hours));
    }
}

See, you are not just returning a collection of individual results -- you are aggregating it in a meaningful way, so that it doesn't matter from the caller's side whether they are working with a Composite or a single entity.


text:
Q: How to throw an exception in server and catch it in client c++? I was wondering if I could send an exception from server and receive it in the client.
Here's my server:
void MyServer::on_new_message(int identifier, string message) {
    if(/*some condition for message*/)
      throw BadIO();
}

and here's my client's main:
int main(){
try{
          cin>>c;
          socket.send(c);
          socket.receive();
        }
            catch(BadIO& exp)
        {
          cout<<exp.what()<<endl;
        }
    return 0;
    }

after runing this code I get:

terminate called after throwing an instance of 'BadIO'
  Aborted (core dumped)

Thanks in advance :)

A: It is possible.
The exception needs to be serialized in the server, just like any other object you pass between processes. Have a special message for exceptions, so that socket.receive can detect it, deserialize the exception and throw it in the client.


text:
Q: Using changePage in JQuery Mobile in Cordova (PhoneGap) I have downloaded the file structure of my JQuery Mobile app. I have done this to test running it from the local file system. The reason why is I want my app to run with Cordova. From my understanding cordova runs files under file://. Currently, my file structure looks like this:
index.html
account
  register.html
  reset.html

In index.html, I have a "sign up" button. When someone clicks it, I use the following code:
$.mobile.changePage("account/register.html", { transition: "slide" });

I've verified that register.html works fine if i put the complete path in the browser url.  Oddly, I see "error loading page" when I click "sign up". Is there some problem with using changePage under file://. If so, how do I overcome this?
Thank you!

A: try this
$.mobile.changePage("../account/register.html", { transition: "slide" });

A: You can just leave .. links in the code and it will work fine. Unless you have a reason to explicitly call changePage.

A: This answer is specificly if you run into an issue running the PhoneGap app on iOS.
Be sure you set the $.mobile.allowCrossDomainPages = true; which is required for AJAX calls to inject pages.
In your PhoneGap app object definition:
var app = {
    initialize: function() {
        // setting required to use $.mobile.changePage()
        // http://jquerymobile.com/demos/1.2.0/docs/pages/phonegap.html
        $.mobile.allowCrossDomainPages = true;
    },
};

So when you call app.initialize() in your index.html, this property will be set prior to any $.mobile.changePage() function calls.
This will save you hours of trying to figure out the issue as no error is returned via the Safari Web Inspector.


text:
Q: REMOTE_EXEC_OUTPUT_MARKER_ build.txt doesn't exist This PhpStorm 2022.2.1 issue may happen when you are trying to Download your IDE after assertively pointing the Installer the remote development server project folder.
I can see the remove folder is recognized, the SSH connection is OK, but it suddenly stops to work and displays the following log. The above-mentioned build.txt can't be found, as it can be seen at the last line:
[ip here] :: uname -sm :: exit
code: 0 :: stdout: Linux x86_64 :: stderr:
[ip here] :: uname -sm :: exit code: 0 :: stdout: Linux x86_64 :: stderr:
[ip here] :: echo $HOME :: exit code: 0 :: stdout: /home/ec2-user :: stderr:
[ip here] :: test -f /home/ec2-user/.cache/JetBrains/RemoteDev/remote-dev-worker/remote-dev-worker_8be48ed1f7d9d149a663842f0df2735b7433265d1654774596e54ce70af850f2 :: exit code: 0 :: stdout:  :: stderr:
[ip here] :: test -x /home/ec2-user/.cache/JetBrains/RemoteDev/remote-dev-worker/remote-dev-worker_8be48ed1f7d9d149a663842f0df2735b7433265d1654774596e54ce70af850f2 :: exit code: 0 :: stdout:  :: stderr:
[ip here] :: echo $SHELL :: exit code: 0 :: stdout: /bin/bash :: stderr:
[ip here] :: /bin/bash -lc echo\ REMOTE_EXEC_OUTPUT_MARKER_\ \&\&\ /home/ec2-user/.cache/JetBrains/RemoteDev/remote-dev-worker/remote-dev-worker_8be48ed1f7d9d149a663842f0df2735b7433265d1654774596e54ce70af850f2\ exists\ --path=/home/ec2-user/.cache/JetBrains/RemoteDev/dist/d230e8fa76ec0_PhpStorm-222.4167.9/.expandSucceeded\ --file=true :: exit code: 0 :: stdout: REMOTE_EXEC_OUTPUT_MARKER_
false :: stderr:
[ip here] :: /bin/bash -lc echo\ REMOTE_EXEC_OUTPUT_MARKER_\ \&\&\ /home/ec2-user/.cache/JetBrains/RemoteDev/remote-dev-worker/remote-dev-worker_8be48ed1f7d9d149a663842f0df2735b7433265d1654774596e54ce70af850f2\ create-dir\ --path=/home/ec2-user/.cache/JetBrains/RemoteDev/dist/d230e8fa76ec0_PhpStorm-222.4167.9 :: exit code: 0 :: stdout: REMOTE_EXEC_OUTPUT_MARKER_ :: stderr:
[ip here] :: /bin/bash -lc echo\ REMOTE_EXEC_OUTPUT_MARKER_\ \&\&\ /home/ec2-user/.cache/JetBrains/RemoteDev/remote-dev-worker/remote-dev-worker_8be48ed1f7d9d149a663842f0df2735b7433265d1654774596e54ce70af850f2\ available-space\ --path=/home/ec2-user/.cache/JetBrains/RemoteDev/dist/d230e8fa76ec0_PhpStorm-222.4167.9 :: exit code: 0 :: stdout: REMOTE_EXEC_OUTPUT_MARKER_
2790494208 :: stderr:
[ip here] :: /bin/bash -lc echo\ REMOTE_EXEC_OUTPUT_MARKER_\ \&\&\ /home/ec2-user/.cache/JetBrains/RemoteDev/remote-dev-worker/remote-dev-worker_8be48ed1f7d9d149a663842f0df2735b7433265d1654774596e54ce70af850f2\ product-code\ --ide-path=/home/ec2-user/.cache/JetBrains/RemoteDev/dist/d230e8fa76ec0_PhpStorm-222.4167.9 :: exit code: 1 :: stdout: REMOTE_EXEC_OUTPUT_MARKER_
{"type":"error","errorCode":"CommandError","data":"/home/ec2-user/.cache/JetBrains/RemoteDev/dist/d230e8fa76ec0_PhpStorm-222.4167.9/build.txt doesn't exist"} :: stderr:

In fact this file doesn't exist, and I even tried touch build.txt at this /home/ec2-user/.cache/JetBrains/RemoteDev/dist/d230e8fa76ec0_PhpStorm-222.4167.9/ but then it can't be parsed and a corresponding error emerges.
This same issue was open here: https://youtrack.jetbrains.com/issue/WI-68709/REMOTEEXECOUTPUTMARKER-buildtxt-doesnt-exist

A: This problem occurs because of a reason that prevented the IDE of being downloaded on the server.
In the link you provided it is said that it may be because of a low bandwidth but there could be more reasons.
In my case I had this problem because of a lack of space on server. The IDE requires at least 4GB of empty space to be downloaded.


text:
Q: Representation of a Gradual underflow program I was reading about the gradual underflow concept and how it is op important in the music industry Gradual overflow Application in Music
I well understand the problem of an overflow buffer, but this i don't know how to represent an underflow.
Can you please give me an example(a program preferably in c or c++) as in how a computer handles gradual underflow?

A: Gradual underflow is related to what IEEE 754 calls "subnormal" numbers.
Consider using scientific notation in which you have (say) 10 digits of precision and exponents that can range from -99 through 99.
Under normal circumstances, you treat everything as scientific notation, so if you want to represent 1000, you represent it as 1e3 -- that is, 1 * 103.
Now, consider a number like 1.234e-102. The smallest exponent you can represent is -99. So, if you do your job the simplest possible way, you simply that since it has an exponent smaller than that, it's just 0. That would be "fast underflow".
In IEEE 754 (and related standards) you can store that as (essentially) 0.001234 * 10-99. In doing so, you may lose some precision compared to a normal number that has an exponent in the -99...99 range. On the other hand, you lose less than if you just rounded it to zero because it has an exponent smaller than -99. In fact, in this case it started with 4 significant digits, and as represented it retains all 4 significant digits.
On a computer, the numbers are represented in binary, so the numbers of significant digits and/or maximum range of exponents aren't round numbers when converted to decimal, but the same basic idea applies--when we have a number that's too small to represent in the normal format, we can still store it with the smallest exponent that can be represented, but also includes some leading zeros.
This does lead to one difficulty: numbers are normally stored in what's called normalized form. The "significand" part is normalized by shifting it left until the first digit is a 1 (keep in mind that since it's binary it can only be 0 or 1). Since we know it's a 1, we cheat a little: we don't normally store that 1 in the number as it's stored. So, a double precision floating point number normally has 53 bits of precision, but only actually stores 52 bits of significand.
With a subnormal number, that's no longer the case. That's not terribly difficult to deal with, but it still introduces a special case--and one that's only rarely used, so CPU designers (and such) rarely try to optimize for it. As a result, the exact same code can suddenly run a lot slower when executing on data that contains subnormals.


text:
Q: How to wrap function in haskell? addMod26 a b = (a + b) `mod` 26
char2Int c = ord c - (ord 'a')
int2Char i = chr (i + (ord 'a'))
addChar a b = int2Char ((addMod26 `on` char2Int) a b)

This code try to implement add operation on char. It work well. But function addChar is too redundancy. How to simplify it?
try to write like this
addChar = int2Char . (addMod26 `on` char2Int)

It's wrong. (.) :: (b -> c) -> (a -> b) -> a -> c cannot accept (b -> b -> c) as it's first argument.
any good idea, or suggestion?

A: If you want to write addChar in point-free form, it would be:
addChar = (int2Char .) . (addMod26 `on` char2Int)

Or:
addChar = int2Char .: (addMod26 `on` char2Int)

Where (.:) = (.) . (.), which composes a unary function with a binary function:
(.:) :: (c -> d) -> (a -> b -> c) -> a -> b -> d

You can discover these refactorings using the pointfree tool, although its results tend to be ugly.


text:
Q: MDM prompting for password I have been using Cisco Meraki for mdm and its has been working fine. I have observed today that it is asking for a shared mailboxes password after an ios gets updated. Can you guys help me out?
Thanks


text:
Q: Change value on time PHP/AJAX I have this code which change value on click
$.post('test.php', {val:value}, function (data) {
var value = document.getElementById('value');
val.value = value;
}

I need to change value on time(for example on 10 sec) how i can do that with Ajax?

A: If I understand your question correctly, you need to call the server (i.e. "poll") and get the latest value based on a set time interval. If that is the case, you should look at the setInterval() function and have it call your update method. For example:
function update() {
   $.post('test.php', {val:value}, function (data) {
       var value = document.getElementById('value');
       val.value = value;
   }
}

// Call every 10 seconds
var seconds = 10;
var int = setInterval(update, seconds * 1000);

Be aware that this sort of polling, especially on Apache (my guess since you tagged PHP) can quickly use up your max connections if you have a lot of traffic and effectively DDOS your own web server.

A: So since you said after 10 seconds:
You want to use the setTimeout function, after the delay specified in miliseconds
function postValue() {
   $.post('test.php', {val:value}, function (data) {
       var value = document.getElementById('value');
       val.value = value;
   }
}

Now we set the click handler to call the postValue function after a timeout of 10 seconds
var seconds = 10;
$('#button').click(function(){
    setTimeout(postValue, seconds * 1000)
});


text:
Q: Speech Bubble with background image but here's the kicker with rounded corners I'm creating a speech bubble that has the background in the little triangle, but the only problem is it also needs rounded corners.  I'm not entirely sure how to do this, but any hack or anything would be appreciated.
Here's what I have
HTML

CSS
.image {
    position:relative;
    width:340px;
    background:orange;
}
.image:before, .image:after {
    border-left: 20px solid white;
    content: "";
    left: 0;
    position: absolute;
    width: 0;
}
.image:before {
    border-bottom: 5px solid transparent;
    height: 34px;
    top: 0;
}
.image:after {
    top: 39px;
    bottom:0;
    border-top: 5px solid transparent;
}
.test {
    display:block;
    width:100%;
}

Here's a fiddle. http://jsfiddle.net/yL7Hg/
EDIT: If it helps I only need the top-left corner to have the radius for reasons of the way my design works.  I can get the top-right just using a border-radius on .image.

A: Try this: http://www.html5rocks.com/en/tutorials/masking/adobe/
Clipping and masking using HTML5.
It has browser limitations as it uses HTML5.  But all the recent browsers support it.

A: Here it is:
http://jsfiddle.net/HYgbu/

I know its not the perfect one solution, but still it is as my first thought.

A: This could be achieved much easier and with standard CSS. Just set 2 DIVs, one for the arrow, the other with image as background (instead of IMG tag):

And 2 respective classes:
.arrow {
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-right:35px solid #1E0C01;
    float:left;
    margin-top:50px;
}

.test {
    margin-left:35px;
    width:340px;
    height: 240px;
    background-size:cover;
    background-image: url("http://fc00.deviantart.net/fs71/f/2011/322/e/2/e292b11555866aec8666ded2e63ee541-d4gl4vg.png");

That's it: http://jsfiddle.net/yL7Hg/5/


text:
Q: How to deploy python programs in Anaconda environments on Windows? I am trying to use Anaconda and conda environments to allow Python programs for data acquisition* etc. to run from the (Anaconda) command line on Windows.  The set up will be that the Python programs are installed to a particular location (cloned from Github), within %PATH% or whichever environment variable is more appropriate.
From an Anaconda command prompt in another directory and a particular conda environment, I want (both myself and other users) to be able run either python test.py <args> or test.py <args> (either solution is acceptable) and have a system wide conda environment run its Python to execute the program.  test.py can/will have an appropriate shebang set.
Right now the python test.py calls the correct Python within the active conda environment, but cannot find the test.py program as Python won't search the %PATH% or similar looking for the program. test.py does something (Windows does not complain that the executable can't be found, and I've been playing with the file associations to get this far), but doesn't appear to start Python - a simple print function or raise statement as the only entry in the file does nothing.
I've tried setting file associations in Windows, but this hasn't changed anything.  I've copied the py.exe/pyw.exe across to the Anaconda environments, with no change.
Is this something that can be done within Anaconda, or am I going to have to fall back on installing base Python directly and trying to use the launcher mechanism there?
Note that I'm also intending to deploy these programs on Raspbian, so any solutions, including non-Anaconda ones, that will work cross platform there would be worth extra effort on my part.
*these programs have significant usage of library packages for accessing external USB/GPIB/serial/ethernet connected lab equipment and use matplotlib, scipy, etc., hence the desire for a cloneable conda environment as the base environment.

A: It turns out the correct answer to this is fairly simple, but is fairly hard to find explained well. This might be a little clearer than the other answers I found:
Install the standalone launcher from pylauncher and add #!/usr/bin/env python shebangs to your scripts.
This should register .py files to Python.File and will find your Anaconda Pythons in appropriate environments.  If you don't have a non-Anaconda python, it will use the Anaconda base environment (these two facts were the key element I was missing from various other answers around this problem that I had looked at, including the documents on python.org).
If you have a Python from python.org installed, then a standalone command line shell will use that, defaulting to Python 2.x, then Python 3.x.  With #!/usr/bin/env python shebang, then a regular command shell will try to use python.org pythons first, then the Anaconda base environment.  An Anaconda prompt will use the active environment.  #! /usr/bin/env python2 or python3 will try to use python.org pythons only and fail if they are not found.
Installing Python 2.7 from python.org installers (and letting the installer set the file associations) will break pylauncher, and reinstalling will not fix it.  Instead, set Computer\HKEY_CLASSES_ROOT\Python.File\Shell\open\command default value to "C:\WINDOWS\py.exe" "%L" %* to revert back to the pylauncher set up (assuming you used the launchwin.* packages to install it).


text:
Q: Why is this if-condition always excluding 2? I created this loop to find prime numbers, the int num is initialized as 0, but the debugger always skips 1 (which is correct) and 2 (which is not correct).
How does it come that it always skips 2 % 2 == 0 ?
for (int num = 0; num <= 100; num++) {
    for (int j = 2; j < num; j++) {
        if (num % j == 0) {
            System.out.println(num + " is not a prime number.");
            break;
        }
        if (num - j == 1) {
            System.out.println("PRIME NUMBER FOUND! It's: " + num + ".");
            myPrimeNumbers.add(num);
        }
    }
}

A: The problem with your code is that in the case num=2 you don't get into the part where you add the prime number. You chose to use the last iteration of the inner loop as the place where to add a prime number to your list, but with num=2 the inner loop has 0 iterations.
I'd modify your program as follows:
package test;

import java.util.ArrayList;
import java.util.List;

public class Test {

    private static boolean isPrime(int num) {
        for (int j = 2; j < num; j++) {
            if (num % j == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main (String [] args) {
        List<Integer> myPrimeNumbers = new ArrayList<>();
        for (int num = 2; num <= 100; num++) {
            if (isPrime(num)) {
                System.out.println("PRIME NUMBER FOUND! It's: " + num + ".");
                myPrimeNumbers.add(num);
            }
        }
    }
}

Extracting the prime test into a method makes it easy to place the true and false returns at locations where they are intuitively correct.
And I started the prime number search with 2 instead of 0 as we all know that 0 and 1 are by definition no primes.


text:
Q: Perl: Fastest way to find files older than X number of minutes, sorted oldest to newest? =================
1. Find the files older than X number of minutes
2. Process them from oldest to newest
The Code below works fine, however the directory contains 3 millions of files. Hence I need to optimize it to find the files faster. I don't have to worry about the content of the file just the name.
###########################
sub get_files_to_process{
###########################
# Declare arrays
my @xmlfiles;
my @qulfiedfiles;

# Declare a Dictionary
my %filedisc;

opendir(my $dh, $maindir) or die "opendir($maindir): $!";

 # Read all the files
 while (my $de = readdir($dh)) {
    # get the Full path of the file
    my $f = $maindir . $de;
    # If File is there and has .xml Extension
    if ( -f $f && $f=~ /\.xml/){
       # Put it in a XMLFILES Array
       push (@xmlfiles, $f); }
    }
    closedir($dh);

 # For every file in directory
 for my $file (@xmlfiles) {

    # Get stats about a file
    my @stats = stat($file);

    # If time stamp is older than minutes provided
    if ($stats[9] <= ($now - (( $minutesold * 60) ))){

       # Put the File and Time stamp in the dictionary
       $filedisc{$file} = $stats[9];
    }
 }

# For every file in the dictionary sort based on the timestamp oldest files first
 for my $x (sort {$filedisc{$a} <=> $filedisc{$b} or $a cmp $b } keys %filedisc) {

    # Put the qualified files (Based on the age) in a list
       push(@qulfiedfiles, $x);}

UPDATE: So far this seems promising, more testing to be done:
##########################
sub get_files_count{
##########################

   my $cmd= "find $maindir -maxdepth 1 -name '*.xml' -mmin +$minutesold -printf \"%T+\t%p\\n\"| sort";
   my @output = `$cmd`;

   if (@output){
      foreach my $line (@output){
            chomp $line;
            push (@files2process, ( split '\t', $line )[ -1 ]);
         }
      }
   }

A: Use File::Find
use File::Find

$\ = "\n";

my @files;

# find all files newer that 9 minutes
File::Find::find({wanted => \&wanted}, '.');

# sort them and print them
print for map { $_-[0] }  sort { $b->[1] <=> $a->[1] } @files;

exit;

sub wanted {
   ((-M) < (9 / (24 * 60))) && -f && push @files, [ $_, ( -M ) ];
}

This is recursive - so it will go through all sub-directories (but I assume from your question there are none).
Also, the above is mostly auto-generated code from find2perl, which translates most of unix find parameters into a perl script - cool and fast.
I haven't tested the -M bit with the 9 minutes - I haven't saved anything in the last 9 minutes.

A: I would solve this in two steps:
1) create an Linux::Inotify2 process, what at every change on the directory would updates some cahce file (like Storable or such)
e.g. you will have an actual cache of all file-stats. Loading one Storable file is faster as gathering stats for 3M files at every run
2) when need search, only load the Storable, a search one big hash...

A: I know that this is an old question. I am mostly answering it for the "future generations".
Most of your time is very likely spent in sorting the 3 million file entries, because sort operations are non-linear (ie sorting becomes slower and slower the more files you have), and also because most of the stat calls occur in the comparisons, which mostly occur due to sort.
(Also the file list will probably occupy quite a chunk of your memory.)
So if you can avoid sorting, you will also automatically avoid most of the stat calls and save a ton of time. Since your task is just "moving the files into appropriate directories" I would simply call the processing method for each file you find that fits your criteria, the moment you find it, as opposed to first creating an enormous list, use a bunch of cycles to sort it, and then going through the enormous list and process it in a way that doesn't necessarily need sorting in the first place.
An example from your own script: "find", unlike say "ls", does not create a file list in memory -- it executes the commands for each file the moment it finds it. Which is why it doesn't explode with enormous directories, unlike "ls". Just do it like find does it ^^


text:
Q: numerical dispersion in ODE I am solving an ODE equation : $u_{xx}+k^2u=0$. I use second order approximation to the $u_{xx}$.The exact solution is $\exp(ikx)$, where $k$ is the wavenumber. For the boundary condition I set $u(0) = \exp(ik0) = 1$ and I use $u_x-iku=0$ when $x=2\pi$.
I plotted the graph with Matlab and saw some phase shifting. As my $k$ increases, the phase shifting also increases.
But my scheme does not include time. Why does it still have shifting?


text:
Q: Count Records X of Y across Records on Form I have a Form with fields StudentID, StartDate, TxDate (Treatment Date) among c.60 other fields.
There is a Go To Student drop-down box in the Form's Header that establishes a subset for the StudentID selected records only when a particular StudentID is selected from the drop-down.
There are buttons to click to First, Previous, Next, Last
I want to show on the Form, as you click First, Previous, Next, or Last, and go to the Next record, the number record for that individual StudentID.  That is, if the Student had 6 records, it would display 1 of 6 for their first record, 2 of 6 for the Next, 3 of 6 for the Next....
I've tried things like DCount('RecordNo","Depression Form Query","Student") which counts all the records in the Data Table, not just the individual StudentID's.
I used an Autonumber in the Students Table but it generates a number equivalent to the StudentID being the 3rd Student entered, not a count of their Treatment Dates.
I've tried various loopings I've found on the net but they do not count across records for the same Student.
I made an X of Y Report which I then dragged and dropped into the Form.  It generates the correct Y (6) but an incorrect X.
[]
The Depression Form Query is based on the Students Table and the Depression Table.

A: I am aware you want to count records. The Allen Browne link is discussing counting records.
Your DCount() would have to be:
DCount("*","[Depression Form Query]","StudentID=" & [StudentID] & " AND RecordID < " & [RecordID]) + 1
Just realized the Allen Browne link doesn't really go into use of DCount for this, just barely mentions it to advise that it can be very slow. And it can be.
If you apply filter criteria to the query, the same filter criteria would have to be constructed within the DCount() WHERE argument.
A nested query to rank within grouping would be even more complicated than the examples in the link.
A form is just not a practical vehicle for this calc. Better would be to build a report using its Grouping & Sorting feature and textbox RunningSum property.


text:
Q: OpenCV HDR processing producing bad output on iOS I am trying to create an HDR image from 7 images taken with different exposure values on iOS. I used the OpenCV cocoapod and followed this GitHub repository to implement HDR processing. I have got the fusion image working and it has a decent picture output, however, the HDR version produces a bad output. It somewhat looks like the image is a negative version of what it should be. See below:

I have tried to mess around with my code to produce 8-bit and 32-bit versions of this image since that's what I read on some other questions.
I also included my HDR.cpp file that does the merging to HDR:
cv::Mat mergeToHDR (vector<Mat>& images, vector<float>& times)
{
    imgs = images;
    Mat response;
    Ptr<CalibrateDebevec> calibrate = createCalibrateDebevec();
    calibrate->process(images, response, times);

    // Ptr<CalibrateRobertson> calibrate = createCalibrateRobertson();
    // calibrate->process(images, response, times);

    // create HDR
    Mat hdr;
    Ptr<MergeDebevec> merge_debevec = createMergeDebevec();
    merge_debevec->process(images, hdr, times, response);

    // create fusion
    // Mat fusion;
    // Ptr<MergeMertens> merge_mertens = createMergeMertens();
    // merge_mertens->process(images, fusion);

    // fusion
    // Mat fusion8bit;
    // fusion = fusion * 255;
    // fusion.convertTo(fusion8bit, CV_8U);
    // return fusion8bit;

    // hdr
    Mat hdr8bit;
    hdr = hdr * 255;
    hdr.convertTo(hdr8bit, CV_8U);
    return hdr8bit;
}

Let me know if you need any more of my code.
Here is my code to produce the Mat images:
-(cv::Mat)CVMat
{
    CGColorSpaceRef colorSpace = CGImageGetColorSpace(self.CGImage);
    CGFloat cols = self.size.width;
    CGFloat rows = self.size.height;

    cv::Mat cvMat(rows, cols, CV_8UC4); // 8 bits per component, 4 channels

    CGContextRef contextRef = CGBitmapContextCreate(cvMat.data,
                                                    cols,
                                                    rows,
                                                    8,
                                                    cvMat.step[0],                                                                      colorSpace,
                                                    kCGImageAlphaNoneSkipLast |
                                                    kCGBitmapByteOrderDefault);

    CGContextDrawImage(contextRef, CGRectMake(0, 0, cols, rows), self.CGImage);
    CGContextRelease(contextRef);

    return cvMat;
}

- (cv::Mat)CVMat3
{
    cv::Mat result = [self CVMat];
    cv::cvtColor(result , result , CV_RGBA2RGB);
    return result;
}

-(cv::Mat)CVGrayscaleMat
{
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGFloat cols = self.size.width;
    CGFloat rows = self.size.height;

    cv::Mat cvMat(rows, cols, CV_8UC1); // 8 bits per component, 1 channels

    CGContextRef contextRef = CGBitmapContextCreate(cvMat.data,                 // Pointer to data
                                                    cols,                       // Width of bitmap
                                                    rows,                       // Height of bitmap
                                                    8,                          // Bits per component
                                                    cvMat.step[0],              // Bytes per row
                                                    colorSpace,                 // Colorspace
                                                    kCGImageAlphaNoneSkipLast |
                                                    kCGBitmapByteOrderDefault); // Bitmap info flags

    CGContextDrawImage(contextRef, CGRectMake(0, 0, cols, rows), self.CGImage);
    CGContextRelease(contextRef);
    CGColorSpaceRelease(colorSpace);

    return cvMat;
}

+ (UIImage *)imageWithCVMat:(const cv::Mat&)cvMat
{
    return [[UIImage alloc] initWithCVMat:cvMat];
}

- (id)initWithCVMat:(const cv::Mat&)cvMat
{
    NSData *data = [NSData dataWithBytes:cvMat.data length:cvMat.elemSize() * cvMat.total()];
    CGColorSpaceRef colorSpace;

    size_t elemSize = cvMat.elemSize();
    size_t elemSize1 = cvMat.elemSize1();

    size_t channelCount = elemSize/elemSize1;
    size_t bitsPerChannel = 8 * elemSize1;
    size_t bitsPerPixel = bitsPerChannel * channelCount;

    if (channelCount == 1) {
        colorSpace = CGColorSpaceCreateDeviceGray();
    } else {
        colorSpace = CGColorSpaceCreateDeviceRGB();
    }

    // Tell CGIImageRef different bitmap info if handed 32-bit
    uint32_t bitmapInfo = kCGImageAlphaNone | kCGBitmapByteOrderDefault;

    if (bitsPerChannel == 32 ){
        bitmapInfo = kCGImageAlphaNoneSkipLast | kCGBitmapFloatComponents | kCGBitmapByteOrder32Little;
    }

    CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);

    // Creating CGImage from cv::Mat
    CGImageRef imageRef = CGImageCreate(cvMat.cols,                                 //width
                                        cvMat.rows,                                 //height
                                        bitsPerChannel,                             //bits per component
                                        bitsPerPixel,                               //bits per pixel
                                        cvMat.step[0],                              //bytesPerRow
                                        colorSpace,                                 //colorspace
                                        bitmapInfo,                                 // bitmap info
                                        provider,                                   //CGDataProviderRef
                                        NULL,                                       //decode
                                        false,                                      //should interpolate
                                        kCGRenderingIntentDefault                   //intent
                                        );

    // Getting UIImage from CGImage
    self = [self initWithCGImage:imageRef];
    CGImageRelease(imageRef);
    CGDataProviderRelease(provider);
    CGColorSpaceRelease(colorSpace);

    return self;
}


text:
Q: Use-case of +new in Cocoa? And why it exist?
Possible Duplicate:
alloc, init, and new in Objective-C

There is +alloc/-init... and +new. Their role are almost same in documentation except +new is designed for instance pooling. (according to my understanding :)
However the pooling is possible with +alloc/-init. Why the separated method is required? Or is there any reason for the method?
And I couldn't find any example utilizes the method. When should I use this method? Can I get some use-case of the method +new?

A: In the original Objective-C implementation from Stepstone, +new was what  we used to create instances. It was a holdover from Smalltalk.  NeXT separated +new into +alloc/-init since most classes don't have to do anything different to allocate the memory their instances use, and it didn't make sense to duplicate that code all over the place.


text:
Q: logical drive as dvd drive I am having a English learning DVD, i copy complete dvd into my hard disk then install that english learning software from hard disk, after i install i try to run the installed software it said your dvd is not into Dvd rom please insert dvd and they start play it.

A: "magic Disk" is the one to create virtual drive, works for me chilll


text:
Q: Can one quantify the total luminosity of the cosmological horizon? If I integrate all the power (radiation, matter particles, neutrinos) radiated from the cosmological horizon into the universe, what number do I get?
Is it true that the integral power/luminosity is of the order of $c^5/G = 3.6 \cdot 10^{52}$ Watt?
Has the integral horizon power been constant over the past evolution of the universe?

A: First I will answer your first question, calculating a value for the radiated power.
I was unable to find any discussion of "power" in
https://en.wikipedia.org/wiki/Cosmological_horizon .
I think your concept has a flaw. When you calculate black body radiation power ($P$) in watts from an object, the object will have a surface area ($A$) and a temperature ($T$). The watts per unit area depends on temperature.
http://hyperphysics.phy-astr.gsu.edu/hbase/thermo/stefan.html
$$P = \sigma A T^4$$
$\sigma$ is the Stephan-Boltzmann constant
https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_constant
$$σ = 5.670374419 \times 10^8 \, \mathrm{ W/(m^2 K^4)}$$
I suggest you choose a value for the radius ($R_{\mathrm{ou}}$) of the observable universe and a value for the time of radiation, $t>0$. Then calculate a value for the scale factor value $a(t)$.
https://en.wikipedia.org/wiki/Observable_universe
$R_{\mathrm{ou}}\mathrm{(now)} = 46.5\, \mathrm{ Gly}$
$R_{\mathrm{ou}}\mathrm{(now)}$ is the current radius of the spherical surface that did the radiation at time $t$.  You then need to calculate the radius $R_{\mathrm{ou}}(t)$.
$$R_{\mathrm{ou}}(t) = R_{\mathrm{ou}}\mathrm{(now)} / a(t).$$
The time t chosen should be well into the era when radiation mass equivalent density dominates matter (and also of course dark energy).  Therefore,
$$T(t) = T(\mathrm{now}) / a(t)$$
Now calculate the power radiated.
$$R = \sigma  4 \pi R^2_{\mathrm{ou}}(t)  T^4_{\mathrm{ou}}(t)$$
Now for the second question.  I think this is just wrong. The radiation is watts per area, and there is no area in your calculation, presumably because $t=0$.
Now for the third question. I am not sure what you are intending to ask. There are two possible interpretations.

*

*Is the radiation from time $t$ still radiating? The answer is no. It stopped radiating immediately after time $t$. However, a little later, say at $t+dt$, there will be radiation observed at the same observation place (at the center of the observable universe sphere)  at little later than "now".

*Is the radiation from a sphere at radius $R_{\mathrm{ou}}(t)$ detectable at the center of the sphere at all times since t, and with the same intensity? The answer is yes, it continues to be observable at all times since $t$, but the observed intensity changes with the time "now". For different times "now" the observed intensity depends upon how far the radiation travels to the observer, $R_{\mathrm{ou}}\mathrm{(now)}$. The observed intensity of radiation will be inversely proportion to the square of the distance: $1/R^2_{\mathrm{ou}}\mathrm{(now)}$.


text:
Q: Jquery .on() not working with "e" working
$('.newbubble').live('click', function(e){
    console.log('clicked');
});

Not Working (here i want to get e.pageX and e.pageY)
$('.newbubble').on('click', function(e){
    console.log('clicked');
});

Again Working this one without "e"
$('.newbubble').on('click', function(){
    console.log('clicked');
});

Can anyone please help me with this, how can i get e.pageX with .on()

A: I imagine, .newbubble doesn't exist on DOM ready, so you'll need to delegate.
For example :
$('body').on('click', '.newbubble', function(e){
    // here
});

Read the doc

A: try
$(document).on('click','.newbubble', function(e){
    console.log('clicked');
});


text:
Q: Rails: Can't get fields_for to work inside a nested resource I'm trying to add a fields_for attribute to a nested rails form. Any time I try to create a new object, it returns

Message(#58819400) expected, got
Array(#18903800) ...
app/controllers/discussions_controller.rb:53:in
`create'

If I try to access nested fields_for from forms based on non-nested resources (aka "form_for @parent" instead of "form_for [@parent, @child]" it works fine. Code below - any help with this really appreciated.
Controller:
  # GET /discussions/new
  # GET /discussions/new.xml
  def new
    @forum = Forum.find(params[:forum_id])
    @discussion = Discussion.new
    @discussion.messages.build

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @discussion }
    end
  end

  def create
    @forum = Forum.find_by_id(params[:forum_id])
    @discussion = @forum.discussions.new(params[:discussion])
    @discussion.user = current_user

    respond_to do |format|
      if @discussion.save
        format.html { redirect_to([@forum, @discussion], :notice => 'Discussion was successfu#ly created.') }
        format.xml  { render :xml => [@forum, @discussion], :status => :created, :location => @discussion }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @discussion.errors, :status => :unprocessable_entity }
      end
    end
  end

Models:
class Forum < ActiveRecord::Base
  belongs_to :user
  has_many :discussions, :dependent => :destroy
  validates :title, :presence => true

  accepts_nested_attributes_for :discussions, :allow_destroy => true
end

class Discussion < ActiveRecord::Base
  belongs_to :user
  belongs_to :forum
  has_many :messages, :dependent => :destroy
  validates :title, :presence => true
end

class Message < ActiveRecord::Base
  belongs_to :user
  validates :user, :presence => true
  validates :content, :presence => true
end

The view:
<%= form_for [@forum, @discussion] do |f| %>
  <% if @discussion.errors.any? %>

<%= pluralize(@discussion.errors.count, "error") %> prohibited this discussion from being saved:

      <% @discussion.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

    <%= f.label :title %>

    <%= f.text_field :title %>

  <%= f.fields_for :messages do |builder| %>
    <%= builder.label :content, "Message" %>
    <%= builder.text_area :content, :rows => 10 %>

  <% end %>

    <%= f.submit %>

<% end %>

And finally, the routing:
  resources :forums do
    resources :discussions do
      resources :messages
    end
  end

Any help with this really appreciated - I'm completely stumped.

A: Arghhh - really sorry folks...I just realised I'd forgot the accepts_nested_attributes_for in the discussions model, & consequently forums could access discussions, but discussions couldn't get down to messages.
Thanks anyhow.


text:
Q: Markov Chain with an Exponential Distribution in Python I am new to random number generation in Python.
I understand the concept of a Markov Chain, but I am unable to convert it into a useful code:
Markov Chain - P(X_m+1 = j|X_m = i, X_m-1 = x_m-1,.....,X_0 = i_0) = P(X_m+1 = j |X_m = i)

For example how could I use Python to generate a Markov chain of real numbers distributed according to
the exponential distribution :
P(x) = Ne^{−|x|}

where N is a normalization factor?

A: I think what you are looking for is
import numpy.random as npr
p_x = npr.exponential(N,t)

where N is the inverse of the scaling factor and t is the number of random numbers you want to generate. You'll have to compute the parameters in advance, according to the order of the chain (in your case, 1).


text:
Q: Drupal 6: Make a menu_hook() return a specific view I created a hook in order to add an item to the administrator's menu. When the user clicks on the item, I want to return the content of a specific view I created. How should I return the view?
My current code looks like:
function my_view_menu(){
   $items['view'] = array(
    'title' => 'Report',
    'page callback' => 'return_my_view',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );
   return $items;
}

function return_my_view(){
  return t("Hello!");
}

EDIT:
As suggested by Berdir, this the correct way to call a view:
function return_my_view(){
  $viewName = 'my_report'; // use the machine readable name of the view
  return views_embed_view($viewName);
}

A: You could just add a menu item in the view itself...and restrict access (to the view) to the admin role of choice :)

*

*In your view choose "page" and click
on the "Add Display" button (if there isn't already a page display).

*Under
"Page Settings" add a Path and a
Normal Menu-Entry in the Navigation
Menu

*Next Under Basic Settings
change the access to Role based and
choose the role(s) that should have
access

*Finally go to the
navigation menu settings and drag
the new menu item to the desired
place in the Administer menu

A: You want views_embed_view(), see http://web.archive.org/web/20110213234806/http://thedrupalblog.com/embedding-view-drupal-6-using-views-embed-view

A: views_embed_view() is the correct call. If you are getting a blank page, try checking your apache error log to see if there are any php errors. I also notice that in your revised example you used $viewName = "my-report", but views_embed_view() expects the machine readable name of the view, which only allows for alphanumeric and underscore characters. Perhaps you are using the incorrect name?

A: Third technique: Once you have created a Page Display for a View, Views will provision that page with a menu entry. Once that exists, it is possible to duplicate that menu entry for your own purposes.

*

*Create a module with a weight of at least 11 (higher weight than Views)

*Implement hook_menu_alter() and duplicate the View entry.
function example_menu_alter(&$items) {
  $items['admin/new/path'] = $items['original/view/path'];
}

This approach is somewhat convoluted, but is sometimes a useful alternative for Views or other "page" content you want to clone.

A: In addition to berdir's comment, you can also skip the intermediate callback function and just call views_embed_view directly from your menu router:
function hook_menu(){
   $items['path/to/my/view'] = array(
    'title' => 'Report',
    'page callback' => 'views_embed_view',
    'page arguments' => array('my-view-name'),
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}


text:
Q: What is the shortest way C# I am new to C#. I have a table called invoicemaster. When I am generating a new invoice number I use below code. If someone is cleared a invoice in a multi user environment, I put 'Y' in iscleared column and use that invoice number for the next invoice. Otherwise I generate invoice number by adding 1 to the max number. I have two issues.

*

*Is there a short way to write this code.

*When I try to get the MIN(invno), it returns a null value and rows.count show as 1. But there is no record in the table. How to prevent that?

int intInvNo = 0;
sql = "SELECT MIN(invno) FROM invoicemaster WHERE `iscleared`='Y'";
config.singleResult(sql);

if (config.dt.Rows.Count > 0)
{
   intInvNo = Convert.ToInt32(config.dt.Rows[0].Field<int>(0).ToString());
}
else
{
   sql = "SELECT MAX(invno) FROM invoicemaster";
   config.singleResult(sql);

   if (config.dt.Rows.Count > 0)
   {
      intInvNo = Convert.ToInt32(config.dt.Rows[0].Field<int>(0).ToString()) + 1;
   }
}

lblInvNo.Text= String.Format("{0,12:00000000}", intInvNo);


text:
Q: Timeout on Google Apps Script "maximum execution time" Hi, I have a script that changes the visibility on calendar events. The script reaches the maximum execution time. Is there any way I can prevent this? Or, even better, right now the script goes through each and every event, even if they are already set to private. Could I modify the script so that it only checks the current day?
function ChangeCalendarEvents() {

      //Room1
    var mycal = 'comp.com_38353134313283637333434@resource.calendar.google.com';
    var cal = CalendarApp.getCalendarById(mycal);
      var events = cal.getEvents(new Date('January 1, 2014 00:00:00 CST'), new Date('December 31, 2014 23:59:59 CST'), {visibility: 'default' || 'public'});
      for (var i=0;i<events.length;i++) {
        events[i].setVisibility(CalendarApp.Visibility.PRIVATE);
      }

      //Room2
      var mycal2 = 'comp.com_319373936383633831343039@resource.calendar.google.com';
    var cal2 = CalendarApp.getCalendarById(mycal2);
      var events = cal2.getEvents(new Date('January 1, 2014 00:00:00 CST'), new Date('December 31, 2014 23:59:59 CST'), {visibility: 'default' || 'public'});
      for (var i=0;i<events.length;i++) {
        events[i].setVisibility(CalendarApp.Visibility.PRIVATE);
      }
    }

A: You can try the following modified version of your code.
It has the following changes:
1. mycal is now an array (makes code easier to read, easier to add / remove calendars to modify)
2. start / end boundaries are now variables (by default, start = today, end = today + 1 week)
This should run pretty quickly. If you are still having problems, set a debug point at "for (var i=0..." and tell me how many elements are in the events array.
function ChangeCalendarEvents() {
  var mycal      = ['comp.com_38353134313283637333434@resource.calendar.google.com',   //Room 1
                    'comp.com_319373936383633831343039@resource.calendar.google.com'], //Room 2
      start      = new Date(),
      end        = new Date(start.getYear(),start.getMonth(),start.getDate()+7);
  for (var index = 0; index < mycal.length;index++) {
       var cal   = CalendarApp.getCalendarById(mycal[index]),
          events = cal.getEvents(start, end, {visibility: 'default' || 'public'});
      for (var i=0;i<events.length;i++) {
            events[i].setVisibility(CalendarApp.Visibility.PRIVATE);
          }
      };
    }


text:
Q: PowerShell Invoke-Command with Start-Process outputs different result I have an update script for running the Dell Command Update tool. In short dcu-cli.exe. The thing now is than when i run the same script code on the computer local then everything runs OK but when i run the exact same code in a script with invoke-command(and yes i have full admin rights) than the exitcode is 2 meaning An unknown application error has occurred instead of 0 (everything OK)
It is a very large script so i created a new one to debug this. This is the shorted code:
Invoke-Command -ComputerName "MyComputer" -ScriptBlock {
    $ExitCode = 0

    #Declare path and arguments
    $DcuCliPath = 'C:\Program Files (x86)\Dell\CommandUpdate\dcu-cli.exe'
    $DellCommand = "/applyUpdates -autoSuspendBitLocker=enable -outputLog=C:\Dell_Update.log"

    #Verify Dell Command | Update exists
    If (Test-Path -Path $DcuCliPath) {
        $objWMI = Get-WmiObject Win32_ComputerSystem
        Write-Host ("Dell Model [{0}]" -f $objWMI.Model.Trim())

        $serviceName = "DellClientManagementService"
        Write-Host ("Service [{0}] is currently [{1}]" -f $serviceName, (Get-Service $serviceName).Status)
        If ((Get-Service $serviceName).Status -eq 'Stopped') {
            Start-Service $serviceName
            Write-Host "Service [$serviceName] started"
        }

        #Update the system with the latest drivers
        Write-Host "Starting Dell Command | Update tool with arguments [$DellCommand] dcu-cli found at [$DcuCliPath]"
        $ExitCode = (Start-Process -FilePath ($DcuCliPath) -ArgumentList ($DellCommand) -PassThru -Wait).ExitCode
        Write-Host ("Dell Command | Update tool finished with ExitCode: [$ExitCode] current Win32 ExitCode: [$LastExitCode] Check log for more information: C:\Dell_Update.log")
    }
}

When i remove the Invoke-Command -ComputerName "MyComputer" -ScriptBlock { and then copy + run the script local on the PC then the exitcode = 0
What i also noticed than when i run the command via 'Invoke-Command' then there is also no log file created as i passed along in the arguments... So my best guess is something is going wrong with local an remote paths?
So what am i missing? I'm guessing it is something simple but i spend several hours to get this running without any luck...

A: Try running it this way.  You should be able to see any output or error messages.  I typically add to the path first rather than using & or start-process.
invoke-command mycomputer {
$env:path += ';C:\Program Files (x86)\Dell\CommandUpdate';
dcu-cli /applyUpdates -autoSuspendBitLocker=enable -outputLog=C:\Dell_Update.log }

Using start-process inside invoke-command seems pretty challenging. I can't even see the output of findstr unless I save it to a file. And if I didn't wait the output would be truncated. By default start-process runs in the background and in another window.  There's a -nonewwindow option too but it doesn't help with invoke-command.
invoke-command localhost { # elevated
start-process 'findstr' '/i word c:\users\joe\file1' -wait -RedirectStandardOutput c:\users\joe\out }

A: @js2010, thanks for your additional help. Unfortunately this didn't helped either.
So i did some more debugging and it turns out it was a bug in the dcu-cli version running on my test machine, DOH...!!
On the test machine version 3.1.1 was running and on another machine version 4.0 was running and that worked fine via remote Powershell. So i looked for the release notes, which i found here: https://www.dell.com/support/kbdoc/000177325/dell-command-update
And as you can see in version 3.1.3 there was this fix:
A problem was solved where dcu-cli.exe was not executed in an external interactive session of PowerShell.


text:
Q: Is there a way to use different accessibility modifier for a setter in C#11 when using the "required" keyword? Is there a way to use different accessibility modifier for a setter in C#11 when using the "required" keyword?
    public class Person
    {

        public required string FirstName { get; protected set; }

        public void ChangeNameToMike()
        {
            FirstName = "Mike";
        }
    }

What I would like to achieve, is that when you instantiate the Person class, you'd need to provide a "FirstName" and you can access the name anywhere, but modifying it should only be possible inside the class and classes that inherit from the Person class. I know that it's possible to achieve this via a constructor, but would like to achieve it with the new required keyword, or something similar, basically to use newer way to write C# code.
The exact error I'm getting is:
CS9032 Required member 'Person.FirstName' cannot be less visible or have a setter less visible than the containing type 'Person'.
It works with a constructor, but I wanted to achieve the same result without one.
    public class Person
    {

        public string FirstName { get; protected set; }

        public Person(string firstName)
        {
            FirstName = firstName;
        }

        public void ChangeNameToMike()
        {
            FirstName = "Mike";
        }
    }

A: Similar to the idea here, you can add a protected field, and implement the public get and init accessors explicitly.
public class Person
{
    protected string firstName = "";
    public required string FirstName {
        get => firstName;
        init => firstName = value;
    }

    public void ChangeNameToMike()
    {
        firstName = "Mike";
    }
}

Since the property has a public init accessor, the compiler is happy about the required modifier, and you can set the field when you want to set it.


text:
Q: Adding an iterator of a trait on another trait I have a trait which has a function that should return an iterator of a different trait. I also need a common function which takes this trait and does operations on it.
This is the code I have currenty:
pub trait NodeLike : Sized {
    /// Get the node id
    fn get_id(&self) -> i32;
}

pub trait EdgeLike {
    /// Get the destination node id
    fn get_node_id(&self) -> i32;

    /// Get the edge id
    fn get_edge_id(&self) -> i32;

    /// iterates of the source nodes
    fn iter_source_nodes(&self) -> dyn Iterator<Item = dyn NodeLike>;
                                                       ^^^^^^^^^^^^^
}

fn operation(id: i32, edge: dyn EdgeLike) {
    for node in edge.iter_source_nodes().find(|n| n.get_id() == id) {

    }
}

The underlined part above throws the compiler error:
the trait `NodeLike` cannot be made into an object
`NodeLike` cannot be made into an object rustc E0038
main.rs(1, 22): for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>

Reading through the documentation, I believe my NodeLike trait is object-safe. The only function it has is &Self (i.e. &self)
Now, I can further my code by removing the Sized trait on NodeLike. However, then the error occurs in the function operation; I cannot use the find function on the iterator.
How can I change my code so that I can make NodeLike object safe, AND be able to return an iterator which I can call find on?

A: Following Stargateur's suggestion and your playground link, I got it to compile like this:
Playground link
This is if you do not want to use any unstable features.
The trick is to specify the explicit type of the iterator. If you don't know that type, just put any stupid type in and let the compiler complain about the type mismatch. It'll tell you that we're dealing here with a slice iter, so hence the std::slice::Iter.
The other modifications are then about adding a lifetime parameter to your struct, because iter() returns references. If you don't want that, change it to into_iter, but then you must use self instead of &self.
Also, for your operation, you must do some lifetime magic...
fn operation<'a, Item: NodeLike>(id: i32, edge: &'a impl EdgeLike<'a, Item=Item> )

If you are okay with unstable features, you can avoid having to specify the exact type of the iter: In your playground version just change the dyn to impl. The compiler will tell you that that's an unstable feature and will show you the macro to use.
Finally, to avoid having to add lifetime annotations to the trait itself, there's something about generic associated types, but maybe that's going too far for now.


text:
Q: When does a function call copy its pass-by-value arguments relative to the argument sequences? I would like to understand this code snippet as much as the undefined behavior permits it:
int i = 0;
printf("%d %d %d", i, ++i, i++);

output:
2 2 0

From what I can tell:

*

*a comma , defines a sequence

*the actual printing happens when all of the sequences are evaluated inside the function argument call

*since arguments are pass-by-value, a copy happens sometime(?!) while calling the function

*the order in which the function argument sequences evaluated is undefined ( is this true? )

So as far as I can tell most of the behavior in that single line of code is undefined, still I would like to understand the parts that are NOT undefined behavior.
I know the output depends on the compiler, but what parts are there that are defined in the C Standard?
I am interested in ANSI C, C99 as well, but I believe latest C++ standards improved on this at least in some aspects, is that true?

A:
a comma , defines a sequence

No. Don't confuse the comma operator (What does the comma operator , do?) for a function argument list. The actual , symbol is used in a lot of different places in the C syntax, but the only place where it has a well-defined order of evaluation is when it's used for the actual comma operator. Neither function call argument lists nor initializer lists have well-defined orders.
The C standard says this about function calls and arguments (C17 6.5.2.2):

There is a sequence point after the evaluations of the function designator and the actual arguments but before the actual call. Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function.

I your case the 4 arguments "%d %d %d", i, ++i, i++ are indeterminately sequenced in relation to each other and the sequence point, as mentioned above, is placed after the evaluation of the arguments.

To address your other statements:

*

*

the actual printing happens when all of the sequences are evaluated inside the function argument call

Correct, but then undefined behavior has already struck.

*

since arguments are pass-by-value, a copy happens sometime(?!) while calling the function

You can assume that these are pass by value indeed. printf is an icky variadic function so they end up in a va_list, which I believe has an implementation-defined representation internally.

*

the order in which the function argument sequences evaluated is undefined ( is this true? )

The order of evaluation of function arguments is unspecified behavior, meaning we can't know the order - it can be undocumented - and therefore we shouldn't assume a particular order. The actual undefined behavior happens because of 6.5/2:

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.

*

I would like to understand the parts that are NOT undefined behavior.

I'm not sure what you mean with that, since code can't be "just a little bit undefined". If it has undefined behavior and then all bets are off regarding anything in that program. You can't reason about it or it wouldn't be undefined, but something else. Therefore it doesn't make sense to reason like "undefined behavior turns this value to 55 and then it is passed by value". For example maybe the UB causes the whole function call to be optimized away or get inlined in strange ways.


text:
Q: this is problem when i want to add ui authentication for my laravel project This what it present when i run npm run dev

*

*how can i solve these problem?

npm ERR! code ELIFECYCLE
npm ERR! errno 1 npm ERR! @ dev: `vite`
npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm.
There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\\Users\\master dvd\\AppData\\Roaming\\npm-cache_logs\\2023-01-12T19_06_21_061Z-debug.log


text:
Q: index.js:1375 Warning: Each child in a list should have a unique "key" prop I wrote a BlackJack game, however after I query API from deck of cards API, the cards never showed on the screen. I have console log'd the player deck and deal deck, it has the card data but nothing displayed.
heres the error:
index.js:1375 Warning: Each child in a list should have a unique "key" prop.
Check the render method of BlackJack. See https://reactjs.org/link/warning-keys for more information.
at div
at BlackJack (http://localhost:3000/static/js/main.chunk.js:4166:3)
at WithStyles(BlackJack) (http://localhost:3000/static/js/0.chunk.js:54861:31)
this is the data after query
[Array(2)]
0: Array(2)
0: {code: "6C", image: "https://deckofcardsapi.com/static/img/6C.png", images: {…}, value: "6", suit: "CLUBS"}
1: {code: "JD", image: "https://deckofcardsapi.com/static/img/JD.png", images: {…}, value: "JACK", suit: "DIAMONDS"}
length: 2
__proto__: Array(0)
length: 1
__proto__: Array(0)

[Array(1)]
0: Array(1)
0: {code: "4H", image: "https://deckofcardsapi.com/static/img/4H.png", images: {…}, value: "4", suit: "HEARTS"}
length: 1
__proto__: Array(0)
length: 1
__proto__: Array(0)

below is my code:
import React, { useState, useEffect, useCallback } from 'react';
import axios from 'axios';
import { withStyles } from '@material-ui/core/styles';

const styles = () => ({
  app: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'column'
  },
  deckContainer: {
    textAlign: 'center'
  }
})

const BlackJack = ({ classes }) => {
  const [deckId, setDeckId] = useState(null);
  const [playerDeck, setPlayerDeck] = useState([]);
  const [dealerDeck, setDealerDeck] = useState([]);
  const [gameOver, setGameOver] = useState(false);
  const [winner, setWinner] = useState(null);

  useEffect(async () => {
    const deck_id = await axios.get('https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1')
      .then(res => res.data.deck_id);
    setDeckId(deck_id);
  }, []);

  const handleStartGame = async () => {

    const playerDeckList = [];
    const dealerDeckList = [];
    const playerDrawnCards = await axios.get(`https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=2`).then(res => res.data.cards);
    playerDeckList.push(playerDrawnCards);
    setPlayerDeck(playerDeckList);

    const dealerDrawnCards = await axios.get(`https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=1`).then(res => res.data.cards);
    dealerDeckList.push(dealerDrawnCards);
    setDealerDeck(dealerDeckList);
  };
  console.log(deckId);
  console.log(playerDeck);
  console.log(dealerDeck);
  // console.log(playerDeck[0]);

  return (

Welcome to the Black Jack Game

        <button onClick={handleStartGame}>start game</button>
        {/* <button onClick={handlePlayerHit}>hit</button> */}
        {/* <button onClick={handlePlayerStand}>stand</button> */}
        {/* <button onClick={handlePlayerReset}>reset game</button> */}

        {/* <GameOver isGameOver={gameOver} /> */}

Dealer:

          {dealerDeck.map(card => {
            return (

            )
          })}

Player:

          {playerDeck.map(card => {
            return (

            )
          })}

  )
};

export default withStyles(styles)(BlackJack);

A: The data you are setting is an array of an array, because res.data.cards is already an array.
So change your handleStartGame to
  const handleStartGame = async () => {
    const playerDrawnCards = await axios
      .get(`https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=2`)
      .then((res) => res.data.cards);
    setPlayerDeck(playerDrawnCards);

    const dealerDrawnCards = await axios
      .get(`https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=1`)
      .then((res) => res.data.cards);
    setDealerDeck(dealerDrawnCards);
  };

A: That's probably because fetching api is async operation. React first renders your jsx then go through the logic, at the moment your dealerdeck is getting mapped empty. Try setting up 1 more state for fetching api(default false), when fetch is over set it to false and then in your JSX render relevant component only when isFetching === false.
[isFetching, setIsFetching] = useState(true);
.
.
.
const handleStartGame = async ()=>{
.
.
.
      setIsFetching(false);
   }
.
.
.
return(
    {!isFetching && dealerDeck.map... }
)```


text:
Q: Evaluating absolute inequalities I have the *expression
$$\frac{1}{\sqrt{4a^2-b^2}}$$
and I am being asked to evaluate the case when $2|a| \geq|b|$
Logically I know what this statement mean but don't know how it applies to this problem: Cases when $a$ is twice greater than the distance of $b$ is from $0$.
(Correct me if i'm wrong)
I also know that absolute values on both sides of an equation are inpracticle and it would be better to write the inequality as $|a/b| \geq 1/2$.
Which can also be written as $a/b \geq  1/2$ or $a/b \leq 1/2$ which doesn't make any sense.
here's a link to the problem (#3)
http://imgur.com/a/GheWI
Thank you, I would appreciate help I've been struggling with this for a while

A: The only reason they say $2|a| \geq|b|$ is that if $2|a| \not\geq|b|$, the square root $\sqrt{4a^2 - b^2}$ doesn't make sense.

A: we have $$\frac{\sqrt{4a^2-b^2}}{-(4a^2-b^2)}=-\frac{1}{\sqrt{4a^2-b^2}}$$
and here we have $$2|a|>|b|$$


text:
Q: PDO Class bindParam() not working I'm trying to edit an INSERT query using bindParam().
Here is my code.
public function addProduct()
{
   $query = "INSTERT INTO producten (name, model, price, image, description)
   VALUES (:name, :model, :price, :image, :description)";

   $stmt = $this->dbh->prepare($query);

   $stmt->bindParam(":name", $_POST['name']);
   $stmt->bindParam(":model", $_POST['model']);
   $stmt->bindParam(":price", $_POST['price']);
   $stmt->bindParam(":image", $_FILES['file']['name']);
   $stmt->bindParam(":description", $_POST['description']);

    print_r($stmt);
}

$dbh object is created in the contruct function of the class;
public function __construct()
    {
       $user = "root";
       $pass = "";

       $this->dbh = new \PDO('mysql:host=localhost;dbname=projectname', $user, $pass);

    }

The $stmt->bindParam() returns true when tested but does not replace the given parameters.
Does anyone know what i'm doing wrong?

A: The whole idea about prepared statements is that you don't need to inject your raw parameters into the query to compose some SQL code with escaped data. Instead, you use simple place-holders and keep the data somewhere else. When the query needs to be run, you feed the database engine with both pieces of data (the SQL query with place-holders and the values that correspond to those place-holders) and the database itself takes care of the rest.
So:

*

*PDO will not edit your query. It doesn't need to.

*You still need to run the query. The "prepare" phase simply links a place holder with a variable, so the value can be read from the appropriate location when the query runs.

*You can actually prepare once and run many times with different parameters.

Note: some PDO drivers don't allow regular prepared statements (for instance, because the underlying DB engine does not fully support them). In that case, PDO will emulate prepared statements and actually perform good old escaping. But since PDO is an abstraction layer, this shouldn't change the way you deal with it.

A: Well, you have a typo (INSTERT). How to avoid it next time?
When constructing the PDO object, make sure PDO::ATTR_ERRMODE is PDO::ERRMODE_EXCEPTION, this will cause PDO to throw PDOExceptions upon errors. Do it as follows:
$this->dbh = new \PDO('mysql:host=localhost;dbname=projectname', $user, $pass, array(
                                                                                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
                                                                               ));

Or using PDO::setAttribute():
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

What that does, is that it causes PDO (and PDOStatement) to throw a PDOException upon error. It will kill the script if unhandled, and can be handled in the following way:
try {
    $this->addProduct();
}
catch (PDOException $e) {
    echo $e->getMessage();
}


text:
Q: Dialog component in primeNG no responsive on mobile view I use primeNG (Angular2) to show the modal:
<p-dialog appendTo="body" [(visible)]="displayCreateGateway" modal]="true" [width]="700">

When I am on mobile view (less than declared 700px) modal does not display correctly. For example: I have window width 500 px, but modal generates in 700 px (properly will be width:100%). I think this is not fault of my code, because in official website primeNG situation is the same.
Do you know how to solve this problem? The easiest way is probably add media queries in css, but override component from primeNG isn't easy. Maybe helpful will be JS?

A: If you look at the documentation of the component, you will see a styleClass attribute, used like this :
<p-dialog styleClass="myStyle">

When you do that, it adds a new class to the component, allowing you to style it as you want.


text:
Q: Trying to connect C program to phpMyAdmin I've been trying to successfully connect my Arduino to my phpMyAdmin server but I haven't been able to. The Arduino has some Ultrasonic sensors connected (to measure distance) and for some reason not all the values are being sent to the server. I shouldn't be as complicated.
So each sensor has its own id, measured distance, and a level where the sensor is located.
The id is to identify the sensor (duh!) but for some reason all I'm getting is 0 for this value which I think is because it's only reading the values of the first sensor (with id 0).
So let me show you my code, this is the method that repeats, I think that my mistake is not being able to send the information multiple times, like separating the information from each sensor and it only send the first 4 values and that's what it displays on the data base.
void loop(){

  int distance;

  //=======

  for (uint8_t i = 0; i < SONAR_NUM; i++) {

    if( cm[i] > 10 || cm[i]==0){

      distance = cm [i];//delete if no
    }
    else{
      distance = cm[i];
      //Serial.println(distance);

    }
  }

  for (uint8_t i = 0; i < SONAR_NUM; i++) {
    if (millis() >= pingTimer[i]) {
      pingTimer[i] += PING_INTERVAL * SONAR_NUM;
      if (i == 0 && currentSensor == SONAR_NUM - 1)
        sonar[currentSensor].timer_stop();
      currentSensor = i;
      cm[currentSensor] = 0;

      sonar[currentSensor].ping_timer(echoCheck);
    }
    //client.stop();
  }

  //===================================================
  if(client.connect(serverName, 80) )
  {
    //Serial.println("Connected");
    if (client.connected()){
      delay(100);
      //Serial.println("Client is available, CONNECTED!");
      //client.print( "GET /add.php?distance=");
     //////////////
     int lvl = 0;
  for (uint8_t i = 0; i < SONAR_NUM; i++) {
    if(i<2)
      lvl = 1;
    else if (i>1 && i<3)
      lvl =2;
     else
       lvl = 3;

     Serial.print("SPOT: ");
     client.print( "GET /sendfromarduino.php?sensorID=");
     Serial.print(i);
     client.print (i);

     Serial.print(" DISTANCE: ");
     Serial.print(cm[i]);
     distance = cm[i];
     client.print( "&value=");
     client.print(distance);
     Serial.print("cm ");

     Serial.print(" LEVEL: ");
     client.print( "&level=");
     Serial.print (lvl);
     client.print (lvl);

  }
  Serial.println();
  //////////////////////////////////////
//      Serial.print("Distance: ");
//      client.print(distance);
//      Serial.println(distance);
      client.println( "HTTP/1.1");
      client.println( "Host: test.testserver.com" );
      client.println( "Content-Type: application/x-www-form-urlencoded" );
      client.println();
      client.println();
      client.stop();
    }
    else
    {
      //Serial.println(distance);
      Serial.println("Connection Failed");
    }
  }
  delay(100);
}

and then here is the code for the PHP file that should be perfectly ok according to my knowledge and past experience:
<?php

        $db = new PDO('mysql:host=localhost;dbname=test_alpha;charset=UTF-8', 'test_alpha', 'testtest');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

        $sensorID = intval($_GET['i']);
        //$time = CURRENT_TIMESTAMP;
        $value = intval($_GET['distance']);
        $level = intval($_GET['lvl']);

        $sql = "INSERT INTO `pspace`(`sensorID`, `time`, `value`, `level`) VALUES ('$sensorID',CURRENT_TIMESTAMP,'$value','$level')";

        $stmt = $db->query($sql);
        //echo json_encode(array('spaces'=>$stmt->fetchAll(PDO::FETCH_ASSOC)));

    ?>

Any help is greatly appreciated!

A: Where it says if (client.connected())
It should be while (client.connected())
Problem solved! Thanks to everyone who dedicated time to my question!


text:
Q: Submit a command "sudo chmod 777 -R /dev/kvm" for ever My AVD in android studio has a problem when i want to run it then i searched and i used this command  sudo chmod 777 -R /dev/kvm and it works.
My problem is when i start my PC , i should type this for using emulator , it has a way for submitted it for ever.
My OS : "Ubuntu 18.04.5 LTS"

A: That is never going to work: /dev/ is rebuild every boot. Besides that chmod 777 is never the correct solution. The only time chmod 777 is a solution is when it is for a tmp situation where you also use the sticky bit.
The way to do this: please check the GROUP of /dev/kvm (with ls -l /dev/kvm) and add the user you want to use that device to that group.
The group is likely to be kvm so what you need to do is
sudo adduser $USER kvm

Adjust it to the group /dev/kvm shows though. You need to logout before it is activated too.


text:
Q: WPF Server Data Binding Layer Architecture I have been working with Windows Forms for more than 12 years and now I think its time to learn WPF. So Im in the learning curve process but I have some questions regarding the Server Data Binding Arquitecture.
The Windows Forms apps I have built are Smartclients (clickonce) for SaaS and uses SQL Server with Stored Procedures and Custom Objects that are binded trhough reading DataSets (from Stored Procs), works pretty well but I know its not the cutting edge tech such as using Entity Framework or other ORM but its very flexible.
Now with WPF I was thinking that using Custom Objects that are being binded using Datasets are not the best way so don't know if Entity Framework would be the right choice or maybe other architecture.
Hope someone can give me an advice or guideline on the best practice.
Thanks a lot.

A: Learning WPF the right way can be daunting.
You probably want to break up the learning process.
Initially I would abstracting the data layer from the learning process, and get yourself comfortable with how binding work and validating simple entity objects. Once you are comfortable with this, and the other nice aspects of WPF, then you can come back and try to figure out how to develop an architecture that you can use.


text:
Q: Can I wirelessly download videos from my iPhone camera roll to my Mac? I have an iPhone4, upgraded to iOS5, and a Mac running the latest Lion updates as well.  The new Wireless Sync feature keeps everything up to date with iTunes, and the iCloud Photostream takes care of getting my photos into iPhoto.
However, there doesn't seem to be any way to wirelessly transfer videos taken on the phone from my camera roll to the Mac. Will I still need to plug the phone in via USB and import my videos into iPhoto?

A: It seems that an USB cable is still required.
The article in Apple Support that shows how to import videos into iPhoto has not been updated recently. Either Apple is still behind in updating these support articles (not likely) or there is nothing to update--in other words, you still need USB.
The release notes for iPhoto 9.2 list the major updates to the app. It mentions that iCloud support is now included, but nothing specific about importing videos wirelessly. Hope this helps.


text:
Q: How to Delete folder older than 7 days C# / NET I want to write some code that deletes all DIRECTORIES older than 7 days.
So:

*

*Check directory : D:\this

*If folder older than  7  days -> delete it from the system.

A: You can use DirectoryInfo
http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx
The voice of experience says to include sanity checks in your code that the directories you are deleting are in fact ones that you want to be deleting...

A: You can lookup using the DirectoryInfo util
   DirectoryInfo d = new DirectoryInfo(dir);
   if (d.CreationTime    < DateTime.Now.AddDays(-7))
       d.Delete();


text:
Q: Compare multiple chars without using string compare functions I am trying to create a switch statement using the parameters that can be passed into my File classes constructor in the mode parameter. However, as mode can be up to 2 chars (r, r+, w, or w+), I do not know how to create a switch statement that will get this done for me.
Does anyone have any suggestions on how to implement this? Currently with what I have below, I am getting errors for the r+ and `w+ cases, as those are not chars, but rather strings
File::File(const char *name, const char *mode) {
  int fileMode = 0;    //Initializing mode to 0
  fileName = name;    //Setting the file name of this File object to the name we pass in.

  switch(*mode){
    case 'r':
      //do stuff…
      break;

    // Open a text file for update (that is, for both reading and writing)
    case 'r+':
      //do stuff…
      break;

    case 'w':
      //do stuff…
      break;

    // Open a text file for update (reading and writing),
    // first truncating the file to zero length if it exists
    // or creating the file if it does not exist.
    case 'w+':
      //do stuff…
      break;

    default:    //We should never reach the default case, as the user shouldnt pass in anything else so I assert(0) in this case.
      assert(0);
  }

Problem solved that I cant use more than one char at a time for a switch statement.

A: You can't use more than one value in case.
1 - You can use more than one switch:
switch(mode[0]){
    case 'r':
        switch(mode[1]){
            case '+':
                switch(mode[2]){
                    case 0:
                        fileMode = O_RDWR | O_CREAT;
                        canWeRead = true;
                        canWeWrite = true;
                        break;
                    default:
                        assert(0);
                }
            case 0:
                fileMode = O_RDONLY | O_CREAT;
                canWeRead = true;
                canWeWrite = false;
                break;
        }
        break;
    case 'w':
        switch(mode[1]){
            case '+':
                switch(mode[2]){
                    case 0:
                        fileMode = O_RDWR | O_CREAT | O_TRUNC;
                        canWeRead = true;
                        canWeWrite = true;
                        break;
                    default:
                        assert(0);
                }
            case 0:
                fileMode = O_WRONLY | O_CREAT;
                canWeRead = false;
                canWeWrite = true;
                break;
        }
        break;
    default:
        assert(0);
}

2 - You can make mode's type char[4] and have ugly function call. Like File("filename", {'r', '+'}) (this way can be affected by endian difference)
switch(*(uint32_t *)mode){
    // r
    case 0x72000000:
        fileMode = O_RDONLY | O_CREAT;
        canWeRead = true;
        canWeWrite = false;
        break;
    // r+
    case 0x722b0000:
        fileMode = O_RDWR | O_CREAT;
        canWeRead = true;
        canWeWrite = true;
        break;
    // w
    case 0x77000000:
        fileMode = O_WRONLY | O_CREAT;
        canWeRead = false;
        canWeWrite = true;
        break;
    // w+
    case 0x772b0000:
        fileMode = O_RDWR | O_CREAT | O_TRUNC;
        canWeRead = true;
        canWeWrite = true;
        break;
    default:
        assert(0);
}

Anyway that ways are just too much overkill for simple thing. System calls would eat more than thousands of more time than string compare.


text:
Q: bash continue execution on command failure #! /bin/bash

while :
do
    filenames=$(ls -rt *.log | tail -n 2)
    echo $filenames
    cat $filenames > jive_log.txt
    sleep 0.1
done

I am trying to read latest 2 files from a directory and join them using bash.
However when no files are present in the current directory with an extension .log the command ls -rt *.log fails with error "ls: cannot access *.log: No such file or directory". After the error it looks like the while loop does not execute.
AfterWhat do I do so that the infinite loop continues even if one command fails.

A: I'm not sure what you mean but perhaps:
for (( ;; )); do
    while IFS= read -r FILE; do
        cat "$FILE"
    done < <(exec ls -rt1 *.log  | tail -n 2) >> jive_log.txt
    sleep 1
done

Note the ls option -1 which prints out files line by line.
Anyhow you can join last two files to jive_log.txt with:
while IFS= read -r FILE; do
    cat "$FILE"
done < <(exec ls -rt1 *.log  | tail -n 2) >> jive_log.txt

Another way is to save it to an array (e.g. with readarray) then pass the last 2 elements to cat.
readarray -t FILES < <(exec ls -rt1 *.log)
cat "${FILES[@]:(-2)}" > jive_log.txt  ## Or perhaps you mean to append it? (>>)

A: If you want to sort the output of find, you have to add a sort key at the beginning, which can be removed later on.
find . -name \*.log -printf '%T+\t%p\n' |
sort -r |
head -2 |
cut -f 2-

Using head instead of tail is a bit cheaper.