text:
Q: MongoDB: Query and retrieve objects inside embedded array? Let's say I have the following document schema in a collection called 'users':
{
    name: 'John',
    items: [ {}, {}, {}, ... ]
}

The 'items' array contains objects in the following format:
{
    item_id: "1234",
    name: "some item"
}

Each user can have multiple items embedded in the 'items' array.
Now, I want to be able to fetch an item by an item_id for a given user.
For example, I want to get the item with id "1234" that belong to the user with name "John".
Can I do this with mongoDB?  I'd like to utilize its powerful array indexing, but I'm not sure if you can run queries on embedded arrays and return objects from the array instead of the document that contains it.
I know I can fetch users that have a certain item using {users.items.item_id: "1234"}.  But I want to fetch the actual item from the array, not the user.
Alternatively, is there maybe a better way to organize this data so that I can easily get what I want?  I'm still fairly new to mongodb.
Thanks for any help or advice you can provide.

A: There are a couple of things to note about this:
1) I find that the hardest thing for folks learning MongoDB is UN-learning the relational thinking that they're used to.  Your data model looks to be the right one.
2) Normally, what you do with MongoDB is return the entire document into the client program, and then search for the portion of the document that you want on the client side using your client programming language.
In your example, you'd fetch the entire 'user' document and then iterate through the 'items[]' array on the client side.
3) If you want to return just the 'items[]' array, you can do so by using the 'Field Selection' syntax. See http://www.mongodb.org/display/DOCS/Querying#Querying-FieldSelection for details.  Unfortunately, it will return the entire 'items[]' array, and not just one element of the array.
4) There is an existing Jira ticket to add this functionality: it is https://jira.mongodb.org/browse/SERVER-828 SERVER-828.  It looks like it's been added to the latest 2.1 (development) branch: that means it will be available for production use when release 2.2 ships.

A: The question is old, but the response has changed since the time. With MongoDB >= 2.2, you can do :
db.users.find( { name: "John"}, { items: { $elemMatch: { item_id: "1234" } } })

You will have :
{
   name: "John",
   items:
   [
       {
         item_id: "1234",
         name: "some item"
       }
   ]
}

See Documentation of $elemMatch

A: If this is an embedded array, then you can't retrieve its elements directly. The retrieved document will have form of a user (root document), although not all fields may be filled (depending on your query).
If you want to retrieve just that element, then you have to store it as a separate document in a separate collection. It will have one additional field, user_id (can be part of _id). Then it's trivial to do what you want.
A sample document might look like this:
{
    _id: {user_id: ObjectId, item_id: "1234"},
    name: "some item"
}

Note that this structure ensures uniqueness of item_id per user (I'm not sure you want this or not).


text:
Q: Symfony2: jumping to production env is failing Deployment into production environment is failing, I see a blank page and no log in app/log/prod.log.
I warmed up the prod cache and gave ownership of cahce dirs to www-data, there no php logging either, but this may be an administration error, I asked for it to be checked as I don't have access to it.
I changed my htaccess to omit app_dev.php and consider app.php, this is my .htaccess:
# Use the front controller as index file. It serves as fallback solution when
# every other rewrite/redirect fails (e.g. in an aliased environment without
# mod_rewrite). Additionally, this reduces the matching process for the
# startpage (path "/") because otherwise Apache will apply the rewritting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex app.php
#DirectoryIndex app_dev.php

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Redirect to URI without front controller to prevent duplicate content
    # (with and without `/app.php`). Only do this redirect on the initial
    # rewrite by Apache and not on subsequent cycles. Otherwise we would get an
    # endless redirect loop (request -> rewrite to front controller ->
    # redirect -> request -> ...).
    # So in case you get a "too many redirects" error or you always get redirected
    # to the startpage because your Apache does not expose the REDIRECT_STATUS
    # environment variable, you have 2 choices:
    # - disable this feature by commenting the following 2 lines or
    # - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
    #   following RewriteCond (best solution)
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    #RewriteRule ^app_dev\.php(/(.*)|$) %{CONTEXT_PREFIX}/$2 [R=301,L]
    RewriteRule ^app\.php(/(.*)|$) %{CONTEXT_PREFIX}/$2 [R=301,L]

    # If the requested filename exists, simply serve it.
    # We only want to let Apache serve files and not directories.
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule .? - [L]

    RewriteCond %{REQUEST_FILENAME} -f
    #RewriteRule ^(.*)$ app_dev.php [QSA,L]
    RewriteRule ^(.*)$ app.php [QSA,L]

    # The following rewrites all other queries to the front controller. The
    # condition ensures that if you are using Apache aliases to do mass virtual
    # hosting, the base path will be prepended to allow proper resolution of the
    # app.php file; it will work in non-aliased environments as well, providing
    # a safe, one-size fits all solution.
    RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]
    #RewriteRule .? %{ENV:BASE}app_dev.php [L]
    RewriteRule .? %{ENV:BASE}app.php [L]
</IfModule>

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        # When mod_rewrite is not available, we instruct a temporary redirect of
        # the startpage to the front controller explicitly so that the website
        # and the generated links can still be used.
        #RedirectMatch 302 ^/$ /app_dev.php/
        RedirectMatch 302 ^/$ /app.php/
        # RedirectTemp cannot be used instead
    </IfModule>
</IfModule>

Any clues?

A: This is a supposition but if your dev environment works, and not your prod (on the same project & machine), this is because you forgot to add "umask(0000);" in web/app.php.

PHP Fatal error: require(): Failed opening required
  '/var/www/symfony/app/cache/prod/doctrine/orm/Proxies/_CG_MyProjectPanelBundleEntityAlgoritmo.php'
  (include_path='.:/usr/share/php:/usr/share/pear') in
  /var/www/symfony/vendor/doctrine/common/lib/Doctrine/Common/Proxy/AbstractProxyFactory.php
  on line 165

This is clearly a problem of rights and ownership of folders app/cache (and app/logs).

I gave ownership of cahce dirs to www-data

Depending on the fact you are using ACL, you mustn't do that, check the documentation. There are many solutions to fix this problem, explained in the grey frame.
To fix your problem if you don't use ACL, I think the easily way is to add "umask(0000);" in app.php (as you probably did in app_dev.php), at the beginning of your file and just after "use" declarations. (See "3. Without using ACL" in the grey frame). Otherwise, read the other instructions of the grey frame.
Now the framework will be able to write inside cache folder in the future. But if you don't use ACL, you need additionally to correct your current app/cache and app/logs folder configuration :
Considering your username is "user", say in root that the user "user" of usergroup "user" (usually the same as the username on a Linux machine) is the owner of these folders (and subfolders / files) :
su chown user.user -R app/cache app/logs

