text:
Q: Got an error when dragging files using NSEvent. (macOS) I wanna drag files to my window and then perform actions.
I tried to use snippets below provided in this answer to distinguish whether you're dragging a file or a window.
// In my window controller

class MyWindowController: NSWindowController {

    init() {
        // Some initialization steps below are omitted
        let win = NSWindow(...)
        super.init(window: win)

        let contentView = DropView(frame: win.frame)
        win.contentView?.addSubview(contentView)

        registerGlobalMouseEvent()
    }

    func registerGlobalMouseEvent() {
        self.window?.acceptsMouseMovedEvents = true

        NSEvent.addGlobalMonitorForEvents(matching: .leftMouseDragged, handler: { [self] event in
            // Codes below will cause errors
            let pasteBoard = NSPasteboard(name: .drag)
            guard let fileNames = pasteBoard.propertyList(forType: .init(rawValue: "NSFilenamesPboardType")) as? NSArray else { return }
            let changeCount = pasteBoard.changeCount

            if fileNames.count > 0 && lastChangeCount != changeCount {
                lastChangeCount = changeCount

                // My actions when dragging
            }
        })
    }

}

Then I ran my codes and started dragging, I got three errors:

[sandbox] Failed to get a sandbox extension

[Framework] Failed to issue sandbox extension for /Users/roy/Downloads/test.txt with error 1

[default] Failed to issue sandbox token for URL: 'file:///Users/roy/Downloads/test.txt' with error: 'Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted" UserInfo={NSLocalizedDescription=Cannot issue a sandbox extension for file "/Users/roy/Downloads/test.txt": Operation not permitted}'

But when I just do
NSEvent.addGlobalMonitorForEvents(matching: .leftMouseDragged, handler: { [self] event in
    // My actions
})

, then everything went fine.

The first error seems harmless since it didn't prevent my app from running.
The second and the third ones are deadly and directly caused my app to crash.
I wonder if there are any problems in his code? Any useful thoughts would be great! :)

A: You need to know about Bookmarks and Security Scoped URLs when working with sandbox . A dragged URL gives your app process permission just once to read or read/write a "user selected file" depending on how you configure entitlements.
You can save a bookmark (blob of data) to keep access over subsequent sessions as long as the file isn't updated by another process at which point the bookmark becomes stale and you will need to encourage the user to select the file again.
Handing a URL to another process across an XPC boundary like sharing requires that you own the file so may involve a copy to your sandbox cache.
e.g:
let dragurl = url_of_dragged_file //at this point you have at-least read access
let cachepath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last!
let cachedir = URL(fileURLWithPath: cachepath)
let cacheurl = cachedir
  .appendingPathComponent(UUID().uuidString)
  .appendingPathExtension(dragurl.pathExtension)
try FileManager.default.copyItem(at: dragurl, to: cacheurl)

At this point you have a copy in your local sandbox cache that can be handed off to a share sheet.

A: So I finally got a solution for this. :)
It appears that it indeed have something to do with the snippets I mentioned above, and here's the correction:
NSEvent.addGlobalMonitorForEvents(matching: .leftMouseDragged, handler: { [self] event in
    let pasteboard = NSPasteboard(name: .drag)
    let changeCount = pasteboard.changeCount
    if lastChangeCount != changeCount {
        lastChangeCount = changeCount
        if pasteboard.canReadObject(forClasses: [NSURL.self], options: [:]) {
            /// actions
        }
    }
})

In this way, I got no errors and my codes run perfectly!


text:
Q: Toggle dynamically created objects using dynamically created QRadioButtons I'm working on a QT application. In it the user can create several objects, each one will be added to a list. In the next step the user shall position the objects. The choice which one of the objects shall be positioned, shall be made by clicking QRadioButtons (seems logical as QRadioButtons added to a QGroupbox ensure that only one of them is active).
The problem is I can't find a signal that allows me tell which radio button is active or was clicked. I already connected all radio buttons to one slot, but all I get is a boolean value. How can I get the sender of the signal? Or what would be the standard way to achieve my goal?

A: QObject::sender is a bit too abstract. Try QButtonGroup::buttonClicked

A: You can get the sender of the signal using... QObject::sender() method within your slot!

redpajama_set_name: RedPajamaStackExchange


text:
Q: itextsharp: pdfptable.writeselectedrows vb.net can someone please show me documentation on this method?
i have the following line:
datatable.WriteSelectedRows(0, -1, document.LeftMargin, document.TopMargin, writer.DirectContent)

and it doesnt seem to matter whether its topmargin or bottommargin, it puts it at the bottom of the page.

A: The way absolute positioning works is that the Y coordinate you want needs to be subtracted from the max height of the document. What I've done is create a constant:
Public Const INCH As Integer = 72

Because 72 is the number of points that creates an inch. Then you can create other constants based on this constant, such as:
Public Const MAX_HEIGHT As Single = 11 * INCH
Public Const MAX_WIDTH As Single = 8.5 * INCH
Public Const TOP_MARGIN As Single = 0.5 * INCH

etc.
So to place something at the top of the page, your Y coordinate should be:
MAX_HEIGHT - TOP_MARGIN

Hope this helps :)


text:
Q: Targeting WP 8.0 in VS 2013 Update 2 I have just installed Visual Studio 2013 Update 2. During yesterday's Keynote, it was said that with this update it would be possible to build both WP 8.0 and WP 8.1 apps. I can still open my older solutions, but cannot create a new Windows Phone 8.0 application - anyone knows how to do this?

A: Found a solution: instead of creating a new Blank App (Windows Phone), one should create a new Blank App (Windows Phone Silverlight). :)


text:
Q: How to Associate Holiday and Business Hours in Data Import Is there a way to insert/update Holidays and create the association to an existing Business Hour?  In the UI this is achieved by clicking into the Business Hour, clicking the "Add/Remove" button under Holidays and adding the Selected Holidays.  I have a lot of Holidays to add and I'd like to be able to create this relationship via a data import if possible.  I have to deploy to multiple sandboxes, so a solution via data import or code would be ideal.
Side note: I'm aware of the limitations on querying the junction between Holidays and Business Hours (see here: Business Hours and Holiday Affiliation), but I'm still hoping there might be a solution around the import.
Thanks in advance for any guidance!

A: Official word from Salesforce Support: At this time, this is not a part of standard salesforce functionality.
So it looks like the Holiday/Business Hour association can only be accomplished manually on the UI.  Please go vote on this Idea if you're running into the same problem: https://success.salesforce.com/ideaview?id=087300000006n4CAAQ


text:
Q: Looping through multiple pages using BeautifulSoup I'm quite new to web scraping using BeautifuSoup and I'm attempting to loop through multiple pages and write everything into a CSV file.
Here my current code:
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen

urls = []
url = "https://www.newegg.com/Black-Friday-Deals/EventSaleStore/ID-10475/"
for page in range (1,7):

  pageurl = 'Page-{1}'.format(url,page)
  urls.append(pageurl)

  page = urlopen(url)
  html = page.read().decode("utf-8")
  page.close()

  page_soup = soup(html, "html.parser")

  containers = page_soup.findAll("div",{"class" : "item-container"})
  print(len(containers))

  filename = "BlackFridayNewegg.csv"
  f = open(filename, "w")

  headers = "Product, Previous price, Current price"

  f.write(headers)
  for container in containers:

    rating_container = page_soup.findAll("span", {"class" : "item-rating-num"})
    rating = rating_container[0].text.strip()

    title_container = container.findAll("a",{"class":"item-title"})
    title = title_container[0].text.strip()

    prev_price_container = container.findAll("li",{"class" : "price-was"})
    prev_price = prev_price_container[0].text

    current_price_container = container.findAll("li", {"class" : "price-current"})
    current_price = current_price_container[0].text

    print("Product Name: " +title)
    print("Previous Price: " + prev_price)
    print("Current Price: "+current_price)
    result = title.replace(",","")+ "," + prev_price +"," +current_price +"\n"
    f.write(result)

  f.close()

My code is working properly and will display text from multiple pages, but it won't write it all into the file. Any reason as to why this is happening?

A: f = open(filename, "w") clears the file. You need f = open(filename, "a")


text:
Q: Retrieve the LoadBalancer URL for EKS construct in CDK I'm using the EKS Construct to create an EKS cluster in CDK. I'm adding the NGINX helm chart to the cluster and I want to export the ingress LoadBalancer URL. The EKS Construct exposes a .getServiceLoadBalancer() method, but it wants a service name. I'm not sure how to get the name of the LoadBalancer service to pass it into that method. Feels like I'm missing something. Example:
export class EksClusterStack extends cdk.NestedStack {
  elbUrl: string;

  constructor(scope: cdk.Construct, id: string, props?: cdk.NestedStackProps) {
    super(scope, id, props);

    const clusterAdmin = new iam.Role(this, 'AdminRole', {
      assumedBy: new iam.AccountRootPrincipal()
    });

    const cluster = new eks.Cluster(this, 'Cluster', {
      mastersRole: clusterAdmin,
      version: eks.KubernetesVersion.V1_18,
      defaultCapacity: 2,
    });

    const nginx = cluster.addHelmChart('NginxIngress', {
      chart: 'nginx-ingress',
      repository: 'https://helm.nginx.com/stable',
    });

    this.elbUrl = cluster.getServiceLoadBalancerAddress('{Where do I get the service name?}') //<- This is what I can't figure out
}

I looked at the properties on the helm chart, and it doesn't seem to expose anything that fits the bill. Appreciate any insight. Thanks!

A: What you have deployed is the ingress controller helm chart which it self doesn't expose anything but rather scans any K8S objects of type Ingress. In this case you should deploy an Ingress after you deploy the ingress controller and you can't use the pre-built function to get the LoadBalancerAddress for you.
Example:
        self.alb_domain_name = eks.KubernetesObjectValue(
            self, 'Query',
            cluster=cluster,
            object_type='Ingress',
            object_name='cluster-ingress', # this is your ingress name
            object_namespace='my-ingress-controller', # in which namespace your ingress is deployed
            json_path='.status.loadBalancer.ingress[0].hostname' # this json path will get you the hostname for the deployed AWS ELB/ALB
        )

A: In my particular case, I just needed a way to define the name of the ingress controller so it wouldn't be auto-generated. Doing so would then let me query that ingress controller for its ELB address. The fix is to give the the ingress controller helm chart a release name. Once deployed, CDK appends -nginx-ingress to the end of the release name, but given the release name, you can calculate the k8s Service name. Here's a working version:
import * as cdk from '@aws-cdk/core';
import * as eks from '@aws-cdk/aws-eks';
import * as iam from '@aws-cdk/aws-iam';

export class SimpleEks extends cdk.NestedStack {
  elbUrl: string;

