text:
Q: rails 4. how to create actions using relationships between three models? I would like to create relationships between three models: user, post and comment.

*

*User have many posts and comments

*Post have only one user and many comments

*Comment have one user and one post

so i create next migrations:
class Users < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email

      t.timestamps
    end
  end
end

class Posts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.string :content
      t.integer :user_id
      t.timestamps
    end
  end
end

class Comments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.string :title
            t.string :content
      t.integer :user_id
            t.integer :post_id
      t.timestamps
    end
  end
end

=============================================
models are next:

*

*user.rb
class User < ActiveRecord::Base
        has_many :posts
        has_many :comments
 end

*post.rb
class Post < ActiveRecord::Base
  belongs_to :user
  has_many :comments
end

*comment.rb
class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
end
===============================================
My users_controller.rb
class UsersController < ApplicationController
  before_action :signed_in_user, only: [:index, :edit, :update, :destroy]
  before_action :correct_user,   only: [:edit, :update]
  before_action :admin_user,     only: :destroy
  def index
    @users = User.paginate(page: params[:page])
  end

  def show
    @user = User.find(params[:id])
    @posts = @user.posts.paginate(page: params[:page])
        @comments = @user.comments.paginate(page: params[:page])
    end

  def new
    @user = User.new(params[:user])
  end

  def edit
    #@user = User.find(params[:id])
  end

  def update
    #@user = User.find(params[:id])
      if @user.update_attributes(user_params)
        flash[:success] = "Profile updated"
        redirect_to @user
      else
        render 'edit'
      end
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User deleted."
    redirect_to users_url
  end

  def create
    @user = User.new(user_params)
      if @user.save
        flash[:success] = "Welcome to the Sample App!"
        redirect_to @user
      else
        render 'new'
      end
  end

  private

    def user_params
      params.require(:user).permit(:name, :email, :password,
                                   :password_confirmation)
    end

    # Before filters

    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_url) unless current_user?(@user)
    end

    def admin_user
      redirect_to(root_url) unless current_user.admin?
    end
end

now i want to create some actions for next tasks:

*

*For posts_controller.rb

1.1 create a post by user
1.2 delete a post by user
1.3 show user post with all comments
1.4 show all user posts
class PostsController < ApplicationController
    before_action :signed_in_user, only: [:create, :destroy]
  before_action :correct_user,   only: :destroy

    def create
        @post = user.post.build(post_params)
        @post = post.save
    end

    def destroy
        @post.destroy
    end

    def show_user_post_with_all_comments
        ???
    end

    def show_all_user_posts
        ???
    end

    private

    def post_params
      params.require(:post).permit(:title, :content)
    end

    def correct_user
      @post = current_user.posts.find_by(id: params[:id])
      redirect_to root_url if @post.nil?
    end
end

*For comments_controller.rb
2.1 create a comment by user in post
2.2 delete a comment by user in post
2.3 show all user comments
2.4 find and show a post by user comment
class CommentsController < ApplicationController
  before_action :signed_in_user, only: [:create, :destroy]
  before_action :correct_user,   only: :destroy
def create
    @comment = user.comment.build(comment_params)
    @comment = comment.save
end

def destroy
    @comment.destroy
end

def show_comment
???
end

def show_all_user_comments
???
end

def find_and_show_post_by_user_comment
???
end

private

def comment_params
  params.require(:comment).permit(:content)
end

def correct_user
  @comment = current_user.comments.find_by(id: params[:id])
  redirect_to root_url if @comment.nil?
end

end
Pls check for correct my migrations and models and help me with creating of actions with "???" in bodies
Thank you much for your answers.

A: PostsController
def show_user_post_with_all_comments
    @post = Post.find(params[:id]).eager_load(:comments)
end

def show_all_user_posts
    @posts = current_user.posts
end

CommentsController
def show_comment
    @comment = Comment.find(params[:id])
end

def show_all_user_comments
    @comments = current_user.comments
end

def find_and_show_post_by_user_comment
    @comment = Comment.find(params[:id]).eager_load(:post)
    @post = @comment.post
end

A: What I've done in the past in a similar situation would be to put all this work in the UsersController and add a few new actions to it:
class UsersController < ApplicationController
  ...
  def new_post
    @user = User.find(params[:id])
  end

  def create_post
    @user = User.find(params[:id])
    if @user.update_attributes user_post_params
      redirect_to somewhere_path
    else
      render 'new_post'
    end
  end

  def show_post
    @post = Post.find(params[:id])
    # Not sure how you are implementing sessions, but say you have current_user defined
    # for sessions, then your view could have a delete link conditional on
    # @post.user_id == current_user.id
    @comments = @post.comments
  end

  def show_all_posts
    @user = User.find(params[:id])
    @posts = @user.posts
  end

  def new_comment
    @user = current_user
    @post = Post.find(params[:id])
  end

  def create_comment
    @user = current_user
    @post = Post.find(params[:id])
    @comment = Comment.new(comment_params)
    if @post.update_attributes comment_params
      @user.comments << @comment
      if @user.save
        redirect_to somewhere
      else
        render 'new_comment'
      end
    else
      render 'new_comment'
    end
  end

  def show_comments
    @user = User.find(params[:id])
    @comments = @user.comments
  end
  ...
  private
  def user_post_params
    params.require(:user).permit(:id, posts_attributes: [:title, :content])
  end

  def comment_params
    params.require(:post).permit(:id, comments_attributes: [:content, :user_id])
  end

In show_post.html.erb:
 <% if @post.user_id == current_user.id %>
   <%= link_to 'delete', post, method: :delete, data: { confirm: "you sure?" }
 <% end %>

in your routes.rb:
get '/user/:id/new_post' => 'users#new_post', as: :user_new_post
put '/user/:id/create_post' => 'test_takers#create_post', as: :user_create_post

...and similar lines for the other actions.
Hopefully this can get you started...


text:
Q: Validaterror when installing two modules I want to add two other modules in my application. but when I try to install the modules Waherouse and purchase management, installation is not possible with this error
"
ValidateError
Une erreur est apparue lors de la validation du/des champ(s) vat: Ce code de TVA ne semble pas correct. Note: le format attendu est 'CC##' (CC=Country Code, ##=VAT Number)
"
The accounting module is already installed and the completed status
I need your help
Thank

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jenkins is running different selenium test suite I have created new maven project and added 2 different test suites TS1 and TS2
to run test suites I'm using the following command from cmd prompt
For TS1- mvn -Dtest=TS1 clean test
For TS2 - mvn -Dtest=TS2 clean test
and to run particular test method I'm using
mvn -Dtest=TS1#TestMethodName clean test
my tests are running fine with command prompt..
Now I've planned to integrate my tests in Jenkins but I've create 2 jobs one for TS1 and another for TS2
TS1 is running fine but for TS2, instead of running TS2 it is running TS1
Jenkins log:
[WARNING]
[WARNING] Some problems were encountered while building the effective model for com.ariveguru.tests:eserve:jar:1.0-SNAPSHOT
[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 41, column 12
[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-surefire-plugin is missing. @ line 58, column 12
[WARNING] 'build.plugins.plugin.version' for org.codehaus.mojo:selenium-maven-plugin is missing. @ line 49, column 12
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building eserve 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ eserve ---
[INFO]
[INFO] >>> maven-surefire-report-plugin:2.16:report (default-cli) @ eserve >>>
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ eserve ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Automation-WorkSpace\workspace\Case creation\eserve\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ eserve ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ eserve ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Automation-WorkSpace\workspace\Case creation\eserve\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:testCompile (default-testCompile) @ eserve ---
[INFO] Compiling 24 source files to C:\Automation-WorkSpace\workspace\Case creation\eserve\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ eserve ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (copy-resources) @ eserve ---
[INFO] Tests are skipped.
[INFO]
[INFO] <<< maven-surefire-report-plugin:2.16:report (default-cli) @ eserve <<<
[INFO]
[INFO] --- maven-surefire-report-plugin:2.16:report (default-cli) @ eserve ---
[WARNING] Unable to locate Test Source XRef to link to - DISABLED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.955s
[INFO] Finished at: Mon Mar 17 18:14:30 IST 2014
[INFO] Final Memory: 19M/47M
[INFO] ------------------------------------------------------------------------
Parsing POMs
Modules changed, recalculating dependency graph
maven31-agent.jar already up to date
maven31-interceptor.jar already up to date
maven3-interceptor-commons.jar already up to date
[eserve] $ C:\Java\jdk1.7.0_01/bin/java -cp C:\Automation-WorkSpace\maven31-agent.jar;C:\Automation-WorkSpace\tools\hudson.tasks.Maven_MavenInstallation\maven\boot\plexus-classworlds-2.5.1.jar;C:\Automation-WorkSpace\tools\hudson.tasks.Maven_MavenInstallation\maven/conf/logging jenkins.maven3.agent.Maven31Main C:\Automation-WorkSpace\tools\hudson.tasks.Maven_MavenInstallation\maven C:\Users\USER\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\2\32f78882-1a0ca571 C:\Automation-WorkSpace\maven31-interceptor.jar C:\Automation-WorkSpace\maven3-interceptor-commons.jar 64798
<===[JENKINS REMOTING CAPACITY]===>channel started
log4j:WARN No appenders could be found for logger (org.apache.commons.beanutils.converters.BooleanConverter).
log4j:WARN Please initialize the log4j system properly.
Executing Maven:  -B -f C:\Automation-WorkSpace\workspace\Case creation\eserve\pom.xml install
[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for com.ariveguru.tests:eserve:jar:1.0-SNAPSHOT
[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 41, column 12
[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-surefire-plugin is missing. @ line 58, column 12
[WARNING] 'build.plugins.plugin.version' for org.codehaus.mojo:selenium-maven-plugin is missing. @ line 49, column 12
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[HUDSON] Collecting dependencies info
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building eserve 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ eserve ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Automation-WorkSpace\workspace\Case creation\eserve\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ eserve ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ eserve ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Automation-WorkSpace\workspace\Case creation\eserve\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:testCompile (default-testCompile) @ eserve ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ eserve ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (copy-resources) @ eserve ---
[INFO] Surefire report directory: C:\Automation-WorkSpace\workspace\Case creation\eserve\target\surefire-reports


text:
Q: apache + hhvm fastcgi i'm trying to migrate my project from apache2.2 to apache2 + hhvm with apache as reverse proxy.
Before migration i had this apache configuration ( to make pretty urls ):
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/(server-status)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*)$ index.php/$1 [L]

so portal urls were like: examples.com/post/post-title-as-slug
Now i have this configuration for apache:
<IfModule mod_fastcgi.c>
<FilesMatch \.php$>
    SetHandler hhvm-php-extension
</FilesMatch>

<FilesMatch \.hh$>
    SetHandler hhvm-hack-extension
</FilesMatch>

Alias /ec /ec
Action hhvm-php-extension /ec virtual
Action hhvm-hack-extension /ec virtual

FastCgiExternalServer /ec -host 127.0.0.1:9000 -pass-header Authorization -idle-timeout 300

</IfModule>

And this hhvm config ( server.ini ):
hhvm.server.port = 9000
hhvm.server.type = fastcgi
hhvm.server.default_document = index.php
hhvm.log.use_log_file = true
hhvm.log.file = /var/log/hhvm/error.log
hhvm.repo.central.path = /var/run/hhvm/hhvm.hhbc
hhvm.server.source_root = /w3/dr/

This config works only if i set urls like: examples.com/index.php/post/post-title-as-slug but if url is like: examples.com/post/post-title-as-slug i receive a 404 http error.
I want to remove index.php from url.
Anyone knows a solution ?
Thanks.

A: As per Facebook HHVM Issue #3472 you have to set hhvm.server.fix_path_info = true in the hhvm config if you are using any mod_rewrite rule.


text:
Q: Why am I getting ' when AJAX saving (and repopulating) my form in Django I'm saving a draft of my form using AJAX (and a bit of Angular).
<!-- index.html -->

...
<input id="id_title" name="title" ng-model="title" placeholder="Question Title" type="text" value="" required />
...

<script>

    app.controller("addQuestionCtrl", function($http) {

        $scope.title = '{% if form.title.value is not None %}{{ form.title.value }}{% endif %}';
        ...

        $interval(function() {
            ...
            data = {title:''+$scope.title, ...};
            $http.post("{% url 'save_draft' %}", data).then(function(response) {
                ...
            }, function failureCallback(error) {
                ...
            });
        }, 10000);

    });

</script>

This is all works fine and sends a ' as a '. In my view.py I convert the data and store it in the session:
def save_draft(request):
    ....
    posted = json.loads(request.body.decode("utf-8"))
    ...
    request.session['draft'] = {
        'title': posted.get('title', None),
        ...
    }

and then populate the relevant fields when the page loads
def question_add(request):
    ....
    if request.method == 'POST':
        ....
    else:
        draft_question = request.session.get('draft', False)
        if draft_question:
            form = QuestionAddForm(initial={
                'title':draft_question['title'],
                ...
            })

Unfortunately this turns this

into this

it's not an encoding issue on the client end as the field renders as
 <input id="id_title" name="title" ng-model="title" ... value="'title in quotes'" />

I'm not to sure why this is happening :(

A: What you should do instead (this is only draft code):
class QuestionAddForm(forms.ModelForm):
    # ...

    def draft_json(self, request):
        # use attribute or pass request to form init method
        draft_data = request.session.get('draft', False)
        return json.dumps(draft_data)

# in your view
context['draft_json'] = form.draft_json(request)

# in template
<script>
    var draft_data = JSON.parse('{{ draft_json|safe }}');
    $scope.title = draft_data.title
</script>

The point here is to render and parse data using json format.
A much better way is to use ajax instead of passing draft data from the backend to avoid mixing js code with template rendered content.


text:
Q: Linking libraries I have some project with file:
src/Test.cpp.
 Now I make subproject for it with another file src/TestWrapper.cpp which includes src/Test.hpp (related to Test.cpp).
Sure, to build successful shared library with wrapper I have to link Test.cpp too.
Everything works. I have project with Test.cpp linked and subproject (shared library) which linkes Test.cpp too.
The problem: that shared library would be linked to the main project. Will I have any errors due to this?

A: You should not put Test.cpp in your shared library. You can link your shared library without Test.cpp, it will just have some undefined symbols, which is perfectly normal for a shared library.
What you did will probably work but is dangerous and will make your software unmaintainable.


text:
Q: SOA domain records cannot be retrieved I'm still having trouble setting up my nameservers. DNS check says the following about my nameserver address:

Checking SOA records for domain. Domain server is not answering to UDP requests on port 53. Possible problems: A firewall is blocking port 53, server is down, server is not running software for handling dns requests.

I've run netstat -anp and found out that named is listening on tcp port 53, and it has udp port 53 on all IPs listed among active connections, though I'm unsure if that also means the port is actually active.
edit:
This problem is now solved. Everything was configured correctly, the problem was in zone files which didn't have appropriate permissions, so named couldn't read them.

A: I found what was wrong.
The zone files had read permissions set only for root, so named couldn't open them.

A: From here, I get answers from your servers for the two .arpa zones, but SERVFAIL for the .si domain.  Hence it's clearly not an IP stack or firewall problem.
Your BIND log file should tell you why that particular zone isn't working.  FWIW, I ran your drustvo.zone file against the named-checkzone program and it said there were no errors.


text:
Q: How do I add users to allow ssh tunneling access? I'm running Cent OS 5.6, I've disabled ssh tunnelling for everyone, but I need to know how to enable it for specific users.

A: Hopefully someone can come up with a better answer, but here's something that would work: Start a second sshd daemon on some other port, say 222. In this second sshd daemon, enable tunneling, but use the AllowUsers or AllowGroups options to only allow your specific users to be able to tunnel.

A: Use a "Match" statement in the sshd config can be used with a user or a group to enable or disable specific options.
In centos/rhel, there is an example at the bottom of the /etc/ssh/sshd_config file.
# Example of overriding settings on a per-user basis
Match User anoncvs
       X11Forwarding no
       AllowTcpForwarding no
       ForceCommand cvs server


text:
Q: How can I open a range of ports in ubuntu using (g)ufw I have to open up a group of ports.
Adding the single ports to (g)ufw was easy enough but I can't work out how to open the range 11200-11299.
How do I do that?

A: You can specify port ranges to ufw (the command-line one), using : (colon) to separate the lowest and the highest port in the range.  For example:
ufw allow 11200:11299/tcp

Note that the protocol part (/tcp or /udp) is mandatory with port ranges.
This works at least since Ubuntu 10.04.

A: Its worth adding that if you want to restrict to a specific IP address which is allowed access to those ports you can use the following:
ufw allow proto tcp from 1.2.3.4 to any port 40000:40100

A: Either
ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp

or if you need to use a from source ip range you must use full syntax
ufw allow from AAA.BBB.CCC.DDD/EE to any port 11200:11299 proto tcp
ufw allow from AAA.BBB.CCC.DDD/EE to any port 11200:11299 proto udp

see:
https://bugs.launchpad.net/ufw/+bug/1337767

A: I believe you can specify the range in the last tab of new rule, tick the checkbox at the bottom of the window to add more options (just to be safe). The range can be specified as 1000:1010 to open ports 1000-1010.

A: The cleanest command line way I've seen is a little script like this:
for i in `seq 11200 11299`; do
  ufw allow $i
done


text:
Q: Why does the Facebook Graph API give SSL errors in PHP? Every time I try to use the Facebook  Graph API in PHP 5.6 it gives me the following errors:

Warning: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
Warning: file_get_contents(): Failed to enable crypto in /home/xxx/public_html/api/v1/test.php

To begin with I was using the PHP SDK v4, but I'm now simply trying to connect to this URL:

https://graph.facebook.com/me?access_token=XXXXX

using the following code:
$url = "https://graph.facebook.com/me?access_token=XXXXX";
$result = file_get_contents($url);
$json_response = json_decode($result);
var_dump($json_response);

I have also tried every combination of manually setting the SSL mode and using cURL that I can find on Google but it always gives me the same error. Is there a server setting that I need to change/enable or am I making a simple mistake?
EDIT:
When I try to set the cipher mode to TLS 1.2 using cURL it gives the same error:
$ch = curl_init();
curl_setopt_array( $ch, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSLVERSION => 'TLSv1_2',
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_VERBOSE => true
) );
$output = curl_exec( $ch );
echo $output;

echo 'error:' . curl_error( $ch );

curl_close($ch);

error:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol


text:
Q: MobileFirst Foundation SDK 8.0 Init failure: Can't read checksum.js I'm following this tutorial https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/application-development/sdk/cordova/
and I'm getting "Init failure: Can't read checksum.js" error at the start of the app launch.
I realize that cordova-plugin-mfp -> bootstrap.js is point to a "checksum.js" file,
var WORKLIGHT_CHECKSUM_PATH = WORKLIGHT_DIR + '/checksum.js';

I have try to search to whole project, but there is no such file in the project.
Please advice.

A: running "cordova prepare" solves the issue


text:
Q: Shortcut for mirroring touch bar I would like to see an emulated touchbar on my iMac.
I randomly pressed the shotcut for it, but I don't know, which it was and I couldn't find it one the internet either. Btw., I don't use an Apple keyboard, so i.e. the fn key is missing.

A: You can show the Touch Bar on your screen using Xcode by choosing Window → Show Touch Bar or shift-cmd-8.


text:
Q: How to remove the etex warning when using cryptocode with the llncs document class? When using the cryptocode package along with the llncs document class, as provided by the Overleaf template, etex complains with the following warning:
/usr/local/texlive/2020/texmf-dist/tex/latex/etex-pkg/etex.sty Package etex Warning: Extended allocation already in use. etex.sty code will not be used. To force etex package to load, add \RequirePackage{etex} at the start of the document.

Here's a MWE to replicate the problem:
% This is samplepaper.tex, a sample chapter demonstrating the
% LLNCS macro package for Springer Computer Science proceedings;
% Version 2.20 of 2017/10/04
%
\documentclass[runningheads]{llncs}

\usepackage{cryptocode}

\begin{document}
    Dummy text.
\end{document}

I've also tried to remove the following lines in llncs.cls:
\RequirePackage{multicol} % needed for the list of participants, index
\RequirePackage{aliascnt}

which are the only occurences of \RequirePackage in the whole file. However, the following MWE:
\documentclass{article}

\usepackage{cryptocode}

\begin{document}
    Dummy text.
\end{document}

does not produce the aforementioned warning. Thus:

*

*How important is this warning, how does it affect the final document?

*Is it possible to identify which lines in llncs.cls conflict with cryptocode and to know how to somehow correct them?

A: You could ignore it, or ask the maintainer to remove etex, or silence the warning with
\expandafter\def\csname ver@etex.sty\endcsname{}
\usepackage{cryptocode}


text:
Q: Video Recording in j2me I am doing task in j2me which record the video and save in memory card and displaying it in the canvas. The problem is I want to take snap shoot for displaying the video properly, to be clear for a thumbnail, I used the code
public Image getScreenShot() {
 screenshot = Image.createImage(getWidth(),
                     getHeight());
  Graphics g = screenshot.getGraphics();
  paint(g);
  return screenshot;
}

It gives a null pointer exception. Now my problem is, Is it possible to get a thumbnail for a video in j2me, Anybody suggest some other ways for it??

A: Assuming you are using VideoControl class from javax.microedition.media.control.VideoControlyou can save of of the frames while processing it (before you display it on the screen) with:
byte[] raw = videoControl.getSnapshot(null);
Image image = Image.createImage(raw, 0, raw.length);

Before displaying the image on the form with
form.append(image);
display.setCurrent(form);

Just save it to the storage.
Full source code for running a video (captured tho) can be found here and using VideoControl to play recorded videos here


text:
Q: progress bar for non-loop functions I am currently running some functions on large data sets for which each operation takes a long time to execute.
To see the progress of my calculations, it would be handy to print the iterations/percentage of completed calculations. With loops, this can be easily done.
However, is it possible to have something similar working for vectorized functions or or pre-defined functions without actually making changes to the source code of those functions?
Example data:
generate_string taken from here : Generating Random Strings
generate_string <- function(n = 5000) {
a <- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE))
paste0(a, sprintf("%04d", sample(9999, n, TRUE)), sample(LETTERS, n, TRUE))
}
x <- generate_string(10000)
y <- generate_string(10000)

Example function to be monitored:
(i.e. printing the percentage completed):
library(stringdist)
# amatch will find for each element in x the index of the most similar element in y
ind <- amatch(x,y, method = "jw", maxDist = 1)

A: The pbapply is a option, but is more slow than the direct call:
system.time({ind <- amatch(x,y, method = "jw", maxDist = 1)})
   user  system elapsed
  27.79    0.05    9.72

library(pbapply)
ind <- pbsapply(x, function(xi) amatch(xi,y, method = "jw", maxDist = 1))
 |++++++++++++++++++++++++++++++++++++++++++++++++++| 100% elapsed = 30s

Also, the option that you comment (split data in chunks) is less elegant but faster, and this is easily parallelizable.
library(progress)
system.time({
nloops <- 20
pp <- floor(nloops * (0:(length(x)-1))/length(x)) + 1
ind <- c()
pb <- progress_bar$new(total = nloops)
for(i in 1:nloops) {
  pb$tick()
  ind <- c(ind, amatch(x[pp == i],y, method = "jw", maxDist = 1))
}
pb$terminate()
})
[===================================================================================] 100%
   user  system elapsed
  25.96    0.06    9.21


text:
Q: Xcode not Recognising New Custom Classes I am creating new custom classes for my project, but they're not showing or being recognised by Xcode seemingly. I am simply unable to select the class from the drop-downs.
I have had to resort to renaming a previous ViewController just so I can get it to recognise that one. However I know I will need new classes (VCs, table cells etc).
More importantly though I'm getting an error message for my custom View Controller called 'MatchesVC' so atleast it is trying to load this Custom Class (which I had to rename from a previous VC):
import UIKit

class MatchesVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self

}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 3
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    return MatchDataCell()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}}

CAN ANYONE PLEASE PLEASE HELP THIS POOR NOOB NUMPTY?
I'm following course material, but this problem is definitely isolated to me and my project unfortunately. I'm stumped.
For "tableView.delegate = self" it is returning the error "EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0). Also stating FATAL ERROR: unexpectedly found nil while unwrapping an Optional value (lldb). I literally have no idea what this could be or could mean. Things seemed to be working great before and they do so, when I change the sub class from MatchesVC to UIViewController but I need that functionality.

I also have a table view cell (created via Cocoa Touch) below with the following code:
Any idea why on earth my TableViewCell would not recognise this or show up in the custom classes?
import UIKit

class MatchDataCell: UITableViewCell {

    @IBOutlet weak var profileImg: UIImageView!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func drawRect(rect: CGRect) {
        profileImg.layer.cornerRadius = profileImg.frame.size.width / 2
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

I have tried to clean the Derived Data folder twice and have restarted Xcode and the Mac I am working on.
I have ensured I am referring to the write type of class, but still no success. Would it be worth uninstalling and reinstalling Xcode for this?


text:
Q: select adjacent element's child element
 stuff here

I need to select the div that is rendering the silver border How do I select the div in jquery and hide it? As well as the table cell with colspan.

A: $('.srch-sb-results').next('table').find('td[colspan="3"]').hide();

that should do it. Including the OP's original request to hide the td having a colspan=3

A: Try this:
$('table div').each(function() {//selects all divs inside table

    var bColor = $(this).css('border-color');//checks each element's border-color
    if( bColor === 'silver') {
       $(this).hide();
    }

});

A: If you can't change the html you could use an adjacent siblings CSS selector to select the first div inside the first table cell of the first table row like this:
$('.srch-sb-results + table > tr:first > td:first > div:first').hide();

Easier would be to change the HTML and set an ID on the div and select that directly.

A: if this div is the only:
$('td[colspan="3"] > div').hide();

or more strict to CSS should be something like this:
$('td[colspan="3"] div').each(function(){
  if ($(this).css('border')) $(this).hide();
});


text:
Q: Header only library inline not working I am struggling with my library design. I want to create a library to be used in my future projects (header only for now...)
I have this file structure:
C:\Libs\MYLIB
   - Tools.hpp
   - Tools.cpp

The code looks like this:
Tools.hpp
#pragma once
    class Tools
    {
        public:
            Tools();
            ~Tools();
    };

Tools.cpp
#include "Tools.hpp"

inline Tools::Tools()
{
}

inline Tools::~Tools()
{
}

And then there is is another project, in a totally different folder including this file:
#include <MYLIB/Tools.hpp>

int main()
{
    Tools t;

    return 0;
}

But I always get this error:

undefined reference to Tools::Tools()'
   undefined reference toTools::~Tools()'

When I create a .hpp file only with inline implementation inside my class, like this:
#pragma once
class Tools
{
    public:
        Tools(){};
        ~Tools(){};

        void DoSomething(){};
};

it works (so my include paths are correct), but I don't want to bloat my .hpp file (I want to use doxygen later on, and keep my declaration from implementation).
I know using inline can be ignored by the compiler, I guess this is what happens here?! So what is the best way to create a private header only library
My specs:
Win 10 with CodeLite
MinGW (g++)
Another question:
Should this line in Tools.cpp
#include "Tools.hpp"

better be like this:
#include <MYLIB/Tools.hpp>

A: You can use an ad-hoc static lib, which is convenient for libraries that are small and/or change often and thus don't provide much benefit compared to the overhead of versioning/compiling/distributing separately. The idea is that you separate headers/sources as normal, but you just #include the .cpp file in one translation unit. Be aware that this technique has its benefits, but also limits!


text:
Q: Forcing listener execution I have a problem.
I have an object with a listener attached to it.
I'd like to be able to manually execute it, somehow trick it that the event that triggers it occurred. Maybe there's a way to access the specific listener and tell it to execute?
Object is Box.Filler and listener is ComponentListener (adapter, acctually). It's activated on ComponentResized event.

A: Well if you were using ComponentListener my guess is you could call it directly:
listener.componentResized(new ComponentEvent (this,id))

If you were using an adapter
adapter.componentResized(new ComponentEvent (this,id))

If your class implements ComponentListener
componentResized(new ComponentEvent (this,id))

A: You can manually fire an event. If you are using ComponentListener then you can use one of the methods listed in this interface, see http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/event/ComponentListener.html.


text:
Q: Remove quotes from file export in PHP I've been doing some customizations for Twilio's report export code. I'm stuck on how to remove quote's within the text that appears within the "body" string. I tried str_replace( '"','',$sms )->body, and     addslashes($sms) ->body but am doing something wrong. Can you please help me find a solution to remove all quotes from body? The full code is below:
<?php
/**
* Download the library from: https://github.com/twilio/twilio-php
* Copy the 'Twilio' folder into a directory containing this file.
*/

require __DIR__ . '/Twilio/autoload.php';

use Twilio\Rest\Client;

/* Your Twilio account sid and auth token */
$account_sid = "hidden";
$auth_token = "hidden";

/* Download data from Twilio API */
$client = new Client($account_sid, $auth_token);
$messages = $client->messages->stream(
  array(
  'dateSentAfter' => '2020-01-01',
  'dateSentBefore' => '2020-02-01'
  )
);

/* Browser magic */
$filename = $account_sid."_sms.csv";
header("Content-Type: application/csv");
header("Content-Disposition: attachment; filename={$filename}");

/* Write headers */
$fields = array( 'From', 'To', 'Body', 'Status', 'Date Sent', 'SMS Message SID' );
echo '"'.implode('","', $fields).'"'."\n";

/* Write rows */
foreach ($messages as $sms) {
  $row = array(
    $sms->from,
    $sms->to,
    $sms->body,
    $sms->status,
    $sms->dateSent->format('Y-m-d H:i:s \G\M\T'),
    $sms->sid
  );

  echo '"'.implode('","', $row).'"'."\n";
}

A: Don't write your own serializers, the ones that already exist have logic for escaping built in already, cover all cases, and cover them properly.
https://www.php.net/manual/en/function.fputcsv.php
"But I'm not writing to a file!" yes, you are. Everything is a file.
Replace your echo with:
fputcsv(STDOUT, $row);


text:
Q: How deep Is it possible to control colour font in subsections? I am using this suggestion How to add an extra level of sections with headings below \subsubsection to use more level of sections and I would like to control the font colour as well.
I tried this so far
\documentclass{article}
\usepackage[utf8]{inputenc}

%\usepackage[utf8]{inputnc}

\usepackage{xcolor}

\usepackage{sectsty}

\usepackage{titlesec}
\usepackage{hyperref}

\titleclass{\subsubsubsection}{straight}[\subsection]

\newcounter{subsubsubsection}[subsubsection]
\renewcommand\thesubsubsubsection{\thesubsubsection.\arabic{subsubsubsection}}
\renewcommand\theparagraph{\thesubsubsubsection.\arabic{paragraph}} % optional; useful if paragraphs are to be numbered

\titleformat{\subsubsubsection}
  {\normalfont\normalsize\bfseries}{\thesubsubsubsection}{1em}{}
\titlespacing*{\subsubsubsection}
{0pt}{3.25ex plus 1ex minus .2ex}{1.5ex plus .2ex}

\makeatletter
\renewcommand\paragraph{\@startsection{paragraph}{5}{\z@}%
  {3.25ex \@plus1ex \@minus.2ex}%
  {-1em}%
  {\normalfont\normalsize\bfseries}}
\renewcommand\subparagraph{\@startsection{subparagraph}{6}{\parindent}%
  {3.25ex \@plus1ex \@minus .2ex}%
  {-1em}%
  {\normalfont\normalsize\bfseries}}
\def\toclevel@subsubsubsection{4}
\def\toclevel@paragraph{5}
\def\toclevel@paragraph{6}
\def\l@subsubsubsection{\@dottedtocline{4}{7em}{4em}}
\def\l@paragraph{\@dottedtocline{5}{10em}{5em}}
\def\l@subparagraph{\@dottedtocline{6}{14em}{6em}}
\makeatother

\sectionfont{\color{blue}}
\subsectionfont{\color{orange!90!black}}
\subsubsectionfont{\color{orange!70!white}}
\subsubsubsectionfont{\color{orange!50!white}}

\setcounter{secnumdepth}{4}
\setcounter{tocdepth}{4}

\title{test}

\begin{document}

\maketitle

\tableofcontents

\section{Introduction}
\subsection{Introduction}
\subsubsection{Introduction}
\subsubsubsection{Introduction}

\end{document}


text:
Q: Ignite cache transaction forcibly rolled back I'm using transactions for cache operations in Apache Ignite. I'm seeing warnings in my log where a transaction is forcibly rolled back. Like this:

16-02-2020 02:09:38.249 [-#115][157   ] WARN
  e.internal.processors.cache.distributed.near.GridNearTxLocal-[warning
  ][ 488] The transaction was forcibly rolled back because a timeout is
  reached:
  GridNearTxLocal[xid=fcdfebb4071-00000000-0b85-8094-0000-000000000005,
  xidVersion=GridCacheVersion [topVer=193298580, order=1581818772943,
  nodeOrder=5], concurrency=PESSIMISTIC, isolation=SERIALIZABLE,
  state=ROLLED_BACK, invalidate=false, rollbackOnly=true,
  nodeId=612b38ca-ffbf-46bf-a27b-00fc68555ff7, timeout=10000,
  duration=10006]

It looks like this warning appears in my log randomly and not related to my cache operations.
I'm starting my transaction with this:
Ignite ignite = Ignition.ignite();
IgniteTransactions transactions = ignite.transactions();
tx = transactions.txStart(TransactionConcurrency.PESSIMISTIC, TransactionIsolation.SERIALIZABLE, TRANSACTION_TIMEOUT, 0);

and ending:
  try
  {
      if (tx.state() == TransactionState.ACTIVE)
      {
          if (commit)
              tx.commit();
          else
              tx.rollback();
      }
  } catch (Exception e)
  {
      logger.error(String.format("Error ending transaction for thread(%d) with commit=%b", Thread.currentThread().getId(), commit));

      // re-throw
      throw new Exception(e);
  } finally
  {
      tx.close();
      tx = null;
  }

Why am I not getting the rollback-warning as a TransactionRollbackException on my transaction.commit() call? Isn't commit() supposed to wait until the transaction is fully done?

A: Maybe you never even reach commit(), instead of hanging on some operation earlier than that. You are not guaranteed to ever reach commit: instead, either locking up earlier, failing to catch unhandled error, or just doing busy work indefinitely.


text:
Q: Showing differentiability of the dot product Let $f: \mathbb{R}^n \times \mathbb{R}^n \rightarrow \mathbb{R}$ be defined as the dot product $f(a,b) = a \cdot b$. During the course of the proof, I have reduced the expression of the argument in the limit definition of differentiability to the following:
\begin{align*}
\frac{\left|{f(a+h_1, b + h_2}) - f(a,b) - Df(a,b)(h_1,h_2)\right|}{\|h\|}
&= \frac{\left|h_1 \cdot h_2 \right|}{||h||}\\
&\leq \frac{\|h_1|| \|h_2||}{\|h\|}
\end{align*}
The goal is to show that the LHS is bounded by something that converges to $0$ as $h$ goes to $0$. However, I can't figure out how to further bound the inequality, or how to show that the presented inequality tends toward $0$. Also, since $h \in \mathbb{R}^n \times \mathbb{R}^n$ is considered a 2-tuple of vectors, how does one interpret the norm of $h$ in the denominator?

A: Write
$$h_1 = (h_{1,1},...,h_{1,n})$$
and
$$h_2 = (h_{2,1},...,h_{2,n}).$$
Thus,
$$\|(h_1,h_2)\|^2 = \left(\sqrt{h_{1,1}^2 + \cdots + h_{1,n}^2 + h_{2,1}^2 + \cdots + h_{2,n}^2}\right)^2 = \|h_1\|^2 + \|h_2\|^2,$$
from where
$$\frac{\|h_1\|^2 + \|h_2\|^2}{\|(h_1,h_2)\|} = \|(h_1,h_2)\|.$$


text:
Q: Inject a translated string as an input in an angular 5 component I have an angular component template I want to inject title as an @Input() into, to be displayed as:
  <div class="title" >
    {{ title }}
  </div>

How do I inject the translated title into the parent component using ng2-translate's pipe, like so:
<title-component
    [title]="{{ 'KEY' | translate }}"
></title-component>

I want to pass the translated string dynamically to the child component, but I'd prefer to avoid injecting the translate service into the component's constructor and keep everything in the template, if possible. Thanks

A: {{}} are not required in inputs, so removing those should solve your issue


text:
Q: How to add Azure Monitor OpenTelemetry-based auto-instrumentation to Spring Boot Application? The documented way to add Azure Monitor OpenTelemetry to Java application is by downloading applicationinsights-agent-3.2.11.jar and using the following:
-javaagent:path/to/applicationinsights-agent-3.2.11.jar.
So in Spring Boot, the way it could possibly be run:
java -javaagent:path/to/applicationinsights-agent-3.2.11.jar -jar <jar-file.jar>.
But what happens if this path varies?
The problem is depending on the system it is running, and using maven (pom.xml) to get the artifact, how do we enable opentelemetry with applicationinsights-agent-3.2.11.jar since the location Maven stores the artifact changes from user accounts and computer?
Additionally, how do I specify a relative path to applicationinsights.json file for configuration (as Azure looks for this file inside the applicationinsights-agent-3.2.11.jar directory)?

If you specify a relative path, it will be resolved relative to the
directory where applicationinsights-agent-3.2.11.jar is located.

UPDATE
Regarding suggestions, How to define a relative path in java and this other suggested question
I am not looking to read files from relative paths.
The spring boot application needs to be invoked with a specific argument where it needs to be made aware of the location where maven downloads the the appinsights jar file.
Then when the app starts, the appinsights autoconfigure based on applicationinsights.json file, which once again, may vary by location.

A: Note that the latest applicationinsights-agent*.jar is available through GitHub and not through Maven repository. Therefore, I don't think that it can be downloaded as dependency to the project using the pom.xml
Now, the question here is not specific to ApplicationInsights agent, but for any java agent used for monitoring. The -javaagent parameter is supplied to JVM (java commandline) along with the path. Therefore, it will have to be supplied when JVM starts. How it is being setup would depend on the Server (or the standalone application) being used and its starting mechanism. One such solution is discussed here: How to attach a java agent on to a running spring-boot application. As there are many ways that the application can be deployed/run, the relative path would vary based on it.
If you are running standlone springboot application, you may also modify the mvnw or mvnw.cmd scripts to include %MAVEN_OPTS% with the -javaagent=agent path, where path could be relative to one of the variables defined in it, like %MAVEN_PROJECTBASEDIR%
Regarding the applicationinsights.json file, you can either have it in the same directory as the agent jar, OR set up environment variables to get the settings from there (instead of having the json file). You may refer to this link for details on available Environment variables to configure the agent. These environment variables can be set based on how/where the application is being deployed/run before the JVM initializes to make it available to javaagent.


text:
Q: Error in calculating speed using thread in Android package project.vtrac.tracker;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import android.app.Dialog;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class MapView extends FragmentActivity implements LocationListener {

    GoogleMap googleMap;
    private Double latitude;
    private Double longitude;
    private Double speed;
    private int curTime;
    private int lastTime;
    private Double lastLat;
    private Double lastLng;
    TextView msgArea;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mapview);

        checkGooglePlayService();
    }

    public void checkGooglePlayService()
    {
        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        // Showing status
        if(status!=ConnectionResult.SUCCESS) // Google Play Services are not available
        {
            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }
        else
        {
            createMap();
        }
    }

    public void createMap()
    {
        // Getting reference to the SupportMapFragment of map.xml
        SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        googleMap = mapFrag.getMap();

        // Enabling MyLocation Layer of Google Map
        googleMap.setMyLocationEnabled(true);
        googleMap.getUiSettings().setMyLocationButtonEnabled(false);
        googleMap.getUiSettings().setCompassEnabled(true);

        //Start location manager to start location updates
        startLocationUpdate();
    }

    public void startLocationUpdate()
    {
        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);

        if(location!=null){
            lastLat = location.getLatitude();
            lastLng = location.getLongitude();
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(provider, 5000, 10, this);
    }

    @Override
    public void onLocationChanged(Location location) {

        // Getting latitude of the current location
        latitude = location.getLatitude();

        // Getting longitude of the current location
        longitude = location.getLongitude();

        //get the current date time in reference to milliseconds from location.getTime()
        Date curDate = new Date(location.getTime());

        Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
        calendar.setTime(curDate);    //assign calender to given date

        //convert time to seconds
        curTime =  (int) ((calendar.get(Calendar.HOUR_OF_DAY)*60 + calendar.get(Calendar.MINUTE))*60 + calendar.get(Calendar.SECOND));

        // Creating a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);

        // Showing the current location in Google Map
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        // Zoom in the Google Map
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(16));
        msgArea = (TextView) findViewById(R.id.tv_msgArea);

        String msg;
        msg = "\tLatLong:" + latitude + "," + longitude+
                "\tLatLong:" + lastLat + "," + lastLng+
                "\t Speed:"+speed;
        msgArea.setText(msg);

      //calculateSpeed
        calculateSpeedThread();
        lastTime = curTime;
        lastLat = latitude;
        lastLng = longitude;
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }

    public void calculateSpeedThread()
    {
        Thread sThread = new Thread(null, doCalculateSpeed, "Speed Calculator");
        sThread.start();
    }

    private Runnable doCalculateSpeed = new Runnable()
    {
        public void run()
        {
            speed = calculateSpeed();
        }
    };

    public double calculateSpeed()
    {
        double R = 6371.00; // km
        double lat1 = lastLat * (Math.PI/180);
        double lat2 = latitude * (Math.PI/180);
        double lng1 = lastLng * (Math.PI/180);
        double lng2 = longitude * (Math.PI/180);
        double dLat = (lat2-lat1);
        double dLon = (lng2-lng1);

        double a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        double distance = R*c;
        double timeDiff = (double)(curTime-lastTime);

        //speed in km/hr
        return ((distance/timeDiff) * 60 * 60);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }}

My speed is returning null. I want some help with this!
Speed is fine without using thread but when I use thread to reduce function overhead call time, I need to use thread to calculate speed.
Is it problem with my thread programming or what?

A: I am not quite sure what you want but I found an error in your code. You are passing null as the first parameter while creating thread. Try not to use that. I think you can use,
MapView.this instead


text:
Q: python remove element containing namespace I am trying to remove an element in an xml which contains a namespace.
Here is my code:
templateXml = """<?xml version="1.0" encoding="UTF-8"?>
<Metadata xmlns="http://www.amazon.com/UnboxMetadata/v1">
<Movie>
        <CountryOfOrigin>US</CountryOfOrigin>
        <TitleInfo>
                <Title locale="en-GB">The Title</Title>
                <Actor>
                        <ActorName locale="en-GB">XXX</ActorName>
                        <Character locale="en-GB">XXX</Character>
                </Actor>
        </TitleInfo>
</Movie>
</Metadata>"""

from lxml import etree
tree = etree.fromstring(templateXml)

namespaces = {'ns':'http://www.amazon.com/UnboxMetadata/v1'}

for checkActor in tree.xpath('//ns:Actor', namespaces=namespaces):
    etree.strip_elements(tree, 'ns:Actor')

In my actual XML I have lots of  tags, So I am trying to search for the Actor tags which contain XXX and completely remove that whole  tag and its contents. But it's not working.

A: Use remove() method:
for checkActor in tree.xpath('//ns:Actor', namespaces=namespaces):
    checkActor.getparent().remove(checkActor)

print etree.tostring(tree, pretty_print=True, xml_declaration=True)

prints:
<?xml version='1.0' encoding='ASCII'?>
<Metadata xmlns="http://www.amazon.com/UnboxMetadata/v1">
<Movie>
        <CountryOfOrigin>US</CountryOfOrigin>
        <TitleInfo>
                <Title locale="en-GB">The Title</Title>
                </TitleInfo>
</Movie>
</Metadata>


text:
Q: BerryGSM connection through serial port I'm looking to use the GSM module BerryGSM
https://thepihut.com/products/ozzmaker-berrygps-gsm
It says on the website that you can use the serial port instead instead of the USB interface.
I'm looking to use this device without the USB connector.
The issue I'm having is that I can't find information on how to connect the device through the serial port, their are 2 header pins called PI_TX and PI_RX but not sure if they are for the serial communication?
I also have a copy of the schematic
http://ozzmaker.com/wp-content/uploads/2019/06/BerryGPS-GSM-Schematic-V1.4.pdf


text:
Q: Set spring security remember me cookie after login via facebook I am building a mobile web app that has the option to login via facebook/twitter. I want the app to remember the login via Spring security's remember me functionality so that the user need to have to login frequently.
I have the parts that will call out to facebook and get the access_token that will identify the user. I can login the user using

    SecurityContextHolder.getContext().setAuthentication(
        new UsernamePasswordAuthenticationToken(principal, credentials, authorities));

I am trying to use similar approach to add remember me functionality by

    RememberMeAuthenticationToken auth = new RememberMeAuthenticationToken(key, principal, authorities);
    SecurityContextHolder.getContext().setAuthentication(auth);

While this logs in the user, it does not set the remember me cookie. What am I missing here?
Thanks!

A: Try to inject the implementation of RememberMeServices interface and then try to do:
rememberMeServices.loginSuccess(request, response, auth);

Be sure that _spring_security_remember_me parameter is present in the request.


text:
Q: Simple partial fractions questions with fractions in the numerator.
$$ \dfrac{1}{\left(x+1\right)\left(2x+1\right)}$$

Using the cover up rule, I received the answer of $$\dfrac{\dfrac{1}{2}}{2x+1}-\frac{1}{x+1}$$
or
$$\dfrac{1}{2(2x+1)}-\frac{1}{x+1}$$
Answer at the back of the book says:
$$\dfrac{2}{2x+1}-\frac{1}{x+1}$$
I may have a gap in my knowledge  here, how did the book receive that answer?

A: We have $$\frac{1}{(2x+1)(x+1)} \equiv \frac{A}{2x+1} + \frac{B}{x+1}$$
So, multiply through by $(2x+1)(x+1)$ to get $$1 = A(x+1) + B(2x+1)$$
Let $x = -1$ to get $1 = B \cdot -1 \iff B = -1$
Let $x = -\frac{1}{2}$ to get $\frac{A}{2} = 1 \iff A = 2$.
So, replacing your values of $A$ and $B$ into the first equation we get:
$$\bbox[8px, border:2px lightblue solid]{\frac{1}{(2x+1)(x+1)} \equiv \frac{2}{2x+1} - \frac{1}{x+1}}$$

A: Suppose $\displaystyle \frac{1}{(x+1)(2x+1)}=\frac{A}{x+1}+\frac{B}{2x+1}$.
Then by equating the numerators, $1=2Ax+A+Bx+B$.
Now comparing coefficients, $A=-1$ and $B=2$.


text:
Q: How do you find all references to a method or property in Xcode? If you have a method, e.g., loadMediaImages in a .h file, how do you find all references to that method in the project? In Visual Studio there is a "Find All References" option on the content menu when you highlight and click the method name. Anything similar in Xcode?

A: Using the "Search Navigator" it's possible to search for symbol references within a project or workspace. Click on the little magnifying glass icon in the search box to "Show Find Options", and then select the Style: Symbol References.

Note: This is in Xcode 4.6, but may have been present in earlier versions.

A: I was looking for similar option. I do not know why Xcode did not included that.
But there is a work around I use until Apple give that option in Xcode.
Try this in the source code (.m) file,
Select the symbol, right click -> Refactor -> Rename
-> Give a name whatever you wish, then press Preview.

Now you can see all the references. You can Cancel/do not rename it. :)
Or press Cmd + Shift + F, and choose optons Find > References > Matching or Containing. But it will search all text with similar name. Not elegant like Refactoring.

A: You could do a search in the whole project... I don't have a screen ready but I know Xcode can.

A: If I'm not mistaken, Xcode 4 (not sure about previous versions) does not support a Find All References search. You can perform a text search within the entire project by pressing Shift+Cmd+F (Find in Workspace in the Edit menu), but this does not find exact "references", just matching text. You're best bet is using the Refactoring menu, as talked about in Finding all references of a variable or a method in Xcode4, but it is not very clean and requires more work than it should.

A: Haven't seen this in Xcode. Just FYI you are able to do that with AppCode though.

A: Find selected symbol in workspace is what you need

*

*right click on the method/property -> Find -> Find selected symbol in workspace

*focus the property/method and press ⇧ + ⌃ + ⌘ + F (or you can have a custom one)

Does basically the same search as Refactor -> Rename does


text:
Q: Как реализовать отображения и редактирования различных данных в одном стобце модели? Есть иерархическая структура данных. Данные хранят в себе переменные разных типов (как стандартные Qt-ые типы, так и кастомные).
С моделью для такой структуры проблем нет. А представление должно быть по типу инспектора объектов в Qt дизайнере. Сложность заключается в том, что нужно в зависимости от типа переменных отображать значения этих переменных (возможно даже кнопки и т.д. вместе с текстом или без) и редактировать их. Во всех книжках и примерах используют делегаты только для определенных столбцов или строк модели. Для столбцов с разными данными можно выкрутиться конструкциями типа if else с проверкой типа у QVariant, что не есть гуд. Нужно, чтобы делегат автоматически отрисовывал значение типа и возвращал нужный редактор. Также нужно, что бы элементы, имеющие потомков, отображались и реагировали на действия пользователя отлично от элементов без потомков.
Нашел QtPropertyBrowser (с помощью него сделан инспектор объектов в Qt дизайнере), но он отображает только стандартные Qt-ые типы, в исходниках какой-то ад,  а также по нему нет документации и вообще походу забит болт еще со времен Qt4, ибо версию с гитхаба Qt я скомпилить так и не смог, а получилось скомпилить только версию для Qt4, которую кто-то давным давно портировал под Qt5. Есть еще либа QtnProperty, но на нее нет документации, только статья на хабре и парочка инструкций на гитхабе. Сборка этой либы у меня получается только статическая, что мне не подходит. Да и мне кажется можно сделать все проще и легче, чем там.
Есть мысля сделать делегат с фабрикой редакторов и рисовальщиков для различных типов данных(Что-то типа как в QtnProperty). Для каждого типа данных в фабрике регистрируем редактор и рисовальщик(либо делегата, который будет иметь методы создания редактора и отрисовки, в общем способы есть разные).
Примерный код, показывающий идею, представлен ниже.
class TypePainter;
class DelegateFactory;

class CustomDelegate : public QStyledItemDelegate
{
    Q_OBJECT

public:
    CustomDelegate (QWidget *parent = 0) : QStyledItemDelegate(parent) {}

    void paint(QPainter *painter, const QStyleOptionViewItem &option,
                         const QModelIndex &index) const
   {
      QString name = typeNameForIndex(index);
      TypePainter  * painter = delegateFactory->createPainter(name);
      painter >paint(painter, option, index);
    }

   QWidget * createEditor(QWidget *parent,
                                    const QStyleOptionViewItem &option,
                                    const QModelIndex &index) const

   {
      QString name = typeNameForIndex(index);
      QWidget * editor = delegateFactory->createEditor(name);
      return editor;
   }

   //...

private:

   DelegateFactory * m_delegateFactory;
};

class DelegateFactory
{

public:
    DelegateFactory ();

   QWidget * createEditor(const QString & typeName);
   TypePainter * createPainter(const QString & typeName);

   //...

private:

   QMap<QString, QWidget *> m_editors;
   QMap<QString, TypePainter *> m_painters;
};

class TypePainter
{

public:
    TypePainter ();

   virtual void paint(QPainter *painter, const QStyleOptionViewItem &option,  const QModelIndex &index) = 0;
};

Получить имя типа можно из индекса разными способами. Либо через QVariant, но тогда придется регать кастомный тип в QVariant. Либо хранить имя типа в данных, и из индекса получать указатель на данные.
Имеет ли смысл так делать и есть ли другие варианты?


text:
Q: PDO - using same query for multiple foreach loops I have two foreach loops in my code that use the same query, so I was wondering if I could just make the query at the beginning of the page and just call it later in the code so I only have to access the database once.  I tried this and the first loop went through but the second one did not.  Is there a way to only query once but use it in two foreach loops?  This is what I thought might be the answer:
$sql = "SELECT * FROM champs WHERE $role = '1' ORDER BY id";
if (!empty($role)) {
$champs = $db->query($sql);
}

Some HTML
if (!empty($role)) {
foreach($champs as $row) {
     echo   '

'.$row['name'].'

';
}
}

Some more HTML
if (!empty($role)) {
foreach($champs as $row) {
     echo   '

'.$row['name'].'

';
}
}

A: Try this
    $sql = "SELECT * FROM champs WHERE $role = '1' ORDER BY id";
    if (!empty($role)) {
            $champs = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    }

This will convert your results to an array which you can use as  you like. Also you must check for isset($champs) or !empty($champs) before using it.


text:
Q: How do I send Alt+Ctrl+F1 through Synergy? I use Synergy to control both of my desktops from the same keyboard and mouse.  Is there a way to send Alt+Ctrl+F1 (or related combinations) to the client desktop using Synergy?
I tried using the suggestion below, but got:
$ chvt 1
Couldn't get a file descriptor referring to the console

Other ideas?  I would still prefer a way to send the actual keystrokes over synergy, but if that's not possible, a work around that works will be accepted.

A: You need to run:
sudo chvt 1

Changing virtual tty's requires administrative privileges.

A: I don't know Synergy, but...
I guess with Alt+Ctrl+F1 you intend to switch from the X-Screen to the console.
First guess for synergy: that will not work.
But to answer that particular:
you can open up a terminal on the computer you want to invoke Alt+Ctrl+F1 and enter
chvt 1

to change to virtual terminal number 1.


text:
Q: javascript implementation of newton vs. bisection Out of curiosity, I want to verify that Newton is indeed faster than
bisection (for the cases it successfully converges) for solving nonlinear equations.
I implemented both out of textbook algorithms.
The function tested is:
 f(x) = 5*(x-0.4)*(x^2 - 5x + 10), with a simple real root 0.4

The convergence accuracy is set to 1e-4.
Newton starts at x0 = 0.5, converges in 2 iterations.
bisection starts with an interval [0,1], converges in 14 iterations.
I use performance.now() to measure the elapsed time of both methods.
SURPRISINGLY, with many tries, Newton is always slower than bisection.
Newton time: 0.265 msec: [0.39999999988110857,2]
bisection time: 0.145 msec: [0.399993896484375,14]

I ported the program to C (visual C): Newton is a lot faster than bisection.
These numerical codes are so simple that I cannot spot any weird thing going on.
Can anyone help?
http://jsfiddle.net/jmchen/8wvhzjmn/
// Horner method for degree-n polynomial
function eval (a, t) {

    // f(x) = a0+ a1x + ... + anxn
    var n = a.length - 1;// degree (n)
    var b = [];
    var c = [];
    var i, k;
    for (i = 0; i <= n; i++)
        b.push(0), c.push(0);

    b[n] = a[n];
    c[n] = b[n];
    for (k = n-1; k >= 1; k--) {
        b[k] = a[k] + t*b[k+1];
        c[k] = b[k] + t*c[k+1];
    }
    b[0] = a[0] + t*b[1];

    return [b[0],c[1]];
}

// simple Newton
function Newton (eval, x0, epsilon) {
    var eps = epsilon || 1e-4;
    var imax = 20;
    for (var i = 0; i < imax; i++) {
        var fdf = eval (coeff, x0);
        x1 = x0 - fdf[0]/fdf[1];
        if (Math.abs(x1 - x0) < eps)
            break;
        x0 = x1;
    }
    return [x1, i];  // return [approx. root, iterations]
}

// simple bisection
function bisection (func, interval, eps) {
    var xLo = interval[0];
    var xHi = interval[1];

    fHi = func(coeff,xHi)[0];   // fb
    fLo = func(coeff,xLo)[0];   // fa
    if (fLo * fHi > 0)
        return undefined;

    var xMid, fHi, fLo, fMid;
    var iter = 0;
    while (xHi - xLo > eps) {
        ++iter;
        xMid = (xLo+xHi)/2;
        fMid = func(coeff,xMid)[0];  // fc

        if (Math.abs(fMid) < eps)
            return [xMid, iter];

        else if (fMid*fLo < 0) { // fa*fc < 0 --> [a,c]
            xHi = xMid;
            fHi = fMid;
        } else {  // fc*fb < 0 --> [c,b]
            xLo = xMid;
            fLo = fMid;
        }
    }

    return [(xLo+xHi)/2, iter];
}

// f(x) = 5x^3 - 27x^2 + 60x - 20
//      = 5*(x-0.4)*(x^2 - 5x + 10)
var coeff = [-20,60,-27,5];

var t0 = performance.now();
var sol1 = Newton (eval, 0.5, 1e-4);
var t1 = performance.now();
var sol0 = bisection (eval, [0,1], 1e-4);
var t2 = performance.now();

console.log ('Newton time: '+ (t1-t0).toFixed(3) +  ': ' + sol1);
console.log ('bisection time: '+ (t2-t1).toFixed(3) + ': ' + sol0);

A: There are many external factors that can influence that test, including the order in which your code gets JIT compiled, and caching. Measuring time on such a small number of iterations isn't very meaningful, as those external factors may end up being bigger than what you're trying to measure.
For example, if you invert the order so it calculates bisection before it calculates Newton, you get the opposite result.
If you want to do it better, perhaps run both once, then do a loop to run both again N times, and measure how long it takes to run that loop.


text:
Q: Can the average of a set be lower than all of the averages of subsets? Let's imagine there are marbles of different diameter and color. Can the average diameter of all the marbles be lower than all of the average diameter of marbles per color?

A: Let $S \subseteq \mathbb{R}$ be a finite set. Let $P = \{C_1,C_2,…,C_n\}$ be a partition of $S$. This partition represents the color groupings of the marbles. Also assume that $\overline{C_i} \leq \overline{C_{i+1}}$ for $1 \leq i < n$, where $\overline{C_i}$ denotes the average of $C_i$.
Notice:
$$\overline{S} = \frac{|C_1|\overline{C_1}    + |C_2|\overline{C_2} + … + |C_n|\overline{C_n}}{|S|}$$
And since $\overline{C_i} \geq \overline{C_1}$ for all $1 \leq i < n$ we have:
$$\overline{S} \geq \frac{|C_1|\overline{C_1}    + |C_2|\overline{C_1} + … + |C_n|\overline{C_1}}{|S|}$$
Now factoring out $\overline{C_1}$ and using the fact that $P$ partitions $S$:
$$\overline{S} \geq \overline{C_1}$$


text:
Q: Why is my use of telnet towards a web server providing inconsistent results to others with the same approach? I'm trying to use port 80 to connect to a website(www.ucf.edu), and send a GET request, but I'm getting inconsistent results to other students using the same exact methods. We had to use SSH to connect securely to our schools server before doing this. When connected, we're instructed to send a get request "GET /index.html HTTP/1.1" when I send this I get inconsistent results.
I've tried using Putty on windows, and command prompt of ubuntu on a virtual machine, to no avail.
Expected Result:
telnet www.ucf.edu 80
Trying 10.171.52.44
Connected to www.ucf.edu.
Escape character is '^]'.
GET /index.html HTTP/1.1\r\n
HTTP/1.1 302 Found
Server: Apache
Location: https://www.ucf.edu/index.html
etc. etc.
Actual Result:
telnet www.ucf.edu 80
Trying 52.5.147.12...
Connected to edums-dr-alb-211439321.us-east-1.elb.amazonaws.com.
Escape character is '^]'.
GET /index.html HTTP/1.1\r\n
HTTP/1.1 400 Bad Request
Server: awselb/2.0
Date: Thu, 03 Oct 2019 05:49:42 GMT

A: For you www.ucf.edu resolves to a different IP-address (public internet instead of a private 10.xx.xx.xx address). And obviously that is a different server.
You mentioned that you had to login with SSH to a school server first.
I presume that you are supposed to run the telnet command from within that SSH session while connected to the school server (and in that case you don't get the real www.ucf.edu on the internet but a test-environment that uses the 10.xx.xx.xx private address).
However you mentioned you get same results from Windows and Linux so I can only presume you are NOT logged in to the SSH server when you do this. (If you were connected to the SSH the client OS wouldn't make any difference.)
Or you did login, but logged out again which you shouldn't have done.
So you better check the instructions carefully. Because I'm fairly sure you missed a step along the way. Or took a step too many.

A: You are getting 400 Bad Request because it is actually a bad request.
The HTTP/1.1 request needs at least the Host: <URL> specification in the next line. It is because when you connect to that particular IP address, that particular physical server might be serving multiple domains; and if you don't specify it, the server doesn't know which domain you request. So the correct request goes like:
GET /index.html HTTP/1.1
Host: www.ucf.edu

(followed by empty line), and the whole session looks like:
artax:~> telnet www.ucf.edu 80
Trying 52.5.147.12...
Connected to educms-dr-alb-211439321.us-east-1.elb.amazonaws.com.
Escape character is '^]'.
GET /index.html HTTP/1.1
Host: www.ucf.edu

HTTP/1.1 301 Moved Permanently
Date: Fri, 04 Oct 2019 07:44:49 GMT
Content-Type: text/html; charset=iso-8859-1
Content-Length: 238
Connection: keep-alive
Server: Apache
Location: https://www.ucf.edu/index.html
Accept-Ranges: bytes
X-Varnish: 2087970732
Age: 0
Via: 1.1 varnish
X-Cache: MISS
X-Varnish-Server: DR-VLAMP-4

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>301 Moved Permanently</title>

Moved Permanently

The document has moved here.

Connection closed by foreign host.


text:
Q: How to rotate iOS app only on iPhone 6+ My application is on iPhone in portratit mode. I have also iPad version, that can rotate. Now, with new iPhone 6+, I would like to rotate my app. I have found any problems / solutions regarding this issue.
There are two ways that I can think of
a) better solution (imho) - enable rotation only for certain device. Can it be done without editing code somewhere in project setting ?
b) use iPad version of storyboard on iPhone6+ instead of classic iPhone version of storybaod. Can it be done from within XCode storyboard or project settings, or do I have to do this in my code? I have found no other solution, that to load certain storyboard in code based on device identification.

A: Here's an easy way to accomplish this. Just add the following to your UIApplicationDelegate:
-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    static UIInterfaceOrientationMask rv = 0;
    if( rv == 0 ) {
        if( [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone ) {
            CGSize s = window.bounds.size;
            if( MAX( s.width, s.height ) >= 700.0f ) {
                rv = UIInterfaceOrientationMaskAllButUpsideDown;
            } else {
                rv = UIInterfaceOrientationMaskPortrait;
            }
        } else {
            rv = UIInterfaceOrientationMaskAll;
        }
    }
    return rv;
}

A: The Apple recommended approach is to combine both iPhone and iPad storyboards into one and use Size Classes in that storyboards to change constraints based on the device/orientation.
As for enabling rotation in particular device - again you might check size classes inside your view controller or check for specific devices resolution. I don't think there is way to enable/disable it for device classes (iPhone 6 vs iPhone 6+) in the project settings.


text:
Q: Quais são as diferenças entre require() e library()? Em R, quais são as diferenças entre require() e library(), se houverem? Quando devo incluir o require() e quando devo incluir o library()?

A: A informação a seguir consta do próprio help da função require do R:

library(package) and require(package) both load the namespace of the package with name package and attach it on the search list. require is designed for use inside other functions; it returns FALSE and gives a warning (rather than an error as library() does by default) if the package does not exist

Ou seja, se sugere que require seja utilizada dentro de outras funções, pois ela retorna um warning caso o pacote a ser carregado não conste no sistema. O comando library, por padrão, retorna um erro quando o pacote não está instalado.
Não há diferença para quem for usar estas funções no dia a dia. As duas fazem a mesma coisa.

A: Na execução pura destes comandos não há diferença, mas com o comando require é possível automatizar a verificação da presença do pacote e somente depois disso, acontece instalação deste, pois ele retorna TRUE ou FALSE, segue exemplo para instalar o pacote "datamap":
inst_pacote <- require(datamap)
if (inst_pacote == FALSE) {
        install.packages("datamap")
}


text:
Q: Configuring juju for MAAS 2.0 I'm trying to understand cloud architecture better and decided to setup a private cloud using ubuntu 16.04.
I found this (seemingly) nice guide on setting up a private cloud using MAAS, juju and openstack, and managed to get through the first step of setting up MAAS and connecting some nodes.
https://help.ubuntu.com/lts/clouddocs/en/Intro.html?_ga=1.56396459.1002047384.1448462651
Now I've proceeded to setup juju, and hit a snag at the following step:
Configuring Juju to work with MAAS
3. Edit the Juju environments.yaml file

https://help.ubuntu.com/lts/clouddocs/en/Installing-Juju.html
It seems that the version of juju (2.0-beta15-xenial-amd64) that ubuntu 16.04 grabs no longer has the 'generate_config' command.  I've started following this guide mentioned in a response to a question about the 'generate_config' issue, but this is not MAAS specific.
ERROR unrecognized command: juju generate-config
At the moment, I've gone through the steps up to and including executing the sudo lxd init command.  However, in attempting to run the juju bootstrap lxd-precrime localhost command as described in the guide, but now I'm getting the following errors:
$ juju bootstrap lxd-precrime localhost
ERROR cannot find network interface "lxdbr0": route ip+net: no such network interface
ERROR invalid config: route ip+net: no such network interface

Do I need to continue with this step if I want to integrate juju with MAAS, or is there a way to continue to integrate with MAAS without resolving this networking issue?

A: The guide on help.ubuntu.com is for juju < 2.0.
Re lxd error, did you follow the entire getting-started guide?
The above guide sets up a "cloud" based on LXD, not MAAS.

A: Apparently, my problem was that I needed to first assign an 'network' properly to the 'Ready' nodes.
After assigning the network the next problem was 'no storage defined'.  This was resolve by re-commissioning (after setting the network) and manually power cycling the nodes.


text:
Q: Issue updating infowindow Carto I have a problem with the infowindow of one of my sublayers in a Carto map. First of all I'll show my code. I create the layer options and then I get my sublayer. I set its options and a first version of the infowindow. After that, I create the event onclick, what changes the infowindow based on a variable I've declared before.
var subLayerOptions2 = {
          sql: "SELECT * FROM zonas WHERE cartodb_id IN (SELECT zonaid FROM devices_zonas WHERE deviceid IN (SELECT deviceid FROM users_devices WHERE userid=" + this.auth.getUserId() + "))",
          cartocss: "#layer {polygon-fill: " + ConstantesColores.colores[3] + "; polygon-opacity: 0.25; line-color: " + ConstantesColores.colores[3] + "; line-width: 1; line-opacity: 1;}",
          interactivity: ['cartodb_id']
}

// Creacion e introduccion del layer en el mapa
var sublayer2 = layer.getSubLayer(2);
sublayer2.set(subLayerOptions2);
sublayer2.infowindow.set('template', infow);
sublayer2.on('featureClick', (e, latlng, pos, data, layer) => {
              sublayer2.infowindow.set('template', infow.replace("#DispAsociados#", arrayZonasConDisp[data.cartodb_id].info));
              alert("Hey! You clicked " + data.cartodb_id);
});
sublayers.push(sublayer2);

The problem is that, the first time I click an element of the map, the infowindow is not updating well, the variable is empty, but when I click a second time it appears well. If I change the element I click, the first time appears the info corresponding to the last click, not this one. It's like a delay. It always show the info of the previous one.
Does anyone know why this happens?


text:
Q: Middleware function doesnt exist In my web.php I have a route
Route::get('summary_average_fee', 'Summary@AverageFee')->middleware('CheckParams@dateLimits');

Im trying to refrence the dateLimits function in the CheckParams class
My CheckParams class, saved as CheckParams.php in the Middleware folder
<?php

namespace App\Http\Middleware;

use Closure;

class CheckParams
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function dateLimits($request, Closure $next)
    {
        isEmpty($request->input('startDate'), 'NO_START_DATE');
        isEmpty($request->input('endDate'), 'NO_END_DATE');

        return $next($request);
    }

    private function isEmpty($value, $error, $status)
    {
        if(empty($value))
        {
            return response()->json($error, 422);
        }
    }
}

In the kernal.php file I add this to the routeMiddleware array
'CheckParams' => \App\Http\Middleware\CheckParams::class

When it runs, I get the error that Class CheckParams@dateLimits does not exist

A: Seems to me that your middleware should be rewritten and update the usage:
use App\Http\Middleware\CheckParams;

Route::get('summary_average_fee', 'Summary@AverageFee')->middleware(CheckParams::class);

Middleware:
namespace App\Http\Middleware;

use Closure;

class CheckParams
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $this->isEmpty($request->input('startDate'), 'NO_START_DATE');
        $this->isEmpty($request->input('endDate'), 'NO_END_DATE');

        return $next($request);
    }

    private function isEmpty($value, $error, $status)
    {
        if(empty($value))
        {
            return response()->json($error, 422);
        }
    }
}


text:
Q: What is the more efficient algorithm to equalize a vector? Given a vector of n elements of type integer, what is the more efficient algorithm that produce the minimum number of transformation step resulting in a vector that have all its elements equals, knowing that :

*

*in a single step, you could transfer at most one point from element to its neighbours ([0, 3, 0] -> [1, 2, 0] is ok but not [0, 3, 0] -> [1, 1, 1]).

*in a single step, an element could receive 2 points : one from its left neighbour and one from the right ([3, 0 , 3] -> [2, 2, 2]).

*first element and last element have only one neighbour, respectively, the 2nd element and the n-1 element.

*an element cannot be negative at any step.

Examples :
Given :
 0, 3, 0
Then 2 steps are required :
 1, 2, 0
 1, 1, 1

Given :
 3, 0, 3
Then 1 step is required :
 2, 2, 2

Given :
 4, 0, 0, 0, 4, 0, 0, 0
Then 3 steps are required :
 3, 1, 0, 0, 3, 1, 0, 0
 2, 1, 1, 0, 2, 1, 1, 0
 1, 1, 1; 1, 1, 1, 1, 1

My current algorithm is based on the sums of the integers at each side of an element. But I'm not sure if it produce the minimum steps.
FYI the problem is part of a code contest (created by Criteo http://codeofduty.criteo.com) that is over.

A: Here is a way. You know the sum of the array, so you know the target number in each cell.
Thus you also know the target sum for each subarray.
Then iterate through the array and on each step you make a desicion:

*

*Move 1 to the left: if the sum up to the previous element is less then desired.

*Move 1 to the right: if the sum up to the current element is more than desired

*Don't do anything: if both of the above are false

Repeat this until no more changes are made (i.e. you only applied 3 for each of the elements).
    public static int F(int[] ar)
    {
        int iter = -1;
        bool finished = false;
        int total = ar.Sum();

        if (ar.Length == 0 || total % ar.Length != 0) return 0; //can't do it
        int target = total / ar.Length;

        int sum = 0;

        while (!finished)
        {
            iter++;
            finished = true;
            bool canMoveNext = true;

            //first element
            if (ar[0] > target)
            {
                finished = false;
                ar[0]--;
                ar[1]++;

                canMoveNext = ar[1] != 1;
            }

            sum = ar[0];
            for (int i = 1; i < ar.Length; i++)
            {
                if (!canMoveNext)
                {
                    canMoveNext = true;
                    sum += ar[i];
                    continue;
                }

                if (sum < i * target && ar[i] > 0)
                {
                    finished = false;
                    ar[i]--;
                    ar[i - 1]++;
                    sum++;
                }
                else if (sum + ar[i] > (i + 1) * target && ar[i] > 0) //this can't happen for the last element so we are safe
                {
                    finished = false;
                    ar[i]--;
                    ar[i + 1]++;

                    canMoveNext = ar[i + 1] != 1;
                }

                sum += ar[i];
            }
        }

        return iter;
    }

A: I've got an idea. I'm not sure it produces the optimal result, but it feels like it can.
Suppose the initial vector is the N-sized vector V. You need two additional N-sized vector :

*

*In the L vector, you sum elements starting from the left : L[n] = sum(i=0;i<=n)  V[n]

*In the R vector, you sum elements starting from the right: R[n] = sum(i=n;i<N) V[n]
You finally need one last specific value : the sum of all the elements of V is supposed to be equal to k*N with k an integer. And you have L[N-1] == R[0] == k*N
Let's take the L vector. The idea is that for any n, consider the V vector divided in two parts, one from 0 to n, and the other contains the rest. If L[n]<n*k, then you've got to "fill" the first part with values from the second part. And vice versa if L[n]>n*k. If L[i]==i*k, then congratulations, the problem can be subdivided in two subproblems! There is no reason for any value from the second vector to be transferred to the first vector, and vice-versa.
Then, the algorithm is simple : for every value of n, check the value of L[n]-n*k and R[n]-(N-n)*k and act accordingly. There is just one special case, if L[n]-n*k>0 and R[n]-(N-n)*k>0 (there is a high value at V[n]), you must empty it in both directions. Just choose at random a direction to tranfer.
Of course, don't forget to update L and R accordingly.
Edit : In fact, it seems that you only need the L vector. Here is a simplified algorithm.

*

*If L[n]==n*k, don't do anything

*If L[n]<n*k, then transfer one value from V[n+1] to V[n] (if V[n+1]>0 of course)

*If L[n]>n*k, then transfer one value from V[n] to V[n+1] (if V[n]>0 of course)

And (the special case) if you're asked to tranfer from V[n] to V[n-1] and V[n+1], just tranfer randomly once, it won't change the final result.

A: Thanks to Sam Hocevar, for the following alternative implementation to the fiver's one :
public static int F(int[] ar)
{
    int total = ar.Sum();

    if (ar.Length == 0 || total % ar.Length != 0) return 0; //can't do it
    int target = total / ar.Length;

    int[] left = new int[ar.Length];
    int[] right = new int[ar.Length];
    int maxshifts = 0;
    int delta = 0;
    for (int i = 0; i < ar.Length; i++)
    {
        left[i] = delta < 0 ? -delta : 0;
        delta += ar[i] - target;
        right[i] = delta > 0 ? delta : 0;
        if (left[i] + right[i] > maxshifts) {
            maxshifts = left[i] + right[i];
        }
    }

    for (int iter = 0; iter < maxshifts; iter++)
    {
        int lastleftadd = -1;

        for (int i = 0; i < ar.Length; i++)
        {
            if (left[i] != 0  && ar[i] != 0)
            {
                ar[i]--;
                ar[i - 1]++;
                left[i]--;
            }
            else if (right[i] != 0 && ar[i] != 0
                              && (ar[i] != 1 || lastleftadd != i))
            {
                ar[i]--;
                ar[i + 1]++;
                lastleftadd = i + 1;
                right[i]--;
            }
        }
    }

    return maxshifts;
}


text:
Q: Is ./ really needed for pathing? I'm wondering if the ./ in paths are really needed since,
./myfile.jpg
myfile.jpg

If both targets the current folder. Why are ./ sometimes used and sometimes it isn't used? Are there advantages or bugs it fixed when uploaded to a root server vs sub-domains or other reasons?

A: ./ means the current working directory. You can just reference the file directly by name, without it.
. = This location
.. = Up a directory

It means that ./foo.html is just foo.html. And it is optional, but it may have relevance if a script generated the path (relevance to the script that is, not how the reference works). You can omit it by the way. It's useful only for clarity. There is no functional difference between it being there and not being there.
You can use the following list as quick reference:
/ = Root directory
. = This location
.. = Up a directory
./ = Current directory
../ = Parent of current directory
../../ = Two directories backwards


text:
Q: How to change/update Dynamics crm entity record data and state from Active to Inactive with Javascript I have issues with changing the state, status and additional data for  Entity Record (Dynamics CRM 2015).
. I am trying to update the data in just created Entity record.
But all the time I get Bad Request. Please help me!?
this is my code.

*

*Entity name: "Send Email Campaign"

*Entity Schema Name: "concep_emailcampaign"

*Record test name: 19/05/17-2

function CreateInactiveEmailCampaign(data) {

    var emailcampaignId, EmailCampaignName;
    var context = Xrm.Page.context;
    var serverUrl = Xrm.Page.context.getClientUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    var CRMObject = new Object();
    /////////////////////////////////////////////////////////////
    // Specify the ODATA entity collection
    var ODATA_EntityCollection = "/concep_emailcampaignSet";
    /////////////////////////////////////////////////////////////

    CRMObject.concep_name               = data.Name;
    EmailCampaignName                   = data.Name;
    CRMObject.concep_Subject            = data.Subject;
    CRMObject.concep_SentDateTime   = data.sentdatetime;
    CRMObject.concep_Recipients   = data.recipientsCount;
    CRMObject.concep_CampaignID   = data.CampaignID;
    CRMObject.concep_CampaignCode   = data.CampaignCode;

    //Parse the entity object into JSON
    var jsonEntity = window.JSON.stringify(CRMObject);
    //Asynchronous AJAX function to Create a CRM record using OData
    $.ajax({ type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection,
        data: jsonEntity,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            //alert("success");
            debugger;
            var NewCRMRecordCreated = data["d"];
            ChangeRecordStatus(NewCRMRecordCreated, 1, 2, serverUrl);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("failure");
        }
    });
}
function ChangeRecordStatus(data, stateCode, statusCode, serverUrl) {
 // I need to update the record with
    //CRMObject.statecode    = {}
    //CRMObject.statecode.Value   = 1;    //Inactive
    //CRMObject.statuscode    = {Value:2}
    //CRMObject.statuscode.Value  = 2;    //Inactive
    //CRMObject.concep_Campaign   = {}
    //CRMObject.concep_Campaign.Id   = data.Campaign;
    //CRMObject.concep_SendAccount  = {}
    //CRMObject.concep_SendAccount.Id  = data.SendAccount;
    //CRMObject.concep_SendAccount.LogicalName  = data.SendAccount;
    //CRMObject.concep_SendAccount.Name  = data.SendAccount;
    //CRMObject.concep_ResponsesTotal = ''
    //CRMObject.concep_ResponsesToRecipientsRate = ''
    //CRMObject.concep_concep_emailcampaign_list = ''
    //CRMObject.concep_emailcampaign_campaign. = ''
    //CRMObject.concep_emailcampaign_sendaccount. = ''
    //CRMObject.concep_surveyresponse_emailcampaign. = ''
    //CRMObject.user_concep_emailcampaign. = ''
 var serverUrl = serverUrl;
 var RECORD_ID = data.concep_emailcampaignId
 var EntityLogicalName = data.concep_name;
   var request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    request += "<s:Body>";
    request += "<Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
    request += "<request i:type=\"b:SetStateRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
    request += "<a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
    request += "<a:KeyValuePairOfstringanyType>";
    request += "<c:key>EntityMoniker</c:key>";
    request += "<c:value i:type=\"a:EntityReference\">";
    request += "<a:Id>" + RECORD_ID + "</a:Id>";
    //request += "<a:LogicalName>" + EntityLogicalName + "</a:LogicalName>";
    request += "<a:Name i:nil=\"true\" />";
    request += "</c:value>";
    request += "</a:KeyValuePairOfstringanyType>";
    request += "<a:KeyValuePairOfstringanyType>";
    request += "<c:key>State</c:key>";
    request += "<c:value i:type=\"a:OptionSetValue\">";
    request += "<a:Value>" + stateCode + "</a:Value>";
    request += "</c:value>";
    request += "</a:KeyValuePairOfstringanyType>";
    request += "<a:KeyValuePairOfstringanyType>";
    request += "<c:key>Status</c:key>";
    request += "<c:value i:type=\"a:OptionSetValue\">";
    request += "<a:Value>" + statusCode + "</a:Value>";
    request += "</c:value>";
    request += "</a:KeyValuePairOfstringanyType>";
    request += "</a:Parameters>";
    request += "<a:RequestId i:nil=\"true\" />";
    request += "<a:RequestName>SetState</a:RequestName>";
    request += "</request>";
    request += "</Execute>";
    request += "</s:Body>";
    request += "</s:Envelope>";
    //send set state request
    $.ajax({
        type: "POST",
        contentType: "text/xml; charset=utf-8",
        datatype: "xml",
        url:  serverUrl + "/XRMServices/2011/Organization.svc/web",
        data: request,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
            XMLHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            alert("Success");
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
    alert(XMLHttpRequest);
             alert(errorThrown);
        }
    });
}

This may help: Active/Deactive Record using JS in CRM

A: The problem was a wrong Values that I sent to dynamics. In Microsoft Support page are set wrong values.
  var request = "" +
    "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>" +
    "    <s:Header>" +
    "        <SdkClientVersion xmlns='http://schemas.microsoft.com/xrm/2011/Contracts'></SdkClientVersion>" +
    "    </s:Header>" +
    "    <s:Body>" +
    "        <Execute xmlns='http://schemas.microsoft.com/xrm/2011/Contracts/Services' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>" +
    "            <request i:type='b:SetStateRequest' xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts' xmlns:b='http://schemas.microsoft.com/crm/2011/Contracts'>" +
    "                <a:Parameters xmlns:b='http://schemas.datacontract.org/2004/07/System.Collections.Generic'>" +
    "                    <a:KeyValuePairOfstringanyType>" +
    "                        <b:key>EntityMoniker</b:key>" +
    "                        <b:value i:type='a:EntityReference'>" +
    "                            <a:Id>" + RECORD_ID + "</a:Id>" +
    "                            <a:LogicalName>concep_emailcampaign</a:LogicalName>" +
    "                        </b:value>" +
    "                    </a:KeyValuePairOfstringanyType>" +
    "                    <a:KeyValuePairOfstringanyType>" +
    "                        <b:key>State</b:key>" +
    "                        <b:value i:type='a:OptionSetValue'>" +
    "                            <a:Value>1</a:Value>" +   //<----------
    "                        </b:value>" +
    "                    </a:KeyValuePairOfstringanyType>" +
    "                    <a:KeyValuePairOfstringanyType>" +
    "                        <b:key>Status</b:key>" +
    "                        <b:value i:type='a:OptionSetValue'>" +
    "                            <a:Value>-1</a:Value>" +   //<----------
    "                        </b:value>" +
    "                    </a:KeyValuePairOfstringanyType>" +
    "                    <a:KeyValuePairOfstringanyType>" +
    "                        <b:key>MaintainLegacyAppServerBehavior</b:key>" +
    "                        <b:value i:type='c:boolean' xmlns:c='http://www.w3.org/2001/XMLSchema'>true</b:value>" +
    "                    </a:KeyValuePairOfstringanyType>" +
    "                </a:Parameters>" +
    "                <a:RequestId i:nil='true' />" +
    "                <a:RequestName>SetState</a:RequestName>" +
    "            </request>" +
    "        </Execute>" +
    "    </s:Body>" +
    "</s:Envelope>";

A: May I know why you are using this approach - any specific reason? Bcoz, this can be achieved easily in UI workflow with no code.
Another approach you are doing now using JS. But from where you are calling this method - CreateInactiveEmailCampaign? On form load? or ribbon click?
You have to check the form type for update mode (refer: https://msdynamicscrmblog.wordpress.com/2013/12/11/get-form-types-and-modes-in-dynamics-crm-2013/). Otherwise create mode wont have RecordId.
Debug & see which line you are getting error.