Then clear these folders to be sure there are not broken or missing files (as "user") :
rm app/cache/* app/logs/*

Give 777 rights to the folders so that the framework will be able to write inside :
chmod 777 -R app/cache app/logs

In addition, even you probably did it, check that your app/console file has umask(0000); uncommented, because if you miss it the symfony console will write files as www-data, and you could not read cache file folder (you'll have the same error) !

A: Is your database schema up to date ?
php app/console doctrine:schema:update --dump-sql

I experimented two times a similar situation and solved it the same way :
I had a work in progress in another bundle of the same project with no interaction with the part where that bug occured. Actually, i had not updated my database schema.
hope this helps

redpajama_set_name: RedPajamaStackExchange


text:
Q: Do to set per-project settings on Atom? I want to enable format-on-save (Prettier) on per project basis. I can do it globally, but how do I do that per project? I want developers to use the same formatting without forcing them enabling the global setting.

A: Have you looked at Prettier configuration files? These files should be put in the root of your project or included in you Node package manifest (package.json).
There are multiple options to choose from:

Prettier uses cosmiconfig for configuration file support. This means you can configure prettier via:

*

*A .prettierrc file, written in YAML or JSON, with optional extensions:.yaml/.yml/.json`.

*A .prettierrc.toml file, written in TOML (the .toml extension is *required
  ).

*A prettier.config.js or .prettierrc.js file that exports an object.

*A "prettier" key in your package.json file.

Configuration files are meant to be included in your VCS.


text:
Q: Store SSH command history on local machine I often use SSH to connect to ARM machine which reboots regularly and doesn't have any persistent memory to store sh command history. Is there a way to store such history on my local machine so it could be accessible by ^R and up/down when connected to the remote? Or is there another workaround to such problem besides storing most useful commands in a notepad? :)

A: A possible solution is the rlwrap program, dating from 1999,  which should be available on your home machine in a package of the same name. It uses the GNU readline library to front-end any command with a re-usable history that is saved by default in a file ~/.command_history, so in your case it should end up in ~/.ssh_history if you do:
rlwrap ssh remote

(If you want to test this to a remote running an application or shell that already has readline built-in, you will need to disable the remote readline. For example with a remote bash do: rlwrap ssh remote bash --noediting to see it working.)


text:
Q: Images added to drawable folder not being recognized when the getFields() method is run I have added 720 new images to my Drawable folder, but none of them are being recognized when I use Field[] drawables = android.R.drawable.class.getFields(); .
Field[] drawables = android.R.drawable.class.getFields();
    for (Field f : drawables) {
        try {
            System.out.println("R.drawable." + f.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

This just returns a list of the images added by default to the Drawable folder. I also tried getDeclaredFields but no success.

A: You need to use your own generated R class, that's your.package.name.R.drawable.


text:
Q: Uncaught TypeError: setLoading is not a function I am trying to pass a React hook to react-redux. I pass in loading and setLoading hook. However, when I try to use setLoading I get an error:
Uncaught TypeError: setLoading is not a function
I'm really not sure what I am misunderstanding but I am new to React and even newer to react-redux. I am using mapStateToProps but can't figure out how to use Hooks with it.
import React from "react"
import { connect } from "react-redux"
import Button from '@material-ui/core/Button';

export const CustomForm = ({ loading, setLoading, doAction }) => {
  const onClick = (e) => {
    e.preventDefault();
    setLoading(true);
    doAction("finish", setLoading)
  };

  return (
    <React.Fragment>
        <form onSubmit={onClick}>
            <Button type="submit">
              Submit
            </Button>
        </form>
    </React.Fragment>
  )
}

const mapStateToProps = state => {
  return {
    loading: state.loading,
    setLoading: state.setLoading
  }
}

const mapDispatchToProps = dispatch => {
  return {
    doAction: (action, setLoading) => dispatch(action, setLoading),
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(CustomForm)

Here is how I call CustomForm:
const [loading, setLoading] = React.useState(false);
<CustomForm loading={loading} setLoading={setLoading} />

EDIT: I need loading and setLoading defined outside the component because I use them outside of the component also.

A: I had same doubt as @BlackMath, later I found you have defined it in last.

*

*A better way would be, directly define it inside your component.

*and, we cant call the callback function like this doAction("finish", setLoading) if it is taking any parameter. since, setLoading is expecting a value true or false.

import React from "react"
import { connect } from "react-redux"
import Button from '@material-ui/core/Button';

export const CustomForm = ({ doAction }) => {

  const [loading, setLoading] = React.useState(false);

  const onClick = (e) => {
    e.preventDefault();
    setLoading(true);
    doAction("finish", ()=>{
      setLoading(false); //or true based on your logic
    })
  };

  return (
    <React.Fragment>
        <form onSubmit={onClick}>
            <Button type="submit">
              Submit
            </Button>
        </form>
    </React.Fragment>
  )
}

const mapStateToProps = state => {
  return {
    loading: state.loading,
    setLoading: state.setLoading
  }
}

const mapDispatchToProps = dispatch => {
  return {
    doAction: (action, setLoading) => dispatch(action, setLoading),
  }
}

A: For me it was a pretty silly mistake. Incase someone faces it, it may help.
So I was doing this
const {loading, setLoading} = useState(false);

instead of this:
const [loading, setLoading] = useState(false);

Keep an eye on the curly brackets and square brackets. I mistakenly typed the curly braces


text:
Q: Why does MySQL/Sequelize perform full select queries when a GraphQL query only requires certain fields of an object to be returned? I have a simple schema like this for a user in my application:
type Query {
  users: [User!]!
}

# The User ObjectType and Sequelize model.
type User implements UserI {
  id: ID!
  userName: String!
  firstName: String!
  lastName: String!
  email: String!
  createdAt: DateTime!
  updatedAt: DateTime!
  deletedAt: DateTime!
}

And my type-graphql resolver implements this simple code to return a list of users:
@Resolver()
class UserResolver {
  @Query(() => [User])
  async users(): Promise<User[]> {
    return User.findAll();
  }
}

When I perform a query such as this:
{
  users {
    firstName
  }
}

I expected that the equivalent MySQL query would be something like this: SELECT firstName FROM users, but instead I can see that Sequelize logged the query as this:
Executing (default): SELECT `id`, `userName`, `firstName`, `lastName`, `email`, `password`, `createdAt`, `updatedAt` FROM `users` AS `User` WHERE (`User`.`deletedAt` IS NULL);

Now, while everything works (I can get all the users and their data on the client side) I was wondering if there are any performance hits on the server side if Sequelize performs full attribute selection? Is this due to Sequelize or simply due to how GraphQL resolves the model field's? Am I missing some options?

A:
Am I missing some options?

You need to translate GraphQL query (request) into the proper SQL query. Just calling findAll() does not have any info about the request, so it correctly fetches full entity.
Basically, you need to parse the GraphQL Resolve Info into a more readable format (e.g. using https://www.npmjs.com/package/graphql-fields) and then build a select option for TypeORM (e.g. .findAll({ select: ['id'] })).


text:
Q: Django - Get data from a form that is not a django.form I am working with Django in order to do a quite simple web application.
I am currently trying to have a succession of forms so that the user completes the information bits by bits.
I first tried to do it only in HTML because I wanted to really have the hand on the presentation. Here is my code.
I have two templates, create_site.html and create_cpe.html. I need to get informations from the first page in order to know what to ask in the second page.
Here is my create_site.html

<form action="{% url 'confWeb:cpe_creation' %}" method="post" class="form-creation">
    {% csrf_token %}

        Name of theSite

            <input id="site_name" class="form-control" placeholder="Name" required="" autofocus="" type="text">

<button class="btn btn-lg btn-primary btn-block" type="submit">Créer</button>
</form>

And here is the views.py that I'm using to do all of this :
def site_creation(request):

    template = loader.get_template('confWeb/create_site.html')
    return HttpResponse(template.render(request))

def cpe_creation(request):
    if request.method == "POST" :
        print(request.POST)

What I would like to do is to get the value of the input of my form, inside my view "cpe_creation". I tried getting informations from the "request" object but I didn't manage to do that. Maybe I'm lacking very basic HTML skills but I thought the form information would be in the request body, but it wasn't (or didn't look like it).
I also tried using Django forms, but the problem is, I can't control very precisely what the form will look like. If I create an input, I can't tell it the size it's supposed to take or anything like that.
Hence, my questions are the following :
 - How can I get the data from the submitted form ?
 - Do I have to do it with Django's Forms ? If I do, how can I control the css class of an input ?

A: Your field in your form in your template has to have name attribute in order to pass it to your request.
Then you will be able to get it in your view like this:
site_name = request.POST.get('site_name')

A: Your form field needs a name attribute.
            <input id="site_name" name="site_name" class="form-control" placeholder="Name" required="" autofocus="" type="text">

Alternatively, if you want to use Django forms, you can set the CSS class of a form field by explicitly defining the widget.
class SiteForm(forms.Form):
    site_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))

Judging from the class form-control, I assume you want to use Bootstrap. Check out django-crispy-forms, which makes it really easy style Django forms with Bootstrap.


text:
Q: How do I pass a service to another plugin? I have a plugin that I will instantiate at runtime and I want to pass it a WCF service from the application host.  The application host is responsible for creating the connection to the service.  The reason for this is that a single service can be used by multiple plugins, but the plugins should only know about its interface since there may be several implementation of IMyPluginServices.  For instance, the Run method of the plugin instance would be:
    public void Run(IMyPluginServices services)
    {
        services.DoSomething();
    }

The problem I am running into is that I don't know how to create a service of type IMyPluginServices and pass it to the Run function. The service reference generated by VS 2010 doesn't seem to create an object of type IMyPluginServices that I can pass to it.  Any help would be greatly appreciated.  Thanks.

A: When you add a service reference in VS 2010 for a service it generates an interface named IMyService which contains methods for each OperationContract in your service.  It also generates a concrete class named MyServiceClient, which can be constructed and then used to invoke your service.
Now, the problem that you're running into, I believe, is that MyServiceClient is a subclass of ClientBase<IMyService>, and does not implement the generated IMyService interface (which is a real pain).
To get around this problem I ended up making a new interface:
public interface IMyServiceClient : IMyService, IDisposable, ICommunicationObject
{
}

(Note: IDisposable and ICommunicationObject are only required if you want your module to be able to detect/react to faulted channels and other such things).
I then extend MyServiceClient with a partial class (in the assembly that contains my WCF Service reference):
public partial class MyServiceClient : IMyServiceClient
{
}

Now in my modules I can accept an IMyServiceClient instead of an IMyService, and still execute all of the methods that I need to.  The application in control of the modules can still create instances of MyServiceClient as it always did.
The beauty of this is that your new interface and partial class don't need any actual code - the definitions suffice to get the job done.


text:
Q: jQuery Cycle plugin - pause/resume weird behavior I have a slideshow running with the awesome cycle plugin, and when you click a button in the show, I show a hidden layer on the page and send a 'pause' command to cycle. I'm having two problems:

*

*When the pause command is received, cycle immediately flips back to the 1st slide in the sequence (why??), and doesn't hit my before/after callbacks.

*After closing the layer, I send a 'resume' command to cycle. The slideshow resumes (from the 1st slide, where the pause left it), but now cycle doesn't call my before/after callbacks at all, even as the slideshow progresses.
So I guess my question is: how can I properly pause/resume the slideshow so these strange behaviors don't occur? (And just to be completely clear and avoid any confusion, this isn't about the "pause on hover" feature, which is actually working fine for me. :-)
Here's my cycle() init, and my callback functions. (Why am I manually tracking the nextSlide, you ask? Because the built-in value for the current slide doesn't get updated properly for the before/after callbacks.)
  $(document).ready(function() {
    $('#slideshow').cycle({
      fx: 'fade',        // choose your transition type, ex: fade, scrollUp, shuffle, etc...
        timeout:       4000,  // milliseconds between slide transitions (0 to disable auto advance)
        speed:         1000,  // speed of the transition (any valid fx speed value)
        pause:         1,     // true to enable "pause on hover"
        delay:         0,     // additional delay (in ms) for first transition (hint: can be negative)
        slideExpr:     'img',  // expression for selecting slides (if something other than all children is required)
        before:       moveArrow, // function to call when moving to next slide
        after:       upd, // function to call when moving to next slide
        fastOnEvent:   'fast',
    });
  });

  var nextSlide = 0;

  function upd(a, b, c) {
    nextSlide = nextSlide + 1;        // track which slide we're on
    c = $('#slideshow img').length;
    if(nextSlide > (c - 1)) nextSlide = 0;   // wrap back to 1st
  }

  // move indicator showing which slide we're on
  function moveArrow(a, b, c) {
    $('#slide-indicator').attr('class', 'c'+nextSlide);

    $(".clickmap").hide();          // hide other clickmaps
    $(".clickmap.c"+nextSlide).show();    // show map for this slide

    return true;
  }

Thanks for any thoughts on this--
best,
Eric

A: I had the same problem, pause and resume were not working. It appeared I had installed the lite version, with the full/complete version it's working.

A: You didn't show your code for sending the pause command.  Something is definitely wrong there because pause does NOT reset the slideshow to the first slide.
Also, you don't need to keep track of the slide index yourself.  The third arg to the before/after callbacks is an options object that has the internal state of the slideshow.  On that object you will find 'currSlide' and 'slideCount' properties, among many others.

A: I know this is an old question, but I just had the same problem.  The way I got around it was to simply create my own function to pause and resume the slideshow with JQuery's hover events.
As Eric pointed out in a few comments, a related issue is that the plugin's pause option only allows hovering over the IMG element to pause the slideshow, so if you've got anything over your images, like a pager or any decorative elements, then you are boned.
So, I put my decorative elements, banner (which I called "#banner") and pager all into a div called "#banner-container" and then applied this code to fix my problem:
$('div#banner-container').hover(function(){
   if(!$(this).hasClass('paused')){
       $(this).addClass("paused");
       $('div#banner').cycle("pause")
   }
},function(){
   if($(this).hasClass('paused')){
       $(this).removeClass("paused");
       $('div#banner').cycle("resume")
   }
});

A: The problem is in the JQuery Cycle Plugin version: the "lite" version ignores the pause/resume commands. Using the full version could solve the problem.
EDIT: Sorry, i was wrong: i tried both versions but had the same issue using the full version.


text:
Q: ASP.NET MVC - Render PartialView with AJAX? Earlier today I posted another post where @Darin Dimitrov helped me great, however once again I'm stucked...
My javascript calls the AddWebsite ActionResult which does it job as it should, however the error function in the $.ajax() is always firing since
return PartialView(ListPartialView, MapUserToViewModel);

isn't valid JSON.
I've come across examples where people use something like
RenderPartialViewToString(partialview, model);

and throws it into a JSON object... but it's just too "hackish" if you ask me.. isn't there an easier way to accomplish this?
... And the code:
// DashboardController.cs
[HttpPost]
public ActionResult AddWebsite(CreateWebsiteViewModel website)
{
    if (!ModelState.IsValid)
    {
        throw new HttpException(400, "Client-side validation failed.");
    }

    if (string.IsNullOrWhiteSpace(website.URL))
    {
        throw new ArgumentNullException("URL", "The URL cannot be empty nor contain only whitespaces.");
    }

    using (_session.BeginTransaction())
    {
        _session.Query(new AddWebsite(_contextProvider.GetUserSession.UserId, website.URL));
        _session.Transaction.Commit();
    }

    return PartialView(ListPartialView, MapUserToViewModel);
}

// MyJs.js
$("#testform").live('submit', function () {

    var test = { URL: $("#URL").val() };

        $.ajax({
            url: "/Dashboard/AddWebsite",
            type: "POST",
            data: JSON.stringify(test),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                alert("TRIG");
                $("#content").html(data);
            },
            error: function () {
                alert("Error");
            }
        });

    return false;
});

Thanks in advance!

A: In your particular instance I think the problem is with your javascript code.  You are specifying the dataType (which is what the function expects to parse in the response) as json.  Based on the Action you posted you should have html as the dataType and it should solve your problem.  There's nothing wrong with doing that (you don't have to use JSON for everything).

A: Simple data
Why are you setting dataType and contentType in the first place? Since your object test is very simple you can just provide it as is and it will be consumed by Asp.net MVC without any problems and you will return your partial view.
Complex data
If your object would be more complex then you could use a different jQuery plugin that will make it possible to send complex JSON objects without strigification.


text:
Q: Does converging in probability require $X_n$ and $X$ to be defined on the same space? I read this passage regarding converging in distribution and it claims it is not necessary that $X_n$ and $X$ are defined on the same space (probability space). I read some examples and understood why that would be the case, by the way, I am not very advanced on measure theory.
Now I am wondering if the idea of converging in probability needs to be in the same space. I am particularly concerned in this question because if it doesn't stand then I can construct an example showing converging in distribution does not imply converging in probability by simply constructing random variables that are not on the same space.
I feel like converging in probability has to happen on the same probability space since we are exploring the idea od $\mathbb{P}(|X_n-X|\leq \epsilon).$ In particular, the probability measure has to be the same. However, I am not sure on this and if $(\Omega, F)$ need to be same, too. Could someone please explain to me in the easiest language as I am not looking for an advanced answer. Much thanks!

A: Yes, they have to be defined on the same probability space. The definition of convergence in probability is that for every $\epsilon>0$ we have $\mathbb{P}(|X_n-X|>\epsilon)\to 0$ when $n\to\infty$. The expression $\mathbb{P}(|X_n-X|>\epsilon)$ alone requires them to be defined on the same probability space, otherwise it makes no sense.
Convergence in distribution is different, it is all about the distributions of the variables without any meaning to their actual values. So when we define this type of convergence we can indeed let the random variables be from different probability spaces, the only thing that matters here is their CDF.


text:
Q: Login.php redirects to homepage instead of the header location I am trying to make a notice board where only the admin can login and post updates(for a school) and I am very new to php. My code works fine in MAMP server on mac, but when I upload it to the 000webhost.com for testing purposes, it does not redirect to the correct page after login and redirects to the index.php page.
Here is my code. I did session_start in my conf.php file.
<?php

// Check if the user is already logged in, if yes then redirect him to welcome page
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
   header('location: logout.php');
   exit;
}

//check if not authorized

// Include config file
require_once '../conf.php';

// Define variables and initialize with empty values
$email = $password =  '';
$email_err = $password_err =  '';

// Processing form data when form is submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

   // Check if email is empty
   if (empty(trim($_POST['email']))) {
      $email_err = 'Please enter email.';
   } else {
      $email = trim($_POST['email']);
   }

   // Check if password is empty
   if (empty(trim($_POST['password']))) {
      $password_err = 'Please enter your password.';
   } else {
      $password = trim($_POST['password']);
   }

   // Validate credentials
   if (empty($email_err) && empty($password_err)) {
      // Prepare a select statement
      $sql = 'SELECT id, email, password FROM users WHERE email = ?';

      if ($stmt = mysqli_prepare($link, $sql)) {
         // Bind variables to the prepared statement as parameters
         mysqli_stmt_bind_param($stmt, 's', $param_email);

         // Set parameters
         $param_email = $email;

         // Attempt to execute the prepared statement
         if (mysqli_stmt_execute($stmt)) {
            // Store result
            mysqli_stmt_store_result($stmt);

            // Check if email exists, if yes then verify password
            if (mysqli_stmt_num_rows($stmt) == 1) {
               // Bind result variables
               mysqli_stmt_bind_result($stmt, $id, $email, $hashed_password);
               if (mysqli_stmt_fetch($stmt)) {
                  //if ( password_verify( $password, $hashed_password ) ) {
                  if (($password == $hashed_password)) {
                     // Password is correct, so start a new session
                     //session_start();

                     // Store data in session variables
                     $_SESSION['loggedin'] = true;
                     $_SESSION['id'] = $id;
                     $_SESSION['email'] = $email;

                     // Redirect user to welcome page
                     header('Location: add_notice.php');
                  } else {
                     // Display an error message if password is not valid
                     $password_err = 'The password you entered was not valid.';
                  }
               }
            } else {
               // Display an error message if email doesn't exist
               $email_err = 'No account found with that email.';
            }
         } else {
            echo 'Oops! Something went wrong. Please try again later.';
         }

         // Close statement
         mysqli_stmt_close($stmt);
      }
   }

   // Close connection
   mysqli_close($link);
}
?>

Please help me with it. I would appreciate it a lot.

A: Just to close off the question...
If you are calling session_start() in the conf.php file then it needs to be included before any call for $_SESSION[] variables.
Right now you are checking for $_SESSION['loggedin'] before initialising the $_SESSION variables with session_start().
Move require_once '../conf.php'; above that if statement and it will work e.g.
<?php
// Include config file
require_once '../conf.php';

// Check if the user is already logged in, if yes then redirect him to welcome page
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
   header('location: logout.php');
   exit;
}

//check if not authorized

// Define variables and initialize with empty values
$email = $password =  '';
$email_err = $password_err =  '';

// Processing form data when form is submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

   // Check if email is empty
   if (empty(trim($_POST['email']))) {
      $email_err = 'Please enter email.';
   } else {
      $email = trim($_POST['email']);
   }

   // Check if password is empty
   if (empty(trim($_POST['password']))) {
      $password_err = 'Please enter your password.';
   } else {
      $password = trim($_POST['password']);
   }

   // Validate credentials
   if (empty($email_err) && empty($password_err)) {
      // Prepare a select statement
      $sql = 'SELECT id, email, password FROM users WHERE email = ?';

      if ($stmt = mysqli_prepare($link, $sql)) {
         // Bind variables to the prepared statement as parameters
         mysqli_stmt_bind_param($stmt, 's', $param_email);

         // Set parameters
         $param_email = $email;

         // Attempt to execute the prepared statement
         if (mysqli_stmt_execute($stmt)) {
            // Store result
            mysqli_stmt_store_result($stmt);

            // Check if email exists, if yes then verify password
            if (mysqli_stmt_num_rows($stmt) == 1) {
               // Bind result variables
               mysqli_stmt_bind_result($stmt, $id, $email, $hashed_password);
               if (mysqli_stmt_fetch($stmt)) {
                  //if ( password_verify( $password, $hashed_password ) ) {
                  if (($password == $hashed_password)) {
                     // Password is correct, so start a new session
                     //session_start();

                     // Store data in session variables
                     $_SESSION['loggedin'] = true;
                     $_SESSION['id'] = $id;
                     $_SESSION['email'] = $email;

                     // Redirect user to welcome page
                     header('Location: add_notice.php');
                  } else {
                     // Display an error message if password is not valid
                     $password_err = 'The password you entered was not valid.';
                  }
               }
            } else {
               // Display an error message if email doesn't exist
               $email_err = 'No account found with that email.';
            }
         } else {
            echo 'Oops! Something went wrong. Please try again later.';
         }

         // Close statement
         mysqli_stmt_close($stmt);
      }
   }

   // Close connection
   mysqli_close($link);
}
?>


text:
Q: Area bounded by$ y^2=x^2(1-x^2)$ Find the area bounded by $y^2=x^2(1-x^2)$?
I think in this way as the graph lies between -1 to 1 the area is  4 times of $\int x \sqrt{1-x^2} dx$ limits from 0 to 1. Am I correct?

A: Yes, the area enclosed by such a lemniscate is:
$$ 4\int_{0}^{1}x\sqrt{1-x^2}\,dx = 4\int_{0}^{\pi/2}\sin(\theta)\cos^2(\theta)\,d\theta = \color{red}{\frac{4}{3}}.$$


text:
Q: Unrelated "protected" entry in stack trace Copied from the scala-user list, where it has received no loving...
The following elements are reported to be in the stack during an
exception:
at mypackage.MessageManagerDAO.update(MessageManagerDAO.java:100)
at mypackage.QueueDao.protected$update(QueueDao.scala:58)
at mypackage.QueueDao$$anon$1$$anonfun$to$1.apply(QueueDao.scala:131)
at mypackage.QueueDao$$anon$1$$anonfun$to$1.apply(QueueDao.scala:129)
at scala.Option.foreach(Option.scala:185)
at mypackage.QueueDao$$anon$1.to(QueueDao.scala:129)

The curious thing is, line 131 is unrelated to line 58. Line 58 has no
business in this stack. The only things in common between the two
entries are that they both call the abstract super class method
MessageManagerDAO.update (Java) and that the logic flow is similar.
What does the protected signify? And why could it be appearing in my
stack trace?
I'm using Scala 2.8.1
Here are some code snippets:
57: maybeQueue.foreach{queueDef =>
58:   val updateCount = update(SQL.updateLastReadAttempt, queueDef.category, queueDef.host)
59:   if (updateCount == 0) update(SQL.insertLastReadAttempt, queueDef.category, queueDef.host)
60:  }

129: message.relatedId.foreach{relatedId =>
130:   val updated = update(SQL.incrementMessageCount, relatedId, qd.category, qd.host)
131:   if (updated == 0) update(SQL.insertMessageCount, relatedId, qd.category, qd.host)
132:  }

A: Not a direct answer, but I hope this will be useful:
The Scala compiler sometimes translates your code in ways that are hard to understand, especially if you use closures and other things for which there is no direct equivalent in Java.
Try compiling your code with scalac -print, that will show you what the Scala compiler makes out of your source code. You'd have to search through the output to see exactly what happens with the calls in your code.


text:
Q: AES 256 bit encryption I am trying to encrypt some data using AES 256 bit encryption however I keep getting the error -
Error while encrypting: java.security.InvalidKeyException: Illegal key size or default parameters
My code is -
key = "abcd123456789kjd";
byteKey = key.getBytes();
MessageDigest sha = MessageDigest.getInstance("SHA-256");
byteKey = sha.digest(byteKey);
byteKey = Arrays.copyOf(byteKey, 32); // use only first 256 bit
secretKey = new SecretKeySpec(byteKey, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);

Can someone please help figure out why the error is coming. It is working if I make it into 128 bit instead of 256 bit.

A: By default Java supports only 128-bit encryption. If you want to exceed more than that you need the unlimited strength file installed. To do that download the jars and extract the jar files from the zip and save them in ${java.home}/jre/lib/security/.
For more see here: https://stackoverflow.com/a/6481658/1008278


text:
Q: Change the Chrome default font I installed a new font on my Windows 10 machine, and it seems to have become the default font in Google Chrome. How can I restore Chrome's default font?

A: Click the hamburger icon in the upper-right of Chrome, and click Settings.

At the bottom of this page, press "Show advanced settings..."
Find the "Web Content" section and press "Customize Fonts".

Change the different fonts in here. Keep in mind that a serif font has little tails and lines on various characters, while a sans-serif font does not.

For future reference, please specify more details about your problem in the question's title. A better example would be "Installed new font on Windows 10, how do I make Google Chrome stop using it as default?"


text:
Q: Javascript event handler Garbage collection Will below code result in memory leak? When I remove 'submitBtn' from DOM, will it be garbage collected along with it's event handler?
Or Do I have to call removeEventListener() before I remove 'submitBtn' from DOM?

function addEventHandler() {
  var btnId3 = document.getElementById("id3");
  btnId3.addEventListener(
    "click",
    function () {
      console.log(btnId3.name);
    },
    false
  );
}

addEventHandler();
document.forms[0].lastElementChild.remove();
<!DOCTYPE html>
<html>
<head>
  <title>JS GC</title>
</head>
<body>
  <form id="id1" method="post">
    <input id="id2" type="text" name="username" value="John">
    <input id="id3" type="button" name="submitBtn" value="Echo Username">
  </form>
</body>
</html>

A: Every value (including functions and DOM objects) is viable for garbage collection when all references to it are lost. If you remove a DOM node, it gets detached from the DOM tree, and thus the one reference to it gets removed. As long as there is no other reference to it (which you don't have in your code), the node is viable for garbage collection. Therefore also the function (if it is only referenced inside the node) is viable for gc too.


text:
Q: How to pass a parameter in a querystring to multiple pages? I want to change my site (consists of multiple pages) theme dynamically. I pass a parameter in a querystring as "theme" to all the solution.
It works just for one page that is redirected with query string (It's theme changes correctly), but other webforms' theme don't change.
so how can I pass a parameter in a querystring to multiple pages?
the below code is an Event that when user click the button, redirect him to other page and change the theme of sit.
protected void btn_blue_gray_Click(object sender, EventArgs e)
        {
            String bl = "blue";
            Response.Redirect("page1.aspx?theme=" + bl);
        }

if it helps: it's asp.net 4.5 and we used Microsoft.AspNet.Identity package for login User.

A: When you navigate to other pages you lose the query string passed in unless you add it to the route/links to other pages yourself.
When you pass a parameter to your page (assuming you login you can do it there) store the theme choice in a bit of state (cookie or session or MemoryCache or something) then just look for this value on each page (or stick it into a MasterPage or baseView with the default being your standard theme value.
something like
return Session["theme"] ?? "default";

Then every page derived from that MasterPage or View will have access to the theme value (regardless of where you set it).
If you want to allow the user to change the value then set it behind your button click and then navigate or refresh the page and the new theme value will be picked up automatically.

A: You would need to set the theme in a global class, which all web forms can access.
public static class Theme
        {
            public static string theme = "";
        }


text:
Q: Android - Boot Receiver Error So I have a boot receiver that is supposed to call an intent service but the receiver isn't registering at all.
Manifest file -
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name=".ClockReciever">
    <intent-filter >
       <action android:name="android.intent.action.BOOT_COMPLETED"/>
       <action android:name="android.intent.action.QUICKBOOT_POWERON" />
    </intent-filter>
</receiver>

ClockReceiver.java
public class ClockReceiver extends BroadcastReceiver {
    private final String TAG = "ClockReciever";
    @Override
    public void onReceive(Context context, Intent intent) {
       Log.d(TAG,"onRecive");
       context.startService(new Intent(context, RefreshIntentService.class));
    }

}

I think this is correct, but according to my logcat the ClockReciever is never called and the program crashes with a "Unable to instantiate receiver" error.
Any suggestions? Thank you

A: Here you have a typo
<receiver android:name=".ClockReciever">

Should be ClockReceiver, i.e. same as your class.
Cheers!


text:
Q: View Facebook events outside of Facebook - where to put the access token? Unfortunately, there are many snippets, but no complete code examples. I'm trying to allow my group's events to be seen in a webpage outside of FB, and following the Javascript SDK example quick start I'm able to put the login and share buttons. But when I try to access my group's events, I get the error - "An access token is required to request this resource." Where do I put the access token in this code?
window.fbAsyncInit = function() {
FB.init({
appId : '{myappID}',
xfbml : true,
version : 'v2.8'
});
FB.AppEvents.logPageView();
FB.api(
'/myGroupID/events',
'GET',
{},
function(response) {
// Insert your code here
}
);
};

A couple of things:

*

*I don't need my users to log in, as my group is public; my events are public. If someone is casually browsing through my website I want them to be able to see the events.

*One of the other things that I've had trouble with is extremely short answers. Coming from the .NET community, I'm used to seeing lots of tutorials, and lots of complete code examples for how to do things. There are few "long form" answers or tutorials - even stackoverflow answers (like this one) don't contain enough detail on how to do this stuff. Especially the access token thing.
Is there a complete example of how to do this?
Thanks in advance.

A: You COULD add the Token like this:
FB.api(
'/myGroupID/events',
'GET',
{access_token: 'xxx'},...

...but that would expose your Token (which is always meant to be kept secret) to everyone visiting the website. You have to do that API call server side. Check out the PHP SDK or just use PHP cURL. The Token is just a GET parameter.

A: Ok, I figured it out. The point of all of this is to get the Access Token that Facebook says it wants. The Access Token is really the appsecret_proof (and not the access_token - the access_token is a different thing. See later in this post), so be aware of that. I cobbled together some different code examples (like this one, and a super, very careful reading of the Facebook graph api docs, to reach an answer. I coded in C# rather than Javascript because a lot of this needs to be done server side, and I'm more comfortable there anyway.
I created a console app as a proof of concept. A few notes:

*

*the page_id is, in my case, for a group, not a (capital P) Page,
which is a different thing.

*The access_token and app_secret are from the app
you've (hopefully) already created. (If you need to get the access_token in the first place, there
are some docs out there to help you get this part started.) You should also
make sure to use (as of .NET 1.0) the dotnet core secret manager
to protect your secrets when you develop so you don't pass them
around via source control.

*This last one is big - the appsecret_proof is a combination of your access_token and your app_secret hashed together (with the app_secret being the key) and then made part of the query string. This is what Facebook wants when it says "An access token is required to request this resource."
public static string page_id = {your_page_id};
public static string access_token = {your_app_access_token};
public static string app_secret = {your_app_secret};
public static string appsecret_proof = FaceBookSecret(access_token, app_secret);

static void Main(string[] args)
    {
        Console.WriteLine("Making API Call...");
        using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }))
        {
            client.BaseAddress = new Uri("https://graph.facebook.com/" + page_id + "/");
            HttpResponseMessage response = client.GetAsync("events?access_token=" + access_token + "&appsecret_proof=" + appsecret_proof).Result;
            response.EnsureSuccessStatusCode();
            string result = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine("Result: " + result);

        }
        Console.ReadLine();
    }

internal static string FaceBookSecret(string content, string key)
{
    byte[] keyBytes = Encoding.UTF8.GetBytes(key);
    byte[] messageBytes = Encoding.UTF8.GetBytes(content);
    byte[] hash;
    using (HMACSHA256 hmacsha256 = new HMACSHA256(keyBytes))
    {
        hash = hmacsha256.ComputeHash(messageBytes);
    }

    StringBuilder sbHash = new StringBuilder();
    for (int i = 0; i < hash.Length; i++)
    {
        sbHash.Append(hash[i].ToString("x2"));
    }
    Console.WriteLine(sbHash);
    return sbHash.ToString();
}

So after all of this runs, I get a nice json string with all of my events.


text:
Q: knockout radio group inside foreach binding works one way only Im using Knockout JavaScript library v2.2.0rc.
I wonder, whether it is possible to do the following.
my template looks like this


text:
Q: What is the best way to use a reagent component in react js? Say I have a reagent class with :reagent-render other reagent class/element, how can I convert this and export as a regular react component that can be mounted to regular react application?

A: Depending on which version of Reagent your using, it can vary a bit. If your using 0.5+, look at reagent.core/as-element, documented in the 0.5.0 News under Simple React Integration. If using 0.6+, the output of reagent.core/create-class can be used in JSX directly, as documented in the 0.6.0 Alpha News.


text:
Q: how to login using ssh with password? I want to login using ssh and password store in a text file or may be in a varible
I am trying below method but i am getting an error please suggest me correct way.
echo "123456" | ssh root@127.0.0.1
error: Pseudo-terminal will not be allocated because stdin is not a terminal.

A: Ideally, you would want to use ssh keys instead of a plaintext password stored in a file/script. This looks like a duplicate of https://stackoverflow.com/questions/4594698/using-a-variables-value-as-password-for-scp-ssh-etc-instead-of-prompting-for

A: Install sshpass with below commands.

wget http://dl.fedoraproject.org/pub/epel/6/x86_64/sshpass-1.05-1.el6.x86_64.rpm

 rpm -ivh sshpass-1.05-1.el6.x86_64.rpm

Now login with ssh

sshpass -p 'password' ssh root@IP


text:
Q: Adding a cookie to web service port client I'm using a web service in my app that requires a specific cookie to be set in order access it's methods.
I was using a generated wrapper class for that service that was created using wsdl.exe tool. Everything is working ok using that method.
// this is the instance of object generated with wsdl.exe
WSWrapper service = new WSWrapper();

// set cookie
service.CookieContainer = new CookieContainer();
Cookie cookie = new Cookie(name, value, path, domain);
service.CookieContainer.Add(cookie);

// run method requiring cookie to be set
service.Test();

Now I wanted to do something similar using Service Reference instead of pre-generated class. I added web reference but there seems to be no CookieContainer (or anything similar) in service reference port client that was generated.
Does anyone knows how to add a cookie to that client?

A: There are advantages to the svcutil.exe generated proxies though.
Having the client save and return the cookies returned by the server (as used to be done by simply adding a CookieContainer) can now be controlled through app.config. Add allowCookies="true" to the basicHttpBinding or basicHttpsBinding as an attribute to the binding.
Alternatively use the WCF configuration editor to do the same.

A: I solved the problem. Instead of creating Service Reference I added Web Reference and the generated client had all the properties of the wsdl.exe pre-generated class.


text:
Q: Sluggish ELAN touchpad response in Ubuntu 20.04 I have an issue with my Lenovo Thinkpad X1 Yoga Gen. 6. Problems appeared only recently, and I believe that it is related to some update, either BIOS or system. The problems (such as a problem in suspending, overheating during suspend, touchpad response) appeared only recently. I managed to solve most of the problems but I'm still left with the issue of the touchpad.
It seems that after sleep/suspend the touchpad develops a sluggish response. If after restart the response is smooth and every one-finger click on the touchpad area produces a left mouse click on the desktop then after suspend it behaves very differently. The cursor is moving in a different speed/response and not every click on the touchpad is working (unless I am using the actual left button of the track point or the lower left key/part of the touchpad).
I was trying to look for a solution and it seems that most of the solutions are discussing about no responding/working touchpad and this is not my case.
Here is the xinput output:
nimibachar@nimibachar-ThinkPad-X1-Yoga-Gen-6:~$ xinput
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ Logitech Wireless Mouse                   id=9    [slave  pointer  (2)]
⎜   ↳ ELAN0673:00 04F3:3188 Mouse               id=12   [slave  pointer  (2)]
⎜   ↳ ELAN0673:00 04F3:3188 Touchpad            id=13   [slave  pointer  (2)]
⎜   ↳ Wacom HID 5278 Pen stylus                 id=14   [slave  pointer  (2)]
⎜   ↳ Wacom HID 5278 Finger touch               id=15   [slave  pointer  (2)]
⎜   ↳ TPPS/2 Elan TrackPoint                    id=19   [slave  pointer  (2)]
⎜   ↳ Wacom HID 5278 Pen eraser                 id=21   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Video Bus                                 id=6    [slave  keyboard (3)]
    ↳ Power Button                              id=7    [slave  keyboard (3)]
    ↳ Sleep Button                              id=8    [slave  keyboard (3)]
    ↳ Integrated Camera: Integrated C           id=10   [slave  keyboard (3)]
    ↳ Integrated Camera: Integrated I           id=11   [slave  keyboard (3)]
    ↳ sof-hda-dsp Headphone                     id=16   [slave  keyboard (3)]
    ↳ Intel HID events                          id=17   [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=18   [slave  keyboard (3)]
    ↳ ThinkPad Extra Buttons                    id=20   [slave  keyboard (3)]
nimibachar@nimibachar-ThinkPad-X1-Yoga-Gen-6:~$
Touchpad: ELAN touchpad.
System: Ubuntu 20.04 LTS
Kernel: Linux 5.14.0-1033-oem
There is a duplicate question which is discussing a very old version of Ubuntu and suggesting to upgrade the Kernel but I am not sure that it's related.
Many thanks !


text:
Q: Sorting MySQL table by next due date I have a MySQL table that stores (amongst other things) a persons date of birth.
Is there any way to sort the table so the next due birthday is at the top?
I have the date stored in standard yyyy-mm-dd DATE format and seperate year, month and day fields so I can sort it by the first birthday of the year (ORDER BY month, day) but I can't seem to get any further.
Any help would be greatly appreciated.
Zagga

A: There is no need to store separately the year, month, nor day.
And you don't need to order your table either.
All you've got to do is order your query as you'd like.
Something like this should get you started:
  SELECT month(t.dob) as m,
         dayofmonth(t.dob) as d,
    FROM mytable t
ORDER BY 1,2

A: Select ...
From 'Table'
Where DayOfYear(BirthDate) <= DayOfYear(CurDate())
Order By DayOfYear(BirthDate) Desc

Because of the heavy use of functions in the Where and Order By clause this probably won't perform well.
EDIT David Gelhar has the right idea for the full list. Another way would be:
Select ...
From 'Table'
Where DayOfYear(BirthDate) <= DayOfYear(CurDate())
Order By Case
            When DayOfYear(BirthDate) <= DayOfYear(CurDate()) Then 0
            Else 1
            End ASC
    , DayOfYear(BirthDate)  DESC

Again, not the best performing query but it should give you the answer you want.

A: Interesting question, because to do it right you need to get the remaining birthdays for this year, then wrap around to next year. Something like:
Select ...
From 'Table'
Where DayOfYear(BirthDate) >= DayOfYear(CurDate())
Order By DayOfYear(BirthDate)
union
Select ...
From 'Table'
Where DayOfYear(BirthDate) < DayOfYear(CurDate())
Order By DayOfYear(BirthDate)

EDIT
Thinking about this, you actually do need to use the broken-out "month" and "day" fields instead of just looking at DayOfYear; otherwise you'll get the wrong answer if this year is leap year and the person was born in a non-leap year (or vice-versa). That's because we think of our birthday as being "March 1st", not "the 60th day of the year".
And, of course, you can't use different "order by" clauses in the two halves of the UNION...
So, something more like:
Select 1,mon,day,name
From 'Table'
Where mon > Month(CurDate())
   or ((mon = Month(CurDate()))
       and (day >= DayOfMonth(CurDate())))
union
Select 2,mon,day,name
From 'Table'
Where mon < Month(CurDate())
   or ((mon = Month(CurDate()))
       and (day < DayOfMonth(CurDate())))
Order By 1,2,3


text:
Q: Can I put a "marker" on a QuickTime movie? Is there any way for me to put a "marker" in the timeline of a QuickTime movie? This would be very helpful in certain cases, for example quickly marking parts of long movies from my digital camera which I want to review later. I'm sure I could do this using iMovie or Final Cut Pro, but I'm looking for something specifically in QuickTime player (as I'm previewing movies taken right off my digital camera)
What I envision is something like I have mocked up in this doctored screen capture:

A: I'm afraid no feature like that exists.
However, with QuickTime Pro, you can fairly easily cut out clips of a movie to save for later. You get two selection cursors, and can actually use copy and paste to yank out sections and put them into new players. It will then save them natively inside .mov containers with no need for exporting.


text:
Q: Growth rates, using the last non-NA value by groups I have a dataframe that looks like this:
   value id
1      2  A
2      5  A
3     NA  A
4      7  A
5      9  A
6      1  B
7     NA  B
8     NA  B
9      5  B
10     6  B

And I would like to calculate growth rates of the value using the id variable to group. Usually, I would do something like this:
df <- df %>% group_by(id) %>% mutate(growth = log(value) - as.numeric(lag(value)))

To get this dataframe:
   value    id     growth
   (dbl) (chr)      (dbl)
1      2     A         NA
2      5     A -0.3905621
3     NA     A         NA
4      7     A         NA
5      9     A -4.8027754
6      1     B         NA
7     NA     B         NA
8     NA     B         NA
9      5     B         NA
10     6     B -3.2082405

Now what I want to do is to use the last non NA value as well for the growth rates. Kind of like calculating the growth rates over the "NA-gaps" as well. For example: In row 4 should be the growth rate from 5 to 7 and in row 9 should be the growth rate from 1 to 5.
Thanks!

A: zoo::na.locf will replace NAs with the last non-NA value, so this may work for you:
df <- df %>%
group_by(id) %>%
mutate(
valuenoNA = zoo::na.locf(value),
growth = log(valuenoNA) - as.numeric(lag(valuenoNA)))

1      2      A         NA         2
2      5      A -0.3905621         5
3     NA      A -3.3905621         5
4      7      A -3.0540899         7
5      9      A -4.8027754         9
6      1      B         NA         1
7     NA      B -1.0000000         1
8     NA      B -1.0000000         1
9      5      B  0.6094379         5
10     6      B -3.2082405         6

A: We can use fill from tidyverse
library(tidyverse)
df %>%
    group_by(id) %>%
    fill(value) %>%
    mutate(growth = log(value) - lag(value))


text:
Q: All pairs (x,y) that satisfy the equation $xy+(x^3+y^3)/3=2007$ How we can find the all pairs $(x,y)$  from the integers numbers ,that satisfy the equation :
$$xy+\frac{x^3+y^3}{3} =2007$$

A: Observe that the equation is symmetric.
As $3|(x^3+y^3)$, either $(x,y)$ will be $(3a+1,3b-1)$,  $(3a-1,3b+1)$ or $(3a,3b)$.
If $(x,y)$ is $(3a+1,3b-1)$, $\frac{x^3+y^3}{3}=3(3a^3+3b^3+3a^2-3b^2+a+b)$
So, 3 must divide $xy$ which is impossible as $xy=(3a+1)(3b-1)$
So,  $(x,y)$ will be  $(3a,3b)$.
So,$9(ab+a^3+b^3)=2007\implies a^3+b^3+ab=223$
Now, 223 is prime, so, $(a,b)=1$
If we think of solution in natural number, $a<7$ .
By trial (which is aided by $(a,b)=1$), $(a,b)$ is $(6,1)$ or $(1,6)$.

A: Let $x+y=a,xy=b$ then the equation is equivalent to $$a^3-3abc+3b=6021$$ or $$(a-1)(a^2+a+1-3b)=6020$$
Now it is easy to do.

A: Note that the given equation is $$x^3+y^3+3xy=6021$$ or $$x^3+y^3-1+3xy=6020$$
Factoring it we get , $$(x+y-1)(x^2+y^2+1+x+y-xy)=2^2.5.7.43$$
Obviously check $\equiv 3$ and see $$x+y-1\equiv 2 \mod 3$$
Also, $$x+y-1 < x^2+y^2+1+x+y-xy$$
This means, $$x+y-1 \rightarrow 20,5,2,35$$
so now it's easy to see that $$x+y-1=20$$ and so $(x, y)=(18,3)$ or $(3,18)$


text:
Q: How to find probability of having at least 2 out of 3 students selected to sit together? I have the problem. 25 students are seated in a circle at the campfire night. 3 students are selected (the probability of being selected for each student is the same) and asked to join a game. Find the probability of having at least 2 out of 3 students selected to sit together.
I tried.

*

*There are $ \binom{25}{3} $ ways to select.

*If 3 students selected to sit together, then we have $ 25 $ ways.

*If there are exact 2 students selected to sit together, then we have $ 25 \times 21 $ ways.

*Probability we need to find is $ \dfrac{25 +25 \times 21 }{ \binom{25}{3}} =\dfrac{11}{46}.$
Is my solution true?

A: Yes, your solution is correct.
Refer to the diagram:
$\hspace{4cm}$
You considered two cases:
Case 1: triple students (order does not matter):
$$(\color{red}1,2,3),(\color{red}2,3,4),(\color{red}3,4,5),...,(\color{red}{23},24,25),(\color{red}{24},25,1),(\color{red}{25},1,2) \Rightarrow 25$$
Case 2: double students (order does not matter):
$$(\color{red}1,2,4),(1,2,5),...,(1,2,24) \Rightarrow 24-4+1=21\\
(\color{red}2,3,5),(2,3,6),...,(2,3,25)\Rightarrow 25-5+1=21\\
\vdots\\
(\color{red}{25},1,3),(25,1,4),...,(25,1,23)\Rightarrow 23-3+1=21$$
Hence the result.
Alternatively, select any student, say $1$. Now we will consider the probability of selecting neighboring one or two students. Refer to the diagram (order matters):
$\hspace{5cm}$
Hence:
$$\mathbb P(1,(2 \text{ or } 25))+P(1,3,(2 \text{ or } 4 \text{ or } 25))+P(1,24,(2 \text{ or } 23 \text{ or } 25))+\\
P(1,\color{red}4,(2 \text{ or } 3 \text{ or } 5 \text{ or } 25))+\cdots+P(1,\color{red}{23},(2 \text{ or } 22 \text{ or } 24 \text{ or } 25))=\\
\frac2{24}+\frac{3}{24\cdot 23}+\frac{3}{24\cdot 23}+\frac{4}{24\cdot 23}+\cdots+\frac{4}{24\cdot 23}=\\
\frac{2\cdot 23+3+3+4\cdot (23-4+1)}{23\cdot 24}=\frac{132}{23\cdot 24}=\frac{11}{46}.$$


text:
Q: find probability of n people in a class of x share the same birthday using monte carlo simulation in java As the problem states, i must use monte carlo(randomness) to solve the question given. I am running the simulation 1,000,000 times.
import java.util.*;

public class MonteCarlo {
    public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       System.out.println("Please enter size of the class: ");
       int classSize = sc.nextInt();
       System.out.println("Please enter the amount of people who share the same birthday: ");
       int birthPpl = sc.nextInt();
       System.out.println("calculate the probability that "+birthPpl+" people share the same Birthday in a class size of "+classSize);

       sc.close();

       int birthdays [] = new int[classSize];
       int simulations = 0;
       int success=0;
       for(int i=0; i<1000000; i++){
            simulations++;
            if(Collision(birthdays)>=birthPpl){
                success++;
            }
       }
       System.out.println(success+" "+simulations);
       System.out.println("Answer: "+ (success*100)/simulations + "%");
    }

    public static int Collision(int birthday[]){
        Random rand = new Random();
        for(int i=1; i<birthday.length; i++){
            birthday[i]= rand.nextInt(365);
        }

        int count = 0;
        for(int i=0; i<birthday.length; i++){
            for(int j= i+1; j<birthday.length; j++){

                if(birthday[i]==birthday[j]){
                    count++;
                }
            }
        }
        return count;
    }
}

As per a couple of psuedo code solutions i have seen online i have tried looping through the size of the class x and inserting in a random birthday. then comparing birthdays , reducing the birthdays i look through by 1 each time. I then check the number of collisions against the amount sof ppl who should a birthday , if it is greater or equal to it than i increase the count. i have been given sample imput 20 and 2 which should give 41 % but my program gives eithe 7 or 8 %
What's the problem, and how can it be fixed?

A: You could also make use the Random and HashMap classes. Map.merge will take the key, a birthday in this case, then a default value of 1, and continues to add 1 to the existing value which is returned and compared to x. Then success is appropriately updated.  The Random class provides a variety of methods to return random numbers and is usually preferred over Math.random.
double success = 0;
int tests = 1_000_000;

// instantiate a Random class for selecting the next birthday
Random r = new Random();

// a map to hold the frequency count of same birthdays
Map<Integer,Integer> birthdays = new HashMap<>();

int n = 23;
int x = 2;

for(int i=0; i< tests; i++) {
   for (int j = 0; j < n; j++) {
       if (birthdays.merge(r.nextInt(365), 1, Integer::sum) >= x) {
           success++;
           break;
       }
   }
   // clear the map for the next run
   birthdays.clear();
}

Using System.out.printf facilitates formatting the output.
System.out.printf("probability = %4.1f%%%n", (success/tests) * 100);

prints something like the following:
probability = 50.7%

A: import java.util.Scanner;

public class Birthday {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(); // class size
        int x = sc.nextInt(); // people who share the same birthday
        double tests = 1_000_000;
        double success = 0;

        // fills array of birthdays and breaks out when x amount of people share
        // a birthday. then we find the % of successes.
        for (int i = 0; i < tests; i++) {
            int[] year = new int[365];

            for (int j = 0; j < n; j++) {
                int birthday = (int) (Math.random() * 365);
                year[birthday]++;
                if (year[birthday] >= x) {
                    success++;
                    break;
                }
            }
        }

        System.out.println(Math.round(success * 100 / tests));
    }
}


text:
Q: How can I expand the Fourier coefficient The Fourier series is

How can I expand the Fourier coefficient $a_n$ and $b_n$ to the n order? $x\in [-Pi,Pi]$,$n \gt 0$.

A: Sadly there isn't a FourierTrigCoefficient built in Mathematica up to now, but you can use my easyFourierTrigSeries for the task.
Let me illustrate the solving process with
$$f(x)=e^{-x}$$
If we need to find the general term of $a_n$ and $b_n$ for $x\in(-1,1)$, just write
Clear@f
f[x_] = Exp[-x];
series = easyFourierTrigSeries[f[x], {x, -1, 1}]

The formula of $a_n$ and $b_n$ is already clear at this stage, simply copy them manually from the output isn't a bad idea, still, we can extract them progammatically in the following way:
Cases[series, a_ Cos[_] + b_ Sin[_] :> {a, b}, Infinity]


text:
Q: Cant Set VCard In Asmack im trying to set a Simple NickName with my Beem-asmack to the openfire server like this :
 connection.login(USERNAME, PASSWORD);
            ProviderManager.getInstance().addIQProvider("vCard",
 "vcard-temp", new org.jivesoftware.smackx.provider.VCardProvider());
            VCard card = new VCard();

            card.setNickName("NewNickname");
            try {
                card.save(connection);
            } catch (XMPPException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

the IQ packages are like this :
06-29 14:06:28.560: D/SMACK(2691): 02:06:28 PM SENT (-1274092112): <iq id="RJyL4-4"
from="reza@reza-hp/Smack" type="set"><vCard xmlns='vcard-temp'>
<NICKNAME>NewNickname</NICKNAME>
06-29 14:06:28.560: D/SMACK(2691): </vCard>
06-29 14:06:28.560: D/SMACK(2691): </iq>

and response is:
 06-29 14:06:28.570: D/SMACK(2691): 02:06:28 PM RCV  (-1274092112): <iq type="result"
 id="RJyL4-4" to="reza@reza-hp/Smack"/>

But my V-card is not getting updated. i havent seen a Vcard IQ before, but the response here looks empty , is there some thing else i should do? any help please?

A: You did't load the Card.
Try this:
VCard vCard = new VCard();
card.load(connection);
card.setNickName("NewNickname");
try {
    card.save(connection);
} catch (XMPPException e) {
  // TODO Auto-generated catch block
 e.printStackTrace();
}


text:
Q: A float set to 0.1 compares false against 0.1  int main()
    {
            float f = 0.1;
            if (f == 0.1)
                printf("True");
            else
                printf("False");
        }

I am just a beginner in c. I don't understand the behavior of the above program. The output is false. Why??

A: 0.1 is a double literal.
As 0.1 cannot be represented exactly in floating point, a float set to 0.1 will compare false against a double set to 0.1.
Your comparison would behave as intended if you use a float literal: 0.1f (note the suffixed f: not to be confused with your variable name):
float foo /*renamed for clarity*/= 0.1;
if (foo == 0.1f){
     /*this will compare true*/


text:
Q: Accessing touch events in a global monitor throws an error I'm writing a MacOs app where I'm trying to get the position of a touch in the trackpad. For example the left bottom corner would be 0,0 and the top right would be 100,100.
I want to get that information for touches that happen out of my application, so I'm using a global monitor.
I've found some information and read official documentation (with an impressive lack of examples), but I still can get this to work. I'm getting an error any time I try to access the method allTouches() from the event. Here's the code:
import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        NSEvent.addGlobalMonitorForEvents(matching: NSEvent.EventTypeMask.leftMouseDown) {event in
            let touch = event.allTouches()
        }
    }
}