  constructor(scope: cdk.Construct, id: string, props?: cdk.NestedStackProps) {
    super(scope, id, props);

    const ingressControllerReleaseName = 'ingress-controller'

    const clusterAdmin = new iam.Role(this, 'AdminRole', {
      assumedBy: new iam.AccountRootPrincipal()
    });

    const cluster = new eks.Cluster(this, 'cluster', {
      clusterName: 'cluster',
      mastersRole: clusterAdmin,
      version: eks.KubernetesVersion.V1_18,
      defaultCapacity: 2,
    });

    const ingressControllerChart = cluster.addHelmChart('IngressController', {
      chart: 'nginx-ingress',
      repository: 'https://helm.nginx.com/stable',
      release: ingressControllerReleaseName, //This fixes the service name so it's predictable and not auto-generated
    });

    const albAddress = new eks.KubernetesObjectValue(this, 'elbAddress', {
      cluster,
      objectType: 'Service',
      objectName: `${ingressControllerReleaseName}-nginx-ingress`, //This is what I was missing
      jsonPath: '.status.loadBalancer.ingress[0].hostname',
    });
    // I haven't tried the below code, but I suspect it might work as well as getSvcLBAddress is just a convenience method over `eks.KubernetesObjectValue()`
    //const elb = cluster.getServiceLoadBalancerAddress(`${ingressControllerReleaseName}-nginx-ingress`);

    const elb = albAddress.value; //This is what I needed to get.
  }
}


text:
Q: How to run Github Desktop on Manjaro I am new to Manjaro and Linux in general. I downloaded the AppImage from the github repsitory: https://github.com/shiftkey/desktop/releases/tag/release-2.9.14-linux2 and set the properties to be able to run as program. How can i start Github Desktop from the terminal now? What is the recommended folder to store .AppImage files in my system?

A: Update: I enabled AUR download, downloaded the Github Desktop from AUR.
To run the application from the terminal you have to type github-desktop


text:
Q: Change UITableView direction to Right-to-Left I develop an iOS application and my native language is Persian (a Right-to-Left language). How can I change UITableView direction to right-to-left in iOS programming?
A UITableView with RTL direction has:

*

*Icons are at right

*TableCell detail and button are at left

*TableView header and footer are right-aligned

like this :

Is there any UI or programming way to do this?

A: Try this on Swift
tableView.semanticContentAttribute = .forceRightToLeft

or in StoryBoard Cell properties (Semantic dropdown) select "Force Right-To-Left"

A: As I'm aware it'll automatically change to Right-to-Left since iOS8.

A: You can try to do this as well
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = myTableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell

    cell.textLabel?.textAlignment = .Right

    cell.textLabel?.text = goalsArray[indexPath.row]

    return cell
}

A: Build your view's constraints with NSLayoutAttributeLeading and  NSLayoutAttributeTrailing  instead of NSLayoutAttributeLeft and NSLayoutAttributeRight.
Your view's Direction will be the same with  your app's  language Direction.

A: for me this way worked
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier)! as UITableViewCell

    //cell.myView.backgroundColor = self.colors[indexPath.row]
    cell.textLabel?.text =
    "\((self.FAQs?[indexPath.row].Question)!)"

    cell.textLabel?.textAlignment = .right

    return cell
}


text:
Q: Asynchronously updating a Bootstrap progress bar with jQuery's $.ajax I have a script that loops through IPs on my local network, checking if anything is there.  Every iteration, I submit an AJAX request to get the HTTP status code using cURL, which is returned to my Javascript.  I already have built functions to calculate where the progress bar should be, however it only updates the progress bar when the entire script is finished executing.
Here's what I have so far (I'm only using 0-23 in this example because I'm on 199.235.130.22 and I return '200')
function updateProgress(percentage){
    document.getElementById('progressBar').style.width = percentage+'%';
    $('#progressText').html(percentage+'%');
}
for(host = 0; host <= 23; host++){
    ipToCheck = network_addr+'130.'+host;
    updateProgress(100/host);
    $.ajax({
        type: 'GET',
        url: 'js/scanhelper.php',
        data: {
            ip: ipToCheck
    }
    }).done(function(msg) {
        updateProgress(100/host);
        if(msg!=0){
            logSuccess(ipToCheck);
        }
    });
    pausecomp(200);  //Just a sleep function to simulate actual processing
}

My Bootstrap HTML is simply

And, if it matters, my cURL PHP script is here: http://pastebin.com/JRZckdVb
What this should do is, on every iteration, update the progress bar's width to 100 (as in 100%) divided by the current iteration.  It may not be the correct math, but the point is it's only updating after all iterations are complete, freezing the page while it's running.
How can I fix this?

A: aren't you dividing by zero here when host = 0 in the for loop?
updateProgress(100/host);

you can use a variable hosts to keep track of the number of hosts you have.Then the progress will be as below.
var hosts = 23;// total number of hosts
updateProgress((host/hosts)*100);

The other thing is the ajax you're firing is asynchronous, so what's happening is it fires and doesn't wait for the results. You can either "scan" each host serially one at a time updating the progress bar or scan all of them simultaneously having the progress bar update as the asynch results come back. Can you specify which behavior you're trying to achieve?
[UPDATE]
toggle async flag in the ajax call below for what you want.
function updateProgress(percentage){
    if(percentage > 100) percentage = 100;
    $('#progressBar').css('width', percentage+'%');
    $('#progressBar').html(percentage+'%');
}

var hosts = 23;
var hostsDone = 0;
for(host = 0; host <= hosts; host++){
    ipToCheck = network_addr+'130.'+host;
    $.ajax({
        type: 'GET',
        url: 'js/scanhelper.php',
        async:true,
        data: {
            ip: ipToCheck
    }
    }).done(function(msg) {
        hostsDone++;
        updateProgress((hostsDone/hosts)*100);
        if(msg!=0){
            logSuccess(ipToCheck);
        }
    });
}

if you're looking for visuals you should set the height of '#progressBar' to something non-zero and maybe background green.

A: The answer from @zerObit are onli 2/3 of the thrue! You have also to set aria-valuenow.
In some cases, the progress bar would be hidden.
You can do this by:
$('#progressBar').attr('aria-valuenow', percentage);


text:
Q: Invertible Matrix to Higher power I'm working on showing if A is invertible, that for any positive integer $n$, $(AMA^{-1})^n=(AM^nA^{-1})$
My first idea is induction on $n$ but is there a property of $A$ that explans why its power remains 1 or -1? Thanks in advance.

A: Hint: look at this
$$
AMA^{-1} A MA^{-1}=AM^2A^{-1}.
$$

A: Hint: $AA^{-1}=A^{-1}A=I$ where $I$ is the identity matrix. Induction would be a good idea.


text:
Q: Formatting all files in a directory in vs code Related:
How do I Change VSCode To Indent 4 Spaces Instead Of Default 2?
Is there a way to format all src files in a project in vscode?
In:

the formatting is set by default to LF, but the environment (win) expects CRLF. This can be done by hand but is tedious.
Can vscode set the format to LF for all files (js, html)?
For js files, the .eslintrc.js config needed an extra rule:
  rules: {
     ...
    "linebreak-style": "windows",
  },

A: the question has already been answered: How can I make all line endings (EOLs) in all files in Visual Studio Code, Unix-like?
You can also configure the EOL for that extension so new files will follow your preference. Under "Settings", type in the search bar: @lang:language-name @id:files.eol and then choose the "User" or "Workspace" tab. Example: for java it will be: @lang:java @id:files.eol
java eol configuration


text:
Q: xcode 4.2 tabbed application Heriarcy I have been reading up a bit I am trying to figure out how to create a proper view herarchy for my app. I created a base Tabbed application in xcode 4.2 using arc, but this new app does not include a mainwindow.xib, so many of the tutorials that use IB are uesless to me.  I have a 5 tab application working already and the "base" of the app works as expected.  What I need is to incorporate  more views within a specific "tabbed" window currently being viewed. My heirarchy is simple as seen below. My speculation is added with question marks as I have only the 5 base categories, all currently UIViewControllers within the tabBarController
App heriarchy (proposed)
Home (Currently UIViewController using homeViewController, convert to UINavigationController?)
    Add (UIViewController with HomeAdd.xib?)
    Edit (UIViewController with HomeEdit.xib
    delete  (UIViewController with HomeDelete.xib?)

ViewList - Single page to view list (Currently UIViewController using viewListViewController)

Share - Single page to send emails / invites (Currently UIViewController using shareViewController)

Friends (UINavigationController with root view of FriendsRoot.xib?)
    Add (UIViewController with FriendsAdd.xib?)
    Edit (UIViewController with FriendsEdit.xib?)
    delete  (UIViewController with FriendsDelete.xib?)

Settings - Single page for app settings/preferences (Currently UIViewController using settingsViewController)

I am not even sure if the above heirarchy is possible (i.e. mixing view controllers within a tabBarController), and would love input as to how to accomplish this programmatically as this appears to be my only option within the app delegate since there is no mainwondiw.h/m/xib by default.
My current code for this within my app delegate is as follows:
AppDelegate.h
#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate, UITabBarControllerDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) UITabBarController *tabBarController;

@end

AppDelegate.m
@synthesize window = _window;
@synthesize tabBarController = _tabBarController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    UIViewController *homeViewController = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
    UIViewController *viewListViewController = [[ViewListViewController alloc] initWithNibName:@"ViewListViewController" bundle:nil];
    UIViewController *shareViewController = [[ShareViewController alloc] initWithNibName:@"ShareViewController" bundle:nil];
    UIViewController *friendsViewController = [[FriendsViewController alloc] initWithNibName:@"FriendsViewController" bundle:nil];
    UIViewController *settingsViewController = [[SettingsViewController alloc] initWithNibName:@"SettingsViewController" bundle:nil];
    self.tabBarController = [[UITabBarController alloc] init];
    [self.tabBarController setDelegate:self];
    self.tabBarController.viewControllers = [NSArray arrayWithObjects:homeViewController, viewListViewController, shareViewController, friendsViewController, settingsViewController, nil];
    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];
    return YES;
}

I have tried a few attempts to inject UINavigationControllers, or alternate views with custom buttons but all seem to result in a failed build since I am still learning the context and code.

A: Home (Currently UIViewController using homeViewController, convert to UINavigationController?)
u can use uiviewcontroller for home
for the below 3 u can use model  view controller or u can add separate views .
Add (UIViewController with HomeAdd.xib?)
    Edit (UIViewController with HomeEdit.xib
    delete  (UIViewController with HomeDelete.xib?)
same case for Friends also..
i am not sure about why didnt u find mainwindow.xib ..

A: The bad news is that since the newer Tab Application doesn't have a "MainWindow.xib" by default, you can't follow a lot of the tutorials online.  The good news is that it is still very easy to implement.
In your AppDelegate.m file in the
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

method (where you set up your tabBarController's view controllers you need to actually add ViewControllers of type "UINavigationController" instead of type "UIViewController" (you need to create these files).
For example (for abbreviation's sake I only showed my last UINavigationController declaration),
UINavigationController *nodes = [[NodeNavigationController alloc] initWithNibName:@"NodeNavigationController" bundle:nil];
self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = [NSArray arrayWithObjects:modems, nodes, home,viewController1, viewController2, nil];

Lastly, in your UINavigationController's init method (or similar)
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

you need to add this...
Nodes *viewController = [[Nodes alloc] initWithNibName:@"Nodes" bundle:[NSBundle mainBundle]];
    self.viewControllers = [NSArray arrayWithObjects:viewController, nil];

Now in the "Nodes" viewController you can use the usual "[...pushViewController:...]" stuff you've always used.
example...
[self.navigationController pushViewController:viewController animated:YES];

I hope this was helpful.


text:
Q: is there something I am missing to get this error? why am I getting this error in the image attached below in MATLAB even though I already created the folder path with Plot3DLine.
enter image description here


text:
Q: Showing that product topology (not the one induced by the product metric) is the same as the one induced by the Euclidean metric
My task is to show, that the product topology on $\mathbb{R}^n =
 \mathbb{R} \times \dots \mathbb{R}$, i.e. the one generated by the
  basis $$\mathcal{B} := \{U_1 \times \dots \times U_n : U_i \text{ open
 in } (\mathbb{R},|\cdot|)\}$$ is the same as the one induced by the
  Euclidean standard metric on $\mathbb{R}^n$.

My idea was to show, that the collection of all open balls in $\mathbb{R}^n$ is also a basis for the product topology, since if two topologies have the same basis, then they are equal. So first of all we have to show that each open ball is in the product topology. So we could use the basis criterion, i.e. if $X$ is a topological space and we have a basis $\mathcal{B}'$ for its topology, then $U$ is open in $X$ if and only if for any $p \in U$ we find $B \in \mathcal{B}'$ such that $p \in B \subseteq U$. Pictorially it is very clear, but formalizing it is not that easy. I just want to know if I am on the right track:
Let $B_r(x)$ be an open ball in $\mathbb{R}^n$ and $p \in B_r(x)$. Then the element $$\left(p_1 - \frac{r - \sqrt{\sum_{k = 1}^n |x_i - p_i|^2}}{2}\right) \times \dots \times \left(p_n - \frac{r - \sqrt{\sum_{k = 1}^n |x_i - p_i|^2}}{2}\right)$$ belongs to the product topology. Now we would have to show that any point of this set lies in the open ball. Somehow, this idea is taken from $\mathbb{R}^2$ and i am not sure if it works in higher dimensions. Any help would be appreciated.

A: By the brilliant hint of user160738 it is much more elegant to prove first that $$d(x,y) := \sum_{i = 1}^\infty \frac{1}{2^i}d_i(x_i,y_i)$$ is a metric on $\prod_{i = 1}^\infty (M_i,d_i)$, $d_i \leq 1$, which induces the same topology as the product topology (a nice proof can be found in the book general topology by Ryszard Engelking). This can be adapted for norms, i.e.
$$N(x) = \sum_{i = 1}^\infty\frac{1}{2^i}N_i(x_i)$$
is a norm on $\prod_{i = 1}^\infty (M_i,N_i)$, $N_i \leq 1$. This is obviously also the case in the finite case, i.e. $\prod_{i = 1}^n (M_i,N_i)$. Now all norms on a finite dimensional space are equivalent, hence induce the same topology. Thanks a lot!


text:
Q: Is a specific setting needed to make the "is "keyword work in typescript? interface User {
  id: number;
  name: string;
  foo: string;
  bar: string;
}

interface Tabacudo{
  name:string,
  nickName:string
}

function isUser(o: any) : o is User {
    //by using the type predicate: "o is User"
    //o should be cast to Use as the example on this source:
    // "https://languageimperfect.com/2019/08/05/understanding-typescript-type-predicates.html"
    const u: User = o
    return typeof u.id  === "number"
        && typeof u.name === "string"
        && typeof u.foo === "string"
        && typeof u.bar === "string";
}

let o : any = {};
if(isUser(o)) {
    console.log(o.id); // o is User
}

the return statment within isUser returns false
and if I switch "function isUser(o: any) : o is User" to "function isUser(o: any) : o is Tabacudo" not even a warning is begeted.
is there any special version of typescript to make the "is" keyword to work??


text:
Q: Akeneo API - Getting children product models I'm on Akeneo 2.3 & have a product structure as

Product Model (Master) -> Product Model (Color) -> Product (Size)

I'm trying to call this endpoint
{{url}}/api/rest/v1/product-models?search={
    "parent": [{
        "operator": "=",
        "value": "DRZ9186"
    }]
}

However, I'm getting
{
    "code": 422,
    "message": "Filter on property \"parent\" is not supported or does not support operator \"=\""
}

Now I'm not quite sure whether parent is genuinely not supported via the filter as they are not mentioned here https://api.akeneo.com/documentation/filter.html
Pretty sure it comes down to \Pim\Bundle\ApiBundle\Checker\QueryParametersChecker::checkPropertyParameters but that's where I couldn't move further.

A: The "parent" property is not available right now on the Akeneo Web API.
You are right about QueryParametersChecker::checkPropertyParameters. It checks which properties can be used based on its service definition. As you can see, parent is not one of the authorized fields.
By the way, even if it was available, there is currently no operator = for the property parent. Available operators are IN, EMPTY and NOT EMPTY. So instead of:
search={"parent":[{"operator":"=","value":"DRZ9186"}]

the correct request would be:
search={"parent":[{"operator":"IN","value":"[DRZ9186]"}]

Don't hesitate to open a feature request on Akeneo GitHub repository, describing your use case. Akeneo product owners will certainly be interested.


text:
Q: How to arrange plots in a single column using grid_arrange_shared_legend I've been attempting to use the  grid_arrange_shared_legend code to create a column of ggplot2 plots with a single legend (I can't use straight faceting because I need to use coord_flip and have different x-axis sizes - this has been documented by Hadley as not working - https://github.com/hadley/ggplot2/issues/95)
The code prints out the 4 plots as a 2x2 matrix with the legend underneath (see http://rpubs.com/sjackman/grid_arrange_shared_legend).
I have been trying to get the 4 plots plus legend in a single column, but failed miserably. Oddly enough, I assumed that the ncol=1 argument to grid.arrange would make it all a single column but it doesn't.
At present, given 4 graphs plus a legend, the code gives this layout:
+-----------+      +-----------+
|           |      |           |
|     1     |      |    3      |
|           |      |           |
+-----------+      +-----------+

+-----------+      +-----------+
|           |      |           |
|     2     |      |    4      |
|           |      |           |
+-----------+      +-----------+

        LEGEND HERE

I'm trying to get
+-----------+
|           |
|     1     |
|           |
+-----------+

+-----------+
|           |
|     2     |
|           |
+-----------+

+-----------+
|           |
|     3     |
|           |
+-----------+

+-----------+
|           |
|     4     |
|           |
+-----------+

 LEGEND HERE

Any help appreciated.
Regards
Pete

A: this version has a column parameter for the layout of plots (the other ncol  is to arrange the group of plots and legend)
grid_arrange_shared_legend <- function(..., ncol=1) {
  plots <- list(...)
  g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))[["grobs"]]
  legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
  lheight <- sum(legend$height)
  grid.arrange(
    do.call(arrangeGrob, c(ncol=ncol, lapply(plots, function(x)
      x + theme(legend.position="none")))),
    legend,
    ncol = 1,
    heights = unit.c(unit(1, "npc") - lheight, lheight))
}

Alternatively, consider this strategy which will align the panels
library(gridExtra)

get_legend <- function(p, position="bottom"){
  g <- ggplotGrob(p + theme(legend.position=position))
  gtable::gtable_filter(g, "guide-box")
}
strip_legend <- function(pl) lapply(pl, function(x) x + theme(legend.position="none"))

legend <- get_legend(p1)
pl <- strip_legend(list(p1,p2,p3,p4))
gl <- lapply(pl, ggplotGrob)
lheight <- sum(legend$heights)
grid.arrange(do.call(rbind, gl), legend,
             heights = unit.c(unit(1,"npc") - lheight, lheight))


text:
Q: Python 3.X - Search a list using user input and print the result with open("zipcodes.txt", "r") as ins:
   array = []
   for line in ins:
       array.append(line.split(","))

print(array)

userInput = input("Please enter the codes your looking for: ")

print(array.index(userInput))

First off, this is for a school assignment, so I am not looking for a complete answer, I'm looking for a direction. My assignment is to load in a text file into a list, separate each line. (the text file is every USA zip code, the city the zipcode is for, and the state EX. 93312,BAKERSFIELD,CA). once the list is created the next thing the program needs to do is take in a users zipcode and then print out the zipcode, the city and the state. This is the code I have so far, I am at a total loss of what to do. Again I am not looking for a complete answer, just a direction. Sometimes I miss simple solutions and just need someone to say something that will make it click in my head. Thank you for your time and for any info or help.

A: array.index() does not return the element itself; It returns at which index it is. For example, if '93267' is the second element in a list and you called array.index('93267'), you'd get '1'. Try creating a variable that holds the index, and then print whatever is at that index:
index1 = array.index(userInput)
print(array[index1))

Yet you may run into an issue with this, as in your code you split each line at a comma- and in your description, your postcode, city and state were separated by a comma. I'm not entirely sure what your original text file looks like, so I could be wrong, but just be aware that it may cause some issues down the track.
Hope this helped; if you run into more issues, feel free to say so. Good luck with your school project!

A: EDIT: This version doesn't use a dictionary but uses a list instead.
This code is a quick example of one way you could do that. The file zipcodes.txt only has that single example that you gave in the description.
MATCH = """
Zipcode: {}
City:    {}
State:   {}
"""

with open('zipcodes.txt', 'r') as f:
    zipcodes = [line.rstrip().split(',') for line in f]

while True:
    user_zipcode = input("Enter zipcode (or (Q)uit): ")
    if user_zipcode.lower() == 'q':
        break
    for zipcode, city, state in zipcodes:
        if user_zipcode == zipcode:
            print(MATCH.format(zipcode, city, state))
            break
    else:
        print("\nNo match for zipcode: '{}'\n".format(user_zipcode))

Console:
Enter zipcode (or (Q)uit): 12345

No match for zipcode: '12345'

Enter zipcode (or (Q)uit): 93312

Zipcode: 93312
City:    BAKERSFIELD
State:   CA

Enter zipcode (or (Q)uit): q

A: If I've understood correctly, the structure of array will end up like this:
[['ZIPCODE', 'CITY', 'STATE'], ['ZIPCODE', 'CITY', 'STATE'], ...]
and userInput will hold a string representing a ZIPCODE.
Given that structure of array, for each entry in array (each sublist), the first element in the entry (entry[0]) will be a ZIPCODE.
You could loop through each entry in array, and check if that entry's first element matches the userInput.
If it does, you can print that entry.
Note: To understand why you are getting an error from the print statement, please check this description of list methods, namely the index method.


text:
Q: How to decouple npm package and replace the codebase with unpackaged direct version of the source code? I am trying to understand the codebase of Pancakeswap frontend, the current structure https://github.com/pancakeswap/pancake-frontend has a dependency on
@pancakeswap/sdk and @pancakeswap/uikit
Which is available here https://github.com/pancakeswap/pancake-toolkit/tree/master/packages
So my question is can I just copy the folder and put in the frontend directory and replace all imports to use this path instead of the npm package?
If not what other options are available apart from deploying my own version of the UiKit.


text:
Q: Android SAX parsing retrieval very slow In my app i have some 50 to 100 data to be parsed...also some images within 2 MB size...All these are to be retrieved to a single activity and are sorted and displayed there...
But its taking about 2 minutes...thats too much.
What to do for reducing the parse time?
Or am i wrong using SAX parsing???Suggestions please....
SAXParserFactory spf = SAXParserFactory.newInstance();
      SAXParser sp = spf.newSAXParser();
      XMLReader xr = sp.getXMLReader();

      /** Send URL to parse XML Tags */
      URL sourceUrl = new URL(url);

      /** Create handler to handle XML Tags ( extends DefaultHandler ) */
      XmlHandler xmlHandler4Profile = new XmlHandler();
      xr.setContentHandler(xmlHandler4Profile);
      xr.parse(new InputSource(sourceUrl.openStream()));

      }

Code for XmlHandler.java
public class XmlHandler extends DefaultHandler{
static GetXml getxml;
Boolean currentElement = false;
String currentValue = null;

@Override
public void startElement(String uri, String localName, String qName,
    Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
currentElement=true;
   if (localName.equals("root"))
    {
        /** Start */
       getxml = new GetXml();
    }
}

@Override
public void endElement(String uri, String localName, String qName)
        throws SAXException {
    // TODO Auto-generated method stub
    currentElement=false;

    //**************************display page************************

    if (localName.equalsIgnoreCase("DisplayId"))
         getxml.setDisplayId(currentValue);

     if (localName.equalsIgnoreCase("DisplayPage"))
         getxml.setDisplayPage(currentValue);

    //**************************category details************************

        if (localName.equalsIgnoreCase("CategoryId"))
             getxml.setCategoryId(currentValue);

         if (localName.equalsIgnoreCase("CategoryName"))
             getxml.setCategory(currentValue);

        //**************************news details************************

         if (localName.equalsIgnoreCase("Picture"))
             getxml.setPictureName(currentValue);

         if (localName.equalsIgnoreCase("newsHeading"))
             getxml.setNewsHeading(currentValue);

         if (localName.equalsIgnoreCase("Mainnews"))
             getxml.setMainNews(currentValue);

}
    @Override
public void characters(char[] ch, int start, int length)
        throws SAXException {
    // TODO Auto-generated method stub
     if (currentElement) {
            currentValue = new String(ch, start, length);
            currentElement = false;
        }
}

A: You really should profile your code and find out where it's spending its time.
I can see one performance issue and one correctness issue in your posted code.
You'll gain a bit by adding some else usage in your endElement code.  Once you know localName matches something there's no need to check it against all the later possibilities which can not possibly match.
That may not gain much, but it's certainly worth trying.
Your characters method is wrong, but this has to do with correctness rather than efficiency.  See my answer to another question on SAX parsing for what's wrong and how to write a correct characters method.  The change will also necessitate a change in how endElement gets the value, as it has to be collected into a buffer.

A: The answer is likely that the SAX parser you're using is checking the internet for the schema or DTD of your xml content. If you write an entityResolver that bypasses these checks, you'll likely improve your start time (which is often 2 minutes or so).
See this for more details.
How to read well formed XML in Java, but skip the schema?
This solved the problem for me using Xerces...


text:
Q: How to return a child collection with joins linq query I'm trying to figure out how to get a sub-collection, within a linq query. Basically I have courses, which have multiple schedules, but when I try the query below, it returns multiple objects, for each course, because the schedules are not a collection.
 public JsonResult Required(int programId, int departmentId)
 {
        var courses = (from r in context.ProgramRequiredCourses
                       join c in context.IAUClasses on r.ClassId equals c.id
                       join s in context.IAUClassSchedules on c.id equals s.classId
                       join d in context.IAUDepartments on c.mainDepartmentId equals d.id
                       where r.ProgramId == programId && d.id == departmentId
                       select  new RequiredCourse{
                            Department = d,
                            Course = c,
                            Schedule = s
                       }).AsEnumerable().Distinct(new DistinctCourseComparer());
        return Json(courses, JsonRequestBehavior.AllowGet);
  }

**Supporting code **
I know the Schedule in the RequiredCourse class should be changed to an IEnumerable, but not sure how to go about populating it.
public class RequiredCourse
{
    public IAUClass Course { get; set; }
    public IAUClassSchedule Schedule { get; set; }
    public IAUDepartment Department { get; set; }
}

public class DistinctCourseComparer : IEqualityComparer<RequiredCourse>
{
    public bool Equals(RequiredCourse x, RequiredCourse y)
    {
        return x.Course.id == y.Course.id &&
               x.Course.className == y.Course.className;
    }

    public int GetHashCode(RequiredCourse obj)
    {
        return obj.Course.id.GetHashCode() ^
               obj.Course.className.GetHashCode();
    }
}

A: It sounds like you're asking for a group join:
from r in context.ProgramRequiredCourses
join c in context.IAUClasses on r.ClassId equals c.id
join s in context.IAUClassSchedules on c.id equals s.classId into classSchedules
join d in context.IAUDepartments on c.mainDepartmentId equals d.id
where r.ProgramId == programId && d.id == departmentId
select new
{
    Department = d,
    Course = c,
    Schedules = classSchedules
}

Take special note of the into classSchedules part of the query. Instead of outputting a new row for each schedule, it will group all the schedules together, per class, into the IEnumerable<IAUClassSchedule> classSchedules


text:
Q: Cassandra Rolling Tombstones I am doing some simple operations in Cassandra, to keep things simple I am using a single node . I have one single row and I add 10,000 columns to it, next I go and delete these 10,000 columns, after a while I add 10,000 more columns to it and then delete them after some time and so on ... The deletes will delete all the columns in that one row.
Here's the thing which I don't understand, even though I delete them I see the size of the database increase, my GCGracePeriod is set to 0 and I am using Leveled Compaction Strategy.
If I understand the tombstones correctly, they should be deleted after the first major compaction, it appears that they are not deleted, even after running nodetool compact command.
I read on some mailing list that these are rolling tombstones (if you frequently update and delete the same row) and are not handled by major compaction. So my question is when are they deleted ? if not then the data would just grow, which i personally think is bad. To make matters worst I could not find any documentation about this particular effect.

A: First, as you're discovering, this isn't a really good idea.  At the very least you should use row-level deletes, not individual column deletes.
Second, There is no such thing as a major compaction with LCS; nodetool compact is a no-op.
Finally, Cassandra 1.2 improves compaction a lot for workloads that generate a lot of tombstones: https://issues.apache.org/jira/browse/CASSANDRA-3442


text:
Q: How do i make 2x cash gamepass script Roblox So I was making a script that gives you 5 cash every minute, I also made a game pass for the script if someone owns the game pass they get double money as the Non-game pass holders. Here is my script
I Haven't any scripts to give cash but the problem is in the 2nd script block, the console print an error :
  09:10:57.466  ServerScriptService.CashGiver:6: attempt to index nil with 'UserId'  -  Server - CashGiver:6
local Give5Cash = game.ReplicatedStorage:WaitForChild("Give5Cash")
local Give10Cash = game.ReplicatedStorage:WaitForChild("Give10Cash")

Give5Cash.OnServerEvent:Connect(function()
    print("Player Will Be Given 5 Cash")
end)

Give10Cash.OnServerEvent:Connect(function()
    print("Player Will Be Given 10 Cash")
end)

while wait() do
    local MPS = game:GetService("MarketplaceService")
    local id = 16031172
    local player = game.Players.LocalPlayer

    if MPS:UserOwnsGamePassAsync(player.UserId, id) then
        game.ReplicatedStorage:WaitForChild("Give10Cash"):FireServer()
        print("Player Owns 2x Cash")
    else
        print("Players Doesnt Owns 2x Cash")
        game.ReplicatedStorage:WaitForChild("Give5Cash"):FireServer()
    end

    wait(5)
end

A: local player = Players.LocalPlayer
if MPS:UserOwnsGamePassAsync(player.UserId, id) then

...
Here you assign a nil value to player which you may not index but do.
From the Roblox manual:

Players.LocalPlayer
NotReplicated
This item is not replicated across Roblox's server/client boundary.
LocalPlayer is a read-only property which refers to the Player whose
client is running the game.
This property is only defined for LocalScripts (and ModuleScripts
required by them), as they run on the client. For the server (on which
Script objects run their code), this property is nil.

A: So I figured out a way to solve this issue and I have got the answer for my question.
Here is how I did it I made 3 scripts in ServerScriptService with the name of CashGiver5, CashGiver10, and CashGiverHandler
here are the scripts I added to each script.
CashGiver5:
while wait(1) do
    print("Giving Player 5 Cash ")
    for i, player in pairs(game.Players:GetPlayers()) do
        player:WaitForChild("leaderstats").Cash.Value += 5
    end
end

CashGiver10:
while wait(1) do
    print("Giving Player 10 Cash ")
    for i, player in pairs(game.Players:GetPlayers()) do
        player:WaitForChild("leaderstats").Cash.Value += 10
    end
end

CashGiverHandler:
local MarketPlace = game:GetService("MarketplaceService")

game.Players.PlayerAdded:Connect(function(player)
    local g = 16031172 -- DOUBLE CASH ID

    local Give5Script = game.ServerScriptService.CashGiver5
    local Give10Script = game.ServerScriptService.CashGiver10

    if MarketPlace:UserOwnsGamePassAsync(player.UserId, g) then
        Give5Script:Destroy()
    else
        Give10Script:Destroy()
    end
end)

WHAT THE SCRIPT DOES?
So basically the CashGiver scripts are basic scripts giving player Cash every second.
so the Handler script Destroys one of the scripts (s) when a player is added to the game.


text:
Q: Error in Updating the model from database (EntityFramework Database-First) I know the reason for the following error very well,

The specified type member 'Ticket' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

but the problem is that the property 'Ticket' is not calculated property or anything else, it is a normal field in the database, I am trying to read it.
I am using Database-first and the model was working in a wonderful way, but after I added this property to the database and "Update the Model from database" I started to receive this error?
What I missed in the "Update the Model from database" to deserve this problem?

A: Just in case someone faced the same problem. My problem was in the connection string
<add name="BT_IQMSEntities" connectionString="metadata=res://*/BT_IQMSEntities.csdl|res://*/BT_IQMSEntities.csdl|res://*/BT_IQMSEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=biteg-data;initial catalog=BT_IQMS;user id=sa;password=IWillNotShowYouMyPassword;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />

Actually, the problem was in the three section
BT_IQMSEntities.csdl
BT_IQMSEntities.csdl
BT_IQMSEntities.msl
those sections must be the same as the name of the .edmx, and in my case the names where different from the .edmx name, and after fixing them and make them all the same, the problem solved.


text:
Q: Is there a way to convert an image to black and white pixel by pixel? When using image = image.convert("1") on a very light grey, it'll add little black pixels to "average" it out. I'm looking for something that just looks at every individual pixel and determines whether that pixel is closer to black or to white.

A: Please pay attention to the documentation on PIL.Image.convert:

The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is NONE, all values larger than 128 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the point() method.

So, you actually want no dithering and must set this option explicitly when converting:
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image

# Grayscale image as NumPy array with values from [0 ... 255]
image = np.reshape(np.tile(np.arange(256, dtype=np.uint8), 256), (256, 256))

# PIL grayscale image with values from [0 ... 255]
image_pil = Image.fromarray(image, mode='L')

# PIL grayscale image converted to mode '1' without dithering
image_pil_conv = image_pil.convert('1', dither=Image.NONE)

# Threshold PIL grayscale image using point with threshold 128 (for comparison)
threshold = 128
image_pil_thr = image_pil.point(lambda p: p > threshold and 255)

# Result visualization
plt.figure(1, figsize=(9, 8))
plt.subplot(2, 2, 1), plt.imshow(image, cmap=plt.gray()), plt.ylabel('NumPy array')
plt.subplot(2, 2, 2), plt.imshow(image_pil, cmap=plt.gray()), plt.ylabel('PIL image')
plt.subplot(2, 2, 3), plt.imshow(image_pil_conv, cmap=plt.gray()), plt.ylabel('PIL image converted, no dithering')
plt.subplot(2, 2, 4), plt.imshow(image_pil_thr, cmap=plt.gray()), plt.ylabel('PIL image thresholded')
plt.tight_layout()
plt.show()

The documentation is also imprecise: Actually, all values greater than OR EQUAL 128 are set to white, both for convert as well as for point – which makes sense, since [0 ... 127] are 128 values, and [128 ... 255] are 128 values.
Hope that helps!


text:
Q: Программа для распределения ящиков по контейнерам и грузовикам в зависимости от их количества Смогла решить проблему для 0 ящиков, а вот что делать с 27 я не могу понять. Помогите плиз! Прикладываю исправленный код.
    package practice;

    import java.util.Scanner;

    public class TrucksAndContainers {

    public static void main(String[] args) {
        int container = 0;
        int truck = 0;
        int maxInContainer = 27;
        int maxInTruck = 12;

        Scanner scanner = new Scanner(System.in);

        //получение количество коробок от пользователя
        int boxes = scanner.nextInt();

        // TODO: вывести в консоль коробки разложенные по грузовикам и контейнерам
        // пример вывода при вводе 2
        // для отступа используйте табуляцию - \t

        if (boxes == 0) {

        } else if (boxes < maxInContainer) {
            container++;
            truck++;
            System.out.println("Грузовик: " + truck + System.lineSeparator() +
                    "\tКонтейнер: " + container);
        } else if (boxes >= maxInContainer) {
            container++;
            truck++;
            System.out.println("Грузовик: " + truck + System.lineSeparator() +
                    "\tКонтейнер: " + container);
        }

        for (int i = 1; i <= boxes; i++) {
            System.out.println("\t\tЯщик: " + i);
            if (i % (maxInContainer * maxInTruck) == 0) {
                truck += 1;
                System.out.println("Грузовик: " + truck);
            }
            if (i % maxInContainer == 0) {
                container += 1;
                System.out.println("\tКонтейнер: " + container);
            }
        }

        System.out.println("Необходимо:" + System.lineSeparator() +
                "грузовиков - " + truck + " шт." + System.lineSeparator() +
                "контейнеров - " + container + " шт.");
    }
}

Основное задание:
Есть задача написать программу, которая распределит ящики по контейнерам и грузовикам в зависимости от их количества. Программа должна выводить необходимое для этого число грузовиков и контейнеров. В каждый грузовик помещается максимум 12 контейнеров. В каждый контейнер — не более 27 ящиков. Ящики, контейнеры и грузовики пронумерованы. Не могу понять как сделать число ящиков 0 и 27.
Скрин теста:

A: Как говориться все гениальное просто. Необходимо было просто добавить еще одно условие в код проверки количества контейнеров когда есть ящики. Вот код:
package practice;

import java.util.Scanner;

public class TrucksAndContainers {

    public static void main(String[] args) {

        int truck = 0;
        int container = 0;
        int boxesInContainer = 27;
        int containersInTruck = 12;

        Scanner scanner = new Scanner(System.in);

        //получение количество коробок от пользователя
        int boxes = scanner.nextInt();

        // TODO: вывести в консоль коробки разложенные по грузовикам и контейнерам
        // пример вывода при вводе 2
        // для отступа используйте табуляцию - \t

        if (boxes == 0) {

        } else if (boxes < boxesInContainer) {
            container++;
            truck++;
            System.out.println("Грузовик: " + truck + System.lineSeparator() +
                    "\tКонтейнер: " + container);
        } else if (boxes >= boxesInContainer) {
            container++;
            truck++;
            System.out.println("Грузовик: " + truck + System.lineSeparator() +
                    "\tКонтейнер: " + container);
        }

        for (int i = 1; i <= boxes; i++) {
            System.out.println("\t\tЯщик: " + i);

            if (i % (boxesInContainer * containersInTruck) == 0) {
                truck++;
                System.out.println("Грузовик: " + truck);
            }
            if (i % boxesInContainer == 0) {
                if (i != boxes) {
                    container++;
                    System.out.println("\tКонтейнер: " + container);
                }
            }
        }
        System.out.println("Необходимо:" + System.lineSeparator() +
                "грузовиков - " + truck + " шт." + System.lineSeparator() +
                "контейнеров - " + container + " шт.");

        /*
        Грузовик: 1
            Контейнер: 1
                Ящик: 1
                Ящик: 2
        Необходимо:
        грузовиков - 1 шт.
        контейнеров - 1 шт.
        */
    }

}


text:
Q: Best practice method - creating 2 records in 1 form_for My models:
brand.rb
  has_many :products
  has_many :votes
  belongs_to :user
  accepts_nested_attributes_for :products, :allow_destroy => true

product.rb
  belongs_to :user
  belongs_to :brand

vote.rb
  belongs_to :brand
  belongs_to :user

routes.rb
  resources :brands do
    resources :products
  end

My goal:  Create 2 records (product and vote) on existing Brand record in 1 form, on brand/show page.
My solution:
brand/show.html.erb
<% form_for([@brand, @brand.send(:product).klass.new]) do |f| %>
  <%= f.label :title %>
  <%= f.text_field :title %>

  <%= f.label :price %>
  <%= f.text_field :price %>

  <%= fields_for :votes, @brand.votes.new do |builder| %>
    <%= builder.label :rating %>
    <%= builder.text_field :rating %>
  <% end %>

  <%= f.submit %>
<% end %>

products_controller.rb
def create
  if Brand.exists?(:id => params[:brand_id])
    @review          = Review.new(review_params)
    @vote            = Vote.new(votes_params)
    @review.user_id  = @vote.user_id = current_user.id
    @review.brand_id = @vote.brands_id = params[:brand_id]

    if @vote.valid? && @review.valid?
      @vote.save
      @review.save
      redirect_to brands_path
    else
      flash[:errors][:vote]   = @vote.errors
      flash[:errors][:review] = @review.errors
      redirect_to brands_path
    end
  end
end

private
def product_params
  params.require(:review).permit(:title, :price)
end

def votes_params
  params.require(:votes).permit(:rating)
end

Is this right way of solving my task? Can I use it like that?

A: This is how I would refactor your create method:
def create
  brand = Brand.find(params[:brand_id]) # no test to know if Brand exists, if it does not it means the user gave a wrong Brand id, then a 404 error should be rendered
  @product = brand.products.create(products_params.merge({user_id: current_user.id}) # we can directly create this instance
  @vote    = brand.votes.create(votes_params) # we can directly create this instance
  # we add the errors in the flash if they exist
  flash[:errors][:vote]   = @vote.errors if @vote.errors.present?
  flash[:errors][:product] = @product.errors if @product.errors.present?

  redirect_to brands_path # since we want to redirect to brands_path if the creation succeeded or failed, we don't need to use it twice in the code
end

Also, little improvements:
@brand.send(:product).klass.new
# can become
@brand.products.new # produces a initialized Product instance

fields_for :votes, @brand.votes.new
# can become
f.fields_for @brand.votes.new
# notice the usage of `f` builder to generate the fields_for
# it will nest the params in `params[:brand][:votes_attributes][0]`

# brand.rb
accepts_nested_attributes_for :products, :allow_destroy => true
# add the following:
accepts_nested_attributes_for :votes, :allow_destroy => true

You will obviously have to update your strong params accordingly, but this is the easy part ;-)

A: I'd change the following logic:
@review.user_id = @vote.user_id = current_user.id
@review.server_id = @vote.server_id = params[:server_id]

Just add the current_user.id and params[:server_id] to the product_params and votes_params respectively.
Also, don't see the need for using instance variables for vote/review.
Other than that the saving two models seems OK to me.


text:
Q: How do I debug Ruby's method_missing? Let me clarify this a bit...
I have a class that handles XML files. This class implements method_missing and used the method passed as the identifier of a tag, and then returns an object that represents the XML node for that tag. The code is more or less like this:
def method_missing(m, *args, &block)
  XmlNode.new(@xml.at_css(m.to_s.upcase))
end

I've done something weird, though, and sometimes the m parameter is not being sent to the method call.
Is there a way for me to pinpoint which of the calls is the culprit?
One way that I can think of is to log the method call itself, but how do I do that from within method_missing?

A: A very crude way would be to output the call stack by putting
puts caller

right above your XmlNode... line. That will output the call stack and you can see who called the method.


text:
Q: a question on Lindelöf spaces Let $X=\{(x,y)\in {\Bbb R}^2:y>0\}$ is the subspace of ${\Bbb R}^2$ with the usual topology, then it is still Lindelöf?
If not, with which topology can $X$ be made to be Lindelöf?

A: Yes, $X$ is Lindelöf: this is immediate from the fact that it is second countable. Every second countable space is hereditarily second countable and therefore hereditarily Lindelöf.
Added: As Mariano points out in the comments, you can also use the fact that $X$ is homeomorphic to $\Bbb R^2$, which is itself Lindelöf.


text:
Q: Merge multiple curved lines into one line How to draw with TikZ multiple curved lines which are merged into one line? Below is an example how it should look like:

I tried the following code, but that looks ugly as hell:
\draw[] (2.4,5.4) .. controls (2.4,4.2) and (2.8,4.2) .. (7,8.5);
\draw[] (2,7.6) .. controls (1.8,8.6) and(3,8.5) .. (7,8.5);
\draw[] (1.55,7.6) .. controls (1.7,8.6) and(3,8.5) .. (7,8.5);
\draw[] (9.8,4) .. controls (8.5,5) and (8,6) .. (7,8.5);
\draw[] (7,8.5) .. controls (7,12) and (6,13.5) .. (5,13.5);

A: Welcome to TeX.SE. This kind of drawing can be done with the to path operation, its in and out options to specify incoming and outgoing angles at interesting points, the attach arrow style from Schrödinger's cat and... a bit of patience.
\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{decorations.markings, arrows.meta, bending}

% 'attach arrow' style from Schrödinger's cat:
% <https://tex.stackexchange.com/a/524935/73317>
\tikzset{%
    attach arrow/.style={
    decoration={
        markings,
         mark=at position 0 with {\pgfextra{%
         \pgfmathsetmacro{\tmpArrowTime}{\pgfkeysvalueof{/tikz/arc arrow/length}/(\pgfdecoratedpathlength)}%
         \xdef\tmpArrowTime{\tmpArrowTime}}},
        mark=at position {#1-3*\tmpArrowTime} with {\coordinate(@1);},
        mark=at position {#1-2*\tmpArrowTime} with {\coordinate(@2);},
        mark=at position {#1-1*\tmpArrowTime} with {\coordinate(@3);},
        mark=at position {#1+\tmpArrowTime/2} with {\coordinate(@4);
        \draw[-{Stealth[length=\pgfkeysvalueof{/tikz/arc arrow/length},bend]}]
          plot[smooth] coordinates {(@1) (@2) (@3) (@4)};},
        },
     postaction=decorate,
     },
     attach arrow/.default=0.5,
     arc arrow/length/.initial=2mm,
}

\begin{document}
\begin{tikzpicture}
  \draw[attach arrow=0.2, attach arrow=0.83]
    (-6,-2) to[out=45, in=180] (-4,-1) to[out=0, in=180] (-1.7,-1.8)
    to[out=0, in=-95] (0,0) to[out=85, in=0] (-3,2) to[out=180, in=70] (-5,1);
  \draw[attach arrow=0.5] (-6.5,-4) to[out=-30, in=180] (-5.5,-4.2)
    to[out=0, in=180] (-3,-3) to[out=0, in=205] (-1.1,-3)
    to[out=25, in=-95] (0,0);
  \draw[attach arrow=0.3] (-1.5,-8) to[out=110, in=260] (-0.2,-2.5)
    to[out=80, in=-95] (0,0);
\end{tikzpicture}
\end{document}


text:
Q: Setting maximum height of table row I have an SQL table that is loaded from database into HTML table. Some of the columns contain many lines of information, right now all the lines in the row are shown, which makes the row too high. I would like to set some maximal height of one row, I have used CSS to set the height but it is not working.
table tbody tr
{
    max-height: 20px;
}

Can anyone Help? Thank you

A: Try this HTML code

            Header stays put, no scrolling

            cell 1/1
            cell 1/2

            cell 2/1
            cell 2/2

            cell 3/1
            cell 3/2

I hope it's helpful.

A: You can add a class for the complete table (in the example is variable-rows), this will help to apply the style to the rows of this table only. And will apply the style to all the rows in the table without need to add class for each row:

.variable-rows tr {
  display: flex;
  height: 30px;
  overflow-y: scroll;
  border: 1px solid red;
}

          cell 1

          cell 2 this is a
 test text to set
 the hright of the
 cell with scroll

          cell 3

A: Well another workaround to try is changing the display of the table row or other table elements
Below is a simple example of how that could work but you might need to do a lot of style adjustments due to it
in the example below, I changed the display of the table row to flex

.test {
  display: flex;
  overflow-y: scroll;
  height: 30px;
}

table {
  width: 100%;
}

      heading

test
      test

A: You can easily set 'height' attribute to your 'tr' tag like:


text:
Q: Parse HTML file to excel python I am using BeautifulSoup and trying to parse the output to excel.

SCHOOL:

                                        Class ID:
                                        <input name="ctl00$MainContent$ClassIdTextBox" type="text" value="250" id="MainContent_IdTextBox" disabled="disabled"  class="aspNetDisabled form-control">
                                            Required

                                        Profile ID:
                                        <input name="ctl00$MainContent$ProfileIdTextBox" type="text" value="NA" id="MainContent_ServiceIdTextBox" disabled="disabled"  class="aspNetDisabled form-control">
                                        Required

                                        Serial Number:
                                        <input name="ctl00$MainContent$NumberTextBox" type="text" value="763" id="MainContent_NumberTextBox" disabled="disabled"  class="aspNetDisabled form-control">
                                        Required

                                        MC Number:
                                        <input name="ctl00$MainContent$MCSerialNumberTextBox" type="text" value="290" id="MainContent_SerialNumberTextBox" disabled="disabled"  class="aspNetDisabled form-control">
                                        Required

                                        SK:
                                        <input name="ctl00$MainContent$SkTextBox" type="text" value="384xm" id="MainContent_SkTextBox" disabled="disabled" class="aspNetDisabled form-control">

                                        Profile:
                                        <input name="ctl00$MainContent$ProfileTextBox" type="text" value="NA" id="MainContent_ProfileTextBox" disabled="disabled"  class="aspNetDisabled form-control">

                                        Address:
                                        <input name="ctl00$MainContent$AddressTextBox" type="text" value="192.168.56.54" id="MainContent_AddressTextBox" disabled="disabled"  class="aspNetDisabled form-control">

                                        Dn:
                                        <input name="ctl00$MainContent$DnTextBox" type="text" value="NA" id="MainContent_DnTextBox" disabled="disabled"  class="aspNetDisabled form-control">
                                        Required

                                        Hostname:
                                        <input name="ctl00$MainContent$PrimaryHostNameTextBox" type="text" value="N/A" id="MainContent_HostNameTextBox" disabled="disabled" class="aspNetDisabled form-control">

                                        Primary:
                                        <input name="ctl00$MainContent$PrimarySidTextBox" type="text" value="N/A" id="MainContent_SidTextBox" disabled="disabled" class="aspNetDisabled form-control">

                                        Server:
                                        <input name="ctl00$MainContent$ServerTextBox" type="text" value="sv41" id="MainContent_ServerTextBox" disabled="disabled" class="aspNetDisabled form-control">

                                        Server-Address:
                                        <input name="ctl00$MainContent$AddressTextBox" type="text" value="10.56.1.41" id="MainContent_AddressTextBox" disabled="disabled" class="aspNetDisabled form-control">
                                         Required

Expected output:
Class ID    Profile ID Serial Number MC Number SK       Profile Address         Dn Hostname Primary
 250        NA          763         290       384xm      NA     192.168.56.54   NA  NA      NA
from bs4 import BeautifulSoup
import requests

html= """Inputfile """

for item in soup.select("div.form-group"): print(item.get_text())

A: You want the 'value' attribute. Depending on your full html you may be able to shorten the selectors.
from bs4 import BeautifulSoup as bs
import csv

soup = bs(your_html, 'lxml')

with open("data.csv", "w", encoding="utf-8-sig", newline='') as csv_file:
    w = csv.writer(csv_file, delimiter = ",", quoting=csv.QUOTE_MINIMAL)
    w.writerow([i.text for i in soup.select('.form-group label')])
    w.writerow([i['value'] for i in soup.select('input.aspNetDisabled')])

Specific items:
soup = bs(your_html, 'lxml')

items = ['"Class ID:"','"Serial Number:"','"Hostname:"']
items = ','.join(items)
nodes = [i['value'] for i in soup.select(f'label:contains({items}) + .aspNetDisabled')]
headers =  [i.text for i in soup.select(f'label:contains({items})')]

with open("data.csv", "w", encoding="utf-8-sig", newline='') as csv_file:
    w = csv.writer(csv_file, delimiter = ",", quoting=csv.QUOTE_MINIMAL)
    w.writerow(headers)
    w.writerow(nodes)


text:
Q: Facebook asmack xmpp client returns random numbers for roster I followed the guidlines given in the following SO question to connect to facebook chat using xmpp and I am able to connect to facebook and pull the correct number of contacts but when it prints the contacts they are all random numbers @chat.facebook.com and all return offline.
Android Facebook chat example project
public void connectToFb() throws XMPPException {

        ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com", 5222);
        config.setSASLAuthenticationEnabled(true);
        config.setSecurityMode(SecurityMode.required);
        config.setRosterLoadedAtLogin(true);
        config.setTruststorePath("/system/etc/security/cacerts.bks");
        config.setTruststorePassword("changeit");
        config.setTruststoreType("bks");
        config.setSendPresence(false);
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, MemorizingTrustManager.getInstanceList(this), new java.security.SecureRandom());
            config.setCustomSSLContext(sc);
        } catch (GeneralSecurityException e) {
            Log.w("TAG", "Unable to use MemorizingTrustManager", e);
        }
        XMPPConnection xmpp = new XMPPConnection(config);
        try {
            xmpp.connect();
            xmpp.login("user.name", "password"); // Here you have to used only facebookusername from facebookusername@chat.facebook.com
            Roster roster = xmpp.getRoster();
            Collection<RosterEntry> entries = roster.getEntries();
            System.out.println("Connected!");
            System.out.println("\n\n" + entries.size() + " buddy(ies):");
            // shows first time onliners---->
            String temp[] = new String[50];
            int i = 0;
            for (RosterEntry entry : entries) {
                String user = entry.getUser();
                Log.i("TAG", user);
            }
        } catch (XMPPException e) {
            xmpp.disconnect();
            e.printStackTrace();
        }
        }

A: It sounds like you just want to readable name, so try using
rosterEntry.getName()

which returns the users name, instead of
rosterEntry.getUser()

which returns the JID.
Not sure about your offline problem though.  How are you checking?  You have to set up a roster listener to get changes in presence.

A: Its a bug in XMPP library . There is a work around for that .
Step 1: Connect to XMPP.
Step 2: Login to facebook account through xmpp.
Step 3: get online friend list using this fql query .
    SELECT uid, name, online_presence ,
      sex FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())

Then i concat address with string uid@chat.facebook.com  and communicate via XMPP.

A: (It's not 100% clear what problem you're having regarding the online/offline thing may be a bug or something you're doing incorrectly), but you won't get back the user's actual user IDs in the response, this is mentioned in the docs:
The user's own Jabber ID (JID) is different from the Jabber ID that their contacts will see because the translation is done internally.


text:
Q: Docker tutorial not working for springboot+mysql+react application I am trying to familiarize myself with docker and applications with spring-boot, mysql and react and I want to run this example: https://www.callicoder.com/spring-boot-mysql-react-docker-compose-example/ ( the github repo of the source is :https://github.com/callicoder/spring-security-react-ant-design-polls-app.
I have changed the database_user and password accordingly to mysql( user: root password: no password ->blank field)
I use docker-compose up -d to start it. I get no errors, the containers are made and existing images but in browser I get a : this site can't be reached when trying: localhost:3000 or 3001 or 127.0.0.1:3000 or localhost:9090 .
I can see in docker that the containers are running and their ports :https://imgur.com/a/pbTv4VI
Those ports don't work also. I try with my machine's  virtual box addresses, they don't work.
I have win10 HOME and  I use docker-toolbox(not docker desktop) installed using  https://medium.com/@mbyfieldcameron/docker-on-windows-10-home-edition-c186c538dff3
 Edit:
Using docker logs (server_containerID) I have found a possible issue in the server application:
java.sql.SQLException: Access denied for user 'root'@'192.168.192.3' (using password: NO)

However, the mysql container runs alright( I run it with :  docker run -e  MYSQL_ALLOW_EMPTY_PASSWORD=1 mysql:8) and it shows that it can connect/ awaits connection with the server.
Any idea on how I could access the application? Thank you!
Figured out, apparently the address is 192.168.99.100:9090.

A: I cloned that repository and ran
docker-compose up -d

in my machine with running docker containers,

Docker container for react-app is running in 9090 port, you should hit http://localhost:9090 (NOT localhost:3000, etc) in the browser.
As you have changed MySQL credential - changes should be made in docker-compose.yml file and application.properties file from spring-boot project.
Here is the result,

If you're still facing the issue, try to see the logs of spring-security-react-ant-design-polls-app_app-server_1 by executing,
docker logs -f spring-security-react-ant-design-polls-app_app-server_1

Seeing the server-log - you may encounter the issue.


text:
Q: ES2015:multikeys Map : where is the bottleneck? I have an algorithm coding issue in ES2017 with an async generator. I have to extract some data from a list of randomly-distributed maps.
My initial goal is to code a multi-keys, multiple values (a project I called mukemuva) data structure, with the ability of compacting the overlapping information.
(this is a long post, with some code reviews needed to answers it, so please take a while to answer...)
The problem I attempt to solve is the following:

*

*in a regular ES2015 Map, keys should be scalar values (0, 1, 2, 3, 'avc', true, ...) but not litteral property bags objects (such as 3D points { x:1, y:2, z: 3 } of functions; because JS  Maps use some internal hash of the JS engine, not the shape of the property bag itself.

For example, in the node REPL type
m = new Map()
m.set({ x: 1, y: 2, z: 3 } , 123)
m.set({ x: 1, y: 2, z: 3 } , 456)
m.set({ x: 1, y: 2, z: 3 } , 789)

... and you'll get a 3 pairs (key/value) resulting Map.
In a SQL RDBMS, doing the same will probably result in a  1 row table with just the ending value (789) and it is this behaviour that I expect.
NAIVE IMPLEMENTATION
a fast, but memoty conuming implemetnation is the maintain an internal list of pairs:
const pairs = [
    { bag: { x: 0, y: 0, z: 0 }, with_data: { r: 'ba', g: 'da', b: '55' } },
    { bag: { x: 1, y: 2, z: 3 }, with_data: 123 }
]

and loop the whole list to determine how to fill the array:

*

*if a bag is present inside the list, replace its "with_data" value (UPDATE)

*if not, create a new entriy in the pairs list, with appropriate "bag" and "with_data" fileds (INSERT/CREATE)

This is super fast but can be troubled or messed up while the size of the entry list increases, especially for high numbers of entries (typically 500K to 1000K)
ADVANCED IMPLEMENTATION
First I have conceptualized and named things :
m.set({ x: 1 y: 2, z: 3 }, 'c0ffee' )

*

*'x', ''y  and z: 'z' are so called "roles"

*1, 2, and 3 are called "role partitions" or "parts"

*the 'coffee' string is the stored "item"

duck blocks
For the storage I have developped a blocks memoty pool allocator that stores data under pseudo random keys generated with a MWC (Multiply-With-Carry) genertor, such as :
pool.set(data) --> uid, a key 5 digits of 37 values each (0-9, _ and A-Z)
pool.get(uid) --> arbitrary data, brought back to user

Using the pool, I can store duck blocks with this shape:
type DuckBlock = [
    uid: KEY37(5),
    ducktype: ROLE | PART | ITEM,
    counter: 0,      # refs counter
    related: array of KEY37(5),  # related block UIDs
    fellow: KEY37(5)  # "parent" block UID, for PART roles
    data: <any>    # user arbitrary data object
}

Using lookup Maps to store:

*

*roles: <role_name> => UID,

*parts: <part_value> => [UID] (lsit of parts)

*items

querying ststem:
const generator = await multimap.select({
    x: 0,       // single value search
    y: '*'      // wildcard search,
    z: (val) => -5 < val && val < 5  // filter function search
})

Brief Algorithm:

*

*for each role, find the correponding partitions that martches filters

*for each part duck block, get the items UIDs

*carteian product parts_for_role_X * parts_for_role_Y * parts_for_role_Z

*get the item_uids list for each entry

*intersect the list s of items to get selecteed items

*grab the items by their UID

insert / set up values
For the setting up of the value :
multimap.set({ x: 0, y:0, z: 0}, { rgb: 'bada55'})

... I compute the selection generator, with the values of the key as filters of ther select method, then :

*

*if empty: set anew value

*if not empty, overwrite the existing value

THE QUESTION
the naive code is surprisingly fast (3s for 1M pointsrecorded) but I suspect dlete oprations to be costful (imagine an array.splice of a such array)
The advanced version could make a save of up to 25% space (tested) but it is sadly slow (almost 30 min for 1 M records)
I suspect the mechansim of collecting uids to have a too big algorithmic complexity...
But where is really the bootleneck and how could I proceed to fix it ?
(will have its own repo sooner...)
https://github.com/hefeust/data-manipulation-software/mukemuva
Thanks for replies.


text:
Q: NSPopover OS X Application I am developing a menu bar application for os x. I am using NSPopover to create a popup window.
However when some other application is full screen that popup is not visible. What settings should be set, so that popup window is always on top.

A: I struggled with this as well. When I had this problem, I created a invisible window that would flow above all other windows, including full screen ones. The window would then activate the popover.
However, I found a much cleaner solution here.


text:
Q: Apagar um ficheiro executável ( .exe ) após finalizar sem saber a sua localização? O ficheiro bat foi convertido em executável.
O comando del "%~f0" não funciona! Será necessário terminar a execução do executável primeiro taskkill /f "nome_do_executável.exe" e só depois o eliminar?
Questão:
- Como localizar o ficheiro no windows e o eliminar?
Desde já obrigado @SachaDee pelo %~dpnx0!
start "nome_da_aplicação" cmd.exe /k "mode 90,5 & del /s /q %~dpnx0 >nul 2>&1 & exit"

A: Pode usar isso no final do script bat :
start cmd /k  "del %~dpnx0"


text:
Q: Show single post then all posts (with pagination) On my single.php I would like to show the single post then list all the posts with a pagination.
I use the following code:
<?php while ( have_posts() ) : the_post(); ?>
<!-- Show single post -->
<?php endwhile; ?>

<?php $page = (get_query_var('paged')) ? get_query_var('paged') : 1;
$all_posts_query = new WP_Query( array('posts_per_page' => 12, 'paged' => $page));
while($all_posts_query->have_posts()) : $all_posts_query->the_post(); ?>
<!-- Show all the posts -->
<?php endwhile; wp_reset_postdata(); ?>

<?php next_posts_link('older', '', 'yes'); ?>

As result I can see the single post then the first 12 posts and that all, no pager...
Thanks a lot for your time.

A: Pagination does not work well will with secondary queries.
First, the ordinary pagination functions depend upon the main query in the global variable $wp_query. They won't work with secondary queries. There are already a number of questions here about that if you search the site.
Second, trying to paginate secondary queries tends to result in 404 status pages. That is because the query that runs before the template loads-- the "main" query-- is the one that determines what page to load and it does not know about the query written into your template.
I would suggest you use paginate_links for your secondary query pagination. There are numerous examples of use here on this site, for example: https://wordpress.stackexchange.com/a/73928/21376


text:
Q: OpenCV4Android Kmean doesn't work as expected This code should give centers mat with 3 rows and clusterCount number of columns
    Mat reshaped_image = imageMat.reshape(1, imageMat.cols()*imageMat.rows());
    Mat reshaped_image32f = new Mat();
    reshaped_image.convertTo(reshaped_image32f, CvType.CV_32F, 1.0 / 255.0);

    Mat labels = new Mat();
    TermCriteria criteria = new TermCriteria(TermCriteria.COUNT, 100, 1);
    Mat centers = new Mat();
    int clusterCount = 5, attempts = 1;
    Core.kmeans(reshaped_image32f, clusterCount, labels, criteria, attempts, Core.KMEANS_PP_CENTERS, centers);

I tried same code in C and got centers Mat with 3 rows and clusterCount number of columns.
But in java the Core.kmeans returning 4 columns and cluster number of rows.
centers.reshape(3);

so now the reshape function doesn't work on centers since the number of rows are depended on cluster size. In C the number of rows are always constant i.e 3.
so in java it gives error

the number of rows of the matrix cannot be divided by new number of rows

Can someone figure out what is the problem. I even tried this which is similar to my code and got same error.
Reference C code :
    cv::Mat reshaped_image = image.reshape(1, image.cols * image.rows);
    cv::Mat reshaped_image32f;
    reshaped_image.convertTo(reshaped_image32f, CV_32FC1, 1.0 / 255.0);

    cv::Mat labels;
    int cluster_number = 5;
    cv::TermCriteria criteria(cv::TermCriteria::COUNT, 100, 1);
    cv::Mat centers;
    cv::kmeans(reshaped_image32f, cluster_number, labels, criteria, 1, cv::KMEANS_PP_CENTERS, centers);

A: Finally it worked :-
I converted bitmap to Mat using bitmapToMat function which returns a RGBA image. so the centers has 4 columns instead of 3.
If you are converting bitmap to Mat and if you need BGR image then do this
    Mat imageMat = new Mat();
    Utils.bitmapToMat(bitmap, imageMat);

    Imgproc.cvtColor(imageMat, imageMat, Imgproc.COLOR_BGRA2BGR);

Cheers


text:
Q: Android - Center TextView Horizontally in LinearLayout I have the following basic layout
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/title_bar_background">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:padding="10dp"
        android:text="HELLO WORLD" />

    </LinearLayout>
<LinearLayout>

It seems like the xml is correct but the text is aligned to the left. The textview takes up the entire width of the parent and the textview is set to be centered. Not sure what the problem is...

A: Just use: android:layout_centerHorizontal="true"
It will put the whole textview in the center

A: If you set <TextView> in center in <Linearlayout> then first put android:layout_width="fill_parent" compulsory
No need of using any other gravity
    <LinearLayout
            android:layout_toRightOf="@+id/linear_profile"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:orientation="vertical"
            android:gravity="center_horizontal">
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="It's.hhhhhhhh...."
                android:textColor="@color/Black"

                />
    </LinearLayout>

A: <LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/title_bar_background">

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:padding="10dp"
    android:text="HELLO WORLD" />

</LinearLayout>

A: What's happening is that since the the TextView is filling the whole width of the inner LinearLayout it is already in the horizontal center of the layout. When you use android:layout_gravity it places the widget, as a whole, in the gravity specified. Instead of placing the whole widget center what you're really trying to do is place the content in the center which can be accomplished with android:gravity="center_horizontal" and the android:layout_gravity attribute can be removed.

A: Use android:gravity="center" in TextView instead of layout_gravity.


text:
Q: Apache commons-csv error with quote I'm working with org.apache.commons-csv 1.4, this week I discovered in one of our junit test's, this strange behaviuor:
    CSVReader reader = null;
    List<String[]> linesCsv = new ArrayList<>();
    FileInputStream fileStream = null;
    InputStreamReader inputStreamReader = null;

    try {
        fileStream = new FileInputStream(file);
        inputStreamReader = new InputStreamReader(fileStream, "ISO-8859-1");
        reader = new CSVReader(inputStreamReader, ',', '"', 0);

        String[] record = null;
        while ((record = reader.readNext()) != null) {
            linesCsv.add(record);
        }

    } catch (Exception e) {
        logger.error("Error in ", e);
    } finally {
        if (inputStreamReader != null) {
            inputStreamReader.close();
        }
        if (fileStream != null) {
            fileStream.close();
        }
        if (reader != null) {
            reader.close();
        }
    }

*ERROR CASE
Input .csv
DAR_123451                  ,"XXXXX Hello World "Hello World XXX "
DAR_123452                  ,"XXXXX Hello World "Hello World XXX "

Java KO:
[0.0] DAR_123451
[0.1] XXXXX Hello World "Hello World XXX\nDAR_123456                  ,XXXXX Hello World "Hello World XXX

*CORRECT CASE
Input .csv
DAR_123451                  ,"XXXXX Hello World "Hello World" XXX "
DAR_123452                  ,"XXXXX Hello World "Hello World" XXX "

Java OK:
[0.0] DAR_123451
   [0.1] XXXXX Hello World "Hello World" XXX
[1.0] DAR_123452
   [1.1] XXXXX Hello World "Hello World" XXX
I can't setup commons csv library to work properly, it seems it's a Bug, how we can read correctly strings with single quotes in strings?

A: The CSV format usually use 2 consecutive double-quotes to include a double-quote in the text if the values are surrounded by quotes, e.g. the following works.
When I use the latest version of commons-csv I even get an exception with the your inputs (IOException: (line 1) invalid char between encapsulated token and delimiter)
So to correctly include the double-quotes you need to use the following
DAR_123451                  ,"XXXXX Hello World ""Hello World"" XXX "
DAR_123452                  ,"XXXXX Hello World ""Hello World"" XXX "

And the test-case then works as expected:
    Reader in = new StringReader(
            "DAR_123451                  ,\"XXXXX Hello World \"\"Hello World XXX\"\" \"\n" +
                    "DAR_123452                  ,\"XXXXX Hello World \"\"Hello World XXX\"\" \"");
    Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(in);
    for (CSVRecord record : records) {
        for (int i = 0; i < record.size(); i++) {
            System.out.println("At " + i + ": " + record.get(i));
        }
    }

Output:
At 0: DAR_123451
At 1: XXXXX Hello World "Hello World XXX"
At 0: DAR_123452
At 1: XXXXX Hello World "Hello World XXX"

See https://en.wikipedia.org/wiki/Comma-separated_values#General_functionality for details.


text:
Q: Executing scripts after start X server I need to run a 24 by 7 batch program. On power failures I already configured Ubuntu Server 14.04 to power up as soon as energy is back, auto login and start the program.
The process is based on GPU power and get better results with overclock. I was able to do it configuring xorg.conf and executing xinit. When I do that, the screen go white and the command line disapear. I used a remote SSH client to execute "overclock.sh" and start the program and it worked.
My question is that as I won't be able to use the remote client every time, how can I execute others scripts after executing xinit?
CRTL+ALT+F1 return to command line, but how use that on startup script?
I would like to execute on startup:
 - xinit;
 - overclock.sh;
 - start_program.sh;
Update 08/27/2017:
Right now, I'm understanding more what is happening:

*

*I'm in the console environment tty1.

*When run "xinit" it open a rough screen on tty7.

*By pressing CRTL+ALT+F1 I go back to terminal tty1 but is stucked on the "xinit" command. That is why, the .bash-login script don't execute any other command after.

*By pressing CTRL+C it stops the tty7 environment and the overclocked don't work.

*Now the most strange part: If I press CTRL+Z, I return the control, the overclock works, but when I run the program, only GPU0 start to work.

*Also tried "setsid xinit &> /dev/null" and again, everything seens perfect, but only GPU0 work.
7 Another approach: in the rough screen, tty7, I click with the mouse on the upper command line, type overclock.sh and it works. All 8 gpus work nicely. This seems to be more closely to be the answer.
How can I make a batch file to execute commands soon as the tty7 go up?
Update 08/28/2017:
I solved. The magic was study the xterm called from xinit. It receive the parameter -e "command". Put the script as command.

A: Add the scripts to your crontab using crontab -e:
@reboot /path/to/overclock.sh; /path/to/start_program.sh

If you want to add it to the root crontab (sudo crontab -e), additionally you need to set a user, e. g. root:
@reboot root /path/to/overclock.sh; /path/to/start_program.sh

Read more with man 5 crontab.

A: I can see three ways of doing this :

*

*In /etc/init.d : put the scripts you want to launch at startup. The script needs to be structured as other scripts of the directory (may be intimidating)

*Use your script as a service and then start the service at boot.

*Use crontab with @reboot job.

A: I have tried what the other 2 answers have suggested and have failed. I have found that your best bet is to set a script for auto startup in your desktop's settings.


text:
Q: How to get data from my database and put it on a ListView that is clickable? I'm trying to learn SQLite. I wanted to put the information from the database(TextView) to a ListView that is clickable(I still don't have idea in clickable ListView). Can I get some help on how to get data from my database and put it on a ListView that is clickable? Here is the code from a tutorial site that I wanted to have in a ListView:
Button ViewBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub

    super.onCreate(savedInstanceState);
    setContentView(R.layout.sqlview);

    ViewBack=(Button) findViewById(R.id.bVBack);
    TextView tv = (TextView) findViewById(R.id.tvSQLinfo);
    ViewBack.setOnClickListener(this);

    HotOrNot info = new HotOrNot(this);
    info.open();
    String data = info.geData();
    info.close();
    tv.setText(data);

}
@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    finish();

}

sqlview.xml:
<ScrollView
      android:layout_width="fill_parent"
      android:layout_height="match_parent" >
<TextView
    android:id="@+id/tvSQLinfo"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginTop="10dp"
    android:text="get info from db" />
</ScrollView>

At first I tried putting this:
ListView lv = (ListView) findViewById(R.id.listMe);
ListAdapter listAD = new ListAdapter(this,R.id.listMe, tv);
 lv.setAdapter(listAD);

but I get an error that cannot instantiate the data type ListAdapter, so I tried replacing SimpleCursorAdapter on the new ListAdapter(this,R.id.listMe,tv):
ListAdapter listAD = new SimpleCursorAdapter (this,R.id.listMe,tv, null, null);

but it gives me again an error, it suggest that I change the cast to Cursor so, I changed all of it until it didn't give me any errors. When I tried to run it, it wouldn't work. Here's the HotOrNotClass:
public static final String KEY_ROWID= "_id";
public static final String KEY_NAME= "persons_name";
public static final String KEY_HOTNESS= "presons_hotness";

private static final String DATABASE_NAME= "HotOrNotdb";
public static final String DATABASE_TABLE= "peopleTable";
private static final int DATABASE_VERSION= 1;

private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;

private static class DbHelper extends SQLiteOpenHelper{

    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
                KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                KEY_NAME + " TEXT NOT NULL, " +
                KEY_HOTNESS + " TEXT NOT NULL);"
        );

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
            db.execSQL("DROP TABLE IF EXISTS " +DATABASE_TABLE);
            onCreate(db);
    }

}
public HotOrNot(Context c){
    ourContext=c;
}

public HotOrNot open() throws SQLiteException{
ourHelper = new DbHelper(ourContext);
ourDatabase =ourHelper.getWritableDatabase();

return this;  }

public void close(){
    ourHelper.close();
}

public long createEntry(String name, String hotness) {
    // TODO Auto-generated method stub
    ContentValues cv = new ContentValues();
    cv.put(KEY_NAME, name);
    cv.put(KEY_HOTNESS, hotness);
    return ourDatabase.insert(DATABASE_TABLE, null, cv);

}

public String geData() {
    // TODO Auto-generated method stub
    String[]columns=new String[]{ KEY_ROWID,KEY_NAME, KEY_HOTNESS};
    Cursor c =ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
    String result ="";
    int iRow=c.getColumnIndex(KEY_ROWID);
    int iName=c.getColumnIndex(KEY_NAME);
    int iHotness=c.getColumnIndex(KEY_HOTNESS);

    for(c.moveToFirst(); !c.isAfterLast();c.moveToNext()){
        result=result + c.getString(iRow)+" "+c.getString(iName)+" "+c.getString(iHotness)+"\n";
    }
    return result;

}
public String getName(long l) throws SQLiteException{
    // TODO Auto-generated method stub
    String[]columns=new String[]{ KEY_ROWID,KEY_NAME, KEY_HOTNESS};
    Cursor c= ourDatabase.query(DATABASE_TABLE, columns,  KEY_ROWID+"="+l, null, null, null, null);
    if (c!=null){
        c.moveToFirst();

        String name=c.getString(1);
        return name;
    }
    return null;
}

public String getHotness(long l)throws SQLiteException {
    // TODO Auto-generated method stub
    String[]columns=new String[]{ KEY_ROWID,KEY_NAME, KEY_HOTNESS};
    Cursor c= ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID+"="+l, null, null, null, null);
    if (c!=null){
        c.moveToFirst();

        String hotness=c.getString(2);
        return hotness;
    }
    return null;
}

A: Your getData() method returns a big String with all the results. I don't think this is what you want for your list, so modify the getData() method so you can return a list of String representing your database records:
public ArrayList<String> geData() {
    // TODO Auto-generated method stub
    String[]columns=new String[]{ KEY_ROWID,KEY_NAME, KEY_HOTNESS};
    Cursor c =ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
    ArrayList<String> result = new ArrayList<String>();
    int iRow=c.getColumnIndex(KEY_ROWID);
    int iName=c.getColumnIndex(KEY_NAME);
    int iHotness=c.getColumnIndex(KEY_HOTNESS);

    for(c.moveToFirst(); !c.isAfterLast();c.moveToNext()){
        result.add(c.getString(iRow)+" "+c.getString(iName)+" "+c.getString(iHotness));
    }
    return result;
}

In order to show a list you'll have to put a ListView element in your Activity layout(sqlview) so you could make the layout like this:
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/bVBack"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Something" />

    <ListView
        android:id="@+id/listMe"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Then in your onCreate() method bind the ListView to an Adapter :
//...
ListView lv = (ListView) findViewById(R.id.listMe);
HotOrNot info = new HotOrNot(this);
info.open();
ArrayList<String> data = info.geData();
info.close();
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item1, data));