text:
Q: How to know if a wordpress plugin is safe There are thousands of plugins and themes available at wordpress.org and many other third parties. There is every possibility of bad plugins and themes being uploaded, which once uploaded could send info about the site to its owner. It could also send the information in the wp-config.php (A high security risk).
Please tell me how to protect wordpress sites from this other than by reading the code line by line. Also tell me if plugins and themes at wordpress.org are analyzed by the wordpress developers for threats like this before making it available to public.
Thank you.
Peace to All....

A: As with any code you run on your own server(s), WordPress plugins are caveat emptor.
That said, popular plugins have probably had a fair number of eyes on their code, making it unlikely that they're doing something shady. You probably don't need to go over them with a fine-tooth comb before installing them.
Lesser-known/used plugins, however, should probably be looked over before you install them on a site/server that you care about.
WordPress.org does not review every bit of code that goes into plugins - the only time they even do any review at all is when the plugin is initially submitted to the plugin directory, and that's cursory at best (mostly just to avoid spam). A plugin's code can change drastically after it's initially submitted.

A: Typically I will look at the feedback the plugin received on wordpress.org What kind of rating does it have? What comments/questions are asked in the 'what others are saying' section.
After making the decision to install the plugin, BACKUP YOUR DATA PRIOR TO THE ACTUAL INSTALLATION.
This is just good practice in any case, whether it's a wordpress core installation, plugin installation, or theme. If something breaks, you will have something to go back to.
Also making sure to keep frequent backups is a must. If you do get infected, you will want a snapshot.

A: There is a good article about the safety and security of themes that best plugins for wordpress put together.   Also you can go some off of the rating given by the community straight from the wordpress plugin site. If you keep with plugins that have a 4-5 star rating and lots of downloads/ratings, you will most likely be ok.  However, because this is an open source project, there is really not a 100% way to keep hackers and "bad people" from putting code in a what appears to be good theme/plugin that you are describing.
In this case if you have concern of a theme or plugin, I would always look over the code very carefully and make sure that it all looks good to you.  Of course this is always time consuming and if you are not comfortable with code, this may not be an option.  If you have questions about a certain set of plugins/themes, im sure if you post them here, there are many people that have used the plugin and maybe the theme before that can help you out.
From "Best Plugins for Wordpress"

1 TAC (Theme Authenticity Checker) Plugin
A very simple and straight forward plugin that will scan all files within your theme to >>check for any malicious or unwanted code.
2 Theme-Check Plugin
You may notice that a lot of free themes aren't available directly from WordPress.org, >>the main reason for this is that most free themes don't pass the tests that WordPress.org subjects them too. This nifty plugin will provide you with all the testing tools you will need to conduct the same tests that WordPress.org does. It's also useful for theme developers who want to make sure their theme supports the latest standards.
3 Exploit Scanner Plugin
This plugin isn't just for themes, it's for your entire site, so it's worth keeping once you've checked out the theme you've decided to use on your site. It scans all files, posts and comments on your site for any possible exploits or anything that looks suspicious, please note however that this plugin will not remove any files.


text:
Q: Como realizar update do nome de uma imagem no banco? Esse meu script é para inserir o nome da imagem no banco, está funcionando normalmente
INSERIR.PHP
  if ($_POST){

    $imagem = $_FILES['img_post'];
    $nomeImg = $imagem['name'];
    $tmpImg = $imagem['tmp_name'];
    $formatoBase = explode('.',$nomeImg);
    $formato = end($formatoBase);           //jesus
    $nomeImg = "paranoid_img_".uniqid().".".$formato;

        $titulo = $_POST['titulo_post'];
        $descricao = $_POST['descricao_post'];
        $texto = $_POST['texto_post'];
        $autor = $_SESSION['nome']." ".$_SESSION['sobrenome'];
        $url = uniqid();
        $pastaImg = "../img/posts";

        $query = mysqli_query($conexao, "insert into tbl_post (titulo_post, descricao_post, img_post, texto_post, autor_post, idautor_post, data_post, url_post)
                                        values ('$titulo','$descricao','$nomeImg','$texto','$autor','$id_user','$data','$url')");

        if ($query){

            $uploadPasta = move_uploaded_file($tmpImg, $pastaImg."/".$nomeImg);
            echo "<script>alert('Post enviado!');location.href=('../painel_adm.php');</script>";

        } else {

            echo "<script>alert('Erro!');location.href=('../upload_post.php');</script>";

        }
}

Agora eu não consigo realizar o update do nome caso eu suba outra imagem pelo formulário de alteração.
ALTERAR.PHP
$query1 = mysqli_query($conexao,"select * from tbl_post where url_post = '$url'");
$contSql=mysqli_fetch_array($query1);

if ($_POST){

    $id = $contSql['id_post'];
    $titulo = $_POST['titulo_post'];
    $descricao = $_POST['descricao_post'];
    $texto = $_POST['texto_post'];
  $imagem = $_FILES['img_post'];
    $nomeImg = $imagem['name'];
    $tmpImg = $imagem['tmp_name'];

    $query2 = mysqli_query($conexao,"update tbl_post set titulo_post='$titulo', descricao_post='$descricao', texto_post = '$texto' img_post='$nomeImg' where id_post = $id");

    if ($query2){
        echo "<script>alert('Post atualizado!');location.href='show_post.php?url=$url';</script>";
    } else {
        echo "<script>alert('Erro!');</script>";
    }
}
?>

A: Consegui guys, segue o código pra quem precisar de ajuda

 <?php
    if ($_POST){

    $id = $contSql['id_post'];
    $titulo = $_POST['titulo_post'];
    $descricao = $_POST['descricao_post'];
    $texto = $_POST['texto_post'];
    if(isset($_FILES['img_post']['name']) && ($_FILES['img_post']     ['name']!="")) {
    $temp = $_FILES['img_post']['tmp_name'];
    $nomeImg = $_FILES['img_post']['name'];
    unlink("img/posts/$old_image");
    move_uploaded_file($temp, "img/posts/$nomeImg");
    }
    else {
      $nomeImg = $old_image;
    }

      $query2 = mysqli_query($conexao,"update tbl_post set               titulo_post='$titulo', descricao_post='$descricao',               img_post='$nomeImg', texto_post = '$texto' where id_post = $id");

    if ($query2){

      echo "<script>alert('Post atualizado!');location.href='show_post.php?url=$url';</script>";
    } else {
      echo "<script>alert('Erro!');</script>";
    }
   }
 ?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Events between number of threads c++ If I want thread A to receive its packets and process them, and some thread B can at some point change the socket's IP address.
So the thing that need to be done here is:
Thread A must start on listening on the new IP and thread B must somehow tell that to thread A.
Any suggestions? please it is very important for me.

A: You probably want a workflow such as:
// thread A
// receive packets on initial address
WaitForSingleObject(event, INFINITE); // wait for address change
// receive packets on the new address

and
// thread B
// do some work
// change IP address
SetEvent(event); // signal A to start receiving on the new address

A: In fact, I'll make my comment an answer:
Create/start another thread A instance, passing it the new IP/port. Set some flag in the old thread A, telling to exit itself and clean up if and when it ever wakes up.
If you want to gee things along a bit, or you do this 'change socket' operation frequently, close the listening socket on the old thread A - it's accept() call will fail with some exception or error and the old thread A can then clean up itself and die.


text:
Q: Why equivalence principle is principle and not law? We can prove that the inertial mass and the gravitational mass should be the same (equivalence principle) from the $f=mg=ma$ then $g=a$, so we have equivalence law! But why we said equivalence principle?

A: The definition of a principle is "a fundamental truth or proposition that serves as the foundation for a system of belief or chain of reasoning". A statement can still be a principle even if it is known to be false.
The Oxford dictionary defines a law as a type of principle. By definition, a physical law cannot be known to be false. (There are exceptions. For example, Newton's law of universal gravitation is a law that is known to be false.)
The weak Equivalence Principle (EP) is an experimentally falsifiable hypothesis. Newton did  not consider the EP to be necessary or self-evident. He performed many experiments before accepting it as a universal truth. Einstein called his version of the EP a "hypothesis of complete physical equivalence...". If the hypothesis turned out to be false, so would his theory.
Physicists have been testing the truthiness of the equivalence principle for hundreds of years, so far it has been shown to hold at the level of 1 part in 1014. As the experimental evidence for the EP has been growing, so have the theoretical arguments against it.
Until recently there were several teams of physicists working on big budget experiments to test the EP. Unfortunately due to the global recession many of these projects were cancelled. Other equally important projects such as SETI were defunded as well. Its a shame, I was really looking forward to tossing out 400 years of gravitational theory, and talking to aliens.

A: The original reason was that your first sentence is actually invalid: we can't really prove it (from the first principles). It's a natural assumption of physical theories, so it is a principle itself.
In Newton's theory, one could have the gravitational mass and the inertial mass as two independent and non-proportional quantities. But Galileo already knew that they were proportional or, in some sensible units, equal to one another.
This observation looked like a coincidence but it became an important observation for Albert Einstein when he was discovering general relativity. In some sense, the equivalence principle may be "proven" in the framework of general relativity. But as an assumption, it was the very reason why Einstein directed his search towards similar theories, so in this sense, it begs the question.
There are many things to be said about the validity or violation of the equivalence principle in various frameworks and about the experimental tests that it holds – and so far it does with the full precision we have. However, it may also be true that you exaggerate the difference between a "law" and a "principle". In a judicial analogy, a "principle" could be compared to a "constitutional law" – it's somewhat more important and refers to somewhat more universal issues. But otherwise it ain't such a radically different thing from a law.


text:
Q: Failed to update datatable after Begin/End Edit I am using following code to edit my record in datatable.  It does not update the record.
Dim drCurrent As DataRow
drCurrent = DbResultDataSet.tblResult.Rows(0)
MsgBox(drCurrent.Item("PaperID"))
drCurrent.BeginEdit()
drCurrent.Item("PaperID") = "433"
drCurrent.EndEdit()
TblResultTableAdapter.Update(DbResultDataSet.tblResult)

Please advise what is wrong.
thanks
Furqan


text:
Q: Marshmallow dataclass not working with type hint Union I need the entries field to have only a Tuple of one or two elements, but no more.
But such a design gives an error.
from decimal import Decimal as _Decimal
from dataclasses import field
from typing import Tuple
from typing import Union

import marshmallow
import marshmallow_dataclass
from marshmallow_dataclass import dataclass
from marshmallow_dataclass import NewType

Decimal = NewType("Decimal", _Decimal, field=marshmallow.fields.Decimal, as_string=True)
Entries = Union[Tuple[Decimal], Tuple[Decimal, Decimal]]

@dataclass(frozen=True)
class Signal(Model):
    entries: Entries = field(default_factory=tuple)
    ...

    @classmethod
    @property
    def Schema(cls):
        return marshmallow_dataclass.class_schema(cls)

    class Meta:
        ordered = True

Error message
    super().__init__(*args, **kwargs)
  File "/home/prefixet/.local/share/virtualenvs/telegram-bot-LL7aNOup/lib/python3.8/site-packages/marshmallow/fields.py", line 185, in __init__
    raise ValueError("'missing' must not be set for required fields.")
ValueError: 'missing' must not be set for required fields.

Process finished with exit code 1

Also, im trying use Tuple[Decimal, ...], but it's not working to.
Thanks.

A: This may not have been the case when you asked your question, but currently marshmallow-dataclass has a Union extension.
pip install "marshmallow-dataclass[enum,union]" will install both that extension and the enum extension (not sure how to get just one or the other).
https://github.com/lovasoa/marshmallow_dataclass#installation

A: It's working if i remove default factory:
@dataclass(frozen=True)
class Signal(Model):
    entries: Entries = field()

Hope, it's help someone.


text:
Q: Share Data (cookie) on different domain in angular 2 Share data(cookie or any other way)on two different angular project, which are running on two different domain in angular 2
I using angular2-cookie pkg with "angular2-cookie": "^1.2.6" version,
for set cookie, with
put(key: string, value: string, options?: CookieOptionsArgs): void; &
get(key: string): string; provided functions
in two different projects.
OR is their any another way for sharing data
 import { CookieService } from 'angular2-cookie/core';

  //In project one i.e running on http://www.xyz.in/ domain
  this.CookieService.put('username','my name is abc',
  {domain:'http://www.abc.in/'})

  //In project two i.e running on http://www.abc.in/ domain
  this.CookieService.get('username')
  console.log(this.CookieService.get('username'))

In above case
expected result is it should display
my name is abc
But actual output is
undefined
in project 2 i.e http://www.abc.in/

A: You can not set the Cookie for other domain, it would be very dangerous.


text:
Q: laravel 5 exception Illuminate\Session\TokenMismatchException in unit test I'm trying to write a test that check some activities done only with registered users. so I need to pass through the laravel 5 authentication process (with _token)
this is my test class
    class ImportTest extends TestCase {

            private $files = array();
            /**
             * Creates the application.

         *
         * @return \Illuminate\Foundation\Application
         */
        public function createApplication()
        {
                $app = require __DIR__.'/../bootstrap/app.php';

                $app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

                return $app;
        }

        private function beTheUser(){

            $this->be(User::all()->first());
        }

        public function testAccessImportPageAjaxLoggedIn(){
            $this->beTheUser();
            $import = Import::all()->first();
            if($import!=null){
                $this->call('POST','ImportDocumentsController@status',array(
                    'import_id' => $import->id,
                    '_token' => Session::token()
                ));
                $this->assertResponseStatus('404');
            }

            $this->assertTrue(TRUE);
        }
}

and when I try to test the function with phpunit test, I got testing.ERROR: exception Illuminate\Session\TokenMismatchException
anybody know a workaround?

A: one possible solution, as @lukasgeiter spotted, is to write this line
        public function beTheUser {
            Session::start();
            $this->be(User::all()->first());

        }

I also needed to add this line at the beginning of the file.
use Session;

and not
use use Symfony\Component\HttpFoundation\Session\Session;
then
when needed in the function...
        $this->call('POST','/documents/import/'.$import->id,array(
            '_token' => Session::get('_token')
        ));
//or

        $this->call('POST','/documents/import/'.$import->id,array(
            '_token' => Session::token()
        ));

A: Run php artisan config:clear. Your config could be cached causing the test env to actually be pointing to your local environment
Relevant Laracasts thread: https://laracasts.com/discuss/channels/laravel/laravelphpunit-testing-tokenmismatchexception#reply=486865

A: Try csrf_token() instead of Session::token().


text:
Q: How to reset form after submission in Angular? I have a two field form and i want to just change the tab while submission of form and the problem is since the page is not reloading the form remains as same as previously entered.
Here is my form
<form name="userForm" ng-submit='manageBed.addBed(bedData);'  ng-hide="manageBed.loader">

manageBed is the controller
tried with
$scope.userForm.$setPristine(); and also clearing  bedData this.bedData={}; in controller gives that required field error.

this.addBed = function(bedData) {
  Admin.addBed(this.bedData).then(function(data) {
    if (data.data.success) {
      app.loader = true;
      $timeout(function() {
        app.loader = false;
        $scope.myTabIndex = 0;
        Admin.viewBed().then(function(data) {
          if (data.data.success) {
            $scope.beds = data.data.beds;
          } else {
            $scope.nobed = true;
          }
        });
        app.bedData = {};
        $location.path('/admin/managebeds');
      }, 3000);
    } else {
      app.loader = false;
    }
  });
};

A: Please check the same type of example code to here and check angular form controller methods to here.
And in your case use following code in your controller,
       $scope.form={}
       var self = this;
       this.addBed = function(bedData) {
          Admin.addBed(this.bedData).then(function(data) {
            if (data.data.success) {
              self.loader = true;
              $timeout(function() {
                self.loader = false;
                $scope.myTabIndex = 0;
                Admin.viewBed().then(function(data) {
                  if (data.data.success) {
                    $scope.beds = data.data.beds;
                  } else {
                    $scope.nobed = true;
                  }
                });

                self.bedData = {};

                $scope.form.userForm.$setPristine();
                $scope.form.userForm.$setUntouched()

                $location.path('/admin/managebeds');
              }, 3000);
            } else {
              self.loader = false;
            }
          });
        };

And in your template add following code,
    <form name="form.userForm" ng-submit='manageBed.addBed(bedData);'  ng-hide="manageBed.loader">

Please check more details about the angular form to here.
Hope this will help you !!!

A: if you are using states then use $state.go($state.current,{},{reload:true}) at the end of the form submit function.

A: define form     $scope.form={};
change form name to name = 'form.userForm' in HTML
and after successfull submission
app.bedData ={};
$scope.form.userForm.$setPristine();
$scope.form.userForm.$setUntouched();

this solved my issue


text:
Q: Taleo Password field alignment issue I am trying to modify layout of Taleo career website pages to match with my organisation look and feel. I have business addition of Taleo with trial access.
While designing Job Application form with Password field, it adds Re-type new password  automatically, but the alignment/layout is not proper for Re-type new password input field. Please refer attached sceenshot of UI.
Re-type new Password alignment issue screenshot.
Does any one has encountered similar issues while working with Taleo? Any help on this will be greatly appreciated.


text:
Q: Keyset does not exist - permissions should be OK I'm having an issue deploying a WCF service to IIS on Windows Server 2016.
The service needs a private key, which location is configured as follows:
<serviceCertificate storeLocation="LocalMachine" storeName="My" x509FindType="FindByThumbprint" findValue="..." />

I'm getting the famous error "Keyset does not exist", so I googled and doubled checked permissions etc.
The certificate is correctly placed in LocalMachine/Personal/Certificates. Primary Key export is allowed.
I granted primary key permissions to the APPPOOL identity and IIS_IUSRS.
I evenn tried granting full access to "Everyone".
I also tried running the application pool under my administrator account.
No luck.
I tried creating a small C# console application that reads the certificate, the primary key, and exports the primary key.
That works.
So I'm out of options now.
Any suggestions that might solve this?

A: The application is running as a application of a parent site, but with it's own dedicated app pool. Granting private key permissions to the parent site's app pool, fixes the issue. It doesn't make any sense to me, but at least it works now...


text:
Q: How to make requests to GraphQL-server from my redux action? I have react+redux application and I want to replace rest-requests in my actions to grapqhl-requests. What is the most simple method to do it?
I read about apollo, but I just to want add graphql in my existing requests.

A: You must change the way you will get the data because Apollo is a layer between you and the Api requested where you can join many Apis into one single query call.
The example above is very simple and just to explain the way will place your querys and how it connects to Apollo Server. You can set middlewares to log requests on add some headers too.
You will install [https://github.com/apollographql/react-apollo] and [https://github.com/apollographql/graphql-tag]
After that create a connection file in your project that imports
graphClient.js
import { ApolloClient, createNetworkInterface } from 'react-apollo';
const networkInterface = createNetworkInterface({
  uri: 'yourserver address'
});
const client = new ApolloClient({
  networkInterface,
});
export default client;

yourRequestFile.js
import gql from 'graphql-tag';
import client from './graphClient';

export const getYourData = () => ({
  query: gql`
  query {
    products() {
      info {
        value {
          qty
          value
        }
      }
    }
  }`,
});
const returnYourData = async () => client.query(getYourdata());
export default returnYourData;


text:
Q: Will 'http:url' work for all browsers and devices? In making a function that validates a user URL and prepends http: at the front, I have to take cases of www, https and // into account as being valid urls. The way I have it written now (see below), I only prepend http: , so that cases of //stackoverflow.com don't turn into http: ////stackoverflow.com.
This means that a url like stackoverflow.com becomes http:stackoverflow.com.
In Firefox and Chrome, this works just fine, but these URLS will be clicked from a variety of browsers and devices. Is it something that'll work universally? It'll be easy to rewrite this check for a // case, but I'm interested in the answer.
Prepend method:
function prependHTTPtoWebURL() {
    var url = (el('org_website').value);
    var httpVar;
    var testFor;

    if (url) {// If there's a website URL value
        testFor = url.toLowerCase();
        if (testFor.indexOf("http") != 0){
            httpVar = 'http:'; //add it
            url = httpVar + url;
         el('org_website').value = url;
     }
    }
}

A: Try playing with regex. Check this code for instance:
var someurl = "www.google.com";
var otherurl = "google.com";
var anotherurl = "//google.com";

function prependHTTPtoWebURL(url) {
    var newurl = url.replace(/^(http)?(:)?(\/\/)?/i,'');
    return 'http://' + newurl;
}

console.log(prependHTTPtoWebURL(someurl));
console.log(prependHTTPtoWebURL(otherurl));
console.log(prependHTTPtoWebURL(anotherurl));

The ouput in console.log will be:
http://www.google.com
http://google.com
http://google.com

Since you are specifying a subdomain (www) on the first one, that is respected. It avoids ending with four diagonals, like http:////. If your url was something like :google.com, it would also fix it correctly.
You can see it live here: http://jsfiddle.net/zRBUj/
Edit: Adding the /i Kate mentioned.

A: Change http: to http://
See these links for more info:
Anatomy of a URL
How the web works


text:
Q: Navigation bar color not setting properly Why is the navigation bar color coming so weired? Why is it white above and only a bit red at the bottom. I cannot make out if the status bar is overlapping my navigation bar or what. This is the code I used to change the color of the navigation bar background:
    [navbar setBackgroundColor:[UIColor redColor]];

A: Solution
[navbar setBarTintColor:[UIColor redColor]];
[navbar setTranslucent:NO];

Why
The color of a UINavigationBar is set with its barTintColor property.
What you're seeing is the translucent white navigation bar above your red background. The bit at the bottom is where UINavigationBar renders a shadow below the bar view.

A: I think this image is sufficient to solve your problem.


text:
Q: rails 410 on no route matches When someone goes to my site with wrong route, rails responses with 404 code and the error
ActionController::RoutingError No route matches
Can I response with 410 code on the rails's error instead of 404?

A: I am not sure why you would want to as a 410 error (Gone) is for a resource that was once available but isn't anymore.
If you follow the answer at https://stackoverflow.com/a/5360684/219743 then it allows you to do it.
Just change the render_404 method to
def render_404
  if /(jpe?g|png|gif)/i === request.path
    render :text => "404 Not Found", :status => 410 # Change the status here
  else
    render :template => "shared/404", :layout => 'application', :status => 410 #and here
  end
end

If you still want to point to 404.html in the public folder:
render :file => "#{Rails.root}/public/404.html"


text:
Q: Relative path (image) resolved incorrectly in external resource (SVG) of external resource (JSON) The problem
I am making an (experimental) web app, where the URL to an external file is given in the actual URL, like so:
https://example.com/path1/app.html#https://otherdomain.com/path2/data.json
So when the page is opened, the external file (in this example data.json) is fetched and evaluated. So far so good.
Now data.json contains HTML markup, which includes an inline SVG image, which in turn features external images. In other words, in the SVG I have an <image> with an xlink:href (or href) attribute that is a relative path to an image, supposed to be stored in https://otherdomain.com/path2/ (i.e. where the JSON file is).
The problem is that when the SVG file is embedded, the relative paths of external resources with be resolved based on the URL of the web page, i.e. https://example.com/path1/, which results in 404 errors for the <image>s in the SVG. The question is now how to deal with this in the best or most proper way.
Current workaround
Basically, as current workaround I am manipulating the href attribute of each <image> in the SVG before the SVG is added to the DOM. This works well, for a workaround.
However, I have to take some less straightforward methods of parsing the SVG, to avoid eager loading of images before the paths have been fixed. (The browser already attempts fetching, when imageElement.src is getting changed.) So something like parentElement.innerHTML = svgText does not work as I hoped.
I have tried a couple of things to avoid eager loading of images. From those that worked, almost all had the new problem that the added HTML element did not pick up any CSS styles for some reason unknown to me. As workaround-within-the-workaround (yeah I know) I am doing parentElement.innerHTML = svgElement.outerHTML, which feels really bad, but at least works. I am sure there is a better way yet to be discovered.
Other notes
In summary a relative path within an external resource, loaded from an external resource, is not resolved correctly. Which is not a surprise, but I wonder how to go about it.

*

*I would like to keep the SVG in the JSON, i.e. to be added to the DOM. (I assume loading the SVG as (HTML) <img> with absolute path would help.)

*I want to avoid embedding images as binary blobs in the SVG.

*Making the href of SVG <image>s an absolute path during SVG creation would probably work, but seems like a pain to create and maintain in my case.

*Going with the workaround and rewriting href attributes within the SVG seems cumbersome and slightly wrong, but it works. However, it should be optimised.

I wished there would be some way where I can specify explicitly what the base path is to which relative paths are added, when it comes to loading of external resources. But I wonder whether something in the overall approach needs to change here. Any help greatly appreciated!

A: If the path is relative the browser will concatenate the URL of the webpage to it automatically. So make sure to get everything with a full path i.e "https://example.com/images/image_1"


text:
Q: Comparing an input to the values of an array only works with a single value I have some fruits names stored in an array. If the user enters a food name which is already stored in the array then true should be returned, otherwise false.
But it only returns true when I input the value Mango, otherwise always returning false, why?
Here's my code:
JSfiddle link
HTML:
<input type="text" id="value" />
<button onclick="check()">test</button>

JavaScript:
var myVar;

check = function() {
    myVar = document.getElementById("value").value;

    var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];

    for(i = 0; i < fruits.length; i++) {
        if(myVar == fruits[i]) {
            document.getElementById("pValue").innerHTML = "true";
        }
        else {
            document.getElementById("pValue").innerHTML = "false";
        }
    }
}

A: This is because you are using a for increment loop so only the last value will  return true. You can add a break; to the loop if you choose to keep this as the method. See updated fiddle below ::

var myVar;

check = function() {
    myVar = document.getElementById("value").value;
    var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];

    for (i = 0; i < fruits.length; i++) {
        if (myVar == fruits[i]) {
            document.getElementById("pValue").innerHTML = "true";
            break;
        } else {
            document.getElementById("pValue").innerHTML = "false";
        }
    }
}
<input type="text" id="value" />
<button onclick="check()">test</button>


text:
Q: How to print stream in page using jQuery mobile I am little bit confused. Actually I am getting data from server like this:
data
-------------
a
ab
abc
abcd...... and so on

Data is being returned in real time. It means data is being sent each second, again and again. So I need to show data only abcd

waiting...

socket.onmessage = function(msg) {
     if(JSON.stringify(msg)!=null)
    $('#log').append('
'+JSON.stringify(msg[data])+'
')

};

But when I used this code it showing(response) like this.
a
ab
abc
abcd...

Every second this function call prints new from starting.
I need the output only in a straight line with
abcd...

A: You have to use .html instead of .append.....
socket.onmessage = function(msg) {
 if(JSON.stringify(msg)!=null)
   $('#log').html('
'+JSON.stringify(msg[data])+'
')
};


text:
Q: Python: add column to dictionary but not map in correct order I am adding back data that is query from Flask sqlalchemy core. The column of all the data is missing. So I add it back with the code below: There are are many columns but I just simplify to a few.
col = ['index','Stock','Name','MACD','STOCH','RSI']
a = call.fetchall()
print a
>>>a=[(0, 'MAGNUM', 'MAGNUM BERHAD', 'SS', 'S', 'H1'),(1,'ABC','ABC BH','SS','S','H2')].
dicts = [dict(zip(col, d)) for d in a]
print dicts
>>>[{'MACD': 'JAC', 'RSI': 'SS', 'STOCH': 'SB', 'Name': 'H',Stock':'H'}]

The dicts output skip the first result, which is index 0. It went to the index 1. Also, index was not map into the dicts.
How to make it mapping everything in correct order?

A: You cannot pre-suppose of the order in a dictionary.
Since you changed your question, I changed my answer. The a is a list of tuples so the following would work:
from collections import OrderedDict
col = ['index','Stock','Name','MACD','STOCH','RSI']
a=[(0, 'MAGNUM', 'MAGNUM BERHAD', 'SS', 'S', 'H1'),(1,'ABC','ABC BH','SS','S','H2')]

d = [OrderedDict(zip(col,t)) for t in a]

print (d)

It creates a list comprehension containing OrderedDict elements built by zipping the col list with each element of the a list of tuples.
result:
[OrderedDict([('index', 0), ('Stock', 'MAGNUM'), ('Name', 'MAGNUM BERHAD'), ('MACD', 'SS'), ('STOCH', 'S'), ('RSI', 'H1')]), OrderedDict([('index', 1), ('Stock', 'ABC'), ('Name', 'ABC BH'), ('MACD', 'SS'), ('STOCH', 'S'), ('RSI', 'H2')])]


text:
Q: hive read mongodb bson file at first:when i select count(*) from table it issue :
Caused by: java.lang.OutOfMemoryError: Java heap space
    at org.bson.BasicBSONDecoder.readFully(BasicBSONDecoder.java:65)
    at org.bson.BasicBSONDecoder.decode(BasicBSONDecoder.java:57)
    at com.mongodb.hadoop.splitter.BSONSplitter.getStartingPositionForSplit(BSONSplitter.java:427)
    at com.mongodb.hadoop.mapred.BSONFileInputFormat.getRecordReader(BSONFileInputFormat.java:127)
    at org.apache.hadoop.hive.ql.io.CombineHiveRecordReader.<init>(CombineHiveRecordReader.java:68)
    ... 16 more

FAILED: Execution Error, return code 2 from org.apache.hadoop.hive.ql.exec.mr.MapRedTask
MapReduce Jobs Launched:
after i set:
set mapreduce.map.memory.mb=4096;
set mapreduce.reduce.memory.mb=2048;
it issue:
Caused by: org.bson.BsonSerializationException: Expected size to be 7169396, not 109.
    at org.bson.BsonBinaryReader$Context.popContext(BsonBinaryReader.java:445)
    at org.bson.BsonBinaryReader.doReadEndDocument(BsonBinaryReader.java:285)
    at org.bson.AbstractBsonReader.readEndDocument(AbstractBsonReader.java:360)
    at org.bson.AbstractBsonWriter.pipeDocument(AbstractBsonWriter.java:763)
    at org.bson.AbstractBsonWriter.pipe(AbstractBsonWriter.java:753)
    at org.bson.BasicBSONDecoder.decode(BasicBSONDecoder.java:48)
    at org.bson.BasicBSONDecoder.decode(BasicBSONDecoder.java:57)
    at com.mongodb.hadoop.splitter.BSONSplitter.getStartingPositionForSplit(BSONSplitter.java:427)
    at com.mongodb.hadoop.mapred.BSONFileInputFormat.getRecordReader(BSONFileInputFormat.java:127)
    at org.apache.hadoop.hive.ql.io.CombineHiveRecordReader.<init>(CombineHiveRecordReader.java:68)
    ... 16 more

what is the problem?


text:
Q: Video keeps playing after moving to a new route I have 2 views A and B, that are loaded in the routes "routeA" and "routeB".
In the view A I'm loading a video.
When I click on the button that exists in the view A that executes $router.push({ name: 'routeB'}), it loads the view B, but I can still listen to the video audio, meaning the DOM did not clean whatever was loading on the previous view.
The way I load the routes is like below:
const routeA = () => import('./components/A.vue');
const routeB = () => import('./components/B.vue');

export default [
{
    path: '/routeA',
    name: 'routeA',
    component: routeA,
},
{
    path: '/routeB',
    name: 'routeB',
    component: routeB,
},
];

Code I use to load the video:
let url = window.URL || window.webkitURL;
var vid = document.getElementById("my_video_player");
vm.video.profile_video_src = url.createObjectURL(xhr.response)+'#t=1';
vid.load();

Is it related to the memory leak that is explained here: https://v2.vuejs.org/v2/cookbook/avoiding-memory-leaks.html?
Is there any chance that I can clean the DOM after moving to another view? Or at least ensure that things like videos don't keep loading / playing?


text:
Q: Getting all vertices of a rectangle In my program, I had a requirement to plot a rectangle that that is prependicular to a line coming from the centre.
To orient the rectangle in this way in 3D space, I used the gluLookAt giving it the lookAt point and plotted the rectangular figure. This worked correctly for me.
To draw the rectangle (in my framework, that uses openGL at the back), I now use a rectangle class and have extended it with a 3D Node (where node is something that has a lookAt point). Given width, height and the top vertex, the rectangle is drawn (node is at the top left vertex and orients the rectangle using lookAt).
Node also has a getPosition() function that gives me its 3D position (top left in rectangle - say 300,400,20). I am trying to get the position of the other three vertices in 3D space to use for my operation. Since the rectangle is oriented in 3D space, other three vertices can't just be fetched by addition of width and height. With the rectangle oriented in 3D, how do I get the position of the other three vertices?

A: The minimum amount of coordinates is just slightly less than 9: that's three vertices of a generic rectangle in 3d-space (Ax,Ay,Az, Bx,By,Bz, Cx,Cy,Cz).
The last one is e.g. D=A+(B-A)+(C-A)=B+C-A.
Why it's slightly less, is that any triplet of A,B,C coordinates do not necessarily form a 90 degree angle -- but it really doesn't make much sense to pursuit for the simplistic possible arrangement and be prepared to calculate cross-products or normalize vectors.
 A----B
 |    |
 C---(D)

EDIT: Vector arithmetic primary:
To Add / Subtract vectors, one sums the elements.
 A=B+C means (ax = bx+cx; ay=by+cy; az=bz+cz).
Dot product in (any dimension) is the sum of product of terms:
 dot(A,B) = ax*bx + ay*by + az*bz;  // for 2,3,4, any number of elements/dimensions.
Cross product is a special operator that is well defined at least in 2 and 3 dimensions. One of the geometric interpretations of cross product is that it produces a vector that is perpendicular to both vectors of it's parameters.
If A is a vector (ax,ay,az), it also means a direction vector from origin O=(0,0,0) i.e. A = A-O = (ax-0,ay-0,az-0);
Likewise (B-A) is a [direction] vector from A to B (sometimes written as AB (with an arrow --> on top))
One can 'add' these directed vectors e.g. as:
    o----->
           \
            \
      <------o
     /
    /
   x

And so, if one adds the vector A+(B-A) + (C-A), one ends to the point D.

A: You can retreive the position of the 3 other points using the normal of the rectangle. In order to orient a rectangle in space, you need 2 information:

*

*its position, commonly represented as a 3 or 4 components vector, or a 4x4 matrix ;

*its orientation, commonly represented as a quaternion.

If you have the orientation represented with a normal, and only have one point, you just can't deduce the other points (because you need another information to solve the rotation equation around the normal). I think the best idea is to use quaternion to orient things in space (you can still retreive the normal from it), but you can also use a normal + one vector from the rectangle. You said you only have one point, and a tuple (width,height), so the common method based on the × operation won't make it through.
I suggest you to:

*

*make your Node class a class that correctly handles orientation; lookAt isn't designed for that job ;

*combine the translation matrix (position) with a cast matrix from the quaternion (orientation) to correctly handle both position and orientation ;

*use that matrix to extract a rotated vector you'll used like rotated × normal to get the 3 points.


text:
Q: OpenLayers3 functionalities not working I have no difficulties exploring interesting features among the OpenLayers3 Examples. However, when I copy the code below into a local .html file and open it in the same browser, certain functionalities (e.g. vector layers) stop working.
The Earthquakes heatmap, for instance, comes only with the black base layer and the heat (vector) layer is not displayed at all. All CSS and js are accessed properly via CDNs. I've tested many examples on 3 different computers in total.
Can anybody say what may cause this problem and how to solve it?
Thanks a lot.

A: The issue is likely to be that the urls for the data in the examples are relative paths, and you don't have the data required. In the Earthquakes heatmap example the data source for the heatmap is set in this chunk:
 var vector = new ol.layer.Heatmap({
  source: new ol.source.Vector({
    url: 'data/kml/2012_Earthquakes_Mag5.kml',
    format: new ol.format.KML({
      extractStyles: false
    })
  }),
  blur: parseInt(blur.value, 10),
  radius: parseInt(radius.value, 10)
});

Unless you are hosting 2012_Earthquakes_Mag5.kml locally with the same relative path the data will not be found. The url of the data is actually http://openlayers.org/en/v3.11.1/examples/data/kml/2012_Earthquakes_Mag5.kml, which you could download and serve locally to test out the examples.


text:
Q: Teradata : Query to find CPU utilization user level (History data) I have the query to find the current CPU and IO utilization at user level
Query
SELECT ACCOUNTNAME, USERNAME, SUM(CPUTIME) AS CPU, SUM(DISKIO) AS DISKIO FROM DBC.AMPUSAGE GROUP BY 1,2 ORDER BY 3 DESC

But I want to check the history data( date and time) of CPU/IO utilization at user level
AccountName|UserName|CPU|DISKIO|Date/Time
Big Picture
A utility will be created which will fetch data from Teradata and try to generate graphs for the same on daily basis. The report will provide all the utilization details for the whole day which will help us to plot graph. The whole utility will be schedule to run once on daily basis.
Restrictions:
Being developer . we are not allowed to use Teradata Manager

A: Normally data in AmpUsage will be historized, i.e. a daily job INSERTs the result of your query into a history table and then DELETEs all from AmpUsage.
Depending on the Account strings used there might be "account string expansion" (ASE) in place, e.g. ..._&D_&H results in one row per AMP per user per hour like ..._131025_09 which can produce hourly usage data.


text:
Q: Extracting counts of a variable grouped at 2 levels I have weather data tagged by year, month and day. Here is some of the data:
Date         MinT     Year   Month
1976-01-01   1.1      1976   1
1976-01-02   0.3      1976   1
1976-01-03   1.3      1976   1

The data run is 1976:2016 for all months. Call this TestData.
I can group and subset as follows (it is very clunky but that is because I have been trying to test each step)
temp1 <- TestData  %>%
  group_by(Year)
temp2 <- temp1 %>%
  subset(between(Month, 1, 3))
temp3 <- temp2
v1 <- replace(temp3$minT, temp3$minT >-2.0,0)  ### replaces data above the threshold
temp3["v1"] <- v1
index1 <- with(temp3, tapply(X = v1, INDEX = Year, FUN = sum)) ##       sums the month  1-3-2 degree values
index2 <- with(temp3, tapply(X = v1, INDEX = Year, FUN = length)) ## counts the number of items in each year for the selected period.

index2 gives me a count of the days in each month. I can use index1 and 2 to create index of 'weather for the month'.
What I would like is to be able to get a count of all of the days below -2 (or whatever) and so get an index of comparable severity for each month.
The v1 assignment is necessary because if I use rle to count instances, some months will have zero instances and they drop from the final tally meaning the compiled table of indices against minT, year and month has index vectors of different lengths which R doesn't like. I have tried rle as the FUN in the index2 assignment but that would not let me reach the day counts. The same was true for using a range value with length in that assignment (index3) as well.
Short of generating a mini table for each year, I am stuck. Does anyone have any suggestions?

A: I guess summarise is the function you are looking for. Something like this (different data, same principle):
library(latticeExtra)

threshold <- 40

SeatacWeather %>%
  group_by(year, month) %>%
  filter(min.temp < threshold) %>%
  summarise(days_below_threshold = n())


text:
Q: Using Redis in an express service running in minikube I've got an express service running in a minikube cluster and I'm trying to set up a Redis client, but when I try run the service with the Redis client created it basically stalls on deployment and times out. As soon as I add the line:
const client = redis.createClient('http://127.0.0.1:6379');

My service will not deploy and run (even running the default with no supplied address causes the same issue).
I'm quite new to Kubernetes in general so I'm not sure if this is potentially an issue with minikube? Like trying to create a client from inside the cluster with that address isn't possible or something along those lines..
I'm completely lost with why just trying to create a client is causing this issue so any advice or direction would be greatly appreciated.

A: Try using "service-name.namespace-name.svc.cluster.local" instead of IP address to connect to service.
For example: If my service name is car-redis-service and namespace is default then the command goes like
redis.createClient(REDISPORT, redis://car-redis-service.default.svc.cluster.local)

Or
redis.createClient(REDISPORT,car-redis-service.default.svc.cluster.local)

(source)
Here REDISPORT is the port where redis is configured.
For more information on redis in kubernetes refer to this article.


text:
Q: Create a data structure with the features of an array in the constructor I want to create a special list data structure that works like an array, in that it's like a list with values x[0], x[1], ... Any advice would be much appreciated.
I know all of my code isn't perfect I just want to figure out how to fix the one problem I've outlined below. This is some of the code I have:
public class SpecialList {

int[] specialList;
int lengthList;

public SpecialList(int x[]) {
    this.lengthList = x.length;
    this.specialList = new int[lengthList];
    this.specialList = x;
    for (int i=0; i<lengthList; i++) {
        this.specialList[i] = x[i];
    }
}

public SpecialList(SpecialList w) {
    this.specialList = w.specialList;
}

public SpecialList doSomething(SpecialList y) {
    int len = y.lengthList;
    //The line below is an example to show the error I get
    System.out.println(y[0]);
    //Do some other stuff to the list y
    return y;
}

//I test the code with this
public static void main(String[] args) {
    SpecialList y = new SpecialList(new int[] {14, 17, 30});
    SpecialList z = x.doSomething(y);
}

However I get the error 'array required, but SpecialList found' when I try to do stuff with y[i] like with System.out.println(y[0]); line of code.
'lengthList' works but getting the individual values of y[i] , the list doesn't. I cant work out whats wrong with my constructor for it to not work how I want it to.

A: You can't redefine what [n] means based on what object it's applied to; that's an array-specific notation. So y[0] where y is a SpecialList instance just won't work. If it could work, List (or at least ArrayList or other implementions where direct addressing is cheap) would probably have that feature.
Although you can do that in some other languages, you can't in Java. It's just not a feature Java offers. (Which is a good thing or a bad thing depending on your point of view...) Instead, you'll have to provide get and set methods or similar, just like List does.


text:
Q: How to use some property of parent class in child class Vb.net? Lets say I have a class named as "Class Section" having two properties i.e. area and mElement. Like this:
    Public Class ClassSection

    Public Property area as double
    Public Property mElement as ClassElement

    End Class

Now i want to use ClassSection (parent class) property "area" in mElement. Like this in below code.
    Public Class ClassElement

    Public Sub CalculateAreaRatio()
    Dim AreaRatio as Double
    AreaRatio=Area/10 'This area is ClassSection Area
    End Sub

    End Class

How this can be done. Thank you in advance

A: As I have said in my comment every ClassElement that you create is unaware if it is contained in a ClassSection element or not. If you want to let know each element of this relationship you should pass the container to the ClassElement instance.
So let's change the ClassElement structure to this one
Public Class ClassElement

    Dim myParent As ClassSection

    Public Sub New(parent As ClassSection )
        myParent = parent
    End Sub

    Public Function CalculateAreaRatio() As Double
        Dim AreaRatio As Double
        AreaRatio = MyParent.Area / 10 'This area is ClassSection Area
        Return AreaRatio
    End Function
End Class

Now every time you create a ClassElement you are forced to pass into the constructor code the ClassSection container. And you save the instance passed in a private field. This private field can be used inside the CalculateAreaRatio.
The calling code could be something like this one
Dim section As ClassSection = New ClassSection With {
        .area = 3
}
section.mElement = New ClassElement(section)
Console.WriteLine(section.mElement.CalculateAreaRatio())


text:
Q: Прогрессивный торг Финеас Барнум предложил Филиппу Карлайлу перспективное место работы в цирке. Эта работа непроста и сопряжена с некоторыми рисками, но мистера Карлайла заверили, что именно здесь он получит бесценный жизненный опыт. После долгих уговоров и большого количества аргументов мистер Карлайл готов был согласиться, но тут встал вопрос о деньгах.
Мистер Барнум готов заплатить мистеру Карлайлу x (история умалчивает чего), но тот ценит свой труд больше, и хочет получать y. Узнав об этом, мистер Барнум решил сторговаться и увеличил свое предложение на a. Мистер Карлайл пошел ему навстречу, и уменьшил свое предложение на b. После этого мистер Барнум поднял свое предложение на 2⋅a, затем мистер Карлайл уменьшил свое предложение на 2⋅b, затем мистер Барнум увеличил свое на 3⋅a, и так далее...
Как только очередное предложение, которое хочет назвать мистер Барнум становится больше или равно последнему предложению мистера Карлайла, или же сумма, которую хочет назвать мистер Карлайл, меньше или равна той, которую только что назвал мистер Барнум, торг заканчивается на последней названной сумме. Ваша задача — определить эту сумму.
Входные данные
В первой строке содержится единственное число t — количество тестов (1≤t≤2⋅103).
Далее следуют t строк, каждая из которых соответствует отдельному тесту. Каждый тест задан четырьмя целыми числами x,y,a,b (1≤x,y≤1012,1≤a,b≤106) — суммы, с которых начинали торг Финеас Барнум и Филипп Карлайл, и их первый шаг в торге соответственно. Гарантируется, что x≤y.
Выходные данные
Для каждого теста в отдельной строке выведите по одному число — сумму, на которой договорятся мистер Барнум и мистер Карлайл.
Мой код выдает неправильный ответ на 2 блоке с тестами, не знаю в чем ошибка
#define int long long
using namespace std;
signed main() {
    int x,y,a,b,res,m,t,bestm,i;
    cin >> t;
    vector<int> ans;
    for(i = 0; i < t; i++) {
    cin>> x >> y >> a >> b;
    int l = 0,r = y;
    res = 10e8;
    while(l + 1 != r) {
        m = (l + r)/2;

        if(y - m*b < 0) r = m;
        else {
            if(res > abs(x + m*a - y + m*b) and y - m*b <= x + m*a) {
                res = abs(y - m*b - x - m*a);
                r = m;
            } else l = m;
        }
    }
    if(x == y) ans.push_back(x);
    else ans.push_back(max(x+r*a,y-r*b));
    }
    for(i = 0; i < ans.size(); i++) cout << ans[i] << " ";
}

A: Вы ищете количество полных шагов m, когда оба спекулянта сделали свои предложения, а консенсус может быть достигнут на шагах
x + m*a   vs   y - (m-1)*b   //Барнум поднял, полушаг
x + m*a   vs   y - m*b       //Карлайл опустил, полный шаг

И поиск вроде как не нужен, шаг вычисляется арифметически и один раз уточняется.


text:
Q: Why scale tensor products like that? Studying the sum of angular momentum in quantum mechanics, tensor products were introduced to us to get the general system from the individual states. There's a property that says: $(av)\otimes w = a(v \otimes w)= v\otimes (aw)  $. We will call it (1).
But I don't get it's physical meaning. It's as if I scale one vector, but not the other, and the vector of the total system scales by that factor¿?.
For example, for two particles with spin $\frac{1}{2}$, I have the state $ |\frac{1}{2},m_1\rangle \otimes |\frac{1}{2},m_2\rangle $ for $m_i=\frac{1}{2},-\frac{1}{2}$. If I measure the $z$ component of the spin of the first particle ($S_1$), I get the value $\hbar m_1$, with $|\frac{1}{2},m1\rangle$ an eigenvector of that operator. Hence, we have that: $ (S_{1,z} \otimes 1) (|\frac{1}{2},m_1\rangle \otimes |\frac{1}{2},m_2\rangle)=(\hbar m_1 |\frac{1}{2},m_1\rangle) \otimes |\frac{1}{2},m_2\rangle  $ and by the property (1) that's just equal to:   $ \hbar m_1( |\frac{1}{2},m_1\rangle \otimes |\frac{1}{2},m_2\rangle)$. Which seems to imply that $|\frac{1}{2},m_1\rangle \otimes |\frac{1}{2},m_2\rangle$ is an eigenvector of $S_{1,z} \otimes 1$ with eigenvalue $\hbar m_1$ (the measurement of state 1 is scaling the total system by that factor). Or what's worse, by the third equality in (1), that: $ (S_{1,z} \otimes 1) (|\frac{1}{2},m_1\rangle \otimes |\frac{1}{2},m_2\rangle)= |\frac{1}{2},m_1\rangle \otimes (\hbar m_1 |\frac{1}{2},m_2\rangle) $  (that the measurement in the first state scales the second one by that factor ¿¿¿???).
But that's not the case in reality. The measurement in state 1 doesn't change things that way.
I don't get what's going on, I don't understand much tensor products. If you can shed some light on this.

A: This is because of geometry.
Tensors actually generalise vectors to higher dimensional arrows. Whilst a  vector is a single arrow, a 2-tensor, which was can also call a 2-vector, is defined by two arrows and so on.
This means, that  whilst there is only one way of adding two vectors - the usual parallelogram law - there are 2 ways of adding 2-tensors and 5 ways of adding 5-tensors and so on. And these additions are just generalisations of the vector additivity law. It's quite clear if you draw out the second and third cases - the higher cases obviously can't be drawn in our 3d world.
This takes care of the additivity of tensors. Your question is about the internal scaling of tensors where $au \otimes v = u \otimes av = a(u \otimes v)$.
Again this is a geometric property, it means that we can recale a tensor whilst keeping its geometric area the same. If you draw a 2-tensor, that is a 2-vector as two arrows so that they form a parallelogram, you'll see that rescaling one side by $a$ means that you must rescale the other side by $1/a$, and hence the geometric area remains the same. I recommend drawing out the diagram as it's quite clear then.
Tensors are very geometric notions, although typically they aren't introduced in this fashion.


text:
Q: Mongoose suddenly broken, not getting callbacks This is the strangest, most frustrating issue I've yet to encounter with Node.js and Mongoose. I don't know what has cause this to be happening at all, but none of my Model functions are executing. For example, I have a model:
const UserSchema = new Schema({
    email : {...},
    password: {...},
    etc...

module.exports = UserSchema

All schemas are in their own file, and then made into models in the models/index.js:
const UserSchema = require('./UserModel')
const User = mongoose.model('users', UserSchema)
module.exports.User = User

There are routes to /login and /register, and these routes have worked fine before, but now it seems the actual mongoose calls, like findOne, are never actually being called, and it's thoroughly stumping me.
Here is an example of what I mean:
// This is inside an AuthController, which is called by the Express router
console.log('a')
UserModel.findOne({'email':email}, (error, result) => {
    console.log('b')
    if (error) callback(error)
    else callback(null,result)
})

Now, I always see 'a' in the console, but I am never given an error or the result. For example, 'b' would never be printed to the console.
Is there something simple I am missing? Why did it break seemingly out of nowhere? Why aren't these functions being called?


text:
Q: Cannot display copy of Angular model in a different view I have a sample application, and I am trying to display my model in one view, and edit it in another. Here is my controller:
var app = angular.module('plunker', ['ngRoute']);

app.controller('MainCtrl', function($scope, $location) {
  var self = this;
  this.name = 'World';
  this.someData = {name: 'test'};
  this.someCopyData = {};

  this.theEdit = function(path){
    self.someCopyData = angular.copy(self.someData);
    $location.path(path);
  };
});

app.config(['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/', {
           templateUrl: 'foo.html',
            controller: 'MainCtrl as main'
        })
        .when('/edit', {
          templateUrl: 'fooedit.html',
          controller: 'MainCtrl as main'
        });

}]);

The partial HTML is extremely simple:
Data: {{ main.someData.name }}

Resolve View

and:
<input name="name" type="text" ng-model="main.someCopyData.name"/>

Plunker here.
How can I get the copy of my model to be displayed? This is clearly a scope issue, but I haven't figured out yet a proper explanation for the behaviour.

A: It seems you only have 1 view have you tried to make 2 views for the same model? can you tell me what your trying to achieve exactly?

A: AFAIR, controller is created each time anew, that is you will get a new instance when you navigate to edit. You might want to read this guide, in particular to this part:

Do not use controllers to:
  ...
  Share code or state across controllers — Use angular services instead.


text:
Q: Google Classroom 403: "The caller does not have permission" error I am trying to register the user with Google Classroom Pub/Sub notifications, but I keep getting a 403: "The caller does not have permission" error. I have set up the Pub/Sub topic correctly in the Google Admin Console with the ID "gclassroom", so my topic ID is along the lines of "projects/myappid-12345/topics/gclassroom". I have also set up classroom-notifications@system.gserviceaccount.com as a Pub/Sub publisher under this topic.
My code:
private let scopes = [kGTLRAuthScopeClassroomCoursesReadonly, kGTLRAuthScopeClassroomCourseworkMeReadonly, kGTLRAuthScopeClassroomPushNotifications, kGTLRAuthScopeClassroomRostersReadonly]
private let service = GTLRClassroomService()

@IBAction func signInButtonTapped(_ sender: Any) {

    // Configure Google Sign-in.
    GIDSignIn.sharedInstance().delegate = self
    GIDSignIn.sharedInstance().uiDelegate = self
    GIDSignIn.sharedInstance().scopes = scopes

    GIDSignIn.sharedInstance().signIn()
}

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
          withError error: Error!) {

    self.service.authorizer = user.authentication.fetcherAuthorizer()

    let feed = GTLRClassroom_Feed()
    feed.feedType = kGTLRClassroom_Feed_FeedType_DomainRosterChanges

    let topic = GTLRClassroom_CloudPubsubTopic()
    topic.topicName = "projects/myappid-12345/topics/gclassroom"

    let registration = GTLRClassroom_Registration()
    registration.cloudPubsubTopic = topic
    registration.feed = feed
    let query = GTLRClassroomQuery_RegistrationsCreate.query(withObject: registration)
    service.executeQuery(query,
                         delegate: self,
                         didFinish: #selector(displayResultWithTicket(ticket:finishedWithObject:error:)))
}

When I run it, I am able to sign in with my Google Classroom account, but it then immediately throws this error:
["GTLRStructuredError": GTLRErrorObject 0x604000a566b0: {errors:[1] message:"The caller does not have permission" code:403 status:"PERMISSION_DENIED"}, "NSLocalizedDescription": The caller does not have permission]

What can I do to fix this code and let the user register? Thanks.


text:
Q: Qual o tipo correto para se armazenar telefone e endereço? Como o título diz, qual o tipo correto e a maneira correta para se armazenar telefone e endereço, de acordo com a normalização de banco de dados?

*

*No caso de telefone, qual o tipo correto para armazenar, o telefone fixo e celular? Com máscara de formatação ou não?

*E no caso de endereço, como armazená-lo? Em vários outros campos, como rua, bairro, número e cidade, ou tudo em um/dois somente?

A: No caso de telefone, qual o tipo correto para armazenar, o telefone fixo e celular? Com máscara de formatação ou não?
Varia de programador para programador, mas no meu caso eu faço sempre com mascara de formatação para deixar mais fácil para ler os dados ou ate mesmo retornar ele. Sobre o armazenamento eu geralmente crio Duas tabelas uma para fixo e outra para cel e utilizo a chave estrangeira do usuario para poder linkar.
E no caso de endereço, como armazená-lo? Em vários outros campos, como rua, bairro, número e cidade, ou tudo em um/dois somente?
Para este aqui eu gosto de fazer a seguinte arquitetura

Perceba que eu vou desmembrando cada campo do endereço em uma tabela. E na hora de juntar tudo utilizo um inner join.
obs.: utilizei um exemplo claro que você pode colocar até CEP, complemento etc.


text:
Q: Audio file tagging/renaming I would like to properly tag my music collection in the following way:
Filename:
Artist - Song Title - Key(Original Key) - BPM - Genre
Tags:
The tags match above(each token above is a id tag).
Is there any software out there that can automate this? I am currently doing this by hand and it is slow(mainly getting the key and bpm of the song).
Even if I could just fill in the tag's for Genre it would speed up things(Really looking for general and specific, e.g., Rock(Classic), Country(Swing), etc...).
Obviously once the tags are filled in it is easy to generate the file name.

A: It happens to me too, I use Boilsoft 3GP/iPod/PSP/MP4 Converter which can easily solve the problem.
Here is the link: http://www.boilsoft.com


text:
Q: Factorizing the Sum of Two Fibonacci numbers The Fibonacci and Lucas numbers are defined for all integers $n$ by the recurrence relations
$$F_n=F_{n-1}+F_{n-2}\text{ where }F_1=1\text{ and }F_2=1,$$
$$L_n=L_{n-1}+L_{n-2}\text{ where }L_1=1\text{ and }L_2=3.$$
I would like to know for what values of $k\in\mathbb{N}$ can one write
$$F_{n+(2k+1)}\pm F_n=cP(k,n)$$
where $c\in\mathbb{N}$ and $P(k,n)$ is some product of Fibonacci or Lucas numbers. Note that it is easy to show that that:
\begin{align*}
F_{n+2k}+F_{n}=F_{n+k}L_k\text{ where $k$ is even,}\\
F_{n+2k}+F_{n}=L_{n+k}F_k\text{ where $k$ is odd.}\\
F_{n+2k}-F_{n}=F_{n+k}L_k\text{ where $k$ is even,}\\
F_{n+2k}-F_{n}=L_{n+k}F_k\text{ where $k$ is odd.}\\
\end{align*}
It is also easy to see that
\begin{align*}
F_{n+1}+F_{n}=F_{n+2}\\
F_{n+1}-F_{n}=F_{n-1}\\
F_{n+3}+F_{n}=2F_{n+2}\\
F_{n+3}-F_{n}=2F_{n+1}\\
\end{align*}
Are these the only such expressions?
Ideas tried: I've tried the Binet formula to see what insights this might provide, but I can't see anything. I've also tested small values of $n$ numerically but couldn't find any further examples than those four given.

A: It seems unlikely that there will be a simple factorization for $F_{n+5}\pm F_{n}$ because these numbers are prime for several values of $n$.
Primes of the form $F_{n+5}+F_{n}$ are listed in oeis/A091157.
Primes of the form $F_{n+5}-F_{n}$ are listed in oeis/A153892.

A: Among Lucas numbers $L_{n+1}^2-L_n^2=L_{n+2}L_{n-1}, n\ge 2$.  This is just a differeence of squares factorization together with applying the recursive relation.


text:
Q: Trying to search reddit submissions and subreddits based on comment word search Can you search for submissions (over all subreddits) to find those having a particular keyword use in the discussions i.e comments of that submission?
I am trying to :

*

*Collect all the submission ids and hence the comments that have this word say "awesome".

*I would also like to know if there are some subreddits that are likely to have this word used often based on the comments?

I have already looked at PRAW & PSAW documentation and even found the exact solution to this problem i.e the aggs paramter but apparently it is not working at the moment? Every query gives me a JSON that is empty(with the same code as in the documentation)?
I was wondering if there are alternatives or workarounds to this? Or something that could solve my problem.
Thanks in advance for your time.


text:
Q: deserialize with JSON a huge file android I have a 10M serialized file on sdcard in android. I need to deserialise it with jason. Can someone please tell me how to do this?
Can I deserialise in chunks of 1024bytes or something like this the file which is written on sdcard? I am working in an android project which cannot handle big files in just one stream due to memory allocation.
Need help!
I am new to jason and android handling big files.

A: you can use the standard Android implementation of Android in parsing Json
http://android-pro.blogspot.com/search/label/JSON
another alternative is Google Gson library http://code.google.com/p/google-gson/ which supports streaming.
Example:
Suppose you want to parse a chunk of persons date:
First: create a class that maps the json response to your data type
class Person{
        @SerializedName("PersonName")
        public String name;
        @SerializedName("PersonAge")
        public String age;
        @SerializedName("PersonAddress")
        public String address;
    }

*Second:*to deserialize (parse) the Json response with Gson:
Gson gson=new Gson();
Type collectionType=new TypeToken<ArrayList<Person>>(){}.getType();
ArrayList<Person>persons=gson.fromJson(jsonResponse, collectionType);


text:
Q: When should the Ecommerce tracking take place? I am implementing Google analytics onto a ecommerce site. We are already tracking events like adding to cart, removing etc using the event tracking. I would like to know what is the ideal time to use the ecommerce tracking apis (addTrans & addItem). Here are my questions:

*

*Should I call these functions for each product being added to cart?

*Should I call these functions only when the payment is complete and them while displaying receipt screen?
What is the ideal way of implementation? please provide best practices if possible.
Thanks in advance

A: I would track few things,
1.How many got into payment form and failed to buy, which can indicate to you that something wrong with payments or page itself. Count number of visitors in checkout - number of orders.
2.How many users got into site and haven't added at least one product, which will indicate that something wrong with advertisement, landing page or website layout in general. Number of unique visitors - those who added at least one item.
Adding statistics for each product added to cart shows you what? If users buy certain product you can get that this product is most wanted but in cart means noting imho. As for your second question, i would implement my solutions written above.

A: I wonder if your customers should go to an externally hosted page to make a payment. If they do, then GA tracking will not show you the real source of your profitable traffic - it will show you the payment processor page as the source.

A: It is recommended, or at least suggested, that you place the eCommerce tracking that includes the _trackTrans call on the "Thank You" or "Confirmation" stage of your checkout process.
Also, it's worth noting that if the user refreshes that page that the tracking is on then the code will be fired again and you may see skewed figures in Google Analytics.

A: I was like you, I also implemented the event tracking first but I wanted to get a chance to implement the ecommerce tracking to get some $ data in there to browse. So, on the developers page. One of the examples is on the reciept page, but on my implementation that wasn't going to work since I am use a payment API. So, On my checkout page I setup the parent transaction. using :
_gaq.push(['_addTrans',
'1234',           // transaction ID - required
'Acme Clothing',  // affiliation or store name
'11.99',          // total - required
'1.29',           // tax
'5',              // shipping
'San Jose',       // city
'California',     // state or province
'USA'             // country
 ]);

Then when I am listing my items in the cart, I use PHP and a foreach to dump each item, sku, price per item and quantity into the parent level transaction like this :
  _gaq.push(['_addItem',
'1234',           // transaction ID - required
'DD44',           // SKU/code - required
'T-Shirt',        // product name
'Green Medium',   // category or variation
'11.99',          // unit price - required
'1'               // quantity - required
 ]);

For the last step in the process, I send transaction data to my merchant processing (paypal) via the SOAP api and get numerous responses back. I do different stuff based on the response I get back. If there is no error from the JSON response I get an COMPLETED response, at that point is when I fire the :
_gaq.push(['_trackTrans']);

I'm not really sure if this is the true way to go about it, but it makes sense to me.


text:
Q: mongodb queries both with AND and OR can I use combination of OR and AND in mongodb queries?
the code below doesn't work as expected
db.things.find({
           $and:[
                {$or:[
                     {"first_name" : "john"},
                     {"last_name" : "john"}
                ]},
                {"phone": "12345678"}
            ]});

database content:
> db.things.find();
{ "_id" : ObjectId("4fe8734ac27bc8be56947d60"), "first_name" : "john", "last_name" : "hersh", "phone" : "2222" }
{ "_id" : ObjectId("4fe8736dc27bc8be56947d61"), "first_name" : "john", "last_name" : "hersh", "phone" : "12345678" }
{ "_id" : ObjectId("4fe8737ec27bc8be56947d62"), "first_name" : "elton", "last_name" : "john", "phone" : "12345678" }
{ "_id" : ObjectId("4fe8738ac27bc8be56947d63"), "first_name" : "eltonush", "last_name" : "john", "phone" : "5555" }

when querying the above query - i get nothing!
> db.things.find({$and:[{$or:[{"first_name" : "john"}, {"last_name" : "john"}]},{"phone": "12345678"}]});
>

I'm using mongo 1.8.3

A: db.things.find({
    $and: [
        {
            $or: [
                {"first_name": "john"},
                {"last_name": "john"}
            ]
        },
        {
            "Phone": "12345678"
        }
    ]
})

AND takes an array of 2 expressions OR , phone.
OR takes an array of 2 expressions first_name , last_name.
AND

*

*OR

*first_name

*last_name

*Phone Number.
Note: Upgrade to latest version of MongoDB, if this doesn't work.

A: Shorter to use an implicit AND operation:
db.things.find({
    $or : [
        {"first_name": "john"},
        {"last_name": "john"}
    ],
    "phone": "12345678"
})

A: This is possible in following manner (mongodb 3.4)
Here is the good example
https://docs.mongodb.com/manual/reference/operator/query/and/#and-queries-with-multiple-expressions-specifying-the-same-operator

        db.getCollection('tbl_menu_items').find({
        $and : [
            { $or : [ { price : 0.99 }, { price : 1.99 } ] },
            { $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
        ]
    } )

This query will select all documents where:
the price field value equals 0.99 or 1.99, and
the sale field value is equal to true or the qty field value is less than 20.
Here is the example of $and condition with $or query i.e matching any of condition for example
consider following query...

        db.getCollection('tbl_menu_items').find(

        { '$or':
           [ { '$and':
                [ { location: { '$in': [ ObjectId("588054c63879f2e767a1d553")  ] } },
                  { is_ryward: 1 },
                  { points_reqiured_to_redeem_reward: { '$lte': 500 } } ] },
             { '$and':
                [ { location: { '$in': [ ObjectId("588054c63879f2e767a1d553")  ] } },
                  { is_freebie: 1 } ] } ] }
        )

This query will select all documents where:
location array in 588054c63879f2e767a1d553 and is_ryward = 1 and     points_reqiured_to_redeem_reward < 500
Or
location array in 588054c63879f2e767a1d553 and is_freebie

A: I believe $and is only supported in MongoDB v2.0+. I'm surprised that the console accepted the expression in the first place. I'll try to recreate against a 1.8 server I have.
Also check 10Gen's Advanced Query Documentation for $and.
Update
I entered your sample data into both a v1.8x and v2.0x MongoDB server. The query works on the v2.0x and fails on the v1.8x. This confirms my (and Miikka's) suspicions that the problem is with $and and your server version.
I found a (arguably) clever workaround for this on the Web here. I hope this helps.
-SethO


text:
Q: DataTable - Why can't I get individual column searching (select inputs) working? I'm using a JavaScript table goodies-pack from  DataTables.net and I've come across a feature that greatly fits to my need, the individual column searching (select inputs), found here.
This feature allows to drill-down on the column data, filtering it down.
I've tried the standard implementation with no luck. I find no specific field on the implementation and have tried removing all other properties.
My code is:

The demo on the datatables.net page shows buttons beneath each column to filter it. I don't get those and the filtering feature. What am I missing here?

A: Your code works fine. I am 100% certain that you just have forgotten to include a
 section. The footer is not added by magic, if
 is not present your <select>'s is inserted to nothing. So remember :

A: This is my ajax side code I have an issue when I select the dropdown option the records are not filtering it only shows me processing. when I remove the serverside: true it works perfectly but my records show mi very slow. Any one has solution in this dropdown serchfilter.
$("#ajaxTable").DataTable({
  bPaginate: true,
  bProcessing: true,
  bDestroy: true,
  serverSide: true,
  searching: true,
  order: [],
  //"ordering": true,
  //"columnDefs": [{ orderable: false, targets: [5] }],
  pageLength: 25,
  //"deferRender":    true,
  ajax: {
    url: "",
    type: "POST",
    data: {},
    error: function (html) {},
    beforeSend: function () {
      //$('#image').show();
    },
    complete: function (data) {
      //let obj = JSON.parse(data);
      //console.log(data['responseJSON'].recordsTotal);
    },
  },
  columns: [
    { data: "srno" },
    { data: "id" },
    { data: "date" },
    { data: "ref" },
    { data: "pname" },
    { data: "regional_manager" },
    { data: "al_backend" },
    { data: "area_manager" },
    { data: "territory_manager" },
    { data: "customer_name" },
    { data: "mobile_no" },
    { data: "modified_date" },
    { data: "status" },
    { data: "action" },
    { data: "edit" },
    { data: "remark" },
    { data: "lead_remark" },
    { data: "gender" },
    { data: "currentlocation" },
    { data: "employ_type" },
    { data: "damount" },
    { data: "nooldcard" },
    { data: "rcbook" },
    { data: "model" },
    { data: "disbursed_amount" },
    { data: "disbursed_date" },
    { data: "disbursed_bank" },
    { data: "sanction_amount" },
    { data: "sanction_date" },
    { data: "sanction_bank" },
    { data: "pan_card" },
    { data: "aadhar_card" },
    { data: "bank_state" },
    { data: "salary_slip" },
    { data: "rc_card" },
    { data: "zip" },
  ],
  language: {
    searchPlaceholder: "Search...",
    search: "",
    lengthMenu: "_MENU_ items/page",
    infoFiltered: "",
    processing:
      "",
  },
  dom: "Blfrtip",
  buttons: [
    {
      extend: "excel",
    },
  ],
  initComplete: function () {
    this.api()
      .columns([4])
      .every(function () {
        var column = this;
        var select = $('
<select><option value="">ALL</option></select>')
          .appendTo($(column.header()))
          .on("change", function () {
            var val = $.fn.dataTable.util.escapeRegex($(this).val());

            column.search(val ? "^" + val + "$" : "", true, false).draw();
          });

        column
          .data()
          .unique()
          .sort()
          .each(function (d, j) {
            select.append('<option value="' + d + '">' + d + "</option>");
          });
      });
  },
});


text:
Q: Revert after I pushed to the wrong remote branch I had one master branch, then decided to work on new feature and created branch for it. After I did some stuff I've pushed it to remote. Then I switched to master and continued work on it made some feature.
And the I tried to push it to remote and got message that I have to pull first as far as:
"hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart."
Inspecting pull gave me info that remote I'm trying to push to contain all changes from "feature" branch. So first guess -- I've pushed to wrong remote branch. But I see featured branch in remotes as well(may be latter I've pushed to right one)
I'm the only one contributor so I have all power to revert anything and etc.
What is best strategy to revert remote branch from last push(I use bitbucket)?

A: Assuming that you have already committed all the changes, use the following commands:
git checkout master
git reset --hard <commit_id_you_wish_to_reset_your_master_to>
git push --force origin master

A: If you haven't pulled down the remote changes yet, you can just do a force push:
git push origin +master --force

This will set the state of the remote master branch (and only the master branch, which is what the + is for) to the state that your local branch is in.
If you've already pulled down the changes and merged/rebased then you'll need to get your local branch into the state you want the remote to be in. You can do this with a reset:
git reset --hard <hash of commit you want to be last on master>

Then do the force push.


text:
Q: Accessibility: Use high offscreen resolution to get better zoom quality? (compiz, gnome-shell) I'm visually impaired and using Ubuntu 20.04 (Windows was harder to customize)
Wondering if it is possible to set a higher than monitor resolution (eg: 4k root window for a 2k display).
If I understand correctly, the application windows could be rendered in offscreen textures with the high 4k resolution. Then, the compositing manager (gnome-shell/mutter, compiz) will map them to the 2k physical monitor pixels.
This would mean that when you zoom on a window you could get a better image quality (the rescale would map a bigger texture to the monitor). eg: with a 4k for 2k setup and a x2 zoom you would still have a perfect one for one pixel scale factor between offscreen and monitor.
I guess this is not a big issue for most of you but I'm using high zoom factors and I'm getting very fuzzy results that are making things even harder to read. (the OpenGL antialias upscale is great but it cannot guess the "missing" pixels when you zoom at x5 so you loose a lot of sharpness)
As found in old posts, I've tried xrandr but see below. I'm not even sure that it is still relevant on my 20.04 system:
xrandr --output HDMI-0 --mode 3840x2160 --scale 2.0x2.0
xrandr: cannot find mode 3840x2160

BTW: I've tried gnome-shell but had to switch back to compiz to get the mandatory "zoom with mouse-wheel" option of "enhanced-zoom".
Thank you for your help.

A: Thank you user.dz.
With your pointer I managed to improve things by doing:
output=$(xrandr | grep " connected" | cut -d ' ' -f 1)
xrandr --output $output --scale 2.0x2.0 --dpi 200

This gives me a bigger (2k->4k) offscreen resolution that any composer (gnome-shell/mutter, compiz, ...) will use to get a far better looking zoom. In the case of text, this makes it a lot easier to read.
For this to work properly you also need to make everything 2x bigger to use all the new available pixels. To compensate for the 2x bigger screen you have to set the scale factor to 200% in the gnome settings: Displays
So, everything drawn on the bigger (off)screen has the same apparent size on your monitor but is made of 4 times more pixels (doubled for x and y axis)
Unfortunately, the 200% display scale won't work for all UI elements, so some things will look too small (known issues relatied to High DPI). eg: thunderbird does not scale the font when editing a new mail (be prepared to do quite a lot of Ctrl-+ or Ctrl-mousewheel)
After two weeks in this mode I'm happy and will continue using it. The better overall zoom quality/readability is worth a couple remaining issues.
Hope it helps if you are struggling with accessibility and readability of zoomed text.
Would be great if Ubuntu could support this "trick" as an official accessibility option.

A: I may not help as you expect, I didn't try zooming with scaling. I would explain my experience as I understand it.
Frame Buffer (FB) → Position → Transformation (TR) → Panning → Output Port → Physical connection to Monitor

*

*--scale works at Transformation step (same as --reflect and --rotate too) but auto-set the Frame Buffer as needed.

*--mode sets Output port (resolution), it only depends on Monitor/Connection/Graphic adapter capabilities.

So, setting the mode as you mention in your question will fail as it is not supported, even if you able to enforce adding that mode. Monitor will stay blank.

*

*You may set: double --fb, double --scale, keep original --mode. You will notice some blurring due to image scaling down (transformation from large frame buffer to smaller resolution output port). Not sure how zoom gonna be? if it is using FB as source, probably gonna be clear.

*Another option is Panning --panning either on single monitor (only section of buffer is visible, follows mouse to view other corners) or on multiple monitors.
You can even have one normal monitor and another with scaling & panning, either for same buffer area (kind of permanent zoom) or on the side (extended desktop with zoom)
Look at my post here with pictures & screenshots of scaling: Scale application differently on different monitors - Ubuntu 16.04 . By the way, scrambled area on screenshots is the blind inaccessible section of the frame buffer. But you can set panning and get active.


text:
Q: Which port does the RX100M3 use Liveview? I'm developing on a SONY camera RX100M3. I want to know on which port does the camera use to return pictures during Liveview? is it on the same port to spend requests (port : 8080/sony/camera)?
I'm using 2 WiFi adaptors, one is connected to my box and the other to the camera. I have rerouted with "iptables" to redirect every packets coming form  port 8080 to 192.168.122.1:8080/sony/camera. I am sending request to 192.168.1.46:8080/sony/camera (first WiFi adaptor).
Actually I'm able to spend requests to the camera with the "pysony" library, take pictures, videos, Zoom In and Zoom out. But I can't get back the Liveview from the camera.
I hope I have been enough clear.

A: When you call "startLiveview" it will return the URL to the live view stream in the response, which contains the port number.
{
   "result": [
        "http://ip:port/liveview/liveviewstream"
   ],
   "id": 1
}

Not sure what platform you are working on, but if it's Android or iOS have you taken a look at the CameraRemoteSampleApp project that comes with the SDK?  It contains sample code on how to start and display the live view stream.


text:
Q: pgfplots/standalone: setting new layer trims pgfplot output when called by \includestandalone[mode=tex] For the main file
\documentclass{article}

\usepackage{pgfplots}
\usepackage[subpreambles=true]{standalone}

\pgfplotsset{compat=newest,
    layers/my layer set/.define layer set={
        background,main, rpim40 , rpim85 , sph,expint, exp
    }{},
    set layers=my layer set,
    mark layer=like plot,
    }

\usepgfplotslibrary{groupplots}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{siunitx}

\begin{document}
\begin{figure}
  \frame{
    \includestandalone[mode=tex,width=\textwidth]{exsurfacetikz}
  }
  \caption{My TikZ picture}
\end{figure}
\end{document}

calling the following standalone pgfplot using \includestandalone[mode=tex] results in an incorrectly bottom-trimmed output only if I use the new layer set in the main file set layers=my layer set.
% exsurfacetikz.tex

\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
    \begin{axis}[
%        view={0}{90},
        % you need to add this to get the desired result
        unbounded coords=jump,
        colorbar horizontal
    ]
        \addplot3 [
            surf,
        ] table [
            x=x,
            y=y,
            z expr={\thisrow{z} == 100 ? NaN : \thisrow{z}},
        ] {
            x   y       z
            3.1 1.00    21.8
            3.1 0.98    19.16666667
            3.1 0.96    17.83333333
            3.1 0.94    16.16666667
            3.1 0.92    15.5
            3.1 0.90    14.83333333
            3.1 0.88    14.16666667
            3.1 0.86    13.5
            3.1 0.84    12.83333333
            3.1 0.82    12.16666667
            3.1 0.80    12.16666667
            3.1 0.78    11.5
            3.1 0.76    100
            3.1 0.74    100

            3.3 1       21.83333333
            3.3 0.98    20.5
            3.3 0.96    18.5
            3.3 0.94    16.83333333
            3.3 0.92    15.5
            3.3 0.9     14.83333333
            3.3 0.88    14.16666667
            3.3 0.86    13.5
            3.3 0.84    12.83333333
            3.3 0.82    12.16666667
            3.3 0.8     12.16666667
            3.3 0.78    11.5
            3.3 0.76    11.5
            3.3 0.74    11.5
        };
    \end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Xcode-perform Segue in main view controller from action in popover I'm creating an an that requires either logging in or signing up. Both logging in and signing up are currently performed in popover views over the main logged out screen.
Thus I need to trigger a segue to be performed in a different view controller from my popover view controller. How and/or is this possible?
this is my registration code in my 'registerViewController'(popover view) and I want to perform the segue from my 'loggedOutViewController' to my 'mainViewController' (logged in view).
registerViewController.m:
- (void) registerNewUser {

PFUser *newUser = [PFUser user];
newUser.email = _emailField.text;
newUser.username = _usernameField.text;
newUser.password= _passwordField.text;
newUser[@"name"] = _nameField.text;

[newUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
    if (!error) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Registration Successful" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];

        //Where I need to call the segue

    } else {
        NSString *errorString = [error userInfo][@"error"];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Oops" message:errorString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
}];

Apologies if this been asked already, I could not find a solution to my problem anywhere, and if you would like/need anymore information or code please let me know.

A: It's difficult to know exactly what your desired behavior is.  Here is one method:
// Display settings view
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
SettingsVC *report = [storyboard instantiateViewControllerWithIdentifier:@"SettingsViewController"];
[self presentViewController:report animated:YES completion:nil];

Replace story board and desired view controller name with your own.  Also, make sure your view controller is correct by replacing SettingsVC with the name of your desired view controller.


text:
Q: Change the encoding of SPSS data files I have a mixture of SPSS data files where part is in English (windows-1252) encoding and other part is in Turkish (windows-1254) encoding. Is it possible to change the encoding of a SPSS file? For example, I would like to change the encoding of all data files to Turkish (windows-1254).
I know the SET LOCALE command. I can change a locale before opening file. But it is not possible to change a locale during a data file is open. So I do not see an option to save a data file in a different encoding using SPSS syntax.
* Change SPSS locale to Turkish (windows-1254).
* Only for SPSS 13.0 and above.
new file.
set locale = tr_TR.
show locale.

* Change SPSS locale to English (windows-1252).
* Only for SPSS 13.0 and above.
new file.
set locale = en_US.
show locale.

There are variable and value labels defined. They should be kept.
Unicode is not an option here. The data files have to be compatible with old SPSS versions below version 16 (when Unicode support was introduced in SPSS). Anyway I have no clue how it would be possible to re-encode all data files in Unicode.

A: You can't have a file with a mixed encoding.  If you happen to only have characters that don't conflict in the two code pages, you might be able to get away without Unicode, but it would be iffy.
What you could try is to set Unicode on and your locale to one of the two.  Read the file and save it.  It will be in Unicode.  Then close the data, set the other locale, and read the second file.  Save it.  Now merge the two files.  You have a Unicode file that has all the characters correct.  Open Statistics, set Unicode off, and set the one locale you want to make primary, and open the merged file.  If you are lucky, all the characters will work, but if there are conflicts, Unicode would be your only option.


text:
Q: hide/show a view(image or button) on a single item click in a recyclerview list I really need some help regarding the recyclerview list.
Suppose there is a list with 10 items, Suppose i click one item (at position 1), i need make the view(button/image) visible on that particular item clicked. But when i will click any other item (at position 5) then the view(button/image)should be visible on position 5 and not on position 1. Can anyone tell me how can i achieve this result ? I would really appreciate if anybody help me with this. If you want some more details please do comment.
Thanks.

A: in recyclerview adapter when handling click listener in onBindViewHolder(Holder, Position) method you must choose the position of the view not fixed number(eg: 1,2 ,3)
ex:
=========
 @Override
public void onBindViewHolder(final YourHolder holder, final int position) {

 holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          view.setVisibility(View.VISIBLE);
        }
    });

A: I've updated mi code, this is working fine!
You need to add a boolean attribute to your ItemAdapter (the item you inflate on the recyclerView).
public class YourItem{
    private String title;
    private String image;
    private boolean showView;

    public String getTitle() {
        return title;
    }
    public String getImage() {
        return image;
    }

    public void setShowView(boolean showView) {
       this.showView = showView;
    }

    public boolean mustShowView() {
       return showView;
    }

}

Then on your Adapter:
public class YourAdapter extends RecyclerView.Adapter<YourAdapter.MyViewHolder> {

    ...
    private int lastPosition;
    ...
    class MyViewHolder extends RecyclerView.ViewHolder {
        private TextView title;
        private ImageView image;
        private View.OnClickListener onRowClicked = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (lastPosition != getAdapterPosition()) {
                    Prize lastItem = getItem(lastPosition);
                    lastItem.setShowView(false);
                    adapterList.set(lastPosition, lastItem);
                    lastPosition = getAdapterPosition();
                }
                Prize item = getItem(getAdapterPosition());
                item.setShowView(!item.mustShowView());
                adapterList.set(getAdapterPosition(), item);
                notifyDataSetChanged();
            }
        };

        MyViewHolder(View itemView) {
            super(itemView);
            image = (ImageView) itemView.findViewById(R.id.image);
            title = (TextView) itemView.findViewById(R.id.prize_title);
            itemView.setOnClickListener(onRowClicked);
        }

        void bind(final Prize item) {
            title.setText(item.getTitle().toUpperCase());
            Picasso.with(context).load(item.getImage()).into(image);
            image.setVisibility(item.mustShowView() ? View.VISIBLE : View.GONE);
        }
    }
}

A: i hope this code is good enough to explain the way to do that:
    public class myAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
      private List<Object> list;
      public myAdapter(List<Object> list){
         this.list=list;
      }
     ItemViewHolder openedRow=null;
     @Override
     public RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, parent, false);
            ItemViewHolder view = new ItemViewHolder(v);
            v.setOnClickListener(this);
            return view;
        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
            final ItemViewHolder myRowHolder = (ItemViewHolder) holder;

              myRowHolder.itemView.setOnClickListener(new View.OnClickListener(){

    @Override
    public void onClick(View v) {
   if(openedRow!=null)
   {
      openedRow.image.setVisibility(View.GONE);
   }
        openedRow=myRowHolder;
        openedRow.image.setVisibility(View. VISIBLE);
    }
    });
    }

public static class ItemViewHolder extends RecyclerView.ViewHolder {
    ImageView image;

    public ItemViewHolder(View itemView) {
        super(itemView);
                   image = (ImageView)
   itemView.findViewById(R.id.img_item_main);

    }
    }

    }

A: I had this problem and change these:
1-Don't set  attribute of android:visibility="visible" or "gone" in xml
2-Set this attribute in function of onBindViewHolder() in adapter():
holder.yourView.setVisibility(View.GONE);
    holder.yourBottun.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!(holder.yourView.isShown() ) {
                holder.yourView.setVisibility(View.VISIBLE);
            }
        }
    });


text:
Q: Non-linear assumed form in Galerkin method The wikipedia article on Method of mean weighted residuals has a section on choice of test functions, in particular it says about Galerkin method:

The Galerkin method, which uses the basis functions themselves as test functions or in the more general case of a nonlinear assumed form (where the nonlinearity is in the degrees of freedom) of the solution the Galerkin method uses the test functions:
  $$ w_{i}={\frac {\partial u}{\partial a_{i}}}$$

I'm really interested in the "nonlinear assumed form". I would like to know what is known about Galerking when we assume nonlinear form of the trial function.
Unfortunately the wiki article gives only one reference to a book which I was unable to get hold of. Can anyone direct me to any other source where I can read more about this topic?


text:
Q: React native Found errors while update expo sdk 42 to 45.Also setup new environment on react native all packages are exist but still giving errors We have issue found during installing a new expo app whenever we update newer version of expo app from play store our development related things not working so we have updated it with expo sdk 45 but it giving error still so we have set a new environment and trying to solve this after set new environment it still giving errors like below
ERROR  Error: Requiring module "node_modules\react-native-reanimated\src\Animated.js", which threw an exception: Error: Reanimated 2 failed to create a worklet, maybe you forgot to add Reanimated's babel plugin?
ERROR  Invariant Violation: "main" has not been registered. This can happen if:

*

*Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.

*A module failed to load due to an error and AppRegistry.registerComponent wasn't called.

A: I don't think this is a fix for everyone, but try:

*

*yarn global add expo-cli
(Mine upgraded when I do this)

*yarn install
(To rebuild the package)

*expo --version
Then use the package version on the package.json
"expo-cli": "5.4.12",

*expo start
Give it a go, you might be lucky...