I'm getting the following error:
2018-11-17 12:49:08.693873+0000 App[76030:1935325] [default] Unable to load Info.plist exceptions (eGPUOverrides)
2018-11-17 12:49:09.910842+0000 App[76030:1935325] *** Assertion failure in -[NSEvent touchesMatchingPhase:inView:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1671/AppKit.subproj/NSEvent.m:4752
2018-11-17 12:49:09.910996+0000 App[76030:1935325] [General] An uncaught exception was raised
2018-11-17 12:49:09.911019+0000 App[76030:1935325] [General] Invalid message sent to event "NSEvent: type=LMouseDown loc=(760.789,273.406) time=414257.3 flags=0 win=0x0 winNum=42380 ctxt=0x0 evNum=30352 click=1 buttonNumber=0 pressure=1 deviceID:0x200000001000000 subtype=NSEventSubtypeTouch"
2018-11-17 12:49:09.913059+0000 App[76030:1935325] [General] (
    0   CoreFoundation                      0x00007fff32b6943d __exceptionPreprocess + 256
    1   libobjc.A.dylib                     0x00007fff5ea76720 objc_exception_throw + 48
    2   CoreFoundation                      0x00007fff32b8408e +[NSException raise:format:arguments:] + 98
    3   Foundation                          0x00007fff34f2055d -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 194
    4   AppKit                              0x00007fff303e3cd2 -[NSEvent touchesMatchingPhase:inView:] + 494
    5   App                             0x00000001000018a2 _T07App14ViewControllerC11viewDidLoadyyFySo7NSEventCcfU_ + 34
    6   App                             0x0000000100001c4e _T0So7NSEventCIxx_ABIyBy_TR + 62
    7   AppKit                              0x00007fff3063f2b5 GlobalObserverHandler + 117
    8   HIToolbox                           0x00007fff31d468d9 _ZL23DispatchEventToHandlersP14EventTargetRecP14OpaqueEventRefP14HandlerCallRec + 1502
    9   HIToolbox                           0x00007fff31d45c16 _ZL30SendEventToEventTargetInternalP14OpaqueEventRefP20OpaqueEventTargetRefP14HandlerCallRec + 371
    10  HIToolbox                           0x00007fff31d45a9c SendEventToEventTargetWithOptions + 45
    11  HIToolbox                           0x00007fff31d62c54 _ZL29ToolboxEventDispatcherHandlerP25OpaqueEventHandlerCallRefP14OpaqueEventRefPv + 1336
    12  HIToolbox                           0x00007fff31d46d0c _ZL23DispatchEventToHandlersP14EventTargetRecP14OpaqueEventRefP14HandlerCallRec + 2577
    13  HIToolbox                           0x00007fff31d45c16 _ZL30SendEventToEventTargetInternalP14OpaqueEventRefP20OpaqueEventTargetRefP14HandlerCallRec + 371
    14  HIToolbox                           0x00007fff31d631cd SendEventToEventTarget + 39
    15  AppKit                              0x00007fff30005b36 _DPSNextEvent + 1472
    16  AppKit                              0x00007fff300046fa -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1362
    17  AppKit                              0x00007fff2fffe75d -[NSApplication run] + 699
    18  AppKit                              0x00007fff2ffede97 NSApplicationMain + 780
    19  App                             0x00000001000039ed main + 13
    20  libdyld.dylib                       0x00007fff5fb44085 start + 1
)

What am I doing wrong and how do I fix it?

A: allTouches is not valid for mouse down events, only from within NSEventTypeGesture events, as noted by the comment in the header file:
/* Only valid for NSEventTypeGesture events. Equivalent to [event
touchesMatchingPhase:NSTouchPhaseAny inView:nil] */
- (NSSet <NSTouch *> *)allTouches NS_AVAILABLE_MAC(10_12);

For the NSEvent.EventTypeMask.leftMouseDown you are asking to be notified of the following are the primary properties you will likely want to access:
/* these messages are valid for all mouse down/up/drag events */
@property (readonly) NSInteger clickCount;
@property (readonly) NSInteger buttonNumber;    // for NSOtherMouse events, but will return valid constants for NSLeftMouse and NSRightMouse
…
/* -pressure is valid for all mouse down/up/drag events, and is also valid for NSEventTypeTabletPoint events on 10.4 or later and NSEventTypePressure on 10.10.3 or later */
@property (readonly) float pressure;
/* -locationInWindow is valid for all mouse-related events */
@property (readonly) NSPoint locationInWindow;

If you are actually trying to get gestures then use the NSEventTypeGesture mask.  Then you can use allTouches and touchesForView.  Note you may need to distinguish between gesture scroll related events and other gestures, depending on your situation and goals.


text:
Q: Why is this class property not being modified in PHP? I have this function:
public userID = 1;

public function setID($id)
    {
        $this->userID = $id;

    }

It's located in a class so this function should set the userID variable on the top. As you can see here I create an object and call the function with the correct parameter:
$data = new Data();
$data->setID(($_SESSION['ID']));

The session ID is indeed available to use I echo'd the session ID.
But now I have another function to use the userID variable and then i get the error:

Undefined variable: userID.

The function I use this variable is this one:
$ordSql = "INSERT INTO order(DATUM, KLANT_ID) VALUES($datum, $userID)";
$resultaat = mysqli_query($verbinding, $sql) or die (mysqli_error($verbinding));

This is in another function below my setID function. Does anyone know how to fix this?

A: You are missing the $ on your public $userId variable. This example prints 42:
<?php

class Data {
    public $userId = 1;

    public function setId($id) {
        $this->userId = $id;
    }

    public function otherFunction() {
        echo $this->userId;
    }
}

$data = new Data();
$data->setId(42);
$data->otherFunction();

A: change
 $userID;

to
$this->userID;

A: You have to use $this->userID instead of $userID
$ordSql = "INSERT INTO order(DATUM, KLANT_ID) VALUES($datum, $this->userID )";
$resultaat = mysqli_query($verbinding, $sql) or die (mysqli_error($verbinding));

A: It was posted but deleted again this is the solution :
$ordSql = "INSERT INTO order(DATUM, KLANT_ID) VALUES($datum, $this->userID)";
$resultaat = mysqli_query($verbinding, $sql) or die (mysqli_error($verbinding));

instead of :
$ordSql = "INSERT INTO order(DATUM, KLANT_ID) VALUES($datum, $userID)";
$resultaat = mysqli_query($verbinding, $sql) or die (mysqli_error($verbinding));

A: As the error says, the variable $usedID is not set. The property userId is set though.
You are trying to use a property of the class as a variable, which is not possible. (You may have another variable named $userID, it's quite common in setters for example)
You should always use$this->userId and not $userID.


text:
Q: Pagination redirect is not working in laravel Using render function in pagination i am getting  this url
http://localhost/laravel_admin/public/undo/?page=2

So it will redirect wrong page so how to fix that issue
To redirect this way
http://localhost/laravel_admin/public/undo?page=2

in laravel 5
I think minor error is in my code by i can't found that any one got this error.

A: I think you have wrong configuration. You should set up your web server, so it point to /laravel_admin/public folder.

A: Try changing your code like this:
{!! str_replace('/?', '?', $yourVar->render()) !!}

I think this will fix your issue!
Hope it helps!


text:
Q: GLSL Render to Texture not working I'm trying to do a compute pass where I render to a texture that will be used in a draw pass later on. My initial implementation was based on shader storage buffer objects and was working nicely. But I want to apply a computation method that is going to take advantage of the blend hardware of the GPU so I started porting the SSBO implementation to RTT one. Unfortunately the code has stopped working. Now when I read back the texture it is getting wrong values.
Here is my texture and frame buffer setup code:
glGenFramebuffers(1, &m_fbo);
glBindFramebuffer(GL_FRAMEBUFFER, m_fbo);

// Create render textures
glGenTextures(NUM_TEX_OUTPUTS, m_renderTexs);
m_texSize = square_approximation(m_numVertices);
cout << "Textures size: " << glm::to_string(m_texSize) << endl;
GLenum drawBuffers[NUM_TEX_OUTPUTS];
for (int i = 0 ; i < NUM_TEX_OUTPUTS; ++i)
{
    glBindTexture(GL_TEXTURE_2D, m_renderTexs[i]);
    // 1st 0: level, 2nd 0: no border, 3rd 0: no initial data
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_texSize.x, m_texSize.y, 0, GL_RGBA, GL_FLOAT, 0);
    // XXX: do we need this?
    // Poor filtering. Needed !
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glBindTexture(GL_TEXTURE_2D, 0);

    // 0: level
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, m_renderTexs[i], 0);
    drawBuffers[i] = GL_COLOR_ATTACHMENT0 + i;
}
glDrawBuffers(NUM_TEX_OUTPUTS, drawBuffers);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
    cout << "Error when setting frame buffer" << endl;
    // throw exception?
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);

And this is the code to start the compute pass:
m_shaderProgram.use();

// setup openGL
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glViewport(0, 0, m_texSize.x, m_texSize.y); // setup viewport (equal to textures size)
// make a single patch have the vertex, the bases and the neighbours
glPatchParameteri(GL_PATCH_VERTICES, m_maxNeighbours + 5);

// Wait all writes to shader storage to finish
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);

glUniform1i(m_shaderProgram.getUniformLocation("curvTex"), m_renderTexs[2]);
glUniform2i(m_shaderProgram.getUniformLocation("size"), m_texSize.x, m_texSize.y);
glUniform2f(m_shaderProgram.getUniformLocation("vertexStep"), (umax - umin)/divisoes,
            (vmax-vmin)/divisoes);

// Bind buffers
glBindFramebuffer(GL_FRAMEBUFFER, m_fbo);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo);
glBindBufferBase(GL_UNIFORM_BUFFER, m_mvp_location, m_mvp_ubo);

// Make textures active
for (int i = 0; i < NUM_TEX_OUTPUTS; ++i)
{
    glActiveTexture(GL_TEXTURE0 + i);
    glBindTexture(GL_TEXTURE_2D, m_renderTexs[i]);
}

// no need to pass index array 'cause ibo is bound already
glDrawElements(GL_PATCHES, m_numElements, GL_UNSIGNED_INT, 0);

I then read back the textures using the following:
bool readTex(GLuint tex, void *dest)
{
    glBindTexture(GL_TEXTURE_2D, tex);
    glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, dest);
    glBindTexture(GL_TEXTURE_2D, 0);

    // TODO: check glGetTexImage return values for error
    return true;
}

for (int i = 0; i < NUM_TEX_OUTPUTS; ++i)
{
    if (m_tensors[i] == NULL) {
        m_tensors[i] = new glm::vec4[m_texSize.x*m_texSize.y];
    }
    memset(m_tensors[i], 0, m_texSize.x*m_texSize.y*sizeof(glm::vec4));
    readTex(m_renderTexs[i], m_tensors[i]);
}

Finally, the fragment shader code is:
#version 430
#extension GL_ARB_shader_storage_buffer_object: require

layout(pixel_center_integer) in vec4 gl_FragCoord;

layout(std140, binding=6) buffer EvalBuffer {
    vec4 evalDebug[];
};

uniform ivec2 size;

in TEData {
    vec4 _a;
    vec4 _b;
    vec4 _c;
    vec4 _d;
    vec4 _e;
};

layout(location = 0) out vec4 a;
layout(location = 1) out vec4 b;
layout(location = 2) out vec4 c;
layout(location = 3) out vec4 d;
layout(location = 4) out vec4 e;

void main()
{
    a= _a;
    b= _b;
    c= _c;
    d= _d;
    e= _e;
    evalDebug[gl_PrimitiveID] = gl_FragCoord;
}

The fragment coordinates are correct (each fragment is pointing to a x,y coordinate in the texture), so are all the input values (_a to _e), but I do not see them outputted correctly to the textures when reading back. I also tried accessing the texture in the shader to see if it was only a read-back error, but my debug SSBO returned all zeroes.
Am I missing some setup step?
I've tested both on linux and windows (titan and 540M geforces) and I'm using openGL 4.3.

A: As derhass pointed out in the comments above, the problem was with the texture format. I assumed that by passing GL_FLOAT as the data type it would use 32bit floats for each of the RGBA channels. It was not so.
As derhass said, the data type parameter here does not change the texture format. I had to change the internalFormat parameter to what I wanted (GL_RGBA32F) so that it would work as expected.
So, after changing glTexImage2D call to:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, m_texSize.x, m_texSize.y, 0, GL_RGBA, GL_FLOAT, 0);

I was able to correctly render the results to the texture and read it back. :)


text:
Q: c# application doesn't perform batch file command correctly public void runBatchfile(String batchfilename)
{
   try
   {
      ProcessStartInfo processInfo = new ProcessStartInfo(batchfilename);
      processInfo.UseShellExecute = false;
      Process batchProcess = new Process();
      batchProcess.StartInfo = processInfo;
      batchProcess.StartInfo.CreateNoWindow = true;
      batchProcess.Start();
      batchProcess.WaitForExit();
   }
   catch (Exception r) { }
}

runBatchfile(@"c:\lol.bat");

lol.bat contains these 2 lines
dir c:\ /s /b > c:\filelist.txt
exit

and when I run my code all it does is creating a filelist.txt file, but doesn't actually perform the rest of the command, which does work if I manually insert it into CMD.
Btw I've tried making the extension .cmd and I also tried without the exit command, without any other results.
please help me :)

A: On my Windows 7 64-bit machine with Visual Studio 2010, running this code straight from the IDE doesn't do anything whatsoever.
On a hunch that it might have something to do with permission to write to the root directory of drive C:, I tried running the .exe directly from an Explorer window with admin rights (right-click, Run as Administrator) and that worked.
I'd say it's a permission problem.
Maybe you could redirect the output to a file located elsewhere?
update:
I changed the batch file so that the dir command gets redirected to my desktop and it runs just fine.

A: I've had issues with this as well when calling from C#. The workaround that I usually use is to physically allow it to show the window when running the command. Not sure why this makes a difference but it has worked for me in the past.


text:
Q: Inertial Torque Exerted By Engine on Crankshaft In Shigley(5th Edition), in Chapter 14. Dynamics of Reciprocating Engine ,Section 14.7 Inertia Forces,
the inertia torque exerted by the engine on the crankshaft is given as

$$
\mathbf{T}_{21}^{\prime \prime}=-\left(-m_{B} A_{B} \tan \phi\right) x \hat{\mathbf{k}}
$$
Background : In this section they have assumed equivalent masses $m_A$ and $m_B$ for the crank and connecting rod (link 3) at the crank Pin A and wrist pin B respectively. (with $m_A$ rotating mass at A ($m_{A}=m_{2} \frac{r_{G}}{r}$ + $m_{3} \frac{l_{B}}{l}$) where $r_G$ is the CG of Crank from $O_2$ and $l_B$ is the CG of connecting rod from B  and $m_B$ reciprocating mass at B, ($m_{B}=m_{3} \frac{l_{A}}{l}$ + $m_{4}$) , $l_A$ is the CG of connecting rod from A) . From the formulas for inertia force and torques or equivalently Frame Force and Frame Moment(Sec 12.7 Shaking Forces and Moments) as :
$$
\begin{array}{l}
\mathbf{F}_{s}=\sum\left(-m_{j} \mathbf{A}_{G_{j}}\right) \\
\mathbf{M}_{s}=\sum\left[\mathbf{R}_{G_{j}} \times\left(-m_{j} \mathbf{A}_{G_{j}}\right)\right]+\sum\left(-I_{G_{j}} \alpha_{j}\right)
\end{array}
$$
we can calculate the inertia forces :
\begin{array}{l}
-m_{A} \mathbf{A}_{A}=m_{A} r \omega^{2}(\cos \omega \hat{t} \mathbf{i}+\sin \omega t \hat{\mathbf{j}}) \\
-m_{B} \mathbf{A}_{B}=m_{B} r \omega^{2}\left(\cos \omega t+\frac{r}{l} \cos 2 \omega t\right) \hat{\mathbf{i}}
\end{array}
As per my understanding we incorporate Inertia Forces in dynamic systems to reduce the system to static system using d'Alembert Principle.
My doubt is although we have reduced the system to its equivalent mass system and the respective inertia forces for both of them pass through $O_2$

*

*How is the inertia force generating a torque about $O_2$ ? (like as mentioned in the text, it says $-m_A\mathbf{A}_A$ can be neglected because it does not have any moment arm about $O_2$ , so why isn't  $-m_B\mathbf{\ddot{X}}$ also ignored along the same line of reasoning?

*The inertia force due to $m_B$ is resolved into components and only one of the component ($-m_B\mathbf{\ddot{X}}\:tan \phi$ ) is used to calculate the torque. Won't the net torque if we use both the component be zero, as the force  $-m_B\mathbf{\ddot{X}}$ has zero moment arm in the first place and hence the net torque of its components about $O_2$ will also be zero.

A: Upon reading further I came to the conclusion. The inertial force acting $-m_B\mathbf{\ddot{X}}$ on B can 'transmit' the force(acting along the connecting rod $F_{43}$ ) through the connecting rod, and the rod being mass-less will transfer the forces.We have  $F_{34}=\frac{-m_B\mathbf{\ddot{X}}}{cos\phi}$ using force balance at point $B$ . Torque at $O_2$ will be $r_\perp*F_{43}$ and $r_\perp=x*sin\phi$. Using these two equations we get $\mathbf{T}_{21}^{\prime \prime}=-\left(-m_{B} A_{B} \tan \phi\right) x \hat{\mathbf{k}}$


text:
Q: 0x800a1391 - JavaScript runtime error: 'PageMethods' is undefined I need to call server side code "c# Function" in my asp.net project in javascript so i used this way:
<script type="text/javascript">

    function doReadPublicData() {
        PageMethods.btnVerifyPubData_Click(OnGetMessageSuccess, OnGetMessageFailure);
    }

    function OnGetMessageSuccess(result, userContext, methodName) {
        alert(result);
    }

    function OnGetMessageFailure(error, userContext, methodName) {
        alert(error.get_message());
    }
</script>

And I enabled the EnablePageMethods property in the script manager:
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
</asp:ScriptManager>

<asp:Button ID="btnVerifyPubData" runat="server" OnClientClick="doReadPublicData();"
    OnClick="btnVerifyPubData_Click" Text="Show Information"
    CssClass="submitButton" PostBackUrl="~/ParsePublicData.aspx" />

But this error occurs.

A: solved finally ..
I have to add "static" to my web method to work successfully ! :
[WebMethod]
    public static void btnVerifyPubData_Jscript(string t)
    {

    }


text:
Q: Kotlin: repeat n time while condition is true I need to repeat a piece of code a maximum of n times, but terminate the loop once a condition is false, like in the following:
val runs = 100
var ctr = 0
var condition = true

while (ctr++ < runs && condition) {
    //stuff and updates
}

Can this logic be stated more idiomatic, maybe with repeat?

A: You can nest lambdas and non-locally return to the outer one - I won't say this is pretty but it's an option:
run loop@{
    repeat(100) {
        if(!condition) return@loop
        // stuff and updates
    }
}

A: This is what I would consider an idiomatic way of doing this, lazily generate a sequence, limit to 100, stop on the first condition==true then do something if not null (i.e. condition==true)
            generateSequence {
                // do stuff per iteration
                Unit // or whatever value per iteration
            }.take(100).firstOrNull { condition }?.let {
                // on condition
            }

A: val runs = 100
var condition = true

for(ctr in (0..runs)){
    if(condition){
        //stuff and updates
    }
}


text:
Q: Connection Problems With Mirrored Database The setup is as follows:
A C++ client connects via OLEDB/SQL Native Client to a SQL Server 2005 database located on another machine.  The server is setup with mirroring (automatic failover) with a synchronized server located on yet another server and a witness server on another server.
Occassionally (once every couple of days), our application seizes up in that it appears to attempt to establish a database connection to the database and rather than simply failing and OLEDB throwing a database connection failure it just gets "stuck" (we have a timeout for the connection but it's never timing out).  24 to 36 hours later we'll get an error:
TCP Provider: An existing connection was forcibly closed by the remote host.

And things will continue you on with lots of these errors and our app will eventually need to be restarted.  We can't really figure out what condition could be causing this behavior and what we can do about it?
In preliminary research, I've seen some related problems that were solved by setting the Connection Lifetime connection string property to something non-zero.
Does anyone have any thoughts on what might be going on here?


text:
Q: Condition doesn't work I use button in ViewController to go TableViewController. In TableViewController I create int NInt1. But when I go to TableViewController condition doesn't work.
ViewController.m
- (IBAction)Button:(id)sender {
MasterViewController *trns =[[MasterViewController alloc]init];
[_Button.titleLabel.text isEqualToString:@"1"];
    trns.NInt1=1;
}

TableViewController.m
 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(_NInt1 == 1){
    return 5;
}else{
    return 20;
}
}

A: If you are using the story pass the value like this:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    RecipeDetailViewController *destViewController = segue.destinationViewController;
    destViewController.NInt1 = 1;
}

Now see the value of NInt in viewDidLoad of your destination view controller.

A: I think you need to modify like
- (IBAction)Button:(UIButton *)sender {
 MasterViewController *trns =[[MasterViewController alloc]init];
if [sender.titleLabel.text isEqualToString:@"1"]{
  trns.NInt1=1;
 }
}

on that tableviewController viewDidload check like use NSLog for the object is 1 or not

A: If you use storyboard, then the destination view controller is not created from your IBAction. It can be verified easily : you never push or present the newly created view controller, which is local in your method.
Instead use prepareForSeguemethod as described in Jaimish answer.

A: I tried the solution.Finally I got.Thank you.The condition has worked now.
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
  if([segue.identifier isEqualToString:@"goTableViewController"])
  {
    TableViewController *tableVC = (TableViewController *) segue.destinationViewController;
    tableVC.NInt1 = 5;
  }
}


text:
Q: Why do we need an algebraic closure to state this theorem about splitting fields? I have the following theorem:

Let $k^a$ be the algebraic closure of $k$ and take $K_i$ to be a splitting field of $f_i$ in $k^a$. Then the compositum of the $K_i's$ is a splitting field for $\{f_i\}_{i\in I}$

My question is why do we need here the splitting field in $k^a$, because we have defined a normal splitting field to be an extension of $f$ such that $f$ splits into linear factors in it and we have never mentionned an algebraic closure. So I don't see why they use it here, is then $K_i\subset k^a$?
Thanks for your help

A: You did not tell us what book or other reference you are reading. More precisely, is the author actually using an algebraic closure for any other purpose than to see there is a splitting field?
You do not need algebraic closures to show a polynomial has a splitting field or to do Galois theory for finite extensions of fields.  That you can construct a splitting field of a polynomial inside an algebraic closure does not mean you must use them. Just because an author mentions algebraic closures to get a splitting field doesn't mean you have to pay any attention to it.
However, I think I know what is going on. You are referring to an indexed set of polynomials $f_i$.  If that is a finite set, then you could let $f = \prod f_i$, which is another polynomial, and a splitting field of $f$ will be a splitting field for all the $f_i$'s together. But what if $\{f_i\}$ is an infinite set of polynomials? How do you know there is a splitting field for all of them?  For example, what is a splitting field over $\mathbf Q$ of all the polynomials $x^3 - nx - n$ where $n$ runs over the integers?  To show there is a splitting field for an arbitrary set of polynomials, possibly being an infinite set, then it is understandable why an author might like to appeal to the algebraic closure and find the splitting field in there. That could be technically simpler than trying to build up an infinite abstract field extension from scratch that plays the role of a splitting field for all $f_i$.


text:
Q: working with ajax variables and post I have the following ajax function:
$("#signInButton2").click(function() {
   $.ajax({
    type: "POST",
    data: {couponcode: $('#couponCode').val(), userEmail: $('#login-username').val() },
    url: 'coursePayment.php',
    success: function (response) {//response is value returned from php (for    your example it's "bye bye"

    }
   });
});

My problem are as follow:

*

*It does not seem to post anything to the coursePayment.php

*userEmail can be refered in both the login-username and the registration, username, how do i associate both id with the userEmail variable

*essentially similar to point 2. I have couponCodeRegisterAmount and I have couponCodeLoginAmount ID that I would like to associate with one post variable called couponCodeAmount, and which I would like to be able to retrieve on the coursePayment page

For any clarification, let me know thanks
Update HTML
<input type="text" oninput="calculate()" name="couponCode"  id="couponCode"  value="" placeholder="Please Enter Coupon Code" required>

<?php ?>

Sign In to Proceed with Purchase

   Don't have an account!

                                            Sign Up Here

                        <form method="post" action="">

                        <input type="hidden" id="couponCodeLogin" name="couponCodeLogin">
                             <input type="hidden" id="couponCodeLoginAmount" name="couponCodeLoginAmount">

                                        <input id="login-username" type="text" class="form-control" name="email" value="" placeholder="username or email">

                                        <input id="login-password" type="password" class="form-control" name="pass" placeholder="password">

                                          <input id="login-remember" type="checkbox" name="remember" value="1"> Remember me

                                        Forgot password?

                                      <input id="signInButton2" class="btn btn-danger" name="login" type="submit" value="Sign In">

                            </form>

Sign Up

Sign In

                            <form id="signupform" action="" method="post" class="form-horizontal" role="form">

Error:

                                <input type="hidden" id="couponCodeRegister" name="couponCodeRegister">
                             <input type="hidden" id="couponCodeRegisterAmount" name="couponCodeRegisterAmount">

                                    First Name

                                        <input type="text" class="form-control" name="fname" placeholder="First Name">

                                    Last Name

                                        <input type="text" class="form-control" name="lname" placeholder="Last Name">

                                    Email

                                        <input type="text" id="emailSignup" class="form-control" name="email" placeholder="Email Address">

                                    Phone Number

                                        <input type="number" class="form-control" name="pnumber" placeholder="Phone Number">

                                    Password

                                        <input type="password" class="form-control" name="pass" placeholder="Password">

                                    Company Name

                                        <input type="text" class="form-control" name="cname" placeholder="Company Name (Optional)">

                                    Position

                                        <input type="text" class="form-control" name="cposition" placeholder="Position (Optional)">

                                        <input id="signInButton" class="btn btn-danger" name="register" type="submit" value="Sign Up">

                            </form>