text:
Q: How can I install and execute Elasticsearch? I want to install Elasticsearch.I downloaded this and I need to activate Elasticsearch.Actually,in command prompt,I executed this line in bin directory:
bin/elasticsearch.bat

As follows,I added screenshot of the command prompt.
https://drive.google.com/open?id=0BxZmkxB6kqAkdmt2MHRtOWJreTg
While commant prompt is open,this site executes.http://localhost:9200/
But when I closed command prompt,this site is not execute.

A: Instructions to install ES on windows can be found here:
https://www.elastic.co/guide/en/elasticsearch/reference/5.6/zip-windows.html#windows-service


text:
Q: How to find contours of soccer player in dynamic background My project is a designation for a system which analyze soccer videos.  In a part of this project I need to detect  contours of players and everybody in the play field. For all players which don't have occlusion with the advertisement billboards, I have used the color of play field (green) to detect contours and extract players. But I have problem with the situation that players or referee have occlusion with the advertisement billboards. Suppose a situation that advertisements on the billboards are dynamic (LED billboards). As you know in this situation finding the contours is more difficult because there is no static background color or texture. You can see two example of this condition in the following images.

NOTE: in order to find the position of occlusion, I use the region between the field line and advertisement billboards, because this region has the color of the field (green). This region is shown by a red rectangular in the following image.

I expect the result be similar to the following image.

Could anyone suggest an algorithm  to detect these contours?

A: You can try several things.

*

*Use vision.PeopleDetector object to detect people on the field. You can also track the detected people using vision.KalmanFilter, as in the Tracking Pedestrians from a Moving Car example.

*Use vision.OpticalFlow object in the Computer Vision System Toolbox to compute optical flow. You can then analyze the resulting flow field to separate camera motion from the player motion.

*Use frame differencing to detect moving objects. The good news is that that will give you the contours of the people. The bad news is that it will give you many spurious contours as well.

A: Optical Flow would work for such problems as it captures motion information. Foreground extraction techniques using HMM or GMM or non-parametric may solve the problem as I have used for motion analysis in surveillance videos to detect anomaly (Background was static). Magnitude and orientation of optical flow seems to be an effective method. I have read papers on segmentation using optical flow. I hope this may help you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot reach a dynamic page with puppeteer I need to read data on https://www.cmegroup.com/tools-information/quikstrike/options-calendar.html
I tried to click on FX tab from page.click in puppeteer, but the page remains on the default.
Any help welcome

A:     const puppeteer = require('puppeteer');

    let scrape = async () => {

    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();
    await page.goto('https://www.cmegroup.com/tools-information/quikstrike/options-calendar.html');

    await page.waitFor(1000);

//div select FX
        await page.click('#ctl00_MainContent_ucViewControl_IntegratedCMEOptionExpirationCalendar_ucViewControl_ucProductSelector_lvGroups_ctrl3_lbProductGroup');
    //browser.close();
    return result;
    };

    scrape().then((value) => {
    console.log(value); // Success!
    });

A: I couldn't find the element you're looking for on that page. However, this might be helpful:
Wait for the selector to appear on the page before clicking on it:
await page.waitForSelector(selector);

If still facing the issue, try using Javascript click method:
await page.$eval(selector, elem => elem.click());


text:
Q: Python: How to get Outer class variables from inner static class? I want to specify variable once by making instance Outer(variable), than this variable use in all static classes, how should I do that? Is there any other solution than use not static methods and pass Outer into each inner class?
class Outer():
    def __init__(self, variable):
        self.variable= variable

    class Inner1():
        @staticmethod
        def work1():
            **print Outer.variable**

    class Inner2():
        @staticmethod
        def work2():
            **print Outer.variable**

A: If you really want such thing, metaclass may help a little, for example:
from types import ClassType

class OuterMeta(type):
    def __new__(mcls, name, base, attr):
        ret = type.__new__(mcls, name, base, attr)
        for k, v in attr.iteritems():
            if isinstance(v, (ClassType, type)):
                v.Outer = ret
        return ret

class Outer(object):
    __metaclass__ = OuterMeta
    var = 'abc'
    class Inner:
        def work(self):
            print self.Outer.var
        @classmethod
        def work2(cls):
            print cls.Outer.var

then
>>> Outer.Inner.work2()
abc

A: No. Inner-class methods have no way of accessing instances of the outer class.


text:
Q: Saving check box values to the database I allow users to group contacts together using checkboxes in the new and edit forms:
<% current_user.contacts.all.each do |contact| %>
    <% checked = @group.contacts.include?(contact) %>
    <%= check_box_tag "contacts[]", contact.id, checked %>
    <%= f.label contact.name %>
<% end %>

Until recently, I was able to use the following code in create action to create a group:
def create
        @group = current_user.groups.new(group_params)
        @contacts = Contact.find(params[:contacts])
        @group.contacts << @contacts
        if @group.save
        ......
end

To ensure that already checked values aren't added to a group during the update action, I used a hidden tag in the form.
<%= hidden_field_tag "contacts[]",'' %>
<% current_user.contacts.all.each do |contact| %>
    <% checked = @group.contacts.include?(contact) %>
    <%= check_box_tag "contacts[]", contact.id, checked %>
     <%= f.label contact.name %>
<% end %>

Now, I'm unable to create or update a group as the hidden_field value is also passed along. An Active Record not found : Couldn't find all Contacts with 'id': (, 3, 4) (found 2 results, but was looking for 3) error. How can I solve this?

A: I think you want the hidden field tag to be nil rather than an empty string
<%= hidden_field_tag "contacts[]", nil %>

But as you're using rails 4 then collection_check_boxes might be of interest


text:
Q: C define array size automatically I'm trying to copy a const char* string to a char array[?]
is there a way in C to set my array size automatically?    char word[255]; instead of using 255 my program will automatically use the correct size in my case 10. If there's a better way to do it I'm open to any suggestions thx a lot.
const char* test_str = "my string.";

   int lenght = strlen(test_str), x=0;
    char word[255] = {'\0'};
    //memset(word, '\0', sizeof(word));
    while (x < lenght) {
        word[x] = test_str[x];
        x++;
    }

    printf("%s", word);

edit: Removed memset(word, '\0', sizeof(word)); and replaced with word[255]= {'\0'};

A: You have two options here.
The first is using malloc. It's basically used like this:
char *word = malloc(sizeof *word * (strlen(test_str)+1));

and when you're done, you free the memory.
free(word);

The other alternative is using a VLA (variable length array):
char word[strlen(test_str) + 1];

I would recommend using malloc. It's a little bit messier, but in my opinion, VLA:s have considerable drawbacks, and if you're about to learn C, you will have to learn malloc sooner or later anyway, but you can do perfectly fine without VLA:s.
I have written an answer about why I consider VLA:s bad here: https://stackoverflow.com/a/58163652/6699433


text:
Q: Implement UItabbarController + UInavigationBar in project I have navigation controller based project. In my project I have Splash Screen & Login Screen where i have hidden the navigation controller.
Now i have to implement TabbarController in the application and It need to be shown the screen after Login Page.
I want to add it in AppDelegate.But my problem is that I have set rootviewcontroller of Window as navigation controller.
And Now i want to use Tabbar controller also into the Appdelegate class.
I am finding difficulty into it.
Any help will be appreciated  a lot.

A: What you can do is set the rootviewcontroller as a tabbarcontroller and add a tab for your login screen but make sure to hide the tabbar initially, after the user login, you can remove the tab programatically and show the tabbar.

A: Maybe you really need that kind of navigation in your application, to me it sounds a bit of a unnecessary workaround and against guidelines. Try having a look at Apple's ("View Controller Programming Guide > Combined View Controller Interfaces") and maybe you'll find a more elegant solution to your problem.


text:
Q: PyravenDB wrong query parsing I'm using pyravendb + ravendb in order to store webpages. The main issue here is that when the url is in this form :
http://www.somedomain.com/nicepage.html?stuff=param&id=021345

pyravendb seems lost and tries to find the 021345 index (which obviously doesnt exists).
An example would be the following :
the url
http://www.example.com/ebx/LinkResolverServlet?classofcontent=Standard&id=63935

the query
    session.query().where_equals("url",url).select("Id","html","date","metadata")
gives this stack
  File "/home/myusername/***********/somepythonfile.py", line 60, in getDocumentbyURL
    query_result = list(session.query().where_equals("url",url).select("Id","html","date","metadata"))
  File "/usr/local/lib/python3.5/dist-packages/pyravendb/store/session_query.py", line 92, in __iter__
    return self._execute_query().__iter__()
  File "/usr/local/lib/python3.5/dist-packages/pyravendb/store/session_query.py", line 332, in _execute_query
    includes=self.includes)
  File "/usr/local/lib/python3.5/dist-packages/pyravendb/d_commands/database_commands.py", line 286, in query
    raise exceptions.ErrorResponseException(response["Error"][:100])
pyravendb.custom_exceptions.exceptions.ErrorResponseException: Could not find index named: 63935

Could not find index named: 63935

Which is normal since there is no index 63935, it seems to be mistaking the url parameter for a query parameter.
Any help in how to fix it ?
Thank you !

A: Fixed via a new version of RavenDB !


text:
Q: coin package wilcox.test function returns neither error nor result My mat data matrix is like:
V3      V7
ASD     4.4
ASD     4.3
control 4.3

I use following codes:
mat <- transform(mat, V3 = factor(V3))
wilcox_test(V7 ~ V3, data =mat, distribution = "exact")

But I get neither error nor results:

When I delete "distribution",the function works well:

Although this test is obviously meaningless, I want it for consistency with other tests in our work (all using permutation tests), so I wish to keep "distribution=exact". Can anybody find out what is going wrong and how to fix it?Thanks!
Edit:I try to save and export the result as:
pdis=wilcox_test(V7 ~ V3, data =mat, distribution = "exact")
pdis
summary(pdis)

But i get"Can't find the boject pdis".Did i make a mistake?

A: The coin::wilcox_test function will accept a distribution parameter with an argument of "exact".
library(coin)
mat <- read.table(text="V3      V7
ASD     4.4
ASD     4.3
control 4.3",header=TRUE)

mat <- within(mat, V3 = factor(V3))

wilcox_test(V7 ~ V3, data =mat, distribution = "exact")
#------

    Exact Wilcoxon-Mann-Whitney Test

data:  V7 by V3 (ASD, control)
Z = 0.70711, p-value = 1
alternative hypothesis: true mu is not equal to 0

Not clear what your problem might be:
>  pdis <- wilcox_test(V7 ~ V3, data =mat, distribution = "exact")
> summary(pdis)
                Length                  Class                   Mode
                     1 ScalarIndependenceTest                     S4

Perhaps you really do have an R data.matrix but in that case, you cannot have a factor column. R matrices do not allow attributes, and factors get coerced to integers.


text:
Q: Undefined reference to constructor when using QT I am new in c++ programming and also in QT.
I want to test Qt slots and signals and see how they work. I have a header file named myclass.h which has following code:
#ifndef MYCLASS_H
#define MYCLASS_H
#include <QObject>
#include <QString>
class myclass: public QObject
{
   Q_OBJECT
   public:
     myclass(const QString &text, QObject *parent=0);
     const QString& text() const;
     int getlengthoftext() const;
   public slots:
     void settext(const QString &text);
   signals:
     void changedtext(const QString&);
     private:
     QString m_text;
};

and a file with class_mine name with the following code :
#include "myclass.h"
#include <QObject>
#include <QString>
void myclass::settext(const QString &text)
{
     if (m_text==text)
        return;
     m_text =text;
     emit changedtext(m_text);
}
#endif

and in my main file I have this :
#include "mainwindow.h"
#include <QApplication>
#include "myclass.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    // MainWindow w;
    // w.show();
    QObject parent;
    myclass *a1 , *b , *c;
    a1=new myclass("foo" , &parent);
    b=new myclass("bar" , &parent);
    c=new myclass("baz" , &parent);
    QObject::connect(a1,SIGNAL(changedtext(const QString&)),
    b,SLOT(settext(const QString&)));
    QObject::connect(b,SIGNAL(changedtext(const QString&)),
    c,SLOT(settext(const QString&)));
    QObject::connect(c,SIGNAL(changedtext(const QString&)),
    b,SLOT(settext(const QString&)));
    b->settext("text");
    return a.exec();
}

I don't know why I'm getting this error:

main.cpp:13: error:
  undefined reference to `myclass::myclass(QString const&, QObject*)'

A: Define your constuctor in myclass.h
myclass(const QString &text, QObject *parent=0) { /* your code here */ };

or in myclass.cpp
myclass::myclass(const QString &text, QObject *parent) { /* your code here */ };


text:
Q: prove or disprove: every non satisfiable set of WFF has a non satisfiable sub set such every proper subset of it is satisfiable Let $\Gamma$ be a non-satisfiable set of well-formed formulas (wff).
prove or disprove:
$\Gamma$ has a non-satisfiable subset $\Delta\subseteq\Gamma$ such that for every $\phi\subsetneq\Delta$ is satisfiable.
I believe this is wrong, because there are wffs that if I join them I'll get a contradiction, but I wasn't able to find a concrete example.

A: The statement essentially says that if a set of formulas in unsatisfiable, then there is a minimal subset of it that is unsatisfiable. The statement is true.
Indeed, consider the two following general facts.

*

*Given a set $\Gamma$ of formulas, by compactness theorem, if $\Gamma$ is unsatisfiable then there is a finite $\Delta \subseteq \Gamma$ that is unsatisfiable.

*Given a set $\Gamma$, the relation $\subsetneq$ is well-founded on the finite powerset $\mathcal{P}_\text{fin}(\Gamma)$ of $\Gamma$ (see the footnote below).
As $\Gamma$ is unsatisfiable by hypothesis, the set $\{\Delta \subseteq \Gamma \mid \Delta \text{ is finite and unsatisfiable}\}$ is not empty by Point 1, and so it has a minimal element $\Delta_\min$ (with respect to $\subsetneq$) by Point 2, that is, $\Delta_\min \subseteq \Gamma$ is finite and unsatisfiable, but  every $\Phi \subsetneq \Delta$ is satisfiable.
Note that we have proved something stronger than the statement, because we are claiming that such a minimal unsatisfiable $\Delta \subseteq \Gamma$ must be finite. We can also claim that $\Delta \neq \emptyset$, because $\emptyset \subseteq \Gamma$ is trivially satisfiable.

Footnote: Saying that the relation $\subsetneq$ is well-founded
on $\mathcal{P}_\text{fin}(\Gamma)$ means that every non-empty set of finite subsets of $\Gamma$ has a minimal element with respect to $\subsetneq$. This essentially amounts to say that it is impossible to build an infinite descending chain $\Delta_0 \supsetneq \Delta_1 \supsetneq \Delta_2 \supsetneq \dots$ of finite $\Delta_i \subseteq \Gamma$. The fact that the $\Delta_i$'s have to be finite is crucial. Indeed, if $\Delta_0$ has a finite cardinality $n \in \mathbb{N}$, then $\Delta_1$ has cardinality at most $n-1$, and $\Delta_2$ has cardinality at most $n-2$, and so on, thus it is impossible to build an infinite descending chain. Luckily, in your case the compactness theorem allows us to consider only finite subsets of $\Gamma$.


text:
Q: iframe scroll event not fired when using srcdoc= I'm using an iframe to display an html document. I need to detect scroll events in the iframe. Using src= works fine, but srcdoc= does not fire the scroll event.
HTML:
<iframe id="TermsConditionsText" srcdoc="<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" /><title></title>
 ...
" class="form-control" style="overflow-y: scroll; height: 600px;">

jQuery:
jQuery(document).ready(function () {
    var termsWereScrolled = false;

    $("#TermsConditionsText").scroll(function () {
        if (termsWereScrolled) return true;

        if ($(this).scrollTop() + $(this).innerHeight() + 2 >= $(this)[0].scrollHeight) {
            termsWereScrolled = true;
        }
    });
});

Does iframe trigger scroll events when using srcdoc= ?

A:
Does iframe trigger scroll events when using srcdoc= ?

Yes it does trigger scroll events when using srcdoc.
The thing with iframe is that it is a new window and it has its own document; so, you have to attach the event to its document not to the element itself. Nonetheless, all you have to do is query the iframe's contents like $("#TermsConditionsText").contents() to attach the event. Check this out:
var iframeContents = $("#TermsConditionsText").contents();

$(iframeContents).scroll(function () {
    console.log('scroll');

    var html = $(this)[0].scrollingElement;
    console.log('scrollHeight', html.scrollHeight);
});


text:
Q: How to define an user that has same element with current user with Rails? I'm trying to make a function that show a recommended user(s) to a new user based on the category that a new user picked.
So recommended user should be user_type: "star" and it has same category.id that a current_user picked.
These are the models.
class User < ActiveRecord::Base
 has_many :categorizings, as: :categorizable, dependent: :destroy
 has_many :categories,    through: :categorizings
end

class Categorizing < ActiveRecord::Base
 belongs_to :category
 belongs_to :categorizable, polymorphic: true
end

class Category < ActiveRecord::Base
 has_many :categorizings, dependent: :destroy
 has_many :users, through: :categorizings, source: :categorizable, source_type: 'User'
end

And, this is my pseudo coded method to find a recommended user that I'm stuck on...
CategoriesController < ApplicationController
 def recommended_user
  @recommended_user = User.where(user_type: 'star' && Who has same category.id with a current_user)
 end
end

Sorry for the confusing explanation, but anything helps.
Thanks!

A: @recommended_user = User
                    .joins(:categories)
                    .where(
                      users: { user_type: 'star' },
                      categories: { id: current_user.categories.first.id }
                    )

A: @recommended_user = User.where(user_type: 'star').where(category_id: current_user.category_id)


text:
Q: Missing required parameters for [Route: Admin.update] [URI: Admin/{Admin}] I get the fallowing error. Missing required parameters for [Route: Admin.update] [URI: Admin/{Admin}]. It only disappear if i comment the form of the edit.blade. I checked what i did wrong but couldn't find it.
I also checked my web.php but i doub't it is comming from there.
If someone can see the error i would be happy.
Here is my route,
<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\AdminController;

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

Route::resource('Admin', AdminController::class);

this is me admin controller
<?php

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function edit(User $user)
    {

        $roles = Role::all();

        return view('Admin.edit', [ 'user' => $user, 'roles' => $roles]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, User $user)
    {
//        $user->roles()->sync($request->roles);
//
//        return redirect()->route('Admin.index');
    }
}

This is me edit blade.
@extends('layouts.app')

@section('content')

User edit page

 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam amet aperiam blanditiis consequatur dolore id iste itaque nisi officia reiciendis! Distinctio dolor dolore doloremque esse impedit, iusto nostrum quidem vitae?

            <form action="{{ route('Admin.update', $user) }}" method="post">
                    @method('PUT')
                    @csrf

                    @foreach($roles as $role)
                        <input type="checkbox" name="roles[]" value="{{$role->id}}">
                        {{ $role->name }}
                    @endforeach

                <button type="submit" class="btn btn-primary">
                    Update
                </button>
           </form>

@endsection

A: You have to match the typehinted parameter of your Controller method to the route parameter name, in this case it would be Admin. So your edit method needs to be:
public function edit(User $Admin)
{
    return view('Admin.edit', ['user' => $Admin, ...]);
}

At the moment you are getting a non existing instance of the User model as Dependency Injection instead of Route Model Binding because Admin does not match  $user. So you are passing a null value to the route helper:
route(..., $user);

Since $user is a non existing Model instance its "id" is null and you can't pass nulls to the route helper.


text:
Q: typedef required in struct declaration I'm trying to create an array of struct elements, as shown below:
#include <stdio.h>
#include <stdlib.h>

struct termstr{
double coeff;
double exp;
};

int main(){

termstr* lptr = malloc(sizeof(termstr)*5);

return 0;
}

When i compile this, i get errors as follows:
term.c: In function 'main':
term.c:11:1: error: unknown type name 'termstr'
term.c:11:31: error: 'termstr' undeclared (first use in this function)

However, when i change my code to the following, it compiles as usual:
#include <stdio.h>
#include <stdlib.h>

typedef struct termstr{
double coeff;
double exp;
}term;

int main(){

term* lptr = malloc(sizeof(term)*5);

return 0;
}

I've added typedef (with type name as term), changed the name of struct to termstr and am allocating memory with term* as the type of pointer.
Is typedef always required for such a situation i.e. for creating arrays of structs? If not, why was the first code giving errors? Is typedef also required to create and use a single instance of a struct?

A: First type is not working because you have forgot struct keyword before termstr. Your data type is struct termstr but not just termstr. When you typedef, the resulting name is used as an alias for struct termstr.
Even you don't need to do that. Using typedef is better:
By the way don't forget to free the memory:
read why to use typedef?
Your working code should be:
#include <stdio.h>
#include <stdlib.h>

struct termstr{
  double coeff;
  double exp;
};

int main(){

struct termstr* lptr = malloc(sizeof(struct termstr)*5);
free(lptr);
return 0;
}

A: It should be:
struct termstr * lptr = malloc(sizeof(struct termstr)*5);

or even better:
struct termstr * lptr = malloc(sizeof(*lptr)*5);

A: In C, the name of the data type is "struct termstr", not just "termstr".

A: You can do something like this:
typedef struct termstr{
   double coeff;
   double exp;
} termstrStruct;

And then you can use only termstrStruct as the struct's name:
termstrStruct* lptr = malloc(sizeof(termstrStruct)*5);

It is not always required, you can simply write struct termstr.
Don't forget to free the allocated memory!

A: Typedef is a convenient way of shortening this:
struct termstr* lptr = (struct termstr*)malloc(sizeof(struct termstr)*5);

to this:
typedef struct termstr* term;
term* lptr = (term*)malloc(sizeof(term)*5);

Casting the malloc is also a good idea!

A: If you want to use the typename termstr on it's own you can use typedef:
    typedef struct {
      double a;
      double b;
    } termstr;

A: In C you need to add the struct keyword as well, so either you use a typedef to link an alias with 'struct termstr' or you need to write something like
struct termstr* lptr = malloc(sizeof(struct termstr)*5);

In C++ however you can reference it as 'termstr' directly (read: the struct keyword isn't required there anymore).


text:
Q: How do I set Fancybox Height and Width as a Percentage with Dynamic HTML? I'm currently using Fancybox 2.1.2 and would like to know how I can create an overlay on my web application.  I can set the height and width of the the popup (note... this is not an iframe) and it will adjust with static values, but I would like to be able to set the height to a dynamic value like 80%.  I can't seem to get this to work though.  When I load fancybox with no height or width set I get this really small lightbox and it does not go to the default values of 600px for height and 800px for width.  Is this because I am adding in the HTML for the lightbox dynamically through the content method? I am also adding in content dynamically after the lightbox is done loading. The goal is to create a full overlay for my app with setting height as a percentage.
The current code is:
$.fancybox.open({
    'content' : '\

\

Your Photos of '+city+'
\

\

\

\

'
});

And my CSS is:
.light_box.upload{
    width: 980px;
}

A: Yes, you can turn off "autoSize" and then set width as "auto":
$.fancybox.open({
    content  : '
Lorem ipsum dolor sit ame
',
    autoSize : false,
    width    : "auto",
    height   : "80%"
});

See in action: http://jsfiddle.net/2VmrG/


text:
Q: A problem with div positioning A have something like that:
alt text http://img718.imageshack.us/img718/9625/88827634.png
It's OK but i want to add some Title block at the top of Content.
So it can be look like that:
alt text http://img824.imageshack.us/img824/9541/31597153.png
I don't know what Title height will be, because there will be some dynamic content.
How to solve this problem?

A: why are you positioning all your divs in absolute?
anyways you can wrap Title and Content with 2 divs, the outer div must be in absolute and the inner div is a relative, and you can put an absolute positioning in your Title and Content

Title

Content

Figure out the Top and Left of Title and Content, since it will not go outside the green and blue colors of your drawing..
I position absolute the outermost div since you are positioning all your divs in absolute. I assume you already have the measurements for all just like in your first drawing.


text:
Q: Combination of git revert and merge results in lost file I experienced strange behaviour of git merge after using revert, respectively Reverse commit action in SourceTree.

*

*I added a file called 'new_file' to a master branch.

*Then I reverted the commit in master and created branch feature/2

*I reverted the commit on branch feature/2 as well.

*I created 'new_file' on branch feature/2 once more.

*I merged feature/2 into master, merge introduced no changes, file 'new_file' is not present in master.

Does anybody have any explanation for this behaviour?
Is anybody aware of any Git or Source option that changes this behaviour?

A: Unfortunately this is the expected behavior of git merge in your situation.
Here is a rough outline of how git merge works :
# starting point :
  * eacff2 (feature/2) Added new_file again
  * eacff1 Revert "Added new_file"
* | eacfmm (HEAD -> master) Revert "Added new_file"
|/
* eacfXX Added new_file

when you run git merge feature/2, git first computes the "merge base" between the current branch, master, and feature/2.
In the above diagram, it is commit eacfXX Added new_file.
Then : it looks at git diff eacfXX master and git diff eacfXX feature/2, and see how these two diffs can be combined.
In the example you post, the solution is pretty straightforward : since there are no changes at all in git diff eacfXX feature/2, git decides that keeping the state in master is the way to go.
So you end up with an end result where new_file stays deleted.

The bottom line is : git merge does not inspect the intermediate states of the merged branches, it just tries to combine the state at the tip of the branches together.
Note however that if new_file had received any modifications on feature/2 (rather than being just a verbatim copy of the original file), there would have been a merge conflict which would have prompted for a closer look.
Running git rebase origin/master from feature/2 before merging would have helped, but systematically rebasing features before merging them isn't very practical, as it would add so many occasions to trigger irrelevant merge conflicts.
The generic advice is : do review your merges, be aware that, if a git revert of a past commit landed in the main branch, double check what the feature branch did with those same files.


text:
Q: Using case_when for conditional statement with dplyr across I'm trying to do a case_when between several columns with similar names using dplyr across:
For instance: Dataframe
df <-
  data.frame(f1_nom = c(1,2,5,7,2,3,5,1), f2_nom = c(3,4,2,8,3,4,3,7),
             f3_nom = c(1,2,5,7,5,8,5,1), f4_nom = c(3,4,2,8,3,3,3,2),
             f5_nom = c(2,3,5,1,6,8,5,9), f6_nom = c(3,4,3,7,5,7,5,8),
             f7 = c(1,2,4,7),
             f1_nom_wt = c(1,3,1,2,7,2,3,5), f2_nom_wt = c(6,8,5,9,4,2,8,3),
             f3_nom_wt = c(1,1,1,2,5,7,5,8), f4_nom_wt = c(3,3,3,2,1,6,8,5),
             f5_nom_wt = c(5,8,5,1,6,8,5,9), f6_nom_wt = c(6,11,1,2,5,9,4,2))

what am trying to do is:
mutate(case_when(f1_nom <= f1_nom_wt ~ 1, TRUE~  0))

I have hundred of these, but observe that the the names are similar except for the "_wt".
my attempt:
res1 <- DF1 %>%
  mutate(across(f1_nom:f100_nom, ~ case_when(.x <= "{.col}_wt" ~ 1, TRUE~ 0),.names = "{.col}_xyz"))

I was thinking by concat the name I could get the values for all the _wt for the case, but my results are all zeros. I know am doing this wrong. Basically i want the case to compare between
f1_nom:f100_nom and f1_nom_wt:f100_nom_wt

Thanks for your help!

A: Couple of options -

*

*Using tidyverse -

library(dplyr)
library(purrr)

df %>%
  mutate(map2_df(across(ends_with('_nom'), .names = '{col}_val'),
                 across(ends_with('_wt')), ~as.integer(.x <= .y)))

#  f1_nom f2_nom f3_nom f4_nom f5_nom f6_nom f7 f1_nom_wt f2_nom_wt f3_nom_wt f4_nom_wt
#1      1      3      1      3      2      3  1         1         6         1         3
#2      2      4      2      4      3      4  2         3         8         1         3
#3      5      2      5      2      5      3  4         1         5         1         3
#4      7      8      7      8      1      7  7         2         9         2         2
#5      2      3      5      3      6      5  1         7         4         5         1
#6      3      4      8      3      8      7  2         2         2         7         6
#7      5      3      5      3      5      5  4         3         8         5         8
#8      1      7      1      2      9      8  7         5         3         8         5

#  f5_nom_wt f6_nom_wt f1_nom_val f2_nom_val f3_nom_val f4_nom_val f5_nom_val f6_nom_val
#1         5         6          1          1          1          1          1          1
#2         8        11          1          1          0          0          1          1
#3         5         1          0          1          0          1          1          0
#4         1         2          0          1          0          0          1          0
#5         6         5          1          1          1          0          1          1
#6         8         9          0          0          0          1          1          1
#7         5         4          0          1          1          1          1          0
#8         9         2          1          0          1          1          1          0

*Base R -

wt_cols <- grep('_wt', names(df), value = TRUE)
cols <- sub('_wt', '', wt_cols)
df[paste0(cols, '_val')] <- +(df[cols] <= df[wt_cols])
df


text:
Q: How to read a specific row in excel file using python I want to read single row from an Excel_file1, Sheet1, Row number 7 using python, any help?

A: You can also use pd.read_excel of pandas library:
You would need to install pandas and xlrd first:
import pandas as pd
import xlrd
df = pd.read_excel('abc.xlsx', sheet_name='Sheet1')

Now, you can filter your dataframe to get any specific row using iloc
df.iloc[6] ## This will give you 7th row

A: First install xlrd
pip install xlrd

then open python file and
import xlrd

# Give the location of the file
loc = ("path of file")

# To open Workbook
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

print(sheet.row_values(7))

location is relative path not absolute path.
To read more about xlrd and its usage visit https://xlrd.readthedocs.io/en/latest/
Happy coding.


text: Q: How to link Note Velocity to Volume in Live or FL Studio? I have raw midi data generated through a script (in form of note on, note off , velocities etc). I am sending this data to a DAW ( FL Studio and Ableton Live) using LoopMIDI. How do I control say volume of a sound being played in FL Studio or Ableton Live using the value of Note Velocity?


text:
Q: Java program not showing output This is the coding i have come up with for a simple car rent java program. it compiles with no error but the output is not showing, so what should i do? Please help tx. I am a java beginner.
import java.util.Scanner;
public class carRent
{
  public static void main(String args[])
  {
    Scanner input = new Scanner(System.in);
    String name, address;
    double bodo,endodo, kilo;
    double days, charge;

    System.out.print("Name: ");
    name=input.nextLine();
    System.out.print("State: ");
    address=input.nextLine();
    System.out.print("Beginning Odometer : ");
    bodo=input.nextDouble();
    System.out.print("End Odometer : ");
    endodo=input.nextDouble();
    System.out.print("Days car used : ");
    days=input.nextDouble();

    kilo = endodo - bodo;
    System.out.printf("\nKilometer car driven  : ", + kilo ,"km");
    System.out.printf("\nNumber of days rented : ", + days);
    charge = days * 150.00 + kilo * 1.00;
    System.out.printf("\nTotal charge of rent  : ", + charge);
    }
}

A: You are not using printf correctly (since you didn't specify any place holders for the variables in the format String). I suggest you use println instead :
    kilo = endodo - bodo;
    System.out.println("\nKilometer car driven  : " + kilo + "km");
    System.out.println("\nNumber of days rented : " + days);
    charge = days * 150.00 + kilo * 1.00;
    System.out.println("\nTotal charge of rent  : " + charge);

Sample input and output :
Name: Eran
State: IL
Beginning Odometer : 1000
End Odometer : 2000
Days car used : 2

Kilometer car driven  : 1000.0km

Number of days rented : 2.0

Total charge of rent  : 1300.0

A: printf is short for "print format" which takes a format String and parameters with which they need to be formatted...
Instead you should be using something more like...
System.out.printf("%nKilometer car driven  : %.2fkm", kilo);

Which can output something like...
Name: test
State: Test
Beginning Odometer : 123.456
End Odometer : 789.123
Days car used : 10.25

Kilometer car driven  : 665.67km
Number of days rented : 10
Total charge of rent  : 2203.17

For example of the values...
    System.out.printf("%nKilometer car driven  : %.2fkm", kilo);
    System.out.printf("%nNumber of days rented : %.0f", days);
    charge = days * 150.00 + kilo * 1.00;
    System.out.printf("%nTotal charge of rent  : %.2f%n", charge);

For more details, take a look at these examples

A: If you want to be able to add multiple Strings on one line use:
System.out.print("I am an example String!");

If you want the String to be on its own line use:
System.out.println("I am an example String on my own line!");

A: I would suggest using:
System.out.println("Insert String Here");

Rather than printf, since you are not using placeholders .


text:
Q: Looking for a way to backup/mirror a drive by swapping I want to duplicate a drive.
I am unable to hook up both the old and new drive at the same time (the old powerbrick died; so I have one powerbrick to swap between two drives).
In years and years past, backup programs would read in as much as possible into memory, have you swap disks, and then output; repeat until finished.
Thinking about that, a script that used dd to read from the source, compress and store in a local file, and when the local drive is full (or the temp file is a given size), stop, let you change the disk, and then output.
It's ... well, it would probably take me two weeks to write and debug a bash script for this. And that's assuming a fixed-sized to read and write -- not using gzip to reduce the swaps.
The drive in question includes a time machine backup, so file copy is out of the question. And none of the file copy tools that I can think of will work to break it up into partial copies.
Has anyone run into this, and have a script for repeated DD's of partial copying to duplicate a drive in pieces?

A: My recommendation would be to do the dd over the network. I've used that method to back up laptop hard drives (much easier than pulling it out, or getting an external drive), and as long as you have a decently fast network, it's generally not TOO slow. It'll certainly be far more convenient than anything involving manual switching.
Omit the of= parameter to dd and it'll write the content to stdout; then pipe that into ssh user@othercomputer 'cat >disk.img' to push it over the network and save it.


text:
Q: copy row values based on result from isin() in pandas I have 2 dataframes:
df_a = pd.DataFrame({'A':[1,2,3,4],'B':[4,5,6,7],'ID':['a','b','c','d']})
df_a
   A  B ID
0  1  4  a
1  2  5  b
2  3  6  c
3  4  7  d
df_b = pd.DataFrame({'A':[1,2,3],'ID':['b','a','c']})
df_b['CopyB'] = ""
    A   ID  CopyB
0   1   b
1   2   a
2   3   c

Now I want to match ID columns in both the dataframes and upon a successful match, I want to copy respective value of B from df_a to df_b['CopyB']. I tried df_b.loc[df_b['ID'].isin(df_a['ID']),'Copy']= df_a['B]
but that is not correct. Then I tried comparing the ID using '==' but got an error  since the length of the ID series is not equal. Any help? Sorry if it is a very trivial query.

A: use join
df_b.join(df_a.set_index('ID').B, on='ID')

   A ID  B
0  1  b  5
1  2  a  4
2  3  c  6

join works on indices.  So I set the index of df_a to be the ID column and access the B column so that df_a.set_index('ID').B is a series with the column I want to add as values and the merge column as the index.  Then I use join.  I wouldn't have to specify an on parameter if ID was the index of df_b but it isn't, so I do.

A: You could use merge
In [247]: df_b.merge(df_a, on=['ID'])
Out[247]:
   A_x ID  A_y  B
0    1  b    2  5
1    2  a    1  4
2    3  c    3  6

In [248]: df_b.merge(df_a, on=['ID'])[['A_x', 'ID', 'B']].rename(columns={'A_x': 'A'})
Out[248]:
   A ID  B
0  1  b  5
1  2  a  4
2  3  c  6

A: If you set the ID column as a common index for both dataframes you can easily add the column:
df_a = df_a.set_index('ID')
df_b = db_b.set_index('ID')

df_b['Copy B'] = df_a['B']


text:
Q: C++ What is more efficient: defining a sum with a loop or unraveled with Horner's method? I am currently learning C++, and I have a sum of terms to implement as a function. More to the point, see this, slide 115, the formula for Ωi.
What I'd like to know is how efficient would it be to implement it (this is valid for σ0, on slide 114, too): with a loop that iterates through each terms of the nominator and denominator, or with a readily expanded and factored with Horner's method version?
I know that the latter will have the downside of being fixed, and it will need rewriting everytime a change is needed, but that may well be something done only in the beginning, while "calibrating". My guess would be the 2nd method would be faster, but if it's not by much, then I'd rather have the 1st version, since it will be more readable. Still, I'd like to hear what experience has to say.


text:
Q: Calling C# Unity Script from Android I have been trying to communicate with my Unity C# script through my Android Application using
"UnityPlayer.UnitySendMessage("Cube", "Test","HELLO") - where "Cube" is my Unity Object, "Test" is the name of the method present in the C# script it is using and "HELLO" is the message String I want to pass.
This line is placed in my onClick function, like this:
      ImageButton right_button = (ImageButton) findViewById(R.id.right_arrow);
      right_button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            UnityPlayer.UnitySendMessage("Cube", "Test","HELLO");
       }
      });

But when I run my android application and as soon as I click this button, I get this error:
    09-11 14:22:37.526: E/AndroidRuntime(1330): java.lang.NoClassDefFoundError:         com.unity3d.player.UnityPlayer

I have included classes.jar in my build path also.
Is there anything else I am missing out?
Thanks in advance!

A: Check if the class.jar file is in the Build Path of your Project. And if so, check if it is selected (check box is marked).

Tip: if you get ClassDefNotFound runtime errors (or similar), you might need to perform this extra step:
go to Project > Properties > Java Build Path -> Order and Export tab and check (tick) the classes.jar, Android x.y and Android Dependencies items; then Apply and rebuild the probject.

A: Happened to me the other time too.
I clean, re-link and rebuild my eclipse project. Re-Export my jar file to unity and also restart Unity. Build again and the error is gone.


text:
Q: Combine two wordlist in one file Python I have two wordlists, as per the examples below:
wordlist1.txt
aa
bb
cc

wordlist2.txt
11
22
33

I want to take every line from wordlist2.txt and put it after each line in wordlist1.txt and combine them in wordlist3.txt like this:
aa
11
bb
22
cc
33
.
.

Can you please help me with how to do it? Thanks!

A: Open wordlist1.txt and wordlist2.txt for reading and wordlist3.txt for writing. Then it's as simple as:
with open('wordlist3.txt', 'w') as w3, open('wordlist1.txt') as w1, open('wordlist2.txt') as w2:
    for l1, l2 in zip(map(str.rstrip, w1), map(str.rstrip, w2)):
        print(f'{l1}\n{l2}', file=w3)

A: Try to always try to include what you have tried.
However, this is a great place to start.
def read_file_to_list(filename):
  with open(filename) as file:
      lines = file.readlines()
      lines = [line.rstrip() for line in lines]
  return lines

wordlist1= read_file_to_list("wordlist1.txt")
wordlist2= read_file_to_list("wordlist2.txt")

with open("wordlist3.txt",'w',encoding = 'utf-8') as f:
  for x,y in zip(wordlist1,wordlist2):
    f.write(x+"\n")
    f.write(y+"\n")

Check the following question for more ideas and understanding: How to read a file line-by-line into a list?
Cheers

A: Here you go :)
 with open('wordlist1.txt', 'r') as f:
    file1 = f.readlines()

with open('wordlist2.txt', 'r') as f:
    file2 = f.readlines()

with open('wordlist3.txt', 'w') as f:
    for x in range(len(file1)):
        if not file1[x].endswith('\n'):
            file1[x] += '\n'
        f.write(file1[x])
        if not file2[x].endswith('\n'):
            file2[x] += '\n'
        f.write(file2[x])

A: Try this:
with open('wordlist1.txt', 'r') as f1:
    f1_list = f1.read().splitlines()

with open('wordlist2.txt', 'r') as f2:
    f2_list = f2.read().splitlines()

f3_list = [x for t in list(zip(f1, f2)) for x in t]

with open('wordlist3.txt', 'w') as f3:
    f3.write("\n".join(f3_list))

A: with open('wordlist1.txt') as w1,\
        open('wordlist2.txt') as w2,\
        open('wordlist3.txt', 'w') as w3:

    for wordlist1, wordlist2 in zip(w1.readlines(), w2.readlines()):
        if wordlist1[-1] != '\n':
            wordlist1 += '\n'
        if wordlist2[-1] != '\n':
            wordlist2 += '\n'

        w3.write(wordlist1)
        w3.write(wordlist2)

A: Instead of using .splitlines(), you can also iterate over the files directly. Here's the code:
wordlist1 = open("wordlist1.txt", "r")
wordlist2 = open("wordlist2.txt", "r")
wordlist3 = open("wordlist3.txt", "w")

for txt1,txt2 in zip(wordlist1, wordlist2):
    if not txt1.endswith("\n"):
        txt1+="\n"
    wordlist3.write(txt1)
    wordlist3.write(txt2)

wordlist1.close()
wordlist2.close()
wordlist3.close()

In the first block, we are opening the files. For the first two, we use "r", which stands for read, as we don't want to change anything to the files. We can omit this, as "r" is the default argument of the open function. For the second one, we use "w", which stands for write. If the file didn't exist yet, it will create a new file.
Next, we use the zip function in the for loop. It creates an iterator containing tuples from all iterables provided as arguments. In this loop, it will contain tuples containing each one line of wordlist1.txt and one of wordlist2.txt. These tuples are directly unpacked into the variables txt1 and txt2.
Next we use an if statement to check whether the line of wordlist1.txt ends with a newline. This might not be the case with the last line, so this needs to be checked. We don't check it with the second line, as it is no problem that the last line has no newline because it will also be at the end of the resulting file.
Next, we are writing the text to wordlist3.txt. This means that the text is appended to the end of the file. However, the text that was already in the file before the opening, is lost.
Finally, we close the files. This is very important to do, as otherwise some progress might not be saved and no other applications can use the file meanwhile.

A: Open wordlist 1 and 2 and make a line paring, separate each pair by a newline character then join all the pairs together and separated again by a newline.
# paths
wordlist1 = #
wordlist2 = #
wordlist3 = #

with open(wordlist1, 'r') as fd1, open(wordlist2, 'r') as fd2:
    out = '\n'.join(f'{l1}\n{l2}' for l1, l2 in zip(fd1.read().split(), fd2.read().split()))

with open(wordlist3, 'w') as fd:
    fd.write(out)


text:
Q: Sorting 2D javascript array I have an array containing a list of tags and count.
tags_array[0] = tags;
tags_array[1] = tags_count;

I need to sort the arrays base on the count so that I can pick out the top few tags.

A: Supposing tags and tags_count are 2 arrays of same length, I would first build a proper array of objects :
var array = [];
for (var i=0; i<tags_count.length; i++) {
    array.push({tag:tags[i], count:tags_count[i]});
}

And then sort on the count :
array.sort(function(a, b) {return a.count-b.count});

If you need to get your arrays back after that, you may do
for (var i=0; i<array.length; i++) {
    tags[i] = array[i].tag;
    tags_count[i] = array[i].count;
}

Demonstration

A: Sort one, while storing the sort comparisons.  Then sort the other using those results:
var res = [];
tags_count.sort( function( a, b ){ return res.push( a=a-b ), a; } );
tags.sort( function(){ return res.shift(); } );

A: Assuming that both tags and tags_count are arrays with the same length (that part of the question wasn't too clear), the following is one way to do the trick.
var tags_array = new Array();

for (var i = 0; i < tags.length; i++)
{
    tags_array[i] = {};
    tags_array[i].tagName = tags[i];
    tags_array[i].tagCount = tags_count[i];
}

tags_array.sort(function(a,b){return b.tagCount-a.tagCount});

One should note that it might be possible to structure the data in this way from the start instead of rewriting it like this, in which case that is preferable. Likewise, a better structure can be used to save the data, but this will work.


text:
Q: USB Not Recognized after Invalid Pull Out I have a problem, caused by me.
I just bought a NAND usb stick 2 TB which worked out of the box.
I tried to copy 36GB into it. That of course took too long so, I put my laptop on suspension to not interrupt the process, (that's what I thought). The process stopped of course, and I tried to delete half copied files. This also took too long so I closed the window and tried to delete the from command line which also took to long so I stopped the process and pulled out my usb stick.
Since then my stick is not recognized.
I can see these on journlactl
kernel: usb-storage 3-1:1.0: USB Mass Storage device detected
Jan 24 06:40:36 192.168.2.7 kernel: scsi host6: usb-storage 3-1:1.0
Jan 24 06:40:36 192.168.2.7 mtp-probe[29780]: checking bus 3, device 6: "/sys/devices/pci0000:00/0000:00:14.0/usb3/3-1"
Jan 24 06:40:36 192.168.2.7 mtp-probe[29780]: bus: 3, device: 6 was not an MTP device
Jan 24 06:40:36 192.168.2.7 upowerd[3864]: unhandled action 'bind' on /sys/devices/pci0000:00/0000:00:14.0/usb3/3-1/3-1:1.0
Jan 24 06:40:36 192.168.2.7 upowerd[3864]: unhandled action 'bind' on /sys/devices/pci0000:00/0000:00:14.0/usb3/3-1
Jan 24 06:40:37 192.168.2.7 kernel: scsi 6:0:0:0: Direct-Access     NAND     USB2DISK         0.00 PQ: 0 ANSI: 4
Jan 24 06:40:37 192.168.2.7 kernel: sd 6:0:0:0: Attached scsi generic sg3 type 0
Jan 24 06:40:37 192.168.2.7 kernel: sd 6:0:0:0: [sdc] Attached SCSI removable disk
Jan 24 06:41:07 192.168.2.7 kernel: nouveau 0000:01:00.0: Enabling HDA controller
Jan 24 06:41:13 192.168.2.7 kernel: ACPI: \_SB_.PCI0.PEG0.VID_: failed to evaluate _DSM
Jan 24 06:41:14 192.168.2.7 sudo[29855]:     User : TTY=pts/0 ; PWD=/home/User ; USER=root ; COMMAND=/bin/lsusb
Jan 24 06:41:14 192.168.2.7 sudo[29855]: pam_unix(sudo:session): session opened for user root by User(uid=0)
Jan 24 06:41:14 192.168.2.7 sudo[29855]: pam_unix(sudo:session): session closed for user root
Jan 24 06:45:19 192.168.2.7 kernel: brcmsmac bcma0:1: wl0: brcms_c_d11hdrs_mac80211:  txop exceeded phylen 153/256 dur 1730/150
Jan 24 06:47:02 192.168.2.7 dbus[1784]: [system] Activating via systemd: service name='net.reactivated.Fprint' unit='fprintd.se
Jan 24 06:47:02 192.168.2.7 systemd[1]: Starting Fingerprint Authentication Daemon...

With lsusb I have this
Bus 002 Device 003: ID 0a5c:5802 Broadcom Corp. BCM5880 Secure Applications Processor with fingerprint touch sensor
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 004: ID 1bcf:2895 Sunplus Innovation Technology Inc.
Bus 001 Device 003: ID 413c:8197 Dell Computer Corp.
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 005: ID 045e:07fd Microsoft Corp. Nano Transceiver 1.1
Bus 003 Device 006: ID ffff:1201
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

I think
Bus 003 Device 006: ID ffff:1201

is the records for my USB.
I have Centos 7 with kernel 5.4 and xforms as window manager.
I don't know what to do.

A: I am sorry to inform you that the only 2TB USB flash drive available in 2020 is the Kingston DataTraveler.
All other USB flash drives indicated with this capacity are a fake product. They will usually only have a capacity of less than 128GB (or way less even), and trick the OS into thinking they have such a capacity. They will become unwritable once past their true capacity.
I highly suggest getting a refund for your purchase.


text:
Q: Angular 4 - How to apply the rendered height of a div to another div? I have two named templates. I want to apply the height of the first one to the second one whenever the contents of the first one change. I can access both of them using ElementRef inside the component. So, when I change the properties bound to the first template, I use the corresponding ElementRef to get its height and apply it to the second template's ElementRef.
Now, the problem is that, after the property change, the height that I get from the ElementRef corresponding to the first template is not the updated height. It returns the height of the div before the property change and re-rendering.
I want to be able to get the actual rendered height after the div is updated. What am I doing wrong?
Update:
The code:
var height = `${this.profile.nativeElement.offsetHeight}px`;
this.renderer.setStyle(this.board.nativeElement, "height", height);
this.renderer.setStyle(
this.board.nativeElement,
"overflow-y",
"scroll"
);

Here profile is the ElementRef corresponding to the first div and board the ElementRef of second one. After property change, I call the function containing the above code. Then the height I get is the old height of the div, that is, before the property change and re-rendering.

A: Access the ElementRef corresponding to each div using @ViewChild:
@ViewChild("profile") profile;
@ViewChild("board") board;

Implement AfterViewChecked and do the following in ngAfterViewChecked:
constructor(private renderer: Renderer2) {
}

ngAfterViewChecked() {
  if (this.profile && this.board) {
    var height = `${this.profile.nativeElement.offsetHeight}px`;
    this.renderer.setStyle(this.board.nativeElement, "height", height);
  }
}

renderer is Renderer2 available in @angular/core


text:
Q: Iteration over ConsumerIterator object seems to be never ending loop I try to implement a Java consumer client for Apache Kafka in version 0.8.2.1. I know that new version of Java Consumer API will be available in new version of Apache Kafka, but for now I have to implement consumer client in the current version.
So I have done it, but I have problem with checking count of received messages. The problem seems to be in iteration over the ConsumerIterator object to get the message and  its id. The iteration seem to be be never ending loop. Look at the following code:
public class TestKafkaConsumer extends Thread{

private final static Logger logger = Logger.getLogger(TestKafkaConsumer.class);
private Properties appProperties;
private String topic;
private ZookeeperConsumerConnector consumer;

public TestKafkaConsumer() throws Exception {
    topic = "topic";
    consumer = (ZookeeperConsumerConnector) Consumer.createJavaConsumerConnector(createConsumerConfig());
}

public static void main( String[] args ){
    PropertyConfigurator.configure("log4j.properties");
    try {
        TestKafkaConsumer testConsumer = new TestKafkaConsumer();
        testConsumer.start();
    } catch (Exception e) {
        logger.error("Error create consumer ", e);
    }

}

@Override
public void run() {
    logger.info("Consumer thread - start");
    Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
    topicCountMap.put(topic, new Integer(1));
    Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = (Map<String, List<KafkaStream<byte[], byte[]>>>) consumer
            .createMessageStreams(topicCountMap);
    KafkaStream<byte[], byte[]> stream = consumerMap.get(topic).get(0);
    ConsumerIterator<byte[], byte[]> it = stream.iterator();
    //logger.info("Count of consumed messages: " + it.length());
    long msgCount = 0;
    while (it.hasNext()) {
            MessageAndMetadata<byte[], byte[]> messageAndMetadata  = it.next();
            logger.info("Key: " + new String(messageAndMetadata.key()));
            logger.info("Message: " + new String(messageAndMetadata.message()));
            msgCount++;
        }
    logger.info("Summary count of consumed messages: " + msgCount);
}

private ConsumerConfig createConsumerConfig() throws Exception{
    logger.info("createConsumerConfig - start");
    Properties props = new Properties();
    props.put("zookeeper.connect", "localhost:2181");
    props.put("group.id","testGrp");
    props.put("zookeeper.session.timeout.ms", "400");
    props.put("zookeeper.sync.time.ms", "200");
    props.put("auto.commit.interval.ms", "10000");
    logger.info("createConsumerConfig - finish");
    return new ConsumerConfig(props);
}

}

The problem is that the log entry with the count of consumed messages does not appear in log file, so I suppose that iteration never ends. I have tested that all messages are read. So all records are iterated but program does not leave a loop. Additionally I've noticed, when I try to get length of ConsumerIterator (or size) before starting a loop (uncomment appriopriate line) the program seems to stop in this place and the loop doesn't even start - there is no entry about read records in log file.
Where is the problem - in class ConsumerIterator? Maybe I've done something wrong. I would be grateful if someone met such problem and could help me.

A: The javadoc for ConsumerIterator, http://apache.mirrorcatalogs.com/kafka/0.8.2-beta/scala-doc/index.html#kafka.consumer.ConsumerIterator, states "An iterator that blocks until a value can be read from the supplied queue."
Could this be the issue?


text:
Q: Query executes successfully but returns no results The following query is used for a report, the report is still showing live data when accesssed, yet when running the query in Management Studio I am not getting any results despite the message 'query successfully completed'
I have had to declare the @Date parameter which I think I have done correctly at the top of the query.
DECLARE @Date datetime;

BEGIN
    SET @Date = 27/07/2017;
END

SELECT     CAST(CASE WHEN (SOTD_STWH_CODE = 'HPP SHEF') THEN DATE - (CASE
DATEPART(dw, DATE) WHEN 2 THEN 3 ELSE 1 END) ELSE DATE END AS date) AS
ShipDate,
                      DeFactoUser.F_SO_Transaction.SOTR_CUST_CODE,
DeFactoUser.F_SO_Transaction_Details.SOTD_HEAD_NO,
DeFactoUser.F_SO_Transaction.SOTR_DLSC_CODE,
                      DeFactoUser.F_SO_Transaction_Details.SOTD_STWH_CODE,
DeFactoUser.F_SO_Transaction_Details.SOTD_STRC_CODE,
DeFactoUser.F_SO_Transaction_Details.SOTD_QTY_UNITS_ORDERED,

DeFactoUser.F_SO_Transaction_Details.SOTD_QTY_UNITS_OUTSTANDING,
DeFactoUser.F_SO_Transaction_Details.SOTD_QTY_UNITS_PICKED,

DeFactoUser.F_BM_Transactions_Details.BMTD_BMTR_SYS_NO,
DeFactoUser.F_BM_Transactions_Details.BMTD_QTY_OUTSTANDING,
ISNULL(CAST(BaseOn.baseon AS varchar), '') AS BaseOn,
                      CASE BaseOn.baseonstat WHEN '99' THEN 'Complete' WHEN
'98' THEN 'Outstanding' WHEN '1' THEN 'open' ELSE '' END AS BaseOnStatus,
DeFactoUser.F_SL_Customers.CUST_NAME
FROM         DeFactoUser.F_SL_Customers INNER JOIN
                  DeFactoUser.F_SO_Transaction_Details WITH (NOLOCK) INNER
JOIN
                      DeFactoUser.F_ST_Products WITH (NOLOCK) ON
DeFactoUser.F_SO_Transaction_Details.SOTD_STRC_CODE =
DeFactoUser.F_ST_Products.STRC_CODE INNER JOIN
                      DeFactoUser.F_SO_Transaction WITH (NOLOCK) ON
DeFactoUser.F_SO_Transaction_Details.SOTD_HEAD_NO =
DeFactoUser.F_SO_Transaction.SOTR_SYS_NO INNER JOIN
                      tbl_DFBI_Date ON
DeFactoUser.F_SO_Transaction.SOTR_PROMISED_DATE = tbl_DFBI_Date.Date ON
                      DeFactoUser.F_SL_Customers.CUST_CODE =
DeFactoUser.F_SO_Transaction_Details.SOTD_CUST_CODE LEFT OUTER JOIN
                      DeFactoUser.F_BM_Transactions INNER JOIN
                      DeFactoUser.F_BM_Transactions_Details ON
DeFactoUser.F_BM_Transactions.BMTR_SYS_NO =
DeFactoUser.F_BM_Transactions_Details.BMTD_BMTR_SYS_NO ON
                      DeFactoUser.F_SO_Transaction_Details.SOTD_SYS_NO =
DeFactoUser.F_BM_Transactions_Details.BMTD_ORDER_LINK_NUMBER LEFT OUTER JOIN
                          (SELECT     RIGHT(SOTR_BASED_ON_REF, 7) AS link,
SOTR_STATUS AS baseonstat, SOTR_SYS_NO AS baseon
                            FROM          DeFactoUser.F_SO_Transaction AS
F_SO_Transaction_1
                            WHERE      (SOTR_CUST_CODE = 'h075') AND
(SOTR_BASED_ON_REF > '0')) AS BaseOn ON
CAST(DeFactoUser.F_SO_Transaction_Details.SOTD_HEAD_NO AS varchar) =
BaseOn.link
WHERE     (DeFactoUser.F_ST_Products.STRC_NI_CODE = 'panelcut') AND
(DeFactoUser.F_ST_Products.STRC_ANAL1 = '1033') AND
(DeFactoUser.F_SO_Transaction_Details.SOTD_SOTR_TYPE = 10) AND
                  (DeFactoUser.F_SO_Transaction.SOTR_CUST_CODE <> 'h075')
AND (DeFactoUser.F_SO_Transaction.SOTR_STATUS < '99') AND (CASE WHEN
(SOTD_STWH_CODE = 'HPP SHEF')
                  THEN DATE - (CASE DATEPART(dw, DATE) WHEN 2 THEN 3 ELSE 1
END) ELSE DATE END <= @Date)

Any suggestions as to how i can view the results?

A: You need the following to initialize the date:
SET @Date = '20170727'; -- Format as YYYYMMDD which is locale neutral

What you currently have is, 27 divided by 7 divided by 2017. These are integers, so the result is 0. This number is then converted to datetime, which will not result in the date you intended to have.
You best stick to the ISO 8601 formatting of dates, or date/time values. You can read more about that in the DATETIME documentation.


text:
Q: how to sort array of object in php I am not able to sort this array of object. please kindly help.
I am using usort for sorting the array.
Also I am getting this error:

PHP Parse error:  syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ')' in /home/cg/root/128245/main.php on line 7

I need to sort this array by the order of job_name attribute of my class.
<?php
$gfg_array =Array
(
    [0] => Array
        (
            [status] => SUCCESS
            [duration] => 04:32:22
            [date] => 13-Jun-2019
            [start_stamp] => 02:29:32
            [type] => implicit
            [job_name] => build-bbjsd
        )

    [1] => Array
        (
            [status] => SUCCESS
            [change_sets] => Array
                (
                )
                [job_id] =>  # 4156
            [url] => http://www.html.com
            [duration] => 0:39:25
            [test_script] => {"tc_results": [{"status": "pass", "testcase_time": "0:01:06"}]}
            [date] => 2019-06-13
            [start_stamp] => 9:30:34
            [type] => explicit
            [job_name] => json-dhj
        )

    [2] => Array
        (
            [status] => SUCCESS
            [duration] =>
            [date] =>
            [start_stamp] =>
            [type] => implicit
            [job_name] => ci-ulp

    [3] => Array
        (
            [status] => DISABLED
            [duration] =>
            [date] =>
            [start_stamp] =>
            [type] => implicit
            [job_name] => build-c201-qemux86-64
        )

    [4] => Array
        (
            [status] => SUCCESS
            [duration] => 04:30:30
            [date] => 13-Jun-2019
            [start_stamp] => 02:29:15
            [type] => implicit
            [job_name] => build-fss-image-full-l200-qemux86-64
        )

    [5] => Array
        (
            [status] => SUCCESS
            [change_sets] => Array
                (
                )

            [job_id] =>  # 4156
            [url] => http://www.html.com
            [duration] => 0:39:25
            [test_script] => {"tc_results": [{"status": "pass",
            "testcase_time": "0:01:06"}]}
            [date] => 2019-06-13
            [start_stamp] => 9:30:34
            [type] => explicit
            [job_name] => json-ci-ulp-fss-image-full-l200-qemux86-64
        )
)

function querySort ($x, $y) {
   return strcasecmp($x['job_name'], $y['job_name']);
}

usort($gfg_array, 'querySort');

print_r($gfg_array)
?>

A: Use usort function.
You need to create a rule that your objects can be compared with each other.
It is how it's used:
function compareObjects( $a , $b )
{
    return strcmp( $a->job_name , $b->job_name );
}

usort( $gfg_array , "compareObjects" );

Also you have a syntax error in your code and you need to set array values as strings as below:
<?php
$gfg_array =Array
(
    [0] => Array
        (
            [status] => "SUCCESS"
            [duration] => "04:32:22"
            [date] => "13-Jun-2019"
            [start_stamp] => "02:29:32"
            [type] => "implicit"
            [job_name] => "build-bbjsd"
        )

    [1] => Array
        (
            [status] => "SUCCESS"
            [change_sets] => Array
                (
                )
                [job_id] =>  "# 4156"
            [url] => "http://www.html.com"
            [duration] => "0:39:25"
            [test_script] => {"tc_results": [{"status": "pass", "testcase_time": "0:01:06"}]}
            [date] => "2019-06-13"
            [start_stamp] => "9:30:34"
            [type] => "explicit"
            [job_name] => "json-dhj"
        )

    [2] => Array
        (
            [status] => "SUCCESS"
            [duration] => ""
            [date] => ""
            [start_stamp] => ""
            [type] => "implicit"
            [job_name] => "ci-ulp"

    [3] => Array
        (
            [status] => "DISABLED"
            [duration] => ""
            [date] => ""
            [start_stamp] => ""
            [type] => "implicit"
            [job_name] => "build-c201-qemux86-64"
        )

    [4] => Array
        (
            [status] => "SUCCESS"
            [duration] => "04:30:30"
            [date] => "13-Jun-2019"
            [start_stamp] => "02:29:15"
            [type] => "implicit"
            [job_name] => "build-fss-image-full-l200-qemux86-64"
        )

    [5] => Array
        (
            [status] => "SUCCESS"
            [change_sets] => Array
                (
                )

            [job_id] =>  "# 4156"
            [url] => "http://www.html.com"
            [duration] => "0:39:25"
            [test_script] => {"tc_results": [{"status": "pass",
            "testcase_time": "0:01:06"}]}
            [date] => "2019-06-13"
            [start_stamp] => "9:30:34"
            [type] => "explicit"
            [job_name] => "json-ci-ulp-fss-image-full-l200-qemux86-64"
        )
)

function querySort ($x, $y) {
   return strcasecmp($x['job_name'], $y['job_name']);
}

usort($gfg_array, 'querySort');

print_r($gfg_array)
?>

A: You can try this function..
    function multisortByKeyValue( $k, $arr ) {
        $ids   = array();
        $index = 1;

        foreach ( $arr as $key => $row ) {
            $ids[ $key ] = intval( $row[ $k ] ) . '-' . $index . '-' . $key;
            $index ++;
        }

        natsort( $ids );

        $arr = array_merge( $ids, $arr );

        return $arr;
    }
```


text:
Q: Centre of mass of a quarter of disc (doubt in my solution) Can please anyone tell where am i wrong in this approach of solving this question..
The ans i am getting is (4 root2)/pi but ans is (4 root2)/3pi

A: The mistake in your solution is that both $dx$ and $dy$ are integrated from $0$ to $R$, as if the object (i.e. its cross section) was a rectangle. In this particular example, it is much simpler to do the integration in polar coordinates than in Cartesian coordinates.
If you insist on Cartesian coordinates, then the correct integrals would be
$$x_\text{cm} = \frac{\sigma}{M} \int_{0}^{R} dy \int_{0}^{\sqrt{R^2 - y^2}} x dx = \frac{4 R}{3 \pi}$$
$$y_\text{cm} = \frac{\sigma}{M} \int_{0}^{R} dx \int_{0}^{\sqrt{R^2 - x^2}} y dy = \frac{4 R}{3 \pi}$$
where $M = \sigma R^2 \frac{\pi}{4}$ is total mass of the disc.
I show below how to find the center of mass in polar coordinates.

The center of mass is defined as
$$\boxed{x_\text{cm} = \frac{1}{M} \iiint_S x \cdot dm} \tag 1$$
where $M$ is total mass of the disc, $x$ is distance with respect to the arbitrarily chosen origin, and $dm$ is infinitesimally small mass. The idea is simple - sum distance $x$ of each (infinitesimally small) particle in the disc weighted (multiplied) by its mass $dm$ and then divide the sum by the disc total mass. Since disc in your question is homogeneous, i.e. its density $\rho$ is constant, and since cross section is constant throughout the depth of the disc, we can write:
$$dm = \rho \cdot dV = \rho \cdot h \cdot dA = \sigma \cdot dA$$
where $h$ is thickness (depth) of the disc. The total mass is $M = \sigma R^2 \frac{\pi}{4}$ and the Eq. (1) becomes
$$x_\text{cm} = \frac{4}{\pi} \frac{1}{R^2} \iint_S x \cdot dA \tag 2$$
Now we have to express the infinitesimally small area $dA$. As I have already mentioned, the integration is much simpler in polar coordinates:
$$dA = (r+dr)^2 \frac{d\theta}{2} - r^2 \frac{d\theta}{2} = (2rdr + (dr)^2) \frac{d\theta}{2} \approx r dr d\theta$$
where $(dr)^2$ is neglected being much (much!) smaller than $dr$. See figure below for an explanation how infinitesimal small area $dA$ was calculated.

The distance of the infinitesimally small area $dA$ in $x$ direction in polar coordinates is $x = r \cos\theta$ and the Eq. (2) is solved as
$$x_\text{cm} = \frac{4}{\pi} \frac{1}{R^2} \int_{0}^{R} \int_{0}^{\pi/2} r \cos\theta \cdot r dr d\theta = \frac{4}{\pi} \frac{1}{R^2} \int_{0}^{R} r^2 dr \int_{0}^{\pi/2} \cos\theta \cdot d\theta = \frac{4R}{3\pi}$$
The procedure is similar for the $y$ direction - the distance in polar coordinates is $y = r \sin\theta$ and the Eq. (2) is solved as
$$y_\text{cm} = \frac{4}{\pi} \frac{1}{R^2} \int_{0}^{R} \int_{0}^{\pi/2} r \sin\theta \cdot r dr d\theta = \frac{4}{\pi} \frac{1}{R^2} \int_{0}^{R} r^2 dr \int_{0}^{\pi/2} \sin\theta \cdot d\theta = \frac{4R}{3\pi}$$
The position of the center of mass for given disc is
$$\boxed{\vec{r}_\text{cm} = \frac{4R}{3\pi} \hat{\imath} + \frac{4R}{3\pi} \hat{\jmath} = \frac{4R}{3\pi} \sqrt{2} e^{j \pi / 4}}$$

In your question you mention that the correct solution has $\sqrt{2}$ term in $x$ and $y$ coordinates. This is only possible if you rotate the disc by $45^\circ$ clockwise, in which case the center of mass would be at
$$\vec{r}'_\text{cm} = \vec{r}_\text{cm} e^{-j \pi / 4} = \frac{4R}{3\pi} \sqrt{2} \hat{\imath} \qquad \rightarrow \qquad x_\text{cm} = \frac{4R}{3\pi} \sqrt{2}, \quad y_\text{cm} = 0$$
If this explanation with rotation is too abstract, try repeating the above procedure (integration) when $\theta$ goes from $-\pi/4$ to $\pi/4$ and you will get the same result. Since disc is now symmetrical with respect to the $x$ axis, we can conclude that $y_\text{cm} = 0$ even without doing the integration.


text:
Q: Using VSTS to publish Azure Function to Zip file I am trying to use VSTS to publish a project that contains an Azure Function. My MSBuild step is passing the following build arguments

/p:Configuration=Release /p:DeployOnBuild=true
  /p:WebPublishMethod=Package /p:PackageAsSingleFile=true
  /p:SkipInvalidConfigurations=true
  /p:PackageLocation="$(build.artifactstagingdirectory)\MyFunctions.$(Build.BuildNumber)-dev.zip"
  /p:DeployIisAppPath="Default Web Site"

This is giving me a Zip where the folder structure of \Content\D_C\a\3\s\MyFunctions\obj\Release\net461\PubTmp\Out. The Out directory has the content I need and what I'd expect to be the root
The folder structure I need to push a Zip is

As documented Here
Can anyone advise on what I am doing wrong here?
Thanks

A: I do it in a 2 step process

*

*build with a VSTS Build task with settings /p:DeployOnBuild=true /p:DeployTarget=Package;CreatePackageOnPublish=true

*ZIP it with a VSTS Archive Files task. Here I leave the option to Prefix root folder name... unchecked.

Sample:

A: With Azure App Service Deploy task and Publish using Web Deploy option, it won't remain the folder structure and the content files will be in wwwroot folder of azure app service. So you don't need to care the package folder structure.
Otherwise, you can publish the app through FileSystem publish method (e.g. /p:SkipInvalidConfigurations=true /p:DeployOnBuild=true /p:WebPublishMethod=FileSystem /p:publishUrl="$(build.artifactstagingdirectory)\\" /p:DeployDefaultTarget=WebPublish), then zip files through Archive files task, after that you can deploy it through Zip push deployment way (Azure CLI or PowerShell)
Zip push deployment for Azure Functions


text:
Q: WPF - помощь с выбором контрола уважаемые! У меня несколько общий вопрос.
Нужно реализовать: строку (я не сказал, что это должно быть TextBox) для ввода улицы так, чтобы по вводимому значению автоматически определялось множество вариантов адресов с такой улицей (сочетание "область - город - улица, которая начинается на введенные символы"), оперативно показывалась в качестве списка-подсказки к этой строке, и пользователь мог мышкой или стрелками выбрать подходящий вариант. Короче, поведение как у IntelliSence, только для адресов.
Я уже реализовать весь "back-end" (сделал во VM метод, который выдает массив подсказок по введенному префиксу слова). Дело за малым... я не знаю, каким лучше воспользоваться контролом и какими его свойствами. Желательно, если есть такая возможность, это прикрутить к редактируемому ComboBox.
Благодарю за советы и/или примеры :)

A: Все удачно собрал на ComboBox.
В итоге, я создал два класса - один для элемента дерева, содержащего элемент адреса, а другой - подсказка, содержащая информацию по полному адресу, начинающемуся с введенного текста. Оба класса связаны одним интерфейсом.
ItemsSource у ComboBox - List, где Т - мой интерфейс. Это позволило мне оперативно подменять разнородные ItemsSource'ы у ComboBox'а.
ComboBox открыл для редактирования (IsEditable=true). Подписался на события TextChanged и SelectionChanged.
По событию TextChanged на лету получаю список подсказок, подменяю ItemsSource на них - пользователь видит подсказки. По событию SelectionChanged заполняю все вышестоящие ComboBox'ы, включая ComboBox с подсказками, из выбранной подсказки, опять оперативно подменяя ItemsSource.


text:
Q: how to return None for empty array in python? I have a dataframe with two columns. Column one contains an integer, the second column a list with multiple items, which also can be empty.
I want to return a list with tuples, in which the first part of the tuple is the integer from col1, and the second part of the tuple is the integer from col2, listing in total all possible outcomes.
Input:
    col1    col2
0   909101  [1396920, 3094857]
1   21095887    [8383568]
2   8383568 [21095887]
3   2408689 []

desired output:
[(909101, 1396920),
(909101, 3094857),
 (21095887, 8383568),
 (8383568, 21095887),
 (2408689, None)]

So far, I have these, but it only outputs tuples for non empty inputs.
[(df[col1][i],df[col2][i][j])
            for i in range(len(df))
            for j in range(len(df[col2][i]))]

[(909101, 1396920),
(909101, 3094857),
 (21095887, 8383568),
 (8383568, 21095887)]

A: One quick and dirty fix, turning the second loop into a normal for-each loop:
[(df[col1][i], x)
            for i in range(len(df))
            for x in (df[col2][i] or [None])]


text:
Q: RFID coil - ends broke, can I resolder? The 125kHz RFID scanner / reader device I have, has a coil like this:

NB> Don't have a good camera handy at the moment, so had to share a cropped image from Alibaba, but the pic is very close to the one I have, mine being slightly thicker.
Now the problem is that this RFID reader has seen some abuse, and on opening it up, I figured that the 2 coil ends that were soldered to the PCB have snapped. While soldering them back, I have unfortunately broken the thin copper wires bit more, such that, I have very little free length remaining to solder them to the board.
Question now is -

*

*If I undo one round of the coil (which BTW, seems pretty difficult, as the thin wires are stuck together pretty hard), and solder the leads back on PCB, would the reduced coil turn impact functioning of the RFID reader ?

*Alternatively, if I solder 2 offboard wires (26AWG single strand copper) to the remaining tiny lengths of leads, and then solder those offboard wires back to PCBA, can it impact the functioning of the RFID reader ?

*Are these thin copper wires insulated from each other by something like transparent lacquer / clear varnish ? If so, while soldering, I believe I might burn-off some of it, so can I use standard clear-varnish available at hardware stores (for woodworking), to restore the insulation layer ?

A: *

*If you unwind one turn of the coil, you will detune the antenna.  At 125 kHz, the coil should have many turns and maybe this won't throw it off so far that it doesn't work.  But if you have two broken ends, you would be tempted to remove two turns.  That would be even worse.  You might be able to add some capacitance to bring it back in tune.

*Reattaching the wires by, in effect, splicing in some more wire, will work, especially at this low frequency.  There are some mechanical issues with those #26 wires; they will seem huge and will want to pull out the tiny wires, but electrically, it's sound.  It's the approach I would take, especially if I really just wanted to see if that really was the problem in the first place.

*Some types of insulation will burn off so you can solder, but many times it won't, and then you have to scrape the wire.  That's a challenge in itself.  I would not bother trying to apply more insulation unless I didn't think I could prevent the wires from touching.


text:
Q: Need to transform Razor code on ASPX code So, I need help to make this code work as ASPX, can anyone help me?
I know it,s just a few parts to be changed, but i don't know how to do it...
Or if Any one know hot to achive the same result other way this would be very helpfull.
I already try do it myself but got no luck doing so.. =/
So, I need help to make this code work as ASPX, can anyone help me?
I know it,s just a few parts to be changed, but i don't know how to do it...
Or if Any one know hot to achive the same result other way this would be very helpfull.
I already try do it myself but got no luck doing so.. =/
    @{
    ViewBag.Title = "Employee List";
    }

     Add New

            Name
            Position
            Office
            Age
            Salary

<link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

    @section scripts{

}


text:
Q: What is meant by the statement- "Histograms plot binned quantitative data"? The problem lies especially in the word-"binned". I've tried to consult the dictionary but it doesn't gives a satisfactory result.
I came across this while I was reading the difference between histogram and bar graph.

A: In a histogram you typically plot the values of a variable on the x-axis while plotting the frequency/count of the variable's values on the y-axis.
Especially with continous variables it is not very likely that you have the exact same value several times, rather you have similar values or values within a certain range (e.g. 1 to 1.5) that occur more than once.
Binning, thus, simply means that instead of plotting the count of each and every single observed value of a variable, you take ranges or bins of that variable and plot the frequency/count pertaining to values in that bin.
See: https://en.wikipedia.org/wiki/Data_binning

A: A histogram is a graphical representation of the estimated distribution of a variable (usually continuous). It consists of numbers for bins represented as bars.
Each bin is defined by an interval. The bar height for each bin represents the  number of values that lies in the corresponding interval.
So, for example if we have a sample X = (-4.5, -2.7, 3.4, 4.7, 5.5, 5.8, 6.0, 8.9, 9.2, 12.0), we can plot a histogram with, let's say, 4 equal-sized bins.
Intervals for bins would be [-5, 0), [0, 5), [5, 10), [10, 15]. So your 3rd bin will have value of 5, because 5 values of X lie within it (between 5 and 10).

A: As a matter of general graphics, a histogram is $-$ or I would say should be considered as $-$ just a special case of a bar chart. The argument is simple: a histogram uses bars to show information, just like any other kind of bar chart. The information here can be frequencies, probabilities, proportions or fractions, probability densities or frequency densities.
In statistics, a histogram is often considered to be not a bar chart. (The term bar chart seems more common than, say, bar graph or bar plot, but I won't argue for one rather than another: feel free to follow personal or collective taste.) It's hard for me to work out exactly why this is said. It could be just a convention handed down: we have a long-established term (histogram was one of Karl Pearson's coinages) and specific rules that should be used. For example, if bins (classes, intervals) are of unequal width, then arguably only showing some kind of density that scales for those varying widths makes sense. But that still doesn't explain the denial to me. I detect a whiff of academic snobbery in denying that histograms are bar charts. Bar charts are, after all, often taught at an early age and their use by academics, researchers, or students in papers or texts is often considered indicative of limited, low-level analyses.
But I'd argue, and I doubt that I am alone, that any bar chart showing frequencies for a discrete variable is also a histogram. Conventionally, gaps are left to underline that the scale is discrete. If the bars shrink to spikes, many might demur in calling such plots either histograms or bar charts, but again that seems a matter of conventional usage rather than logic. Naturally, or arguably, there is no harm in using a simple evocative term: I've used the term "spike plots" and it is echoed in (for example) Stata's spikeplot command:  see documentation here.
As already implied, I would be happy also to regard a histogram showing a continuous distribution by touching bars as a kind of bar chart. But watch out: if you follow that usage, you might be regarded as ignorant, or a little less bluntly, as just not having learned a standard term.
Either way, bin is a common word for each class or interval used on a histogram, or more generally in any grouping of a distribution into disjoint intervals. General-purpose dictionaries seem slow in catching that usage, which seems to have become increasingly common in recent decades. I think I first encountered it in J.W. Tukey. 1977. Exploratory data analysis Reading, MA: Addison-Wesley. The earliest use I can recall was by the statistically-minded geologist W.C. Krumbein in the 1930s.
(I'd add a precise reference later if I can find it again. Conversely, earlier references would be welcome.)


text:
Q: Openstack Heat - separate templates I am looking for the best way of creating a stack, in a number of separate steps.
I would like in the first template, to only get up the compute nodes and the network configuration.
In the second template, I would like to create the storage nodes and attach them to the already existing compute nodes.
What do you think is the best way to do this?

A: Following is one possible approach.
1) Define first template for your compute nodes and network configuration. But define outputs in your first template to expose your compute node IDs. For example, if you create a OS::Nova::Server with name mynode1, you can expose its ID as the output for that template as follows:
outputs:
  mynode1_id:
    description: ID of mynode1
    value: {getattr: [mynode1, id]}

Once you instantiate a heat stack, say mystack1, with this first template, then you can access the ID of mynode1 as follows:
heat output-show mystack1 mynode1_id

2) Create your second template for storage with IDs of your compute nodes from step1 as input parameters. For example:
parameters:
  mynode1_id:
    type: string
    description: ID for mynode1

Then you can use that in your "resources:" section as follows:
resources:
  ...
  ...
  my_volume_attach:
    type: OS::Cinder::VolumeAttachment
    properties:
      instance_uuid: {get_param: mynode1_id}
      ...

3) Invoke your second heat stack creation as follows:
heat stack-create -f second-template.yaml -P mynode1_id=`heat output-show mystack1 mynode1_id` mystack2

A: You might also want to define dependencies between your resources, using the depends_on attribute.
From your description it doesn't seem like using several templates is the correct solution.
for example - if you want objects 3,4 created after objects 1,2, you can define a template as follows:
heat_template_version: '2015-10-15'
parameters:
   param1:
        type: string
        description: just an example of parameter
resources:
 object1:
  type: OS::Neutron::XXX
  properties:
     property: XXX
  description: object1
 object2:
  type: OS::Neutron::XXX
  properties:
     property: XXX
  description: object2
 object3:
  type: OS::Nova::XXX
  properties:
     property: XXX
  description: object3
  depends_on: object1
 object4:
  type: OS::Nova::XXX
  properties:
     property: XXX
  description: object4
  depends_on: object1


text:
Q: We need to be able to search for punctuation (symbols) Every week or so you get, say, a question about the difference between '==' and '===' in PHP. Of course it inevitably gets closed as a duplicate but some people apparently feel the need to leave comments like 'Already asked! God! (roll eyes)' Well you can't actually search for something like == or === unless you happen to know what it's called.
Can we extend the search to allow for these characters?

A: Try
SymbolHound: Search Stack Overflow for special characters

SymbolHound is a search engine that doesn't ignore special characters. I was always frustrated that I couldn't search for symbols like >> and && using Google or the custom Stack Overflow search, so I made a search engine for programmers. It currently searches mostly Stack Overflow pages, with plans to eventually index a much wider range of programming websites (including symbols, of course).

A: This is now possible with the new search engine, just put your search in quotes, a few examples:

*

*Everywhere: "===" php

*Only in code blocks: code:"===" php

*A good search for == vs === questions/answers: "==" "===" php
The search is case insensitive but is otherwise an exact match engine.

A: Actually, I voted to close one question today (the exact same question, for Javascript instead of PHP) and pointed to three dupes. Two of them did show up right in the "Related" section in sidebar.
Interestingly, I feel the "exact duplicate search" works pretty well in finding the duplicates (better than the SO search box.) Is the algorithm different or it's wrong feeling?

A: Stack Overflow really should extend the search to include symbols. There's a gigantic gap in the market for this. See this frustrated Google user:
Programmer-friendly search engine?
Duplicate questions is a cost that Stack Overflow must accept as a consequence of not having this feature. And it should accept it cheerfully, and not grudgingly, until it gets its act together and adds it.


text:
Q: How do I make two different ArrayLists reference the same object when Parsing a Json file I am trying to parse a json data file that has a singular object inside two different ArrayLists:
{
  "TA": [
    {
      "firstname": "John",
      "lastname": "Smith"
    },
    {
      "firstname": "Jane",
      "lastname": "Doe"
    }
  ],
  "Student": [
    {
      "firstname": "John",
      "lastname": "Smith"
    },
    {
      "firstname": "Kevin",
      "lastname": "White"
    }
  ]
}

My current parsing method just creates a new Person object for each one and adds them to each List object, but I want my Person object John Smith to only be a singular object referenced by both "TA" list and "Student" list. How could I go about doing this?

A: If you're trying to lower memory usage, you can use a static factory method to intern instances. Assuming you use Jackson:
class Person {
    private static Map<Person, Person> cache = new HashMap<>();

    @JsonCreator
    public static Person create(
            @JsonProperty("firstname") String firstname,
            @JsonProperty("lastname") String lastname) {
        Person person = new Person(firstname, lastname);
        return cache.computeIfAbsent(person, Function.identity());
    }

    final String firstname;
    final String lastname;

    private Person(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }

    @Override
    public boolean equals(Object o) {
        return o instanceof Person
                && Objects.equals(((Person)o).firstname, this.firstname)
                && Objects.equals(((Person)o).lastname, this.lastname);
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.firstname, this.lastname);
    }
}

A: TA and Student list are two different list. If you define each list and populate them with the same object (person), yes they would point to the same object. That is object oriented approach.
Parsing a Json and expecting to have the same person object in both arrays is not possible (assuming that person object would get created by the parser). The parser would process each array individually and hence you person object is not going to be the same.
There is a way you can do it that would be by defining person object in a static class. This way you would always get the same instance of the person object.
I your case you will have to create a static person object for each variants (firstname lastname)


text:
Q: how to use CloudFront or any other CDN with meteor application. I am not getting any good document for using CDN with meteor application.
Anyone can guide me to CDN with meteor application ?
Thanks,
hare

A: I've detailed how we accomplished this at Edthena in this post. The TLDR is:
Add this line somewhere in your server code:
WebAppInternals.setBundledJsCssPrefix(CDN_URL);

Where CDN_URL is your CloudFront URL (e.g. https://a27n0s89ik4xb3.cloudfront.net).
We kept the defaults when creating the CloudFront distribution except for the following:
Origin Domain Name: myapp.example.com
Origin ID: myapp.example.com
Viewer Protocol Policy: HTTPS Only
Compress Objects Automatically: yes

If you serve your own fonts, you can end up with cross origin errors (unless you use a font data URL). Josh Owens describes how to deal with that in his post.


text:
Q: Are reversible adiabatic processes always isentropic? If my understanding is correct, neither reversible nor adiabatic processes are necessarily isentropic.
But are reversible adiabatic processes always isentropic?

A: Yes. For a reversible process, we have the relation
\begin{align}
  dS = \frac{\delta Q}{T}
\end{align}
and for an adiabatic process, we have (by definition)
\begin{align}
  \delta Q = 0,
\end{align}
which implies that
\begin{align}
  dS=0.
\end{align}

A: Yes.
From Clausius theorem the following inequality can be deduced:
$$\delta Q \le TdS$$
where the equality holds in the reversible case.
So, a reversible adiabatic process is necessarily isentropic, but irreversible adiabatic processes are not so.
To put it in another way, in an irreversible process, according to the above inequality, either entropy  changes, or heat must be somehow removed from the system to make it possible to have zero change in entropy.  So an irreversible isentropic process can not be adiabatic.

A: I want to explain from fundamentals, rather than invoking the Clausius theorem. Here goes:
STEP 1: REVERSIBLE --> No entropy creation or destruction during the process
Entropy cannot be created or destroyed in any part of any reversible process whatsoever. The reason is, first, entropy can never be destroyed under any circumstance (second law of thermodynamics), and second, if entropy was created in (part of) the process, it would be destroyed in the corresponding part of the reversed-version-of-the-process. But again, entropy cannot be destroyed.
STEP 2: ADIABATIC --> No entropy flow during the process (into or out of the region in question)
If no heat is flowing into or out of the region (definition of "adiabatic"), and no matter is flowing into or out of the region (also part of the definition of "adiabatic" I think), then there's no way that entropy could be flowing into or out of the region.
CONCLUSION: The entropy of the region is fixed if the process is both reversible and adiabatic.

A: Every reversible adabatic process is isentropic. But the converse is not true.Every isentropic process may be reversible adabatic or may not be reversible adabatic.

A: To answer this question, lets start with combined first and second law of thermodynamics,
\begin{equation}
dU = TdS-PdV
\end{equation}
For ideal gas, $dU=c_{v}dT$. Thus
$$TdS = c_{v}dT+PdV \qquad$$
Change in entropy in terms of exact differentials (by using the equation of state for an ideal gas $PV=RT$),
$$\tag{1} dS = c_{v}\frac{dT}{T}+ R\frac{dV}{V}$$
By taking log on both sides of the ideal gas equation $PV=RT$ and taking differentials on both sides yields
\begin{equation}
\frac{dP}{P}+\frac{dV}{V} = \frac{dT}{T}
\end{equation}
Using the above equation in Equation (1), and making use of the relations $c_{p}-c_{v}=R; \gamma=c_{p}/c_{v}$, we find
$$dS= c_{v}\left[\frac{dP}{P}+\frac{dV}{V}\right]+R\frac{dV}{V}$$
or
\begin{equation}
\frac{dS}{c_{v}} = \frac{dP}{P} + \gamma\frac{dV}{V}
\end{equation}
Integrating between two states 1 and 2, gives
\begin{equation}
\frac{\Delta S}{c_{v}} = \ln\left(\frac{P_{2}}{P_{1}}\right)+\gamma\ln\left(\frac{V_{2}}{V_{1}}\right) = \ln\left[\frac{P_{2}}{P_{1}}\left(\frac{V_{2}}{V_{1}}\right)^{\gamma}\right]
\end{equation}
Using both sides of the last expression as exponents we obtain
$$\tag{2} \boxed{\frac{P_{2}V_{2}^{\gamma}}{P_{1}V_{1}^{\gamma}} = e^{\Delta S/c_{v}}}$$

Equation (2) describes a general process. For the specific
situation in which entropy is constant, i.e. $\Delta S = 0$, we
recover the expression $PV^{\gamma}=\text{constant}$. Which is applied
for reversible adiabatic process.
We now see, through the use of the second law of thermodynamics, a
deeper meaning to the expression, and to the concept of a reversible
adiabatic process, in that both are characteristics of a constant
entropy, or isentropic process.

So in general an adiabatic process is not necessarily
isentropic-only if the process is reversible ($\Delta S =0$) and adiabatic ($dQ =0$), we
call it isentropic.


text:
Q: How can I fight the wall of flesh without killing the guide? I'm nearing hardmode, but I have moral objections to sacrificing the Guide in order to fight the Wall of Flesh. Even in a silly video game I don't want to be that evil.
Is there a way to summon the Wall of Flesh without sacrificing the Guide?
I'm not interested in solutions like "accidentally kill a voodoo demon over the lava", I want to actually not kill the Guide.

A: I had the same feelings when I was ready to enter Hardmode. There apparently is not a way to summon the Wall of Flesh or any other bosses from the vanilla console, but there are mods.
I used TShock, a Terraria server that lets you spawn any boss (among other things). It worked nicely, and if you want to quit using it after you beat the Wall of Flesh, that's fine - it's an external server, so there's nothing to uninstall from your game.

*

*Back up your saves! Just because it's better to be safe than sorry.

*Download TShock and start the server.

*Join the server via multiplayer, using 127.0.0.1 as the IP and the default port.

*Become an admin, as described in the instructions linked in step 2.

*Enter /spawnboss wof in the in-game chat, preferably while in the Underworld.

A: The only way to summon the wall of flesh involves killing the town guide.
This is not a great loss, as the guide respawns quite quickly, and there is no penalty for killing an NPC.

A: if you had the cheat i had, you could spawn him in which got banned because it gave you any item you wanted for nothing. Like, if you wanted the best items in the game before hard-mode, you could get them for free and anything else. But it got banned in 2016 so everyone that had it got it took away.

But for your question, what you can do is start a server, invite a few people, make them and yourself admins, then type the command for spawning the Wall of Flesh and, Tada! Done!