text:
Q: new tab in page product view frontend? I need to set a new tab in my page product view in frontend for only my CUSTOM type of product, i have tried:
copy the catalog.xml from /theme/layout and paste in my theme/layout, and inserted my custom product:
<PRODUCT_TYPE_virtual translate="label" module="catalog">
    Catalog Product View (Virtual)
    <reference name="product.info">
        <block type="catalog/product_view_type_virtual" name="product.info.virtual" as="product_type_data" template="catalog/product/view/type/default.phtml">
            <block type="core/text_list" name="product.info.virtual.extra" as="product_type_data_extra" translate="label">
                Product Extra Info
            </block>
        </block>
    </reference>
</PRODUCT_TYPE_virtual>
    <PRODUCT_TYPE_incomm_virtual translate="label" module="catalog">
    Catalog Product View (Incomm Virtual)
    <reference name="product.info">
        <block type="catalog/product_view_type_virtual" name="product.info.virtual" as="product_type_data" template="catalog/product/view/type/default.phtml">
            <block type="core/text_list" name="product.info.virtual.extra" as="product_type_data_extra" translate="label">
                Product Extra Info
            </block>
        </block>
    </reference>
</PRODUCT_TYPE_incomm_virtual>

and calls in my another catalog.xml in subfolder from layout, with this:
<?xml version="1.0"?>
<layout version="0.1.0">
    <PRODUCT_TYPE_incomm_virtual translate="label" module="catalog">
        <block type="catalog/product_view_attributes" name="incomm_termos" as="termos" template="fourward/incomm/product/view/termos.phtml">
            <action method="addToParentGroup"><group>detailed_info</group></action>
            <action method="setTitle" translate="value"><value>Terms of Use</value></action>
        </block>
    </PRODUCT_TYPE_incomm_virtual>
</layout>

but nothing happens, i need to create a new tab after description product and i prefer to make in code and only for my custom type of product. how i have to do?
i have follows the http://twincreations.co.uk/add-custom-product-tab-in-magento-1-9-ce/ but i dont know how to use in multiples ways (filtered for type of product). thanks

A: You forgot the <reference name="product.info"> in your layout.  So your block is added in the page but it not associated to the tabs section.
Try it like this:
<layout version="0.1.0">
    <PRODUCT_TYPE_incomm_virtual translate="label" module="catalog">
        <reference name="product.info">
            <block type="catalog/product_view_attributes" name="incomm_termos" as="termos" template="fourward/incomm/product/view/termos.phtml">
                <action method="addToParentGroup"><group>detailed_info</group></action>
               <action method="setTitle" translate="value"><value>Terms of Use</value></action>
            </block>
        </reference>
    </PRODUCT_TYPE_incomm_virtual>
</layout>


text:
Q: Using WCF to Render HTML? I have a stylistic question, really.
I am wondering which is the best, fastest, most "iterative" way
to generate client HTML?
The road I am currently traveling is to use WCF (or a DLL) to
expose a method that can be called depending on the page being
loaded:
private AuthClient auth = null;

PageLoad {

auth = new AuthClient();

string pageHTML = auth.GetHTML(string param);

ClientElem.InnerHtml = pageHTML;

}

This seems logical to me but, maybe there is a more productive approach
that I am not currently aware of? Also, if anybody has good examples of
WCF methods that pump large HTML strings for rendering on the client, I
would appreciate it (assuming that this is a reasonable approach).
Thanks.

A: This would not be the most efficient approach because you are going to have to go through proxy creation, creation of a soap envelope to send the message to the service, then the delay response from the WCF service to create the string etc.  What is it that you are trying to accomplish?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Проблемное деление чисел Необходимо спарсить участников из группы ВК. В результате не могу продумать логику приложения. Есть опереденное кол-во участников (например 11111) и используя структуру ссылок вк для перехода по страницам, где отображаются эти самые участники, например offset=кол-во(минимальное значение 0 - максимальное кол-во участников).Так вот решил использовать подстановку значений.Тоесть как и сам вк решил брать по 50 на страницу (это максимум). Для того чтобы перейти на вторую нужно добавить ещё 50. И так дальше.
Сам цикл я реализовал так - делил количество участников на 50 и получал сколько раз нужно выполнить. Но в результате не выводилось то,что не делилось на 50(я так понимаю).
Вот небольшой кусок кода:
$kolvo = 11121;
$res = $kolvo / 50;
echo "$res
";
$i = 0;
$link = 0;
 while ($i <= $res) {
  echo "$i =members&offset=$link
"
  $link+=50;
  $i++;
}

A: попробуйте так
$kolvo = 11121;
$res = ceil($kolvo / 50);
echo "$res
";
$i = 0;
 while ($i <= $res) {
  $link = $i * 50;
  echo "$i =members&offset=$link
"
  $i++;
}


text:
Q: How to start Android APK on device via ADB? I have a simple android app .apk file create with Expo (react native) using the expo build:android script.
I am trying to run this on a device which is locked down by the provider so their is no access to Expo client. The only interface is via ADB.
I have successfully installed the app using the following command:
adb -s <device_id> install <package-name>.apk

I am then trying to start the app via the following:
adb shell am start -n host.exp.myapp

But I get the following error:
Exception: java.lang.IllegalArgumentException: Bad component name: host.exp.myapp

When I run adb shell cmd package list packages, I can see the package:host.exp.myapp listed and I am sure it's following naming conventions with lowercase and no special characters.
How can I start my app via ADB?

A: Use the command adb shell monkey -p com.package.name  -c android.intent.category.LAUNCHER 1
It starts the activity as if it was launched using the launcher. Replace com.package.name with desired package name in the command.

A: If you only know the package name and not the Activity you can use AndroidViewClient/culebra which resolves it.
For example, if you only knows the Chrome package name com.android.chrome you can run
#! /usr/bin/env python3

from com.dtmilano.android.viewclient import ViewClient

device, serialno = ViewClient.connectToDeviceOrExit()
device.startActivity(package='com.android.chrome')

and it is resolved to the main Activity and then started.
If you want to do it from adb without using python you can take a look at the source here.


text:
Q: Kotlin reduce operator seems to not work Tried to run this example on Kotlin's online learning tool:
fun toJSON(collection: Collection<Int>): String {
    val str = collection.reduce{ a:String, b:Int -> ""}
    return str.toString()
}

However, it doesn't seem to compile, spitting this error:
Error:(2, 25) Type parameter bound for T in inline fun <S, T : S> Iterable<T>.reduce(operation: (S, T) -> S): S
is not satisfied: inferred type Int is not a subtype of String
Anyone seen this?...not sure if it's an error with the online tool or if it's actually something wrong.

A: The Kotlin Standard Library has two different types of accumulators: fold and reduce. It looks like you want fold:
collection.fold(initial = "") { accumulator: String, element: Int -> "" }

A: You can't reduce a collection of ints to a collection of strings. These compile:
// reduce to int
collection.reduce { x:Int, y:Int -> 0 }

// map to string first, then reduce
collection.map { "" }.reduce { x:String, y:String -> "" }

This is clearer if you take a look at the reduce signature:
fun <S, T: S> Iterable<T>.reduce(operation: (S, T) -> S): S
It basically operates on a collection of type T, and produces an S which is a T or a supertype of T.


text:
Q: django validate multiple inline forms I'm using the Django admin interface and Modelform form validation.
I'm having an issue for one of my models, I can't figure out a way to have the inline forms check for uniqueness on a field. For example there are two inline objects with the the field 'name'. I'd like to raise a validation error if both contain the same name.
From what I can see, each inline is validated as a separate form so its hard to tie them in and check for this.
(Very) basic idea:
Class Parent
    name    charfield
    inlines [Child]

Class Child
    name    charfield   <- I'd like to make sure this is unqiue within the inlines
    age     intfield

A: You write your own FormSet class, and make a clean callable:
class BaseDateFormSet(BaseInlineFormSet):
'''run some validation on the forms dates values'''

    def clean(self):
        super(BaseDateFormSet, self).clean()
        if any(self.errors):
            return
        for form in self.forms:
            start_date = form.cleaned_data.pop('start_date', None)
            end_date = form.cleaned_data.pop('end_date', None)

            if start_date and end_date:
                if start_date >= end_date:
                    raise ValidationError("The end date is before the start date.")

To use, pass into the formset factory:
MyFormSet = inlineformset_factory(
    <parent model class>, <model class>, extra=1, formset=BaseDateFormSet
)


text:
Q: How to combine stderr and stdout to single C++ string? I can grab stdout and stderr separately using fork, execvp, pipe, etc. functions and put them into two separate C++ strings. How can I use this family of functions to combine both stdout and stderr into a single combined string like the shell would as if I am redirecting like "2>&1"? The example below just captures stdout:
#include <sys/wait.h>
#include <unistd.h>
#include <string>
#include <vector>

std::string qx(const std::vector<std::string>& args) {
  int stdout_fds[2];
  pipe(stdout_fds);

  int stderr_fds[2];
  pipe(stderr_fds);

  const pid_t pid = fork();
  if (!pid) {
    close(stdout_fds[0]);
    dup2(stdout_fds[1], 1);
    close(stdout_fds[1]);

    close(stderr_fds[0]);
    dup2(stderr_fds[1], 2);
    close(stderr_fds[1]);

    std::vector<char*> vc(args.size() + 1, NULL);
    for (size_t i = 0; i < args.size(); ++i) {
      vc[i] = const_cast<char*>(args[i].c_str());
    }

    execvp(vc[0], &vc[0]);
    exit(0);
  }

  close(stdout_fds[1]);

  std::string out;
  const int buf_size = 4096;
  char buffer[buf_size];
  do {
    const ssize_t r = read(stdout_fds[0], buffer, buf_size);
    if (r > 0) {
      out.append(buffer, r);
    }
  } while (errno == EAGAIN || errno == EINTR);

  close(stdout_fds[0]);

  close(stderr_fds[1]);
  close(stderr_fds[0]);

  int r, status;
  do {
    r = waitpid(pid, &status, 0);
  } while (r == -1 && errno == EINTR);

  return out;
}

int main() {
  qx({"openssl", "hjas"});
  qx({"openssl", "dkjsah"});
  qx({"uname"});
  qx({"uname"});
}

A: Just use one pipe to collect both:
std::string qx(const std::vector<std::string>& args) {
  int output[2];
  pipe(output);

  const pid_t pid = fork();
  if (!pid) {
    // collect both stdout and stderr to the one pipe
    close(output[0]);
    dup2(output[1], STDOUT_FILENO);
    dup2(output[1], STDERR_FILENO);
    close(output[1]);

    std::vector<char*> vc(args.size() + 1, NULL);
    for (size_t i = 0; i < args.size(); ++i) {
      vc[i] = const_cast<char*>(args[i].c_str());
    }

    execvp(vc[0], &vc[0]);
    // if execvp() fails, we do *not* want to call exit()
    // since that can call exit handlers and flush buffers
    // copied from the parent process
    _exit(0);
  }

  close(output[1]);

  std::string out;
  const int buf_size = 4096;
  char buffer[buf_size];
  do {
    errno = 0;
    const ssize_t r = read(output[0], buffer, buf_size);
    if (r > 0) {
      out.append(buffer, r);
    }
  } while (errno == EAGAIN || errno == EINTR);

Note that your original code doesn't collect the child's stderr output.  Should the child write enough to stderr that the pipe fills up, the child process might block.


text:
Q: Block websites to a specific user in windows server 2016 In the company I'm in, they want to block a specific user to access some websites.
They have to login in the computer so my idea was to block using group policy management, but I dont find that anywhere. Other users can access those websites.
I have been searching for something that can help me, but I dont find anything. I usually don't work with windows server (and others), so I just know the basics.

A: Not ideal, but as temporary bodge you could create a .PAC file, host it on a webserver and create a GPO setting applied only to this one user?
GPO
User Configuration > Preferences > Control Panel Settings > Internet Settings > Internet Explorer XX > Connections > LAN Settings > Use Automatic Configuration Script: http://yourwebserver/proxy/BlockSteve.pac

.PAC file:
function FindProxyForURL(url, host)
{

/* Block these */

if (shExpMatch(url,"*logmein.com"))
   { return "PROXY 127.0.0.1:8081;DIRECT"; }

if (shExpMatch(url,"*google*"))
 { return "PROXY 127.0.0.1:8081;DIRECT"; }

/* Allow everything else */

else
 return "DIRECT";
}


text:
Q: Passing variables in a multi-project solution I am working with a progaram called aspdotnetstorefront.
This is a shopping cart program
The solution has 7 projects in it
There is a file in the web project that is called checkout1.cs that has the checkout1.aspx file
The checkout1.aspx file has a field for state. In the solution, there is project called aspdnsfcommons which has a file called Shoppingcart.cs.
I have tried everything to take the value of the state textbox from web/check1.aspx and pass it to aspdnsfcommons/shoppingcart.cs
Please advice me of the direction I should take.

A: Add a reference to aspdnsfcommons in your project. There should be a state property in Shoppingcart.cs with write access (set property) that you can use to achieve this.


text:
Q: Feature selection for MLP in sklearn: Is using PCA or LDA advisable? I have a binary supervised classification problem with about 62 features, by eye about 30 of them could have reasonable discriminating power. I am using sklearn and the MLP does not have a dedicated feature selection tool like decision trees do.
My question is what is the recommended way to preform feature selection here?
I have read in the sklearn documentation that LDA should not be performed in a binary classification problem and PCA is under the unsupervised methods on the sklearn website.
Does anyone have any experience with this that could suggest a method?
(P.S. Apologies if this question isn't up to standard, this is my first question ever asked)

A: Two suggestions:

*

*One important reason to use neural network is that, the model can do "feature selection and feature engineering" automatically for us. Unless we have a huge problem (say millions features), it is not necessary to use feature selection for neural network.

*Using PCA for feature selection on supervised learning is a bad practice, since it does not consider the "correlation" between feature and label, and direct select feature with large variance. In other words, we can have a completely useless feature but with large variance in data, and PCA will select it. See my answer here for details How to decide between PCA and logistic regression?


text:
Q: User folder on mac OS is empty, but still uses 60GB of hard drive space I have deleted all the files under User folder, but it still says that it uses ~60GB of space. Real usage is ~2MB. There are no more files to delete. Is there any hidden files i am not aware of. If yes, how i can delete them?

I do not want to delete the user account. I just want to get rid of information that is useless, but I don't want to mess up my Mailbox or other stuff, so I want an advice if it's safe to delete some parts of those folders.

A: Rebuild your Mailbox. You can do it by running Mail, and select Mailbox » Rebuild from menu bar. This'll remove all the attachments in all your signed in accounts.
As for the massive file size in ~/Library/Application Support, you have to figure out which apps taking up the largest space. Run these apps and try to reset the caches with the built-in options or menus. If you still can't find one, consider remove the largest file (not entire folder).
Take time to skim through the list and delete folder where apps are no longer installed (usually they're named after the app name). It's possible that you didn't remove apps correctly before.

A: In Yosemite if you use iTunes and have an iPhone - release your older backups - they are categorized as "other" storage on your hard drive and if you have a larger iPhone the backups can be 20+ gigs.

A: I was having a similar issue.  I had over 60 GB of "movies" that I couldn't find anywhere.  It was actually in my recently deleted album of my photos.  If you double click albums, you should see one that says "recently deleted".  There was 57 GB in there.  I permanently deleted them, and problem was solved.

A: The space is most likely being occupied by the various files and folders in ~/Library, which is hidden by default on OS X. You can show the Library folder by navigating to your home folder in Finder, pressing ⌘J and showing the Library folder.
Furthermore, you can run the following command in your home folder which will list all the files and folders in your home folder, including hidden files and folders, and display their sizes.
du -shc .??* *

A: Not sure what you trying to accomplish here, and I would not trust the DiskWave.app to be accurate.
I strongly advise you not to delete hidden files.
There is a reason they are hidden.
If you must see them in Finder, run the following in Terminal.app:
defaults write com.apple.Finder AppleShowAllFiles 1 && killall Finder

To reverse that, use this command:
defaults write com.apple.Finder AppleShowAllFiles 0 && killall Finder

A: Well, I had similar issue in my Download folder.
Many times I got the message 'Startup Disk is almost full'.
Finder was showing 37 GB in that folder, but, checking each subfolder individually, the size of all was like 10 GB smaller.
So, I could not (yet) figure out why it happens, but, I could find out how to fix it.
The only matter is the problem may keep showing itself up.
So, to fix this, go to 'System Preferences' -> 'Spotlight', then, 'Privacy'.
Click on the '+' button, and add the disk which contains the 'wrong sized folder'. Hit OK for confirmation.
Reboot your Mac (when I learned about it, this step was not mentioned. I did it on my own, just to make sure).
After the reboot, go back to system 'System Preferences' -> 'Spotlight', then, 'Privacy'. Now, click in a disk you just added, and remove it (using the '-' button).
And it's done the trick.
PS 1: MacBook Air 2010, OS X v10.8.5 (Mountain Lion), 256 GB SSD
PS 2: Sorry, I do not remember where I learned it, but, in the worst case, you will lose a bit of time while OS X rebuilds the file indexes to improve spotlight search.
PS 3: If you realize the spotlight is not searching how should be, it is a signal that above procedure should be executed.
PS 4: Another tip that may be helpful:
Go to Disk Utility, select your disk, and hit 'verify disk permissions'. After done, click in 'repair disk permissions'.

A: I had a similar problem - my folder usage was 20GB when I look at my user directory. Use muCommander as root (sudo) and check this folder again.

A: Many many files and folders system hidden. You can show and check your capacity.
In Finder show hidden system: View -> Show System Files
Or you can get information about capacity in your profile user by open Terminal and type:
du -shc .??* *

A: I had the same issue. I used the terminal command du -shc .??* *
to show hidden files and looked in the LIBRARY folder in the User folder. Under Application Support was where all the space was being used. A Folder called ILIFEASSETMANAGEMENT .
There were a lot of pictures in there. I went into SETTINGS and under iCloud Photos Options , turned off PHOTO STREAM. Bingo..got all my space back.

A: This was killing me too. I resorted to doing a clean reinstall. Not even a simple reinstall (the one where there's no formatting of the hard disk) would get rid of the infamous "60GB". Now it hovers around 10GB, but I chose not to use iCloud at all. You turn that on and things start to get out of your control. I prefer Dropbox; at least I know that what I put there is what I'm backing up.

A: I recovered somewhere in the neighbourhood of 80 GB yesterday by running Onyx and removing OS X's file versions which causes a fair amount of bloat well beyond regular cache cleaning.
Of course, backup/be careful use at own risk, but:
http://www.titanium.free.fr/onyx.html

A:
Culprit --The hidden library folder!

A: There is a nice program for Mac called CCleaner. While I was a Windows user, CCleaner was a great companion, deleting thrash files and cleaning the registry. ^_^ (well, OS X has no registry...)
I run CCleaner every day, before shutting down my Mac.
https://www.piriform.com/mac/ccleaner

A: Another thing that can eat up a lot of time and disk space is Spotlight, which crawls around looking for things to index.  It can generate a lot of "unexplained" disk activity and very large hidden files.  On my system, I drastically reduced the list of things that it was allowed to index, to include only the things I actually need.

A: In my case, The real culprit was 2 .err files under the following path /usr/local/var/mysql/ which were taking about 45 GB and 4 GB respectively.
After deleting this files I immediately recovered around 50 GB of data.
Hope this is of use to someone.


text:
Q: HotChocolate returns ignored field I have a user object, where i have created an ObjectType to ignore the Password field as it is genearlly not a good idea to expose that in my API :) However HotChocolate still returns the password field in the response.
Account.cs

public class Account {
    [Key]
    public string Id { get; set; }

    [Required]
    [StringLength(250)]
    public string Email { get; set; }

    [Required]
    [StringLength(512)]
    public string Password { get; set; }

    [Required]
    [Range(0, 2)]
    // 0 = Landlord, 1 = Tenant, 2 = Maintenace
    public int AccountType { get; set; }

    [Required]
    [StringLength(150)]
    public string Name { get; set; }

    [Required]
    public long CreatedMilliseconds { get; set; }
    [Required]
    public long UpdatedMilliseconds { get; set; }
    [Required]
    public long LastSeenMilliseconds { get; set; }
}

public class AccountType : ObjectType<Account>
{
    protected override void Configure(IObjectTypeDescriptor<Account> descriptor)
    {
        descriptor.Ignore(f => f.Password);
    }
}

AccountQuery.cs
[ExtendObjectType(typeof(Query))]
public class AccountQuery {
    private readonly Logger log = LogManager.GetCurrentClassLogger();

    [Authorize]
    public Account GetMe(ClaimsPrincipal claimsPrincipal, [Service] DataContext context) {
        string userId = AuthHelper.GetUserId(claimsPrincipal);
        return context.Accounts.Where(x => userId == x.Id).FirstOrDefault();
    }
}

My program.cs
        // Add GraphQL services
        builder.Services
               .AddHttpContextAccessor()
               .AddDbContext<DataContext>()
               .AddGraphQLServer()
               .AddAuthorization()
               .AddQueryType<Query>()
               .AddMutationType<Mutations>()
               .AddTypeExtension<AccountMutations>()
               .AddTypeExtension<AccountQuery>();

A: You can use the [GraphQLIgnore] attribute as described here.
[GraphQLIgnore]
public string Password { get; set; }


text:
Q: Angular set mat-input to error state after http error response is there a possibility to set mat-input in error state after http error response? On submit of form from code below im sending an http request and i would like to show the mat-error but it shows only when input is in error state and i don't know how to set it "manualy" after error response

<form [formGroup]="exampleForm" (ngSubmit)="onSubmit()">
  <mat-form-field>
    <input matInput placeholder="placeholder" formControlName="Input" required>
    <mat-error *ngIf="variable">error message</mat-error>
  </mat-form-field>
</form>

A: serviceClass:
export class serviceClass{
    private url: string = 'your url'// your http request url

    constructor(private http: HttpClient) { }

    callApi() {
        return this.http.get(this.url);
    }
}

componentClass: while subscribing http request if you get error in response can set the errorVariable true.
export class componentClass{
        private url: string = 'your url'
        public errorVariable:boolean;
        constructor(private service: serviceClass) { }

        getApi() {
            return this.service.callApi().subscribe(
              (response:string)=>{
                console.log(response);
             },
            (error)=>{
                console.error(error);
                this.errorVariable=true;
            }
            );
        }
    }

htmlTemplate:
<mat-error *ngIf="errorVariable">error message</mat-error>


text:
Q: Do I need to add null-tests everywhere once I have move functions? I am not quite sure what the way to go here is; if I have a class with pointer members and a move constructor that sets the pointer members to nullptr and the move-functions are the only function that can set the pointer members to 0, do I then need to put tests for zero everywhere I dereference any of the members, as the object might have been passed to a move constructor?
for example, a function
unisgned size()
{
    return memberpointer->size();
}

would become
unisgned size()
{
    if memberpointer == nullptr
        return 0;
    return memberpointer->size();
}

Otherwise of course this would give a segfault if size() is called on a moved object. Would that be the fault of the user or my fault for not building a null-test? If the user does not access moved object before re-initialising it, this could not happen as long as I put a null-test in the copy assignment operator:
C& operator=(C& src)
    {
        if (this != &src)
        {
            if (memberpointer == nullptr)
                init();
            *memberpointer = *src.memberpointer;
        }
        return *this;
    }

Putting test for null everywhere would reduce performance, which would be unnecessary if the user knew that accessing a moved and not re-initialized object is undefined behavior.
What is the way to go about this?

A: No, there's no need for all those tests, any more than if you didn't have move semantics at all.  If it's illegal to use your object before calling some sort of initialization function, then you should also consider it illegal to use the object after moving.  Your object should be left in a state that can be properly destructed, but there are no other rules specifying what that state should be.
For example:
Foo foo;
foo.Init();  // required
// foo is now allowed to be used

Foo bar = std::move( foo );
// No guarantees on whether foo is now initialised or not.

Move semantics do not stipulate what state the object moved from will be in after the move.  It only requires the object is in some internally consistent state.  So, your move constructor or assignment operator is perfectly entitled to swap the members if it wishes...  Provided all the other internal states of the object are consistent with that.  That is, it's perfectly okay to have this situation:
Foo foo, bar;
foo.Init();
bar.Init();
bar = std::move( foo );
// foo and bar contents now swapped.
// caveat: you should not use foo again

However, you must not expect this.  The rule is that after a move, you should not attempt to use the object again.

A: The C++ standard library solves this by leaving the moved-from object in a "valid but unspecified" state: In other words you can operate on it, using it won't crash your program, but the only predictable thing to do is write to it to re-establish a known state.
If your default constructor doesn't leave the pointers null, then your move constructor shouldn't either: It should leave the move-from object in a state where you can safely call members on it but not rely on any particular values. If your default constructor leaves the pointer(s) null then obviously that's fine for the move constructor too.


text:
Q: SQL Server error with query I'm trying to generate a report from data stored in my database but i'm having an error

Msg 8120, Level 16, State 1, Line 1
  Column 'Production.ProductCategory.Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

My query is the following
SELECT
    pc.Name AS Categoria,
    DATEPART(YEAR, soh.OrderDate) AS [ano],
    SUM((det.UnitPrice - det.UnitPriceDiscount) * det.OrderQty) AS total,
    SUM(soh.Freight) AS transporte,
    SUM(det.LineTotal) AS vendas
FROM
    Sales.SalesOrderHeader AS soh
INNER JOIN
    Sales.SalesPerson AS sp ON sp.BusinessEntityID = soh.SalesPersonID
INNER JOIN
    Sales.SalesOrderDetail AS det ON soh.SalesOrderID = det.SalesOrderID
INNER JOIN
    HumanResources.Employee AS e ON soh.SalesPersonID = e.BusinessEntityID
INNER JOIN
    Person.Person AS per ON per.BusinessEntityID = sp.BusinessEntityID
INNER JOIN
    Production.Product AS p ON det.ProductID = p.ProductID
INNER JOIN
    Production.ProductSubcategory AS ps ON p.ProductSubcategoryID = ps.ProductSubcategoryID
INNER JOIN
    Production.ProductCategory AS pc ON ps.ProductCategoryID = pc.ProductCategoryID
GROUP BY
    DATEPART(YEAR, soh.OrderDate)
ORDER BY
    DATEPART(YEAR, soh.OrderDate);

I want to have just one accessories/clothes/bicycle, etc and one time 2011/2012 etc...

A: change this line:
group by DATEPART(YEAR, soh.OrderDate)

to this
group by DATEPART(YEAR, soh.OrderDate), pc.Name

A: add
GROUP BY pc.Name

to the bottom of your query


text:
Q: Enable kafka client metrics in spring app prometheus I have an application that consumes from kafka topics and produce to kafka topics. I am trying to set up Grafana dashboard to display kafka metrics. I am trying to expose the kafka metrics to prometheus and so Grafana dashboard can fetch these metrics and display them further.
Below are the libraries and properties I am using.
org.apache.kafka:kafka-clients:jar:2.5.1:compile
io.micrometer:micrometer-registry-prometheus:jar:1.5.4:compile
io.micrometer:micrometer-jersey2:jar:1.5.4:compile

application properties:
spring.jmx.enabled=true
management.endpoints.web.base-path=/
management.endpoint.metrics.enabled=true
management.endpoints.web.exposure.include=prometheus
management.endpoint.prometheus.enabled=true
management.metrics.export.prometheus.enabled=true

Using micrometer, the prometheus is displaying jvm, tomcat related metrics and also the custom metrics. But the kafka metrics are not being exposed. I tried to debug and left with no clue. Any suggestions would be a great help.
As a heads-up, I am not using spring kafka annotations. I am running it as standalone multi-threaded where I fetch records using consumer.poll(1000L) method.
kafka consumer is created as: new KafkaConsumer<>(getProps()) and kafka producer is created as new KafkaProducer<>(props)
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, ...);
props.put(ConsumerConfig.CLIENT_ID_CONFIG, config.getConsumerName());

props.put(ConsumerConfig.GROUP_ID_CONFIG, config.getGroupId());
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, config.getKeyDeserializer());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, config.getValueDeserializer());
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, config.getEnableAutoCommit());
props.put(ConsumerConfig.RECEIVE_BUFFER_CONFIG, config.getReceiveBufferBytes());
props.put(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, config.getMaxPartitionFetchBytes());
props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, config.getMaxPollRecords());
props.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, RoundRobinAssignor.class.getName());

protected KafkaConsumer<byte[], Event> getConsumer(List<String> inputTopics) {
    KafkaConsumer<byte[], Event> consumer = new KafkaConsumer<>(props));
    consumer.subscribe(inputTopics, new ConsumerRebalanceListener() {
        @Override
        public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
            logger.info("PARTITIONS revoked: " + partitions);
            consumer.commitAsync();
        }

        @Override
        public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
            logger.info("PARTITIONS assigned: " + partitions);
        }
    });
    return consumer;
}

A: I already answered you on Gitter - the code above is not using Spring for Apache Kafka, you are creating your own consumer and producer.
If you use Spring for Apache Kafka's DefaultKafkaConsumerFactory, you can add a MicrometerConsumerListener to it and Spring will register metrics for each consumer with the meter registry via the KafkaClientMetrics. If you create your own consumers, you have to do that yourself.
Same thing for producers.


text:
Q: Determine day based on number I just want to ask if how do you determine
Enter a number: 14
Then the date to day is Sunday.

the above demonstration is  from 1-7=monday-sunday then if the value is 8 then its monday again...but how could I determine it?using loops and modulo?...
I appreciate any comments for helping me...
any language are ok, I just want to know the algorithm with it...

A: You can just use module
Module got to 0 so it would be something like
<?php
    $value = 13;
    $daynames = array("mon", "tues", "wed", "thur", "fri", "sat", "sun");

    // The + 1 is because % is 0, and you want 1-7
    echo (($value % 7) + 1) .  "day of the week";
    echo "the day is " . $daynames[($value % 7)];
?>

Example: http://codepad.org/wbGuMI06

A: If you have a switch/case or if/else for the seven days you can use modulo 7 to get the input into the desired range of 7 days.

A: You can use a switch statement and modulo arithmetic to do this.
The first step to learning computer science is to learn that numbers don't usually start at 1. They start at 0. Getting this idea down will help you tremendously in the future!
// accept numbers 0-6. If 7 were to get put in, it would end up being 0 since 7 % 7 = 0.

switch(num % 7) {
case 0: return "Sunday";
case 1: return "Monday";
case 2: return "Tuesday";
/// rest here...
default: throw new IllegalArgumentException();

}

A: Taking the number modulo 7 would seem like the obvious possibility.

A: string day;
int inputNumber;

if(inputNumber%7 == 0)
  day = "monday";  // or sunday if you prefer :p
else if(inputNumber%7 == 1)
  day = tuesday
...
...
...

A: In C++, int day = (i-1) % 7; will give you a zero-based offset.  Here's sample code:
#include <iostream>
#include<string>

using namespace std;

int main()
{
    static const std::string days [] =
    {
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday"
    };

    static const size_t num_days = sizeof(days)/sizeof(days[0]);

    for( int i = 1; i <= 31; ++i )
    {
        int day = (i-1) % 7;
        cout << day << " = " << days[day] << "\n";
    }
}

A: Get modulo 7 of the int value thats passed in and make a switch statement for it.
switch:
   case 1:
    Sunday
   case 2:
    Monday

    // and so on

A: datArr= new Array ('Sun', 'Mon', 'Tue',Wen', 'Thu, 'Fri', 'Sat');
day =datArr[(daynum%7)];

If Sunday gets treated as day zero there is no need to subtract 1 after the modulo. Of course most of the solutions will fail with zero dive if an actual value of zero is encountered.

A: import java.util.Scanner;

public class TestMain {
    private static final String[] DAYS = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thusday", "Friday", "Saturday" };

    public static void main(final String[] args) {
        System.out.print("Enter a number: ");

        final Scanner scanner = new Scanner(System.in);
        final int n = scanner.nextInt();

        System.out.print("Then the date to day is " + DAYS[n % 7]);
    }
}


text:
Q: External script adds to window, but added functions are undefined in Angular app So, unfortunately I need to embed a Hubspot form in my Angular app. This is done by including an external script and running some Javascript code to create a form on the page.
The following script needs to be included:
<!--[if lte IE 8]>
<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2-legacy.js"></script>
<![endif]-->
<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2.js"></script>

And then you can run hbspt.forms.create() to create the form. Not very interesting, right.
But what is interesting, is that this code doesn't work when using it in an Angular app. I've prepared a Stackblitz for an Angular project, and a project without a framework. Both have the above code in the index.html:
Angular: https://stackblitz.com/edit/angular-bdsz3h
No framework: https://stackblitz.com/edit/typescript-ld9ypn
Now, if you open up your console on the pages and enter hbspt.forms.create(), in Angular it will result in undefined. The framework-less project however, works as expected and shows that it is a function. What's happening here and how can I get it to work in Angular?

A: See line 32 of HubSpot Forms V2 Debug.js
For some reason (didn't look too far into) they loop through and set all listed properties (lines 21/23) to undefined. One of these being window.Promise.
Then when zone.evergreen.js picks up on the activity, specifically this bit of code, it throws a Cannot read property 'prototype' of undefined, as NewNativePromise would be window.Promise, which is now set to undefined.
I've only seen this when loading the script dynamically. When placing the script as you've shown in the index.html, everything seems to run fine. Might be winning a race-condition however...
Tried a few things like running it in it's own Zone.fork and ngZone.runOutsideAngular, but never figured it out.


text:
Q: can i target a :hover function in css after onclick javascript effect? So when i hover over the menu the background turns red and the text turns white.
When i click on the dropdown link the second UL is being displayed.
I wish to target the LI item .dropdown:hover as soon as i click on it. And set it to no hover.
is this done in css or javascript?
I have been trying arround with both but cant seem to target the right li.

let menuBtn = document.querySelector(".menu-Btn");
let menu = document.querySelector(".mainMenu");
// Button toggle-menu
menuBtn.onclick = ()=>{
    if (menu.classList.contains("show")){
        menu.classList.remove("show");
    } else {
        menu.classList.add("show");
    }
}
// Dropdown menu
let toggle = document.querySelector(".dropdown");
let sub = document.querySelector(".submenu");
toggle.onclick = ()=>{
    if (sub.classList.contains("show")){
        sub.classList.remove("show");
    } else {
        sub.classList.add("show");
    }
}
* {
    margin: 0;
    padding: 0;
}
body {
    background: #b3b3b3;
    justify-content: center;
    font-family: 'Open Sans', sans-serif;
}
header {
    margin: 0 0 20px 0;
    padding: 15px 0;
    width: 100%;
    height: auto;
    background: rgb(255, 255, 255);
}
.headerContainer, .container {
    width: 90%;
    margin-left: auto;
    margin-right: auto;
    padding: 15px;
    border: 1px solid #000;
}
.headerContainer {
    position: relative;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.headerBrand a {
    font-size: 30px;
    font-weight: 800;
    text-decoration: none;
    color: rgb(0, 0, 0);
    display: flex;
    align-items: center;
}
.headerBrand a img {
    padding: 0 10px 0 0;
}
header nav {
    top: 100%;
    left: 0;
    width: 100%;
    position: absolute;
    max-height: 70vh;
    overflow-y: auto;
}
header nav::-webkit-scrollbar {width: 10px;}
header nav::-webkit-scrollbar-track {background: #f1f1f1;}
header nav::-webkit-scrollbar-thumb {background: #888; }
header nav::-webkit-scrollbar-thumb:hover {background: #555;}

header nav .mainMenu {
    padding: 15px;
    display: none;
    list-style: none;
    background: #ffffff;
    border-radius: 5px;
}
header nav .mainMenu.show {
    display: block;
}
header nav ul li {
    padding: 5px 0;
    background:rgb(255, 255, 255);
    border-bottom:1px solid rgb(179, 179, 179);
    position: relative;
    justify-content: space-between;
}
header nav ul li:last-child {
    border: none;
}
header nav ul li a {
    display: block;
    font-size: 15px;
    font-weight: 700;
    width: calc(100% - 10px);
    text-transform: uppercase;
    color: red;
    text-decoration: none;
    padding: 0 0 0 15px;
}
header nav ul li.activepage {
    background: red;
    border-radius: 5px 5px 0 0;
}
header nav ul li.activepage a {
    color: white;
}
header nav ul li.dropdown a i {
    top: 10px;
    right: 10px;
    font-size: 10px;
    position: absolute;
}
header nav .mainMenu .submenu {
    display: none;
    padding: 0 0 0 15px;
    position: relative;
    border-radius: 0%;
}
header nav .mainMenu .submenu.show {
    display: block;
}

header nav .mainMenu li .submenu li {
    padding: 5px 0 5px 0;
}
header nav .mainMenu li .submenu li a {
    text-transform: none;
    font-weight: 400;
}
.menu-Btn {
    width: 35px;
    height: auto;
    text-align: center;
    background: red;
    font-size: 25px;
    border-radius: 5px;
    cursor: pointer;
}
.menu-Btn i {
    color: white;
}
header nav ul li:hover {
    background: red;
    border-radius: 5px;
}
header nav ul li:hover a {
    color: white;
}

                    Logo

Home

                            Dropdown

some link

some link

some link

Another link

Contact

                    test

A: Fixed it by adding a active class with javascript

let menuBtn = document.querySelector(".menu-Btn");
let menu = document.querySelector(".mainMenu");
// Button toggle-menu
menuBtn.onclick = ()=>{
    if (menu.classList.contains("show")){
        menu.classList.remove("show");
    } else {
        menu.classList.add("show");
    }
}
// Dropdown menu
let toggle = document.querySelector(".dropdown");
let sub = document.querySelector(".submenu");
toggle.onclick = ()=>{
    if (sub.classList.contains("show")){
        sub.classList.remove("show");
        toggle.classList.remove("active");
    } else {
        sub.classList.add("show");
        toggle.classList.add("active");
    }
}
* {
    margin: 0;
    padding: 0;
}
body {
    background: #b3b3b3;
    justify-content: center;
    font-family: 'Open Sans', sans-serif;
}
header {
    margin: 0 0 20px 0;
    padding: 15px 0;
    width: 100%;
    height: auto;
    background: rgb(255, 255, 255);
}
.headerContainer, .container {
    width: 90%;
    margin-left: auto;
    margin-right: auto;
    padding: 15px;
    border: 1px solid #000;
}
.headerContainer {
    position: relative;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.headerBrand a {
    font-size: 30px;
    font-weight: 800;
    text-decoration: none;
    color: rgb(0, 0, 0);
    display: flex;
    align-items: center;
}
.headerBrand a img {
    padding: 0 10px 0 0;
}
header nav {
    top: 100%;
    left: 0;
    width: 100%;
    position: absolute;
    max-height: 70vh;
    overflow-y: auto;
}
header nav::-webkit-scrollbar {width: 10px;}
header nav::-webkit-scrollbar-track {background: #f1f1f1;}
header nav::-webkit-scrollbar-thumb {background: #888; }
header nav::-webkit-scrollbar-thumb:hover {background: #555;}

header nav .mainMenu {
    padding: 15px;
    display: none;
    list-style: none;
    background: #ffffff;
    border-radius: 5px;
}
header nav .mainMenu.show {
    display: block;
}
header nav ul li {
    padding: 5px 0;
    background:rgb(255, 255, 255);
    border-bottom:1px solid rgb(179, 179, 179);
    position: relative;
    justify-content: space-between;
}
header nav ul li:last-child {
    border: none;
}
header nav ul li a {
    display: block;
    font-size: 15px;
    font-weight: 700;
    width: calc(100% - 10px);
    text-transform: uppercase;
    color: red;
    text-decoration: none;
    padding: 0 0 0 15px;
}
header nav ul li.activepage {
    background: red;
    border-radius: 5px 5px 0 0;
}
header nav ul li.activepage a {
    color: white;
}
header nav ul li.dropdown a i {
    top: 10px;
    right: 10px;
    font-size: 10px;
    position: absolute;
}
header nav .mainMenu .submenu {
    display: none;
    padding: 0 0 0 15px;
    position: relative;
    border-radius: 0%;
}
header nav .mainMenu .submenu.show {
    display: block;
}

header nav .mainMenu li .submenu li {
    padding: 5px 0 5px 0;
}
header nav .mainMenu li .submenu li a {
    text-transform: none;
    font-weight: 400;
}
.menu-Btn {
    width: 35px;
    height: auto;
    text-align: center;
    background: red;
    font-size: 25px;
    border-radius: 5px;
    cursor: pointer;
}
.menu-Btn i {
    color: white;
}
header nav ul li:not(.active):hover {
    background: red;
    border-radius: 5px;
}
header nav ul li:not(.active):hover a {
    color: white;
}

                    Logo

Home

                            DROPDOWN

another link

another link

Manother link

another link

Contact

                    test


text:
Q: The impact of the width property used with flex-grow? Please see the code below:

ul {
  display: flex;
  list-style-type: none;
  flex-wrap: wrap;
}

li {
  flex-grow: 1;
  border: 1px solid;
  width: 1000px;
}

Monday

Tuesday

Wednesday

Thursday

Friday

Notice the width of 1000px.  When I load the page there are five rows as I would expect.  If I remove the width property, then the boxes appear on one row as expected.
Now if I add a width of 1px, then the only change is that all boxes are the same size i.e. 372.28 pixels (not 1px).  It appears to me that the behaviour is as follows:

*

*If any width is added to the flex items that means they can all fit on one row then make sure all boxes are the same size.

*If a width is added to the flex items meaning they cannot all fit on one row then honour the width.

*If a width is not added then the boxes can be any size i.e. the Wednesday box is biggest in this case because Wednesday is the longest word.

Have I understood this correctly and why does the width effect the flex items like this?
I have done my own research and found questions like this: What are the differences between flex-grow and width?.  However, I have not found an answer to my question.  I have also read about the flex grow property here: https://www.w3.org/TR/2018/CR-css-flexbox-1-20181119/#flex-grow-property

A: It's important to note that width, height and flex-basis in a flex container represent the initial size of the item.
Once that size are determined, then flex-grow and flex-shrink enter into the picture and do their work, if possible. That can change the initial size.
Now, let's break down your question into the main points:

Notice the width of 1000px.  When I load the page there are five rows as I would expect.  If I remove the width property, then the boxes appear on one row as expected.

OK

Now if I add a width of 1px, then the only change is that all boxes are the same size i.e. 372.28 pixels (not 1px).

Do you mean "e.g., 372.28 pixels (not 1px)", not "i.e.", because the size of the item will vary depending on the size of the viewport. In other words, the size of each item will scale as you resize the window. But this is not an essential point.
All boxes are indeed equal length. This happens because the width is set to 1px.
If you were to remove the width rule, then the boxes would vary in length based on their content length. This is because the default width / flex-basis is auto.

If any width is added to the flex items that means they can all fit on one row then make sure all boxes are the same size.

Not necessarily.
The width property doesn't always relate to items all fitting on one row. That behavior is controlled by the flex-wrap and flex-direction properties.
Also, the width property doesn't always relate to items all having equal length. Other factors, such as flex-grow, can have an impact.

If a width is added to the flex items meaning they cannot all fit on one row then honour the width.

Not necessarily.
flex-grow, flex-shrink and flex-wrap can all have an impact.
If you want the width /  flex-basis of an item to remain fixed, set both flex-shrink and flex-grow to 0 (which disables those functions).

If a width is not added then the boxes can be any size i.e. the Wednesday box is biggest in this case because Wednesday is the longest word.

Not necessarily.
flex-grow, flex-shrink and flex-wrap can all have an impact.

More details:

*

*Make flex-grow expand items based on their original size

*Flex items are shrinking below flex-basis


text:
Q: How to have the return value of a lambda function as a value in a dictionary? Here is my code
from datetime import datetime
import pytz

timezones = {
    'GMT': lambda t: datetime.now(pytz.timezone(t)).strftime("%Y-%m-%d - %H:%M:%S")
}

for k, v in timezones:
    print(v(k))

What I want is to have a dictionary where the current time is the value for the timezone key.
When I try to do for k, v in timezones: I get: ValueError: too many values to unpack (expected 2)
I assume this is because there are two colons, which python interprets as having three values instead of two.
Any way around this?
Thanks!


text:
Q: How to save two different checkpoints during training in Tensorflow Assume we have test/val/train splits. During training, we want to save some model checkpoints [save_1] that can be used to restart the training later.
In addition, we want to save another model during training that shows the best performance on the validation sets [save_2]. After done with training, we use save_2 to report the performance on the test data.
My question is that how we can have two different tf.savers during training in TensorFlow? whatever examples that I have seen, only save [save_1].
Pointer to any codes would be appreciated.
Thanks.

A: You can get quite close by using an Estimator to wrap your model. Specifically see the options surrounding saving multiple checkpoints in RunConfig (you don't have to throw any away). Could be combined with a ValidationMonitor to find the lowest validation error.


text:
Q: How to go form one view to storyboard programmatically in iPhone How to connect with xib button to storyboard in iPhone? I have one project that every think contain storyboard I want to add this project to viewcontroller xib project, Now how to connect that xib button to storyboard programmatically. How to go form 1 view to storyboard view controller? How to connect that view controller button to story board?

A: If you have not create a Segue for your viewcontroller in storyboard, then you need to get the viewController from storyboard with you view identifier & need to apply pushViewController on action/event.
Example:
@"MainStoryboard_iPhone"   = Storyboard file name
@"TabBarCntrl"             = View controller identifier name
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil];

UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"TabBarCntrl"];
[self.navigationController pushViewController:viewController animated:YES];


text:
Q: Update and replace strings that contain multiple quotes postgresql I have a dataset with a column that I want to split. I'm using pgadmin 4 and I'm new to PostgreSQL. The delimiters I have to use unfortunately contain quotes and double quotes:
1) ', "
2) ", '
3) ", "

To make my life easier working with this data, I would like to replace all of these delimiter strings with something I can use more easily like 'delimiter'. Then I will use something like this to parse my data
SELECT SPLIT_PART(descriptions, 'delimiter', 1)
FROM all_package_hist

I searched how to escape the quotes using additional single quotes (''), forward slash, and dollar signs with no luck. I tried running the following code but it has just removed my double quotes from the text and not replaced it with 'delimiter'
UPDATE all_package_hist SET descriptions = REPLACE(descriptions, $$', "$$, 'delimiter')

Instead it replaced ', " with ',
Please help! Thank you in advance.


text:
Q: Slow boot on Ubuntu 15.04 during ACPI The time seems to be wasted mainly between these two log lines. What could it be waiting for ?
Apr 30 01:19:22 terodde kernel: [    0.907820] [Firmware Bug]: ACPI: BIOS _OSI(Linux) query honored via cmdline
Apr 30 01:19:22 terodde kernel: [    6.527435] ACPI: Interpreter enabled

Further on some more time is spent doing acpi stuff.
Apr 30 01:19:22 terodde kernel: [    6.549824] acpi PNP0A03:02: _OSC: OS supports [ExtendedConfig ASPM ClockPM Segments MSI]
Apr 30 01:19:22 terodde kernel: [    8.560340] acpi PNP0A03:02: _OSC: platform does not support [PCIeHotplug AER]

This is on Supermicro X10DAi with E52660v3 processors and newest BIOS. The problem was there with the stock BIOS settings and didn't change with some tweaking. I boot with acpi_osi=Linux because the system seems to perform better with it. Unsetting this makes no difference during boot.
Here's the kern.log of the first 16 or so seconds.
It would be of some help, if I knew what the kernel could be waiting for at that time.


text:
Q: Symfony 3 - listener on LoginAction - kernelException Description:
I would like to use a Listener on my LoginAction but the one I am using, isn't working.
I have an Entity :
class User implements AdvancedUserInterface {
  public function isEnabled(){}
    ...
  }
}

So, when, I try to connect my user i have the good message :

user is disabled

On this action, I use an ExceptionListener like this :
# src/AppBundle/EventListener/ExceptionListener.php
namespace AppBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Exception\DisabledException;

class ExceptionListener
{
    private $router;

    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        die('-------');

        $ex = $event->getException();
        if($ex instanceof DisabledException) {
            $url = $this->router->generate('accounts.please_activate');
            $response = new RedirectResponse($url);

            $event->setResponse($response);
        }
    }
}

My listener work, cause, if i do a die in the construct, it's ok, but, my die doesn't work in the function onKernelException
So my redirect to the specific route doesn't work...
services.yml
services:
app.exception_listener:
    class: AppBundle\EventListener\ExceptionListener
    arguments: ['@router']
    tags:
        - { name: kernel.event_listener, event: kernel.exception }

Question:
Why am I unable to redirect a user that is considered "disabled" to a specific route?
On a second note, is this considered good practice?

A: You should handle the login failures with customized login handlers.
Creare a new service that implements Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface:
namespace AppBundle\Security;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\DisabledException;

class FailLoginHandler implements AuthenticationFailureHandlerInterface
{
    private $router;

    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        if($exception instanceof DisabledException) {
            $url = $this->router->generate('accounts.please_activate');
            return new RedirectResponse($url);
        }
    }
}

Define a new service
services:
    app.login_fail:
        class:        AppBundle\Security\FailLoginHandler
        arguments:    ['@router']

then add the failure_handler option under the configuration of your firewall on security.yml:
security:
    firewalls:
        firewallname:
             failure_handler: app.login_fail


text:
Q: How do you implement monoid interface for this tree in haskell? Please excuse the terminology, my mind is still bending.
The tree:
data Ftree a = Empty | Leaf a | Branch ( Ftree a ) ( Ftree a )
    deriving ( Show )

I have a few questions:

*

*If Ftree could not be Empty, would it no longer be a Monoid since there is no identity value.

*How would you implement mappend with this tree? Can you just arbitrarily graft two trees together willy nilly?

*For binary search trees, would you have to introspect some of the elements in both trees to make sure the result of mappend is still a BST?
For the record, some other stuff Ftree could do here:
instance Functor Ftree where
    fmap g Empty             = Empty
    fmap g ( Leaf a )        = Leaf ( g a )
    fmap g ( Branch tl tr )  = Branch ( fmap g tl ) ( fmap g tr )

instance Monad Ftree where
    return             = Leaf
    Empty        >>= g = Empty
    Leaf a       >>= g = g a
    Branch lt rt >>= g = Branch ( lt >>= g ) ( rt >>= g )

A: There are three answers to your question, one captious and one unhelpful and one abstract:
The captious answer
instance Monoid (Ftree a) where
    mempty = Empty
    mappend = Branch

This is an instance of the Monoid type class, but does not satisfy any of the required properties.
The unhelpful answer
What Monoid do you want? Just asking for a monoid instance without further information is like asking for a solution without giving the problem. Sometimes there is a natural monoid instance (e.g. for lists) or there is only one (e.g. for (), disregarding questions of definedness). I don't think either is the case here.
BTW: There would be an interesting monoid instance if your tree would have data at internal nodes that combines two trees recursively...
The abstract answer
Since you gave a Monad (Ftree a) instance, there is a generic way to get a Monoid instance:
instance (Monoid a, Monad f) => Monoid (f a) where
    mempty = return mempty
    mappend f g = f >>= (\x -> (mappend x) `fmap` g)

Lets check if this is a Monoid. I use <> = mappend. We assume that the Monad laws hold (I did not check that for your definition). At this point, recall the Monad laws written in do-notation.
Our mappend, written in do-Notation, is:
mappend f g = do
  x <- f
  y <- g
  return (f <> g)

So we can verify the monoid laws now:
Left identity
mappend mempty g
≡ -- Definition of mappend
do
  x <- mempty
  y <- g
  return (x <> y)
≡ -- Definition of mempty
do
  x <- return mempty
  y <- g
  return (x <> y)
≡ -- Monad law
do
  y <- g
  return (mempty <> y)
≡ -- Underlying monoid laws
do
  y <- g
  return y
≡ -- Monad law
g

Right identity
mappend f mempty
≡ -- Definition of mappend
do
  x <- f
  y <- mempty
  return (x <> y)
≡ -- Monad law
do
  x <- f
  return (x <> mempty)
≡ -- Underlying monoid laws
do
  x <- f
  return x
≡ -- Monad law
f

And finally the important associativity law
mappend f (mappend g h)
≡ -- Definition of mappend
do
  x <- f
  y <- do
    x' <- g
    y' <- h
    return (x' <> y')
  return (x <> y)
≡ -- Monad law
do
  x <- f
  x' <- g
  y' <- h
  y <- return (x' <> y')
  return (x <> y)
≡ -- Monad law
do
  x <- f
  x' <- g
  y' <- h
  return (x <> (x' <> y'))
≡ -- Underlying monoid law
do
  x <- f
  x' <- g
  y' <- h
  return ((x <> x') <> y')
≡ -- Monad law
do
  x <- f
  x' <- g
  z <- return (x <> x')
  y' <- h
  return (z <> y')
≡ -- Monad law
do
  z <- do
    x <- f
    x' <- g
    return (x <> x')
  y' <- h
  return (z <> y')
≡ -- Definition of mappend
mappend (mappend f g) h

So for every (proper) Monad (and even for every applicative functor, as Jake McArthur pointed out on #haskell), there is a Monoid instance. It may or may not be the one that you are looking for.


text:
Q: Limit number of tasks processed simultaneously in loop I define a function named fn which I then run in the background as part of a bigger service.
The function fn retrieves messages from a message queue one by one, and processes each message. Processing of each message can take between 1 and 10 minutes (longProcess()).
Using the following code, the for await loop waits for new messages and processes each one, and then fetches a new message once the processing is complete.
const fn = async (subscription: AsyncIterable) => {
    subscription.pullOne();
    for await (const msg of subscription) {
        await longProcess(msg);
        subscription.pullOne();
    }
    subscription.close();
};

fn(subscription).then(() => {});

If I remove the await from before longProcess(msg), messages are sent to be processed as soon as they are received, which is what I want, but I only want a maximum of 5 messages to be processed simultaneously.
I don't want any more messages to be pulled before the current messages are done processing (so that other subscribers may pull and process them).
This question deals with a very similar case, but I can't seem to find a solution that actually works and provides an elegant solution.
I tried using the bottleneck library by defining a concurrency limit, but I can't figure out how to stop the loop from fetching more messages before the active processing is finished.
const limiter = new Bottleneck({
    maxConcurrent: 5,
});

const fn = async (subscription: AsyncIterable) => {
    subscription.pullOne();
    for await (const msg of subscription) {
        limiter.schedule(() => longProcess(msg));
        subscription.pullOne();
    }
    subscription.close();
};

A: You can try processing them in batches/chunks of <= 5 items at a time
// helper function
async function take(aIterable, count) {
  const res = [];
  let done = false
  for(let i = 0; i < count; i++) {
    const next = await aIterable.next()
    if(!next.done) res.push(next.value)
    done = next.done;
  }
  return [res, done];
}

const fn = async (subscription) => {
    subscription.pullOne();
    let done = false;
    while (!done) {
        let [batch, _done] = await take(subscription, 5);
        done = _done;
        await Promise.allSettled(batch.map(msg => longProcess(msg)));
        // subscription.pullOne();
    }
    subscription.close();
};


text:
Q: Laravel 4 authentication with multi database table How can I do authentication with multiple database table in Laravel?
For example, I have 3 tables:
1. General User Login table
2. Membership detail table
3. CMS user detail table
When user login from the CMS or the member login, the Auth will go and verify from the "general user login" table. But how can I make the Auth function also getting info from the second or third table depend on the user type? Then, I can access those info via something like Auth::user()->address, which the address is stored in the membership detail table.
Thank you.

A: Create relationship columns, to relate your user to data in other tables:
<?php

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

    public function membership()
    {
        return $this->belongsTo('Membership');
    }

    public function userDetails()
    {
        return $this->belongsTo('CmsDetail');
    }

}

class Membership extends Eloquent {

    protected $table = 'membership';

}

class CmsDetail extends Eloquent {

    protected $table = 'cms_details';

}

Then you can just
echo Auth::user()->membership->member_since;

echo Auth::user()->userDetails->address;


text:
Q: How to transform react production files with webpack? The issue I'm getting when running my app built in webpack 3.6.0 with React 16 is similar to this SO post. Webpack build runs fine but when running the app on any browser, I'm getting an Uncaught ReferenceError: require is not defined script error even if the noParse option is specified. This only happens in production files. Development mode runs that app in the browser just fine. So, I am not pretty sure what I am missing.
If anyone could point me to my mistake, I'd really appreciate it. The following are my webpack config code, .babelrc and package.json scripts code:
webpack.config.base.js
'use strict';

const path = require( 'path' );
const webpack = require( 'webpack' );

let NODE_ENV = process.env.NODE_ENV;

let env = {
    production  : NODE_ENV === 'production',
    staging     : NODE_ENV === 'staging',
    test        : NODE_ENV === 'test',
    development : NODE_ENV === 'development' || typeof NODE_ENV === 'undefined'
};

Object.assign(
    env, {
        build : (env.production || env.staging)
    }
);

let config = {
    context   : __dirname,
    entry     : {
        'vendor' : [
            'babel-polyfill',
            'html5shiv',
            'react',
            'react-dom',
            'bootstrap',
            'redux',
            'react-redux',
            'redux-saga',
        ],
        'app'    : './src/app/App.js',
    },
    output    : {
        path          : __dirname + '/dev',
        filename      : '[name]/index.js',
        //chunkFilename : 'partials/[name].js' + (env.development ? '?ver=[chunkhash]' : ''),
        chunkFilename : 'partials/[name].js',
    },
    externals : {
        jquery : 'jQuery',
    },
    resolve   : {
        extensions       : ['.webpack.js', '.web.js', '.js', '.jsx'],
        moduleExtensions : [
            'node_modules',
            path.resolve( __dirname, './node_modules' ),
        ],
    },
    devtool   : 'eval-source-map',
    module    : {
        rules   : [
            {
                test    : /(\.js|\.jsx)$/,
                exclude : /(node_modules)/,
                loader  : 'babel-loader',
                /*query   : { presets : ['env', 'stage-1', 'react'] }*/
            },
            {
                test   : /\.json$/,
                loader : 'json-loader'
            },
            {
                test   : /\.css$/,
                loader : "style-loader!css-loader"
            },
            {
                test : /(\.scss|\.sass)$/,
                use  : [
                    {
                        loader : 'style-loader', // inject CSS to page
                    },
                    {
                        loader : 'css-loader', // translates CSS into CommonJS modules
                    },
                    {
                        loader  : 'postcss-loader', // Run post css actions
                        options : {
                            plugins : function () { // post css plugins, can be exported to postcss.config.js
                                return [
                                    require( 'precss' ),
                                    require( 'autoprefixer' )
                                ];
                            }
                        }
                    },
                    {
                        loader : 'sass-loader' // compiles SASS to CSS
                    }
                ]
            },
        ],
        noParse : /\.min\.js/
    },
    plugins   : [
        new webpack.NoEmitOnErrorsPlugin(),
        new webpack.ProvidePlugin(
            {
                React           : 'react',
                ReactDOM        : 'react-dom',
                $               : 'jquery',
                jQuery          : 'jquery',
                'window.jQuery' : 'jquery',
                Popper          : ['popper.js', 'default'],
                Tether          : 'tether',
            }
        ),
        new webpack.optimize.CommonsChunkPlugin(
            {
                names     : 'vendor',
                //filename  : '[name].[chunkhash].js',
                minChunks : function ( module ) {
                    // this assumes your vendor imports exist in the node_modules directory
                    return module.context && module.context.indexOf( 'node_modules' ) !== -1;
                },
                children  : true,
                async     : true,
            }
        ),
        new webpack.optimize.CommonsChunkPlugin(
            {
                names     : 'manifest',
                minChunks : Infinity
            }
        ),
        new webpack.DefinePlugin(
            {
                __DEV__         : env.development,
                __STAGING__     : env.staging,
                __PRODUCTION__  : env.production,
                __CURRENT_ENV__ : '\'' + (NODE_ENV) + '\''
            }
        )
    ]
};

module.exports = config;

webpack.config.production.js
'use strict';
const webpack = require( 'webpack' );
const config = require( './webpack.config.base.js' );
const CleanWebpackPlugin = require( 'clean-webpack-plugin' );

config.output = {
    path          : __dirname + '/dist',
    filename      : '[name]/index.js',
    chunkFilename : 'partials/[id].[chunkhash:8].js',
};

config.devtool = 'cheap-module-source-map';

config.plugins = config.plugins.concat(
    [
        /*new webpack.optimize.UglifyJsPlugin(
            {
                output   : {
                    comments : false
                },
                compress : {
                    warnings  : false,
                    screw_ie8 : true
                }
            }
        ),*/
        new webpack.DefinePlugin(
            {
                'process.env' : {
                    NODE_ENV : JSON.stringify( 'production' )
                }
            }
        ),
        new CleanWebpackPlugin( ['dist'], {
            root    : __dirname,
            verbose : true,
            dry     : false,
            exclude : [],
            watch   : true,
        } ),
    ]
);

module.exports = config;

.babelrc
{
  "presets": [
    "react",
    "stage-1",
    [
      "env",
      {
        "targets": {
          "browsers": [
            "last 2 versions"
          ]
        },
        "debug": true,
        "modules": "commonjs"
      }
    ]
  ],
  "plugins": [
    "transform-class-properties"
  ]
}

package.json scripts
{
  ...
  "scripts": {
    "build": "cross-env NODE_ENV=production webpack --progress",
    "watch": "cross-env NODE_ENV=development webpack --debug --output-pathinfo --progress --watch",
    "build-dev": "cross-env NODE_ENV=development webpack --debug --output-pathinfo --progress",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  ...
}

A: Got it working by commenting/deleting out the noParse : /\.min\.js/ line. Weird/funny but worked.


text:
Q: How can I put date, time, and values from radio buttons to database I have a simple form looking like this:
<input class="form-control" type="date" name="date">
<input class="form-control" type="time" name="time">

and couple of radio buttons:
<input type="radio" name="options" id="option1" autocomplete="off" value="1">

I would like to INSERT date (Y-m-d) from datepicker, time (H:i) and value from radio button into database.
My php script looks like this:
$conn_servername = "localhost";
$conn_username = "root";
$conn_password = "root";
$conn_db = "restaurant";

$conn = mysqli_connect($conn_servername, $conn_username, $conn_password, $conn_db);

if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

if (isset($_POST['reserv-send'])) { //<button name="reserv-send"></button>
$options = $_POST['options'];
$date = date('Y-m-d', strtotime($_POST['date']));
$time = $_POST['time'];

$sql = "INSERT INTO reservations (date, time, options)
    VALUES ('$options', '$date', '$time')";

if ($conn->query($sql) === TRUE) {
   echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}

My table values in database are date for date, time for time and int for options. (I don't know if I schould set default NULL for date and time?).
I try many options but still got nothing, and the result always give me date 0000-00-00 in database.


text:
Q: Verify email before authenticating using Azure B2C auth service Situation
I want to use Azure B2C auth service for my web app. However, I want the admins of the app to restrict access to certain emails or domains e.g. a whitelist as follows:

*

*tom1@abc.com

*tom2@def.com

**@alphabet.com

So only the top two emails and anyone else with an email ending in "alphabet.com" can access the site.
Problem
I have everything implemented and it's working correctly, however I'm struggling to get the email address of the authenticated user to do the whitelist check during the signon/signin process. The AuthenticationTicket has all the claims requested (FirstName, LastName, Name, Object Identifer etc.), but the email is not present (It has been setup in Azure B2C as a claim).
How can I access the email and is this the right place to be checking?
Code in Startup.App.cs
private OpenIdConnectAuthenticationOptions CreateOptionsFromPolicy(string policy)
{
    return new OpenIdConnectAuthenticationOptions
    {
        // For each policy, give OWIN the policy-specific metadata address, and
        // set the authentication type to the id of the policy
        MetadataAddress = String.Format(aadInstance, tenant, policy),
        AuthenticationType = policy,

        // These are standard OpenID Connect parameters, with values pulled from web.config
        ClientId = clientId,
        RedirectUri = redirectUri,
        PostLogoutRedirectUri = redirectUri,
        Notifications = new OpenIdConnectAuthenticationNotifications
        {
            AuthenticationFailed = AuthenticationFailed,
            AuthorizationCodeReceived = (context) =>
            {
                // no claims present here
                return Task.FromResult(0);
            },
            SecurityTokenReceived = (context) =>
            {
                // no claims present here
                return Task.FromResult(0);
            },
            SecurityTokenValidated = (context) =>
            {
                // print all claims - quite a few except email :( Is this where this check should be done?
                foreach (var claim in context.AuthenticationTicket.Identity.Claims)
                {
                    Console.WriteLine(claim.Value);
                }
                return Task.FromResult(0);
            },
        },
        Scope = "openid",
        ResponseType = "id_token",

        // This piece is optional - it is used for displaying the user's name in the navigation bar.
        TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType  = "name"
        },
    };
}

Any help greatly appreciated.

A: You must specify the claims you want to be sent to your application in the policy in the 'Select application claims' blade.
The blade where you can configure this is
Azure AD B2C Settings > Settings > Sign-up or sign-in policies > Application Claims
You should make sure you've got email selected as per the screenshot below.


text:
Q: Doctrine auto limit the length of my text field to 64512 chars I have a field in a table of type "text" which usually contain pictures in "base64"; When the images are large, they condifican approximately 200,000 characters. The "text" of the base allows me to store up to 4 million characters. But Doctrine cuts my character string in 64512.
Versions:

*

*Doctrine 2.4.4 on Symfony 2.5.3

*DB: Microsoft SQL Server  2000 - 8.00.2039 (Intel X86)
May  3 2005 23:18:38
Copyright (c) 1988-2003 Microsoft Corporation
Enterprise Edition on Windows NT 5.2 (Build 3790: Service Pack 2)

Declaration of the field.
 /**
 * @var text
 *
 * @ORM\Column(name="mensaje", type="text")
 */
 private $mensaje;

Getter method:
 public function get($value){
    return mb_detect_encoding($value, mb_detect_order(), true) === 'UTF-8' ?
    $value : mb_convert_encoding($value, 'UTF-8');
 }
 /**
  * Get mensaje
  *
  * @return text
  */
  public function getMensaje()  {
    return $this->get($this->mensaje);
  }

I've tried:

*

*Limiting the size of the text with "length"

*Using other data types such as "clob" or "longtext"

*Add data to the end of the string to verify that there is a problem of php (no problem with that)

Tnks.

A: You can use longtext you can store a text with a length up to 4294967292
    TINYTEXT   : 2 ^  8 - 1 = 255
    TEXT       : 2 ^ 16 - 2 = 65534
    MEDIUMTEXT : 2 ^ 24 - 3 = 16777213
    LONGTEXT   : 2 ^ 32 - 4 = 4294967292

To do so you need to add columnDefinition="longtext" to your field

A: In my project we use a base64 image (not as large as yours though) and we use a doctrine decimal type.
    @ORM\Column(name="image", type="decimal", precision=10, scale=4, nullable=true)
We use sql server 2012 though with a varchar(MAX) data type.
When the image is uploaded we base64_encode($imageFile) and persist that...
    public function preUpload()
    {
        if(null === $this->imageFile){
        return;
        }

        $data = file_get_contents($this->imagefile);
        $base64 = base64_encode($data);

        $this->image = $base64;
    }

    public function getImage()  {
    return $this->get($this->Image);
}

The getImage then returns a base64 encoded string that we use to display. Works on a string length 129400 for me. No converting from DB.

A: PHP truncate all my strings with a several characters. The solution was in the php.ini
mssql.textlimit = 2147483647
; Valid range 0 - 2147483647. Default = 4096.
mssql.textsize = 2147483647

by default was set into 4096, and there be the problem.
Thanks for the time!!!


text:
Q: Filling 2d array Okay probably it's a very easy solution, but I can't seem to find it. I've got two ArrayLists:
ArrayList<Candidate>partyList and ArrayList<Party>electoralList

Now I want to make a 2d int array that represents the parties and candidates like this:
p c
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
etc.

I think I already have the right for-loop to fill the array but I only miss the correct formula to do it.
int[][]ArrList;
for (int i=0; i<parties.size(); i++){
        for(int j=0; j<parties.get(i).getPartyList().size(); j++){
            ArrList[i][j]=

Is the for-loop indeed correct? And what is the formula to fill the array then?

A: First of all, ArrList should not have a starting capital letter (it is not a class but an object).
Second point (I think what troubles you) is that you are not initializing the matrix and the parties.size() are always 0. I am not sure since there is not enough code though.
You could do something like this
    int ROWS = 10;
    int COLS = 2;
    int [][] matrix = new int[ROWS][];
    for(int i=0; i< matrix.length; i++){
        matrix[i] = new int[COLS];
    }

or, with lists
    int ROWS = 10;
    int COLS = 2;
    List<List<Object>> matrix = new ArrayList<>(ROWS);
    for (int i = 0; i < ROWS; i++) {
        ArrayList<Object> row = new ArrayList<>(COLS);
        for (int j = 0; j < COLS; j++) {
            row.add(new Object());
        }
        matrix.add(row);
    }

A: I will try and answer the question from how I understood what you are looking for here.

*

*You should understand this first:

*A 2D array consists of a nestled array i.e. ArrList[2][3] = [ [1,2,3], [1,2,3] ] -> The first digit declares How many arrays as elements, the second digit declares Size or if you like: length, of the array elements

*If you are looking for to represent the candidates and parties as numbers. Here is my solution:
int[][]ArrList = new int[parties.size()][electoral.size()]
for (int depth=0; depth < parties.size(); depth++){
    for(int itemIndex=0; itemIndex<parties.get(depth).getPartyList().size(); itemIndex++){
        ArrList[depth][itemIndex]= itemIndex;

I hope this is what you were looking for.

A: int[][] arrList=new int[parties.size()][2];
    int i=0,j=0,k=0;
    for(;i<parties.size();i++,j++){
        if(j==1){
            arrList[k][j]=electoralList .get(--i);
            j=-1;
            k++;
        }
        else{
            arrList[k][j]=parties.get(i);
        }
    }
    arrList[k][j]=aarM.get(electoralList .size()-1);
System.out.println(Arrays.deepToString(arrList));


text:
Q: Conversion of numbers of type float in MATLAB In my task I had number 12.7 that is represented in septenary number system (base = 7) and I need to convert this number to system with base 11.
I think I should firstly convert this number to decimal system and only after that to system with base 11.
base1 = 7;
base2 = 11;
num = 12.3;
str_num = num2str(12.3);
num_dec = typecast(int16(base2dec(str_num,base1)), 'float');

I got an error as a result.
??? Error using ==> base2dec at 41
String 12.3 contains characters which cannot be converted to base 7.

Is there any solution for this problem? How can I convert such kind of numbers (floating-point numbers) using matlab?


text:
Q: Identify book with different races that have only one sense each but must cooperate in competition I'm trying to identify a book, where several different races (I think at least 3) who all have just one particular sense (seeing, hearing) must cooperate as a mixed group in some kind of competition or race that involved navigating a kind of obstacle course, building, or maze, that possibly involved challenges, where each of the senses and sometimes their combination was necessary to advance.
I think the races initially hated each other (prejudices), but the representatives of at least one group involved in this competition learned to respect each other during the events.
Must be older, before 80s. I read the novel in German, but it was translated from English, as most SF here was at this time. I've no idea if it was aimed at adults or young adults. I don't remember names. I don't remember the perspective. The race was at least a substantial part of the book. It might have been a small book. That's about all I can remember.

A: This sounds like Thousandstar by Piers Anthony (the 4th novel in the Cluster series).
The three races were the Hydr'o (primary sense taste), the Squam (primary sense hearing), and the Erb (primary sense sight), and their combat abilities formed a ring of Tactical Rock Paper Scissors - a Squam's claws could cut a Hydr'o, a Hydr'o's water jets could penetrate an Erb, and an Erb's drill-like leaves could cut through a Squam's scales.
The competition involved many more than those three races, but every other race participating was physically represented by a Hydr'o, a Squam or an Erb, hosting the mind of a member of another race via "Kirlian Aura Transfer" (the primary method of interstellar travel in the Cluster series).
The protagonist was a Hydr'o named Heem - he was representing his own race in the competition, but he was still hosting a mind from a race not directly involved in the competition (a human) in order to gain an advantage.


text:
Q: How to host a html website on a QNAP NAS Server I would like to know how to host a simple html website on a QNAP NAS sever. All of the tutorials I have found are extremely vague and do not work at all. Thank you!
I already have a domain name ready for the website.

A: I can't tell you how to do this since I also tried and failed to find good explanation, leading me to this post. But I can tell you that I read several places that say that this is a BAD IDEA. here

A: Its too simple . Just go to your qnap admin address
Control panel -> Web Server
Then enable it and specify desire port (be careful to use an available port)
Click apply then go to file station.
A new shared folder is created under name of Web.Copy your html file in it and name it index.html
you should see your website on your ip:desired port .
if you get error you should fix index.html file permissions on file station .
I have a simple html page on my nas like this
you can also host multiple websites on your nas using Control panel -> Web Server -> Virtual host.
create a virtual host for every website you want to host . assign a folder (or creat one) to it and specify a port.
It has almost no options for hosting like nginx but it can WORK!
I also use Nginx in docker to achieve more options on my websites on nas .You can install nginx using Entware too (without docker and container station).


text:
Q: How can I get the place where a function is defined in VIM quickly? I've installed taglist and nerdtree plugins, and I wonder if there's way to quickly find the location where some function is defined, just as what Control and pressing function name in Eclipse does? Help would be appreciated!

A: vim comes with ctags support built in. If you have a tags file make sure it can be found by vim by adding it to the tags variable (check if the default works first though)
:set tags+=/path/to/tags

Then you can use :tselect SOME_FUNC to list the file locations. You might only need to type the first characters of the function name and could use TAB to complete.

A: You can also put the cursor somewhere in the function name and press Ctrl-]


text:
Q: Why does \hspace{50mm} not exactly add 50 mm of horizontal space? I wanted to write a line that must be 250 mm from the top and should be at 50 mm from the left side, to do that following is my code.
I have used \vspace* to get the margin from top at the start of the page and \hspace to get a horizontal margin.
    \documentclass[12pt]{article}
    \usepackage[utf8]{inputenc}

    \usepackage[a4paper, margin = 0in]{geometry}

    \begin{document}
          \vspace*{250mm} % using to get a margin from top
          \hspace{50mm} I am at 250 mm from Top and 50 mm from left side.
    \end{document}

Which is giving me the below output.
The text is 250 mm from the top but leaves a margin of an extra 10 mm from the left side, i.e. a total of 60 mm margin from the left side.

A: You have three spaces, an indentation from the start of a paragraph (actually a box not a space), the 50mm space, then a variable word-space coming from the space token you added between \hspace{} and I
\showoutput will show:
...\glue(\baselineskip) 6.16669
...\hbox(8.33331+2.33331)x597.50787, glue set 161.76242fil
....\hbox(0.0+0.0)x17.62482                  % paragraph indent
....\glue 142.26378                          % requested space
....\glue 3.91663 plus 1.95831 minus 1.30554 % inter-word space
....\OT1/cmr/m/n/12 I
....\glue 3.91663 plus 1.95634 minus 1.30684
....\OT1/cmr/m/n/12 a
....\OT1/cmr/m/n/12 m