text:
Q: WMI and MS directshow I am gethering all hardware information for users is there any way to check if end user has MS Directshow available ?

A: The only time DirectShow maybe not be available is on a Win95 without DirectX installed. Since Win98 it is a default component of the system. It is also unavailable if you are writing a Win8 Metro app, here you need to use Media Foundation. But for Win8 Desktop apps it's still available.
If you really really really want to test if it is available, then try to create a Filter Graph.
IGraphBuilder *pGraph = NULL;
HRESULT hr = CoCreateInstance(CLSID_FilterGraph, NULL,
                 CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void **)&pGraph);

If hr is not S_OK or pGraph still NULL then it is not available.
Or there is another possible time DirectShow or parts of it are not available: if someone has totally messed up his system and deregistered the needed COM dll's!


text:
Q: Jetty ConnectHandler with Upstream Proxy I am using Jetty's ConnectHandler to proxy SSL via CONNECT.
Now I'd like to configure the ConnectHandler to forward requests to another proxy which will handle the CONNECT for me.
Is there a way to configure the ConnectHandler to do this?
I checked the ConnectHandler source code but couldn't find a way to do this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot find module "." issue with TypedJSON library and Ionic 2 I have the following issue while doing an ionic 2 serve command using TypedJSON library :
Error: Cannot find module "."
    at webpackMissingModule (http://localhost:8100/build/main.js:82208:69)
    at METADATA_FIELD_KEY (http://localhost:8100/build/main.js:82208:147)
    at Object.<anonymous> (http://localhost:8100/build/main.js:82213:3)
    at __webpack_require__ (http://localhost:8100/build/main.js:20:30)
    at Object.<anonymous> (http://localhost:8100/build/main.js:94414:86)

[...]

I can reproduce it with a simple app.
Here are my step :
//Installing last ionic version
npm install -g ionic@latest cordova typescript

//Creating a new app
ionic start test blank --v2

//Installing webpack support
npm install @ionic/app-scripts@latest --save-dev

//Installing TypedJSON
npm install typedjson-npm

//Installing typings
typings install npm:typedjson-npm

I created a simple model :
import { JsonMember, JsonObject } from 'typedjson-npm';

@JsonObject
export class GeoJsonModel {

  @JsonMember
  type: string;

  public getType() {
    return this.type;
  }

}

And here is my home.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { GeoJsonModel } from '../../models/geojson-model';
import { TypedJSON } from 'typedjson-npm';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController) {

    var geo= TypedJSON.parse('{ "type": "geojson"}', GeoJsonModel);

    console.log("hello world");
    console.log(geo instanceof GeoJsonModel);
    console.log(geo.getType());

  }

}

I also tried to import Typed JSON with typedjson-npm/js/typed-json without any success.
Thank you for your help


text:
Q: ServletException: No servlet class has been specified I have what should be an extremely simple "Hello World" servlet, but I cannot get it to work. I am using Eclipse, Tomcat 8, Java 7, and Servlet 3.1.
I have looked at many tutorials and questions, but they have not completely helped. Most tutorials I have seen talk about creating servlets by extending HttpServlet. I got those to work. Now I'd like to try the cleaner annotation approach.
I've been referring to this tutorial, but it isn't quite complete and seems to have some incorrect or incomplete examples:
Packaging and Deploying RESTful Web Services
Why is com.testing.service.MyApplication not being loaded?
Any help on getting this thing to run would be immensely appreciated!
Here are my files:
MyApplication.java
package com.testing.service;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("app")
public class MyApplication extends Application {
    public Set<Class<?>> getClasses() {
        Set<Class<?>> s = new HashSet<Class<?>>();
        s.add(HelloWorldResource.class);
        return s;
    }
}

HelloWorldResource.java
package com.testing.service;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/helloworld")
public class HelloWorldResource {
    @SuppressWarnings("unused")
    private static final long serialVersionUID = 1L;

    @GET
    @Produces("text/plain")
    public String sayHello() {
        return "Hello World!";
    }
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">
  <display-name>service</display-name>
  <servlet>
    <servlet-name>com.testing.service.MyApplication</servlet-name>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.testing.service.MyApplication</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

</web-app>

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.testing</groupId>
  <artifactId>service</artifactId>
  <version>1.0</version>
  <packaging>war</packaging>
  <name>Rest Test</name>
  <dependencies>
    <dependency>
      <groupId>javax.ws.rs</groupId>
      <artifactId>javax.ws.rs-api</artifactId>
      <version>2.0.1</version>
    </dependency>
  </dependencies>
  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.1</version>
          <configuration>
            <source>1.7</source>
            <target>1.7</target>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

Whenever I run Tomcat, it displays the following error:
INFO: Marking servlet com.testing.service.MyApplication as unavailable
Feb 05, 2015 3:28:55 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet /service threw load() exception
javax.servlet.ServletException: No servlet class has been specified for servlet com.testing.service.MyApplication
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1041)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4944)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5230)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

A: I found the answer in the comments of a related question. The answer was provided by Alvin Thompson. Unfortunately, I don't have enough reputation to up-vote your answer.

If you're using a standard Tomcat install (or some other servlet
  container), you need to include a REST implementation since Tomcat
  doesn't come with one. If you're using Maven, add this to the
  dependencies section:
<dependencies>
  <dependency>
    <groupId>org.glassfish.jersey.bundles</groupId>
    <artifactId>jaxrs-ri</artifactId>
    <version>2.13</version>
  </dependency>
  ...
</dependencies>

Then just add an application config class to your project. If you
  don't have any special configuration needs aside from setting the
  context path for the rest services, the class can be empty. Once this
  class is added, you don't need to configure anything in web.xml (or
  have one at all).

Originally posted here:
How to set up JAX-RS Application using annotations only (no web.xml)?


text:
Q: Как можно убить программу в OSX? Ситуация такая:

*

*OC - OSX HighSierra 10.13.3 (17D102).

*программа зависла, но закрылась. Программы не видно в TaskManager (pid ее неизвестен).

*активности программы в панели doc не видно, но при нажатии ПКМ есть поле ForceQuit. И это ForceQuit не закрывает программу.

*При попытке открыть программу она не открывается.

*При попытке закрыть программу через ForceQuitApplication (левый угол экрана) она не закрывается.

*При попытке перезагрузить систему OSX просит закрыть программу.
Как можно убить этот процесс помимо перезагрузки от кнопки?
Такая ситуация происходит достаточно часто и с разными программами.

A: Найдите нужный вам процесс, выполнив top в терминале. В первой колонке можно найти его pid. Затем процесс можно завершить, послав ему сигнал SIGKILL. Снова через терминал (пусть ваш pid 12345:
kill -9 12345


text:
Q: Last line repeats when doing fgets/fputs I'm doing an insertion, that imply a file, a string, and a new file who will receive all the data of the original file plus the string to be inserted, and it will replace the original file.
So, for example, my original file:
data.txt
 line1
 line2
 line3
 line4
 line5

will become, with the insertion of the string "newline":
data_temp.txt --> renamed later data.txt
 line1
 line2
 line3
 line4
 line5
 newline

With that purpose, I have the following code:
/* FILE variables of the original file and the new file */
FILE *data, *data_temp;
data = fopen( "data.txt", "r" );
data_temp = fopen( "data_temp.txt", "w" );

/* String buffer */
char buf[256];
int i_buf;

/* The string to be inserted in the new file */
char newline[10] = "newline";

/* For each line of the original file, the content of each line
is written to the new file */
while(!feof(data))
{
            /* Removing the \n from the string of the line read */
    fgets(buf, MAX_INSERT, data);
    for(i_buf = strlen(buf)-1; i_buf && buf[i_buf] < ' '; i_buf--)
    buf[i_buf] = 0;

            /* Writing the string obtained to the new file */
    fputs(buf, data_temp);
    fputs("\n", data_temp);
}

    /* The string will be inserted at the final of the new file */
if(feof(datos))
{
    fputs(newline, datos_temp);
}

    /* Closing both files */
fclose(data);
fclose(data_temp);

    /* The original file is deleted and replaced with the new file */
remove ("data.txt");
rename ("data_temp.txt", "data.txt");

My problem is basically in the writing to the original file, to the new file. The last line of the original file shows duplicated in the new file.
In the example given:
data.txt
 line1
 line2
 line3
 line4
 line5

The line5 (last line of the original file) is showed twice on the new file, and then is the string to be inserted.
data_temp.txt --> renamed later data.txt
 line1
 line2
 line3
 line4
 line5
 line5
 newline

I strongly believe the problem is in the reading of the original file (AKA the while(!feof(data)) loop), on the checking the EOF, the fgets, or the fputs. Any idea to solve this?

A: Correct. The problem is in your loop condition.
feof() is evil because it's often misunderstood. feof() doesn't indicate that you are at the end-of-file. It only indicates that it has not yet encountered it (that you haven't fetched a byte past the end of the file).
You must instead detect within the loop when you encounter EOF(when fgets() returns NULL) and break out of the loop then.


text:
Q: how can I ensure content delivered from the DB does not cause my table height to increase more than a certain height? I want my admin section to have a small synopsis of the detail in the main table view all.
I will have an option for admin to open each one separately so I would like to have the td height to not increase as certain fields become text heavy.
this is what is happening
i would prefer all height to be like this and hide additional text heavy fields
I have tried max height for the td, overflow hidden, overflowy, nothing is working.

Contact List

                                ID
                                Image
                                Name
                                Age
                                Breed
                                Description
                                Actions

                          <?php
                            $sql = "select * from contacts";
                            $result = mysqli_query($conn, $sql);
                                    if(mysqli_num_rows($result)){
                                        while($row = mysqli_fetch_assoc($result)){
                          ?>

                            <?php echo $row['id'] ?>
                            <img src="<?php echo $upload_dir.$row['image'] ?>" height="40">
                            <?php echo $row['name'] ?>
                            <?php echo $row['age'] ?>
                            <?php echo $row['breed'] ?>
                            <?php echo $row['description'] ?>

                              <a href="show.php?id=<?php echo $row['id'] ?>" class="btn btn-success">
                              <a href="edit.php?id=<?php echo $row['id'] ?>" class="btn btn-info">
                              <a href="index.php?delete=<?php echo $row['id'] ?>" class="btn btn-danger" onclick="return confirm('Are you sure to delete this record?')">

                          <?php
                              }
                            }
                          ?>

A: I would have to expect this to be a combination of CSS white-space, overflow, and text-overflow.
https://www.w3schools.com/cssref/pr_text_white-space.asp
https://www.w3schools.com/cssref/css3_pr_text-overflow.asp
https://www.w3schools.com/cssref/pr_pos_overflow.asp
The white-space attribute will allow you to pre-format any text, whether you do this in code or in the DB itself, the text-overflow will allow you to set how the overflow is represented (if at all), and overflow will allow you to hide the excess text.
So, something like this.
.hideText {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

Then set the class for the description field the same way you did for the image cell.
<?php echo $row['description'] ?>

You'll also need to set the width of the cells/column, which I'm going to assume you either know how to do or can figure that out. FYI, I'd put that in another class instead of using style. Classes makes it a little more easy to replicate and have in a single file/location, rather than style's scattered around all your pages. I know I fought against CSS classes for years, but I finally figured creating my own were more helpful than they were annoying.
I hope this helps!


text:
Q: How to configure Blazor Webassembly Core Hosted app to serve an index homepage from the server prior to loading the app I have a made an application using the Core Hosted Blazor Webassembly template provided with VS 2022 using .Net 6.
When you start up the server and navigate to the base url it immediately loads up the whole webassembly application - then checks the authentication - sees that the user is not logged in - then redirects to the Identity page for login. Once logged in the user is navigated back to the webassembly application and it goes through the whole load and boot a second time. (It uses the cached app files, so it's not quite so slow, but it's still slow.)
I would like instead to serve an index page directly from the server - this could include a login but also some brochure introduction information - the user could then login and potetially be directed to other server side apages before being routed to the webassembly application.
I can't seem to figure out quite how the server side project decides to boot the webassembly application - I've tried changing the root path using:
app.UseBlazorFrameworkFiles("/UI");

but this still loads the webassembly directly.
I tried adding a wwwroot folder to the server side and adding an index.html there for the server to load - but this results in a conflict with the one that's in the client project (so this is getting copied into the root by reference, I think. IS this done by convention alone or is this configured somewhere in one (or both) of the projects? CAn I move the webassembly to be in an Area or subfolder of the server side without breaking the Identity Server authentication and routing? If so, how would I go about it?


text:
Q: In App Purchase Feature: Iphone I am having an in-app feature where user can upgrade the existing app to pro-version which will provide extra features. I want to publish the first basic version to app store, this version will have options to upgrade it to pro-version and messages will appear if user try to access features that is pro-only. Now my situtation is that i don't have pro-version app ready but want to publish basic version, So will apple reject my app because of this ? I mean i don't have pro-version available but i am providing upgrade (in-app purchase) option in basic version app. So when user selects upgrade option from basic version and only message will appear saying "Pro-version coming soon" (just as example).
Will apple reject my app ? or i am able to publish basic version and publish pro-version later on ?

A: This will definitely get rejected by Apple. You should read the App Store Review Guidelines before you submit any app to the App Store.

A: The change of being reject are very very great. Since you have an option for people to buy something that is not yet available.Apple will see this a misleading and will probably reject your app.

A: Yes your app will be most likely rejected if you do not provide the possibility to upgrade within your app. I had an app rejected for this same reason. And the tips thas I was given by Apple was to remove the 'special feature' button, or to propose the 'special feature' to purchase in-app.

A: No, for the In-App purchase you will have to create first the Pro-Version and this Pro-Version upload first. If this your Pro-Version will approve then you will upload your Basic App to approve.

A: Ofcourse it is gonna be rejected.
check out the appstore guidelines. There should be no button/etc disabled or showing that something/some feature is coming soon. And you are getting money to tell this from the user.
That's dangerous.
just release the app without in app purchase initially, and as you get the pro features good and going, upload the next version of your app.


text:
Q: Uncaught Error: Bootstrap's JavaScript requires jQuery in angular2 I am trying to implement expand/collapse functionality using bootstrap/jquery in angular2.
Tried implementing in the plnkr
I am getting this error in the browser console
`"VM1238 bootstrap.min.js:6 Uncaught Error: Bootstrap's JavaScript requires jQuery"`

Based on the search in the internet suggestions, in the index.html i have specified the .js files in the specified order i.e. first Jquery.min.js and then followed by bootstrap.min.js.
still I am getting this above said error, can somebody help me with this issue?
I am trying to replicate the functionality from this link in angular2


text:
Q: C# does not receive any response values from Jenkins I'm calling Jenkins jobs from C# using the WebClient class and I'm not receiving any response even though the Jenkins job is triggering and executing properly.  I need to read the headers to get the queue number and things like that, so I'm confused as to why this is happening.  Below is my code, which works just fine except for "response" is always an empty string; not null, just an empty string:'
'
using (var wb = new WebClient())
            {

                string url = "http://url:8080/job/CloudTeam/job/Azure/job/Create-Azure-VM/buildWithParameters";

                string queryString = "HOSTNAME=" + virtualMachine.Hostname + "&IPADDRESS=" + virtualMachine.IPAddress + "&RESOURCEGROUP=" + virtualMachine.ResourceGroup + "&STORAGEACCOUNT=" + virtualMachine.StorageAccount + "&BASEIMAGE=" + virtualMachine.BaseImage;

                string password = "password";
                string username = "user";

                string basicAuthToken = Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
                wb.Headers["Authorization"] = "Basic " + basicAuthToken;
                wb.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                wb.Headers.Add("user", "user:password");

                string response = wb.UploadString(url, queryString);
                return response; <-- always an empty string
            }

'


text:
Q: How to get IP addresses from several variables in Terraform I tried to do so
private_ip_ws0 = ["10.0.10.3"]
private_ip_ws1 = ["10.0.20.3"]
private_ip_db0 = ["10.0.11.3"]
private_ip_db1 = ["10.0.21.3"]

resource "aws_network_interface" "ws_interface" {
  count = 2
  subnet_id = aws_subnet.ws_net_public[count.index].id
  private_ips = "${var.private_ip_ws}[count.index]"[0]
  tags = {
    Name = "${var.environment}${count.index}-Interface"
  }
}

But I get error:
Error: Reference to undeclared input variable
│
│   on vpc.tf line 55, in resource "aws_network_interface" "ws_interface":
│   55:   private_ips = "${var.private_ip_ws}[count.index]"[0]
│
│ An input variable with the name "private_ip_ws" has not been declared. Did you mean "private_ip_ws1"?

How to write code correctly?
And why in one place Terraform allows you to write like this
cidr_block = "${var.public_cidr}${count.index+1}0.0/24"

but in another similar expression it doesn't allow to write:
private_ips = "${var.private_ip_ws}[count.index]"[0]

Why?

A: You can't reference a variable name via a variable like that. That just isn't a feature supported by Terraform at all. The correct way to do this would be to convert your variables into arrays, but if you want to keep the variables the same you will need to wrap them in a local array before using them:
private_ip_ws0 = ["10.0.10.3"]
private_ip_ws1 = ["10.0.20.3"]
private_ip_db0 = ["10.0.11.3"]
private_ip_db1 = ["10.0.21.3"]

locals {
  private_ip_ws = [private_ip_ws0, private_ip_ws1]
}

resource "aws_network_interface" "ws_interface" {
  count = 2
  subnet_id = aws_subnet.ws_net_public[count.index].id
  private_ips = local.private_ip_ws[count.index]
  tags = {
    Name = "${var.environment}${count.index}-Interface"
  }
}

And why in one place Terraform allows you to write like this
cidr_block = "${var.public_cidr}${count.index+1}0.0/24"
but in another similar expression it doesn't allow to write:
private_ips = "${var.private_ip_ws}[count.index]"[0]

Because in the first example you are just doing basic string interpolation, which is perfectly valid Terraform syntax.
In the second example you are building a dynamic variable name and then trying to reference the value inside that variable, which is completely invalid Terraform syntax.


text:
Q: Totally continuous implies bounded Consider a separable, reflexive Banach space $V$. We define the mapping $A: V \rightarrow V^{*}$  as totally continuous if it is continuous as a mapping $(V, \text{weak}) \rightarrow (V^{*}, norm)$. I want to show that $A$ is bounded. I am looking for a more direct proof of the boundedness of $A$. I can prove that the mapping $A$ is compact(and therefore bounded) in the following way:
Let $B \subset V$ be a bounded set. Consider a sequence in $A(B)$, say ${A(v_{k})}_{k \in \mathbb{N}} \subset V^{*}$ with $v_{k} \in B$. I will show that it has a convergent subsequence. Since $V$ is separable it follows that the weak topology on the closed unit ball is metrizable. By the Kakutani Theorem we have that the closed unit ball in $V$ is compact in the weak topology, so there exists a weakly convergent subsequence ${v_{k}}_{l} \rightharpoonup v$ in $V$. By total continuity it follows that $A({v_{k}}_{l}) \rightarrow A(v)$ in $V^{*}$. We have shown that $A$ is compact and therefore bounded. $\square$
Is this proof fine and is there a more direct proof of boundedness for a totally continuous mapping $A:V \rightarrow V^{*}$? Maybe missing something trivial.

A: Your proof is fine, though it uses more machinery than necessary (in particular, you need not appeal to sequences):
The norm-closed unit ball of a reflexive normed space is weakly compact. This follows from Alaoglu's theorem and the fact that the natural embedding from such a space onto its second dual is  a weak-weak* homeomorphism.
Now you need only use the fact that a continuous image of a compact set is compact. $A$ maps the weakly compact norm-closed unit ball of $V$ onto a norm-compact, thus bounded, subset of $V^*$.
(Note the separability of $V$ is not needed here.)


text:
Q: Python code is running too slow, do I need to find a way to allocate more memory to python process? I am using 64-bit 3.6.3 python on a 64-bit windows 10 laptop, with 12 gigs of RAM.
I have python code that can extract a zip file (tar.gz). If I use the code, it takes a really long time (~1.5 hour) but if I unzip it directly using 7zip it takes less than 5 minutes, so I am guessing there is something impeding the processing power of python.
I am trying to run this code https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/1_notmnist.ipynb
for convenience, here are the specific commands for unzipping.
import tarfile

tar = tarfile.open(filename)
sys.stdout.flush()
tar.extractall(data_root)
tar.close()

Here is full code.
from __future__ import print_function
import os
import sys
import tarfile
from six.moves.urllib.request import urlretrieve

# Config the matplotlib backend as plotting inline in IPython

url = 'https://commondatastorage.googleapis.com/books1000/'
last_percent_reported = None
data_root = '.'  # Change me to store data elsewhere

def download_progress_hook(count, blockSize, totalSize):
    """A hook to report the progress of a download. This is mostly intended for users with
    slow internet connections. Reports every 5% change in download progress.
    """
    global last_percent_reported
    percent = int(count * blockSize * 100 / totalSize)

    if last_percent_reported != percent:
        if percent % 5 == 0:
            sys.stdout.write("%s%%" % percent)
            sys.stdout.flush()
        else:
            sys.stdout.write(".")
            sys.stdout.flush()

        last_percent_reported = percent

def maybe_download(filename, expected_bytes, force=False):
    """Download a file if not present, and make sure it's the right size."""
    dest_filename = os.path.join(data_root, filename)
    if force or not os.path.exists(dest_filename):
        print('Attempting to download:', filename)
        filename, _ = urlretrieve(url + filename, dest_filename, reporthook=download_progress_hook)
        print('\nDownload Complete!')
    statinfo = os.stat(dest_filename)
    if statinfo.st_size == expected_bytes:
        print('Found and verified', dest_filename)
    else:
        raise Exception(
            'Failed to verify ' + dest_filename + '. Can you get to it with a browser?')
    return dest_filename

train_filename = maybe_download('notMNIST_large.tar.gz', 247336696)
test_filename = maybe_download('notMNIST_small.tar.gz', 8458043)

num_classes = 10

def maybe_extract(filename, force=False):
  root = os.path.splitext(os.path.splitext(filename)[0])[0]  # remove .tar.gz
  if os.path.isdir(root) and not force:
    # You may override by setting force=True.
    print('%s already present - Skipping extraction of %s.' % (root, filename))
  else:
    print('Extracting data for %s. This may take a while. Please wait.' % root)
    tar = tarfile.open(filename)
    sys.stdout.flush()
    tar.extractall(data_root)
    tar.close()
  data_folders = [
    os.path.join(root, d) for d in sorted(os.listdir(root))
    if os.path.isdir(os.path.join(root, d))]
  if len(data_folders) != num_classes:
    raise Exception(
      'Expected %d folders, one per class. Found %d instead.' % (
        num_classes, len(data_folders)))
  print(data_folders)
  return data_folders

train_folders = maybe_extract(train_filename)
test_folders = maybe_extract(test_filename)

I am using 64-bit 3.6.3 python on a 64-bit windows 10 laptop, with 12 gigs of RAM.

A: Tarfile module is implemented in pure Python. 7zip is implemented in C++.
Tarfile in Python is 60/5 = 12 times slower than 7zip.
Extracting too many files is normally slow.
To be honest, Tarfile is doing a pretty good job. There are over 500000 files to be extracted.


text:
Q: Rails 4 Checklist form + validation I have a model called Directive that belongs to the User model, the Directive model has 5 fields (strings). I created a form_for and each field have 5 checkboxes, each checkbox has a number value.
So far, so good. The problem is when I try to submit the form. The checkboxes I checked don't persist on error and they're not being submited. My params are blank.
It work fine with radio buttons though.
Example of my form:
<%= form_for(@directive, url: dashboard_directives_path(:type => params[:type]), html: {method: "post", class: "form-horizontal"}) do |f| %>

  <%= f.check_box :place, "1" %>
  <%= f.check_box :place, "2" %>
  <%= f.check_box :place, "3" %>
  ...
  <%= f.check_box :field2, "1" %>
  ...

<% end %>

This is my controller action:
def new
  @directive = current_member.directives.new
end

def create
  @directive = current_member.directives.new(directive_params)
  if @directive.save
    redirect_to dashboard_path, :success => "Directive created with success!"
  else
    render "new"
  end
end

The params in my controller:
private

def directive_params
  if params[:directive].present?
    params.require(:directive).permit(:place, :field2, :field3, :field4, :field5)
  else
    params.fetch(:directive, {})
  end
end

And the model:
class Directive < ActiveRecord::Base
  belongs_to :members, :class_name => 'Member', :foreign_key => 'member_id'
  validates :place, :field2, :field3, :field4, :field5, presence: true
end

A: Change directive_params as below:
NOTE: Pass 'place` as an array also mandatorily as the last argument.
def directive_params
  if params[:directive].present?
    params.require(:directive).permit( :field2, :field3, :field4, :field5, :place => [])
  else
    params.fetch(:directive, {})
  end
end

Pass 'place' as an array.
And in your model Directive serialize it by adding serialize :place.

Also I had to change my checkboxes to look like this:
<%= f.check_box :place, {:multiple => true}, "1", nil %>


text:
Q: Zend PHP Multiple Database Handling at Run Time I have one site using zend(verison1.1) php. I have created script that is generating dynamic database(for each company that is signing up on site home page) having some tables at run time with respective to url (of specific company) that is coming(means fetching company name string from url string). Now i want to connect that specific company to its dynamic database & fetch records from tables of it by using default database instances modals/classes.
Actually I want to make my application like SAAS(Single application having multiple databases) e.g(Basecamp.)

A: I had to do it once using Zend_Db_Table.
The principle we used was a master database that contained generic site information, and on specific database per retailer (it was on a kind of retail communication system).
Then, based on the domain name (route) or on the route parameters, you can extends Zend_Controller_Action to handle a predispatch and create your specific DB adapter (or more precisely, this would be done in your Zend_Db_Table_Row, and you will call the method from this model inside your extended controller and set it as default if needed. You could also call your Db_Table_Row passing the database connection wherever needed.


text:
Q: Check if ActiveRecord::Relation alread includes JOIN I'm inside method that adds filter (user.type) to my query/relation.
Sometimes if grouping by the user (which needs INNER join to users table in another module) is selected before filtering I receive an error:
PostgreSQL: PG::DuplicateAlias: ERROR: table name "users" specified more than once
Before error happen JOIN is already in query -
$ pry> relation.to_sql
SELECT \"posts\".* FROM \"posts\"
INNER JOIN users ON users.id = posts.user_id
WHERE \"posts\".\"created_at\" BETWEEN '2019-05-01 00:00:00'
AND '2020-05-01 23:59:59' AND \"users\".\"type\" = 'Guest'"

I wanna fix it, by checking if the table is already joined inside my ActiveRecord::Relation object. I added:
def join_users
  return relation if /JOIN users/.match? relation.to_sql

  relation.joins('LEFT JOIN users ON users.id = posts.user_id')
end

This solution works, but I wonder - is there any better way to check if JOIN is inside relation?

A: Perhaps you can use joins_values, which isn't documented, but is an ActiveRecord_Relation public method that returns an array containing the name of the table the current query (object) is constructed with:
Post.joins(:user).joins_values # [:user]
Post.all.joins_values          # []

A: if simple join
 Post.joins(:user)

you can find via joins_values
so it will look like Post.joins(:user).joins_values # [:user]
if post has left joins
Post.left_joins(:user)

you can find via left_outer_joins_values
So in this case if you write Post.joins(:user).joins_values # []
so you can fix it by writing  Post.joins(:user).left_outer_joins_values # [:user]


text:
Q: Redirect all pages to non www and one page to www I want to redirect all my internal pages (eg: example.com/about) to their non-www version but I want my homepage (https://example.com) to redirect to its www version (https://www.example.com).
I searched many articles on the internet but it could not work.
If set both rules then the internal pages get redirected fine but the homepage gets trapped in a loop.
I don't know how to code so please it's a request if you could write the code which I should paste in my .htaccess file
Currently, I have set all pages to redirect to their non-www versions (even homepage) with the below code:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
</IfModule>
# BEGIN Sitepad
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
</IfModule>
# END Sitepad

A:
I searched many articles on the internet but it could not work.

Probably because this is a strange requirement. I would be surprised if you could find any code that you could simply copy/paste that does this.
However, assuming you are constructing the correct absolute URL for all your internal links (since you must not internally link to a URL that redirects) then this is relatively trivial to implement in .htaccess if you understand your existing directives.

RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]

The regex .* in the RewriteRule pattern matches everything. Specifically, it matches 0 or more of any character, as denoted by the * quantifier. It matches the empty URL-path (ie. the "homepage") and every non-empty URL-path (ie. everything else).
You need to alter the above regex so that it matches a non-empty URL-path (ie. everything except the homepage). And create another rule (in the other direction) that matches an empty URL-path only.
(This uses the fact that mod_dir is serving index.php for requests to the homepage, not the mod_rewrite directives that follow.)
To match 1 or more (ie. non-empty URL-path), you can use the + (plus) quantifier, instead of * (star/asterisk).
For example:
# Redirect everything except the homepage (from www to non-www)
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.+)$ https://example.com/$1 [L,R=301]

# Redirect the homepage only (from non-www to www)
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^$ https://www.example.com/ [L,R=301]

You will need to clear your browser cache before testing, since the earlier 301 (permanent) redirect that redirected the homepage from www to non-www will have been cached by the browser.
Test first with 302 (temporary) redirects to avoid potential caching issues.


text:
Q: List View Footer Background on Android 2.3.3 This one is weird. I have a list view that is a part of Relative Layout. I have set a background to this Relative Layout and made list view background as transparent.
Now, everything was working great till this morning. I could see the whole screen covered with my custom background even if there is just one row in my list view.
Then, I got update on Verizon Motorola Droid X for 2.3.3 (it was 2.2 before). Once it was updated, I started my app again and now here is what happens.
If my list view has only one row, I see a white area below it and not my custom background.
But if it has say 100 rows and thus covers the whole screen I won't  see that weird white background. My relative layout has width and height set to "fill_parent".
I have posted my XML at the bottom. Has anyone else faced this problem or I am making some really stupid mistake.
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:background = "@drawable/background"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ListView   android:id = "@+id/listQueue"
                android:layout_width = "fill_parent"
                android:layout_height = "fill_parent"
                android:layout_below = "@id/homeScreenBanner"
                android:background="@android:color/transparent"
                android:divider="@drawable/separator"
                android:scrollingCache="false"/>
</RelativeLayout>

EDIT:
I think I have found the solution to this problem:
Changed the layout_height attribute to wrap_content and it worked like a charm. :)
Following the changed line.
    android:layout_height = "wrap_content"

A: There is actually an easy solution to this problem using basic layouts implemented completely in the .xml layout file.
First off, the Motorola blog suggestion is not acceptable because it requires building to API v2.3 in order to use 'android:overScrollFooter' forcing either multiple builds or inaccessibility to the majority of Android devices.
The suggestion to set the ListView's android:layout_height="wrap_content" does work in many cases and is very useful if there are no layout items below the ListView.
The problem occurs when there are one or more View's above and one or more View's below the ListView. This requires setting both android:layout_below and android:layout_above for the ListView, which stretches the height of the ListView to the height of the available space which is bigger than the necessary 'wrap_content'. When this happens, the "Bug" kicks in - the extra space at the bottom of the ListView is filled with the footer's default background color which is dark gray and not transparent.
Now for the simple solution.
Place the ListView inside of a vertical LinearLayout or equivalent. Allow the LinearLayout to span from top to bottom of the available space with height="fill_parent", the extra will be filled with the correct background drawable or color. Set the height of the ListView to "wrap_content" so there is no unused space for the unsightly gray footer background.
Here is an example:
<Button> android:id=@+id/MyTopButton" ... </Button>
<Button> android:id=@+id/MyBottomButton" android:layout_alignParentBottom="true" ... </Button>

<LinearLayout
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:orientation="vertical"
    android:layout_below="@+id/MyTopButton"
    android:layout_above="@+id/MyBottomButton"
    >

    <!-- Note: This is a bug fix for a particular problem experienced on
         Motorola OS v2.3.3 devices only in which the space below the unused
         portion of the ListView is rendered in gray instead of the desired
         transparent 'cacheColorHint' color. This solution which wraps the
         ListView in another container (a LinearLayout in this case) allows
         the ListView to be of height "wrap_content" while the parent
         container is forced to be the desired height - namely from the
         header area above down to the buttons below. -->

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/MyList"
        android:cacheColorHint="#00000000"
        />

</LinearLayout>

A: I wrote a class that can be used in Android 2.1/2 that will do the right thing in 2.3 using reflection with ListViews:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.ListView;

public class TransparentListView extends ListView {

    private void makeTransparent() {
        if (Build.VERSION.SDK_INT >= 9) {
            try {

                Method overscrollFooterMethod =
                    TransparentListView.class.getMethod("setOverscrollFooter", new Class[] {Drawable.class});
                Method overscrollHeaderMethod =
                    TransparentListView.class.getMethod("setOverscrollHeader", new Class[] {Drawable.class});

                try {
                    overscrollFooterMethod.invoke(this, new Object[] {null});
                    overscrollHeaderMethod.invoke(this, new Object[] {null});
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
    }

    public TransparentListView(Context context) {
        super(context);
        this.makeTransparent();
    }

    public TransparentListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.makeTransparent();
    }

    public TransparentListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.makeTransparent();
    }
}

Use it in XML as follows:
<com.myapp.TransparentListView android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:transcriptMode="alwaysScroll"
    android:layout_weight="1"
    android:dividerHeight="0dip"
    android:divider="#00000000"
    android:cacheColorHint="#00000000"
/>

A: Yes, David's solution works in some cases and allows you to build with an Android before 2.3. In fact, it's the first solution I posted on the MotoDev forum, with a downloadable code sample, back in June.
However, some developers said that it leaves an artifact (meaning: a stray horizontal grey line at the bottom of the list). I've seen this myself. That doesn't work for those who care about design detail. The android:overScrollFooter="@null" solution does not leave an artifact. But you're right, to use it you need to build with Android 2.3 or up.

A: See Motorola's blog post on this behavior -- the answer is that on Motoblur 2.3, they set a default overscroll footer, which is fixable by setting android:overScrollFooter="@null", but only for Android 2.3+.
Their recommended appwide solution is to use a custom theme with a custom listViewStyle set only in the values-v10 folder with that property set.

A: Can you try with setting cacheColorHint of your ListView to transparent?
android:cacheColorHint="@android:color/transparent"


text:
Q: Parallel file IO while doing heavy CPU operations in C# I am rather new to C# and trying to determine best practice when it comes to file operations.
My application is using Parallel.ForEach to parse several large files. In the method, I am writing to a single file with StreamWriter but having to lock the object during that process. I anticipated a slow down with that methodology and knew that I would have to have a separate thread for file IO.
Which brings me to my question. Does C# already provide a namespace for non-blocking, thread-safe file IO?
Thanks!

A: .NET provides operations for asynchronous file IO, and it provides tools for synchronizing asynchronous operations.  You have to combine the two tools yourself if you want both features though, not that that's particularly hard.  You can create a simple queue to serialize asynchronous operations for you, as shown here.  Once you have that you can share a single queue between all of your workers, having them each enqueue a call to WriteAsync to do your writing.
Note that you don't actually need a separate thread for the file writing at all.  It can be asynchronous without needing a dedicated thread.


text:
Q: Django: Allow user to access further only if she has submitted a form or has saved the model The user passes through some forms just after signing up. There is logout link below every form page. I want to give the user further access to the site only if each of those forms have been saved. Now, in my case I have these models:
class Driving_plan(models.Model):
    plan = models.CharField (max_length=25, blank=False)
    duration = models.CharField(max_length=15)
    annual_fee = models.DecimalField(max_digits=4, decimal_places=2, default=50.00)
    ....

class Payment_receipt(models.Model):
    driving_plans = models.ForeignKey(Driving_plan, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    start_date = models.DateField(auto_now=False, auto_now_add=False)
    end_date = models.DateField(auto_now=False, auto_now_add=False)

When a user selects an instance of Driving_plan, this data is saved in the Payment_receipt model through this view:
@login_required
def passPlanPKView(request, pk):
    plan = Driving_plan.objects.get(pk = pk)
    Pay = Payment_receipt.objects.create(
        driving_plans=plan,
        user = request.user,
        start_date=datetime.date.today(),
        end_date= calcEnddate(plan),
        )
        return redirect('add_user_profile')

How do I apply this so that, if the user has got this model saved, redirect her to home. Otherwise, she must fill the form the next time she logs in?
In my case, when a user has not filled all the forms, she still is getting access by logging out; and when logging in she is straight into the home page. And the forms are left unsaved. How do I do this?

A: you can use models field to verified the user is submitted the necessary details or not . you can't track a form weather form submitted or not

A: I solved this using .exists(). I'm explaining with a new view, it's not needed to find similarities with the passPlanPKView in my question.
My view:
def homeview(request):
    if request.user.is_authenticated:
        if not Payment_receipt.objects.filter(user = request.user).exists():
            return redirect('plan_select')
        if not Account.objects.filter(user = request.user).exists():
            return redirect('add_user_profile')
        if not Driving_license.objects.filter(user = request.user).exists():
            return redirect('add_license')
        if not Card_detail.objects.filter(user = request.user).exists():
            return redirect('add_card')
    return render(request, 'services/home.html')

Here, for an authenticated user, I'm querying each table/model to check whether the user has filled in data in that model through a form. If the use has just signed up and then logged out without filling any form, s/he is made to fill up those forms again.
I am checking for Payment_receipt, Account, Driving_license, Card_detail models one after another because, I require the new user to fill all the forms of these models sequentially just after signing up. If s/he logs out at any point while filling these forms, s/he will be redirected to the blank form after logging in.
If every model has data, and/or if the user is not authenticated or anonymous, s/he will be redirected to home.


text:
Q: SSIS Web Service Task Converting UTF-16 to UTF-8 I am currently trying to execute a Web Service task in VS 2013 to dynamically output a flat file.  I am receiving an error that states "The error is: Response is not well-formed XML..". I believethe problem is that the XML that is attempting to be exported as a flat is encoded as UTF-16, instead of UTF-8.  Is it possible to within SSIS to change the encoding of the XML before it is output? Or at least a possible workaround?
Thanks in advance.


text:
Q: Clojure: how to explicitly choose JVM in the environment with Leiningen/Lighttable In my Windows 7 (64 bits) environment, I have quite a few JVM available:
C:\Program Files (x86)\Java\j2re1.4.2_12\bin\client\jvm.dll
C:\Program Files (x86)\Java\jre6\bin\client\jvm.dll
D:\programs\Java\jdk1.7.0_45\jre\bin\server\jvm.dll
D:\programs\Java\jre7\bin\server\jvm.dll

Currently, with Lighttable/Leiningen (I don't know which makes the choice, and how), it uses

C:\Program Files (x86)\Java\j2re1.4.2_12\bin\client\jvm.dll

But I really would like to try

D:\programs\Java\jdk1.7.0_45\jre\bin\server\jvm.dll

It's even more puzzling that when I type

java -version

I got the following:
D:\yushen>java -version
java version "1.7.0_45"
Java(TM) SE Runtime Environment (build 1.7.0_45-b18)
Java HotSpot(TM) 64-Bit Server VM (build 24.45-b08, mixed mode)

It seems that's what I want to have inside Lighttable/Leinengen.
Could you show me how to make the explicit choice/configuration?
I tried Google, but couldn't find some leads.
Thanks a lot!

A: Put the JDK's bin directory in your path first. It's the surest way.
More detail. Windows, you can use the where command to see what version of an executable. It's either where java or where java.exe You can also look at your path from the command prompt by typing path. If you're launching something from the command line, and it's not undertaking strange measures to find the JVM, it should come up with the first one in your path, which should agree with the results of running the where command.
If the where command is coming up with something you don't expect, either add the right directory to your path before the entry that's coming up or rearrange your path so it's coming up first.
To test this in leiningen, start a repl, and evaluate this.
(println (System/getProperty "java.version"))

e.g.
Yoyo-2:Desktop bill$ lein repl
(System/getPnREPL server started on port 61475 on host 127.0.0.1 - nrepl://127.0.0.1:61475
REPL-y 0.3.5, nREPL 0.2.6
Clojure 1.6.0
Java HotSpot(TM) 64-Bit Server VM 1.8.0_20-b26
    Docs: (doc function-name-here)
          (find-doc "part-of-name-here")
  Source: (source function-name-here)
 Javadoc: (javadoc java-object-or-class-here)
    Exit: Control+D or (exit) or (quit)
 Results: Stored in vars *1, *2, *3, an exception in *e

ruser=> (System/getProperty "java.version")
"1.8.0_20"

In my experience, Leiningen has always used the version of java it finds in the path. No experience with light table though.

A: For Leiningen, you can edit lein.bat to point exactly to your desired Java SDK version. I don't know if the same could apply to LightTable.
Or you can set a global JAVA_HOME. That is really Googleable (or DuckDuckGo-able).

A: Finally, I found this link: http://leiningen-win-installer.djpowell.net/
After running the installer, it has the function to re-configure leiningen, using it, I was able to configure my old leiningen to use my desired JDK: D:\programs\Java\jdk1.7.0_45\bin\java.exe, then the JVM instance in leiningen/lighttable is the desired one now.
The moral of the story: leiningen needs to be reconfigured with newly installed JDK with the configuration functionality of leiningen-win-installer.
It might be possible to configure leiningen manually, but I hadn't found a way to do yet.
I tried to manually configure through my project.clj with java-command option, it didn't work.

A: I found a Leiningen profile in
$HOME/.lein/profiles.clj
For me on Windows, $HOME was D:\Users\carl . More generally, it's the directory Windows will (usually) dump you in if you start the shell using CMD .
This contained:
{:user
  {
  :java-cmd "F:\\JDK8\\bin\\java.exe"
  :plugins [

    ]
   }
}

...which I was able to change to good effect.


text:
Q: TextEditor positioning in SwiftUI I added a text editor but couldn't center its position,
The text editor has shifted to the right as shown in the picture.
Sorry, I just noticed that the whole page has shifted to the right.
I don't know what I'm doing wrong. You can fix this.
I want it to stand in the middle.

struct TextSend: View {

    @State private var inputText = ""

    var body: some View {
        GeometryReader { geometry in
            VStack {
                HStack {
                    Text("Picture")
                        .font(.system(size: 60))
                        .frame(width: geometry.size.width, height: geometry.size.height / 10)
                        .foregroundColor(.init(red: 45 / 255, green: 0 / 255, blue: 112 / 255))
                    Spacer().frame(height: geometry.size.height / 5)
                }

                VStack {
                    Text("Hi").frame(width: geometry.size.width, height: geometry.size.height / 10)
                }

                HStack {
                    ForEach(0 ..< 3) { _ in
                        CircleView()
                            .frame(width: geometry.size.width / 5, height: geometry.size.height / 10)
                            .shadow(radius: 10)
                    }
                }
                VStack {

                TextEditor(text: $inputText) .frame(width: geometry.size.width, height:geometry.size.height / 3) .overlay(RoundedRectangle(cornerRadius: 30).stroke(Color.init( red: 45/255, green: 0/255, blue: 112/255), lineWidth: 1)).lineSpacing(10)
                    .autocapitalization(.words)
                    .disableAutocorrection(true)
                    .padding()
                }
                Spacer().frame(height: geometry.size.height / 15)
                VStack {
                    Button(action: {}, label: {
                        Text("Gönder")
                            .frame(width: geometry.size.width / 3, height: 50)
                            .padding(10)
                            .font(Font.system(size: 30, weight: .medium, design: .serif))
                            .foregroundColor(.white)
                            .background(RoundedRectangle(cornerRadius: 30))
                            .foregroundColor(.init(red: 45 / 255, green: 0 / 255, blue: 112 / 255))

                    })
                }
            }
        }
    }
}

A: Remove frame(width: geometry.size.width from everywhere used, as such hardcoding breaks layout. Try to use geometry always only for calculable values.
Here is fixed parts (tested with Xcode 12.1 / iOS 14.1)

    HStack {
        Text("Picture")
            .font(.system(size: 60))
            .frame(height: geometry.size.height / 10)    // << !!
            .foregroundColor(.init(red: 45 / 255, green: 0 / 255, blue: 112 / 255))
        Spacer().frame(height: geometry.size.height / 5)
    }

    VStack {
        Text("Hi").frame(height: geometry.size.height / 10)   // << !!
    }

    // ... other code

    VStack {

    TextEditor(text: $inputText)
       .frame(height:geometry.size.height / 3)      // << !!
       .overlay(RoundedRectangle(cornerRadius: 30).stroke(Color.init( red: 45/255, green: 0/255, blue: 112/255), lineWidth: 1)).lineSpacing(10)
        .autocapitalization(.words)
        .disableAutocorrection(true)
        .padding()
    }

A: You need to add frame to your first child inside the GeometryReader which is VStack in your case
VStack{
}.frame(width:geometry.size.width , height: geometry.size.height)

ps : you can make it : geometry.size.width - 10 for example , for padding purpose


text:
Q: prepared all combination of arraylist in java with arithmetic operator without duplicate combination Input: [first col,
second col,
third col]
Output: first col, second col, third col, first col+second col, first col+third col, second col+third col
and so on for three col as well.
Note: i do not want same combination like: first col+second col and second col+first both are same.
for three column like: a+b+c and b+c+a both are same. i dont want that duplicate column. please help me.
I tried with below code, but it is giving me a duplicate combination as well.
// Prepared combination..
 public static void perm2(ArrayList<String> a) throws IOException {
        ArrayList<String> sub = new ArrayList<String>();
        perm2(sub, a);
    }

    static String inputFileLocation = "";

    public static void perm2(ArrayList<String> sub, ArrayList<String> a)
            throws IOException {
        int L = a.size();
        int g = 0;
        String result = "";

        String newLine = System.getProperty("line.separator");
        if (L != 0) {
            for (int i = 0; i < L; i++) {
                ArrayList<String> ab = new ArrayList<String>(sub);
                ab.add(a.get(i));
                ArrayList<String> bc = new ArrayList<String>(a);
                bc.remove(i);
                perm2(ab, bc);
                /* ArrayList to Array Conversion */
                String array[] = new String[ab.size()];
                for (int j = 0; j < ab.size(); j++) {
                    array[j] = ab.get(j);
                    System.out.println("Array: "+ array[j]);
                }
                for (int k = 0; k < array.length; k++) {
                    if (k == 0) {
                        result = array[k];
                    } else {
                        result = "+" + array[k];
                    }
                    System.out.print(result);
                    for (g = array.length; g > 0; g--) {
                        if (array.length == g) {
                            inputFileLocation = "C:\\project\\"
                                    + g + "ColumnData.txt";
                            writeToFile(result, inputFileLocation);
                        }
                    }
                }
                writeToFile(newLine, inputFileLocation);
                System.out.println();
            }
        }
    }

A: I haven't gone through the full code yet but you can't do something like this:
bc.remove(i);

This statement will only hold good until the value of i remains less than the size of the list. Once, i becomes more than the size of the list, this will be a problem.
You should be doing something like this:
bc.remove(0);


text:
Q: How to read a txt file and show it as a table in a console application? I am sorry if i worded to question wrongly and caused confusion. But here is what I want to do. I want the program to read the txt file and then arrange the data into like a table format?
The txt file can look something like this:
fullname1|ID1|age1|mark1
fullname2|ID2|age2|mark2
fullname3|ID3|age3|mark3

I have looked up several ways to do it but none of them worked for me, and I am self learning C# but my English is limited so it is hard for me to look for deeper solution.

A: Because i'm bored
Given
fullname1|ID1|age1|mark1546
sdfdsf|ID2|age56|mark2
gfhxcxvxcvxc|ID3|age3|mark3

Code
// read lines
var lines = File.ReadAllLines(@"D:\Data.txt")
                .Select(x => x.Split('|'))
                .ToArray();

// calculate column widths
var widths = Enumerable.Range(0, lines[0].Length)
                       .Select(x => lines.Max(y => y[x].Length))
                       .ToArray();

// Write the lines with padding each column with its max width
foreach (var line in lines)
   Console.WriteLine(string.Join(", ", line.Select((x,i) => x.PadRight(widths[i], ' '))));

Output
fullname1   , ID1, age1 , mark1546
sdfdsf      , ID2, age56, mark2
gfhxcxvxcvxc, ID3, age3 , mark3

DISCLAIMER : obviously this makes assumptions, therefor i am not responsible for the people you potentialy maim or otherwise harm with this code


text: Q: Use rails to access a local link, click on the file and open the corresponding program How do I (within a Rails application): click on the address of an RVT extension file inside my machine, RFA, RTE, RFT. Open Revit, for example.


text:
Q: How to properly cast generic collections in Java? Let's say that I have initially declared and defined a set of integers as follows:
Set<Integer> s = new TreeSet<>();

Now, later I want to use methods that are specific to a TreeSet. And imagine that I need to this a lot of times in my project. Which of following ways is considered a better practice to stick to?
1- Writing this before starting to use s, at the beginning of my method
s = (TreeSet) s;

2- Writing with the type included (again at the beginning of my method)
s = (TreeSet<Integer>) s;

3- Casting from Set to TreeSet only at times that I need to access a TreeSet specific method
Integer x = ((TreeSet)s).first();

A: As others have said, you don't need to lose the context of the Set being a TreeSet after your declaration if it is important.
A TreeSet is-a Set, so you should be able to pass it around as a Set.
For example:
Set<Integer> getSetButDoSomethingSpecial() {
  TreeSet<Integer> treeSet = new TreeSet<>();
  //Do something specific to treeSet
  return treeSet;
}


text:
Q: Multilevel dynamic linear models in R I am interested in fitting a multilevel bayesian structural time series with a hierarchical structure of the dynamic regression coefficients. The reason I want to do this is is that I have a number of dynamic regressors and many of them are related at a grouping level (imagine many prices for each category of good, with a number of categories).
In short, I am interested in fitting a model something like the following (I'm not sure this specification is perfectly nailed down, so if you know what I'm trying to specify and this has errors, please edit!):
$$Y_t = X\beta_t + v_t$$
$$\beta_t = Z\Delta_{t} + w_t$$
$$\Delta_t = \Delta_{t-1} + u_t$$
Where the X are the "varying intercepts" / category-level coefficients, so to speak, and the Z are the good-level coefficients.
The software that I typically use to estimate bayesian structural time series is bsts in R. I have gone through as much of the dlm documentation as I can understand but I don't think that something like this is possible.


text:
Q: Finding the formulae in terms The cost, $£C$,  of building a circular pond is proportional to the square of its diameter, $d$ meters. A pond with diameter $2$ meters costs $£52$.
Find the formulae for $C$ in terms of $d$.
Okay so I got $C=d^{52}$ but the mark scheme says $C=d^2$ can someone talk me through why they answer is that?

A: You need to solve for the constant of proportionality: you are told that $C=kd^2$, and are given an additional piece of information that $52=k \times 2^2$. This tells you that $k=13$, so the answer should be $C=13d^2$
(Sorry but $C=d^{52}$ is certainly not correct!)

A: The problem statement says the cost $C$ is proportional to $d^2$ (the square of the diameter). There must exist a constant $A$ such that $$C = Ad^2$$ This is simply all it means for two things to be directly proportional. Raising $d$ to the power of the cost does not make any sense if you think about it. What would this accomplish? You are given that the value $d=2$ corresponds to a cost $C$ of $52$. If you plug this into the equation you simply get $$52 = A\cdot 2^2$$ This is enough information to solve for $A$, and hence you'll have all the information you need to calculate the cost of a pond given any value of $d$.

A: "The cost, $C$, of building a circular pond is proportional to [something]" means $C = \alpha$[something] for some $\alpha \in \mathbb{R}$.
In this case, the [something] is "the square of its diameter, d", i.e. $d^2$.
Thus we have $C = \alpha d^2$ for some $\alpha$.
Next we solve for $\alpha$ using that $52 = \alpha 2^2$,  so $\alpha = 52/4 = 13$.
Thus $C = 13d^2$.


text:
Q: What is the meaning of the term "inductively P map"? In this page is the definition of an inductively open map. But in this pdf is the definition of a inductively P map, where P is a property of maps.
But there is a difference in the definitions. In the former it's said that "the image of the subset is the same as the image of the whole space," but in the other it's said symbolically that the image of the subset is the entire codomain space.
It's more credible that the terminology of the paper is the correct, but in some papers is used nonstandard terminology and I'm a little bit confused. What is the meaning of the term "inductively P map" is the sense of the paper standard or is the other page correct? and in any case what is the terminology of the other case?

A: There's no conflict between the two definitions, since the one in the paper refers to a map onto the codomain, so in this case the image of the domain is the entire codomain.


text:
Q: How to get a dynamic node JSON value    {
        noteCount_xxx:
              {
              favorite:"favorite-border",
              id:"noteCount_xxx",
              note:"noteContent",
              title: "notetitle",
            }
    }

*

*This JSON data created at runtime,

*parent noteCount_xxx is dynamic

*I want to get value of that parent node

*the output will be
{
  favorite: "favorite-border",
  id: "noteCount_xxx",
  note: "noteContent",
  title: "notetitle"
}

I am not able to get data from dynamic node, what is the best way to get that
  data....?

A: You can use Object.keys to find out nodeCount_xxx's value as:

const yourJSON = {
  noteCount_xxx:  {
    favorite:"favorite-border",
    id:"noteCount_xxx",
    note:"noteContent",
    title: "notetitle",
  }
}

const firstKey = Object.keys(yourJSON)[0]

console.log(yourJSON[firstKey])

Or in case you already know the value of nodeCount_xxx, simple access your object:
yourJSON[noteCount]

A: The object should be created dynamically instead in case the values are not properly escaped:

var noteCount = "noteCount_" + 123

var parent = {
  favorite: "favorite-border",
  id: noteCount,
  note: "noteContent",
  title: "notetitle",
}

var person = { }
person[noteCount] = parent

console.log( parent )
console.log( person )
console.log( JSON.stringify( person ) )

If the JSON is from a separate process, the key value pairs can be accessed during the parsing:

var parent, currentNote = '{"noteCount_123":{"favorite":"favorite-border","id":"noteCount_123","note":"noteContent","title":"notetitle"}}'

var person = JSON.parse(currentNote, function(key, value) {
  return key ? parent = value : value })

console.log( parent )
console.log( person )


text:
Q: Emitting a value any time one of several observables emit a value, even if not all have yet? I have two observables - let's call them A and B. I need to perform the following operations in the following order:

*

*Get the latest value of A

*Get the latest value of B by dispatching an action to my store using the value of A (dispatching the action initiates an async operation that eventually causes B to emit a value)

*Use the latest values from both A and B to make a decision

The action is dispatched like this (assume a is the last value emitted by A, and dispatch returns void)
this.store.dispatch(
  new fromStore.LoadItem(a)
);

Since B depends on the value of A, I can't use combineLatest, since it requires all observables to have emitted at least one value. I would also prefer not to use merge, as that would require identifying which observable the value came from, and these are not primitives. It seems like a natural solution would be a version of combineLatest that doesn't require all provided observables to have emitted something, but I'm not sure if that exists, or is the proper solution here.
I've made it work in a hacky fashion by subscribing to A and B separately and storing the values globally, but it's messy and I'd like to see if there's a neat means of doing it in a single block of code.
EDIT: trying Fabricio's answer:
A.mergeMap(a => {
  this.store.dispatch(
    new fromStore.LoadItem(a)
  );
  return a
 }, (a, b) => {
   ...
 })

I don't understand what I'm supposed to return in the first argument (a => ???). B is another observable, I can't pass it the value of A, so a => B(a) doesn't work. Do I return a after dispatching the action? An observable of a? The second observable B? In all of these cases I just get Argument of type '(a: any, b: any) => void' is not assignable to parameter of type 'number'.

A: I ended up making it work like this:
A.mergeMap(a => {
  // dispatch action that causes B to eventually emit a value here
  return B.map(b => {
    // access both results here
  });
});

Not sure if Fabricio's answer is the short hand of this or something like that, but I couldn't his version to compile so this is what I'm going with.


text:
Q: Is there anyway to use cognitive services to detect if a string contains words vs just junk shift chars/gibberish? I'm trying to find a way to use cognitive services to detect if a string contains a piece of coherent text or is just junk. Example:

SDF#%# ASFSDS b

vs

Hi my name is Sam.

This seems impossible to do. I had the idea of running the text through the keywords text analysis (which would give me a keyword of ASDSDS (how useful!)) and then run that keyword though the Bing Spell Check. I'm not sure what is going on in the the USA but it seems ASFSDS is English. It really is quite... erm.. dumb.
I've tried running similar text through a bunch of services (like language detection) and they all seem convinced that my gibberish samples are 100% coherent English.
I'm going to quiz an MS rep about it on Friday but I was wondering if anyone has achieved something like this using Cognitive services?

A: Rather than a binary is-word-or-not question, what you might consider instead is the probability of a word being gibberish.  You can then choose a threshold that you like.
For computing word probalities, you might try the Web Language Model API.  You could look at the joint probability, as an example.  For your set of words, the response looks as follows (values for the body corpus):
{
  "results": [
    {
      "words": "sdf#%#",
      "probability": -12.215
    },
    {
      "words": "asfsds",
      "probability": -12.215
    },
    {
      "words": "b",
      "probability": -3.127
    },
    {
      "words": "hi",
      "probability": -3.905
    },
    {
      "words": "my",
      "probability": -2.528
    },
    {
      "words": "name",
      "probability": -3.128
    },
    {
      "words": "is",
      "probability": -2.201
    },
    {
      "words": "sam.",
      "probability": -12.215
    },
    {
      "words": "sam",
      "probability": -4.431
    }
  ]
}

You will notice a couple of idiosyncrasies:

*

*Probabilities are negative.  This is because they are logarithmic.

*All terms are case-folded.  This means that the corpus won't
distinguish between, say, GOAT and goat.

*Caller must perform a
certain amount of normalization themselves (note probability of
sam. vs sam)

*Corpora are only available for the en-us market.  This could be problematic
depending on your use case.

An advanced use case would be computing conditional probabilities, i.e. the probability of a word in the context of words preceding it.


text:
Q: Convert Bound List to Generic List I need to convert a bound (UnityEngine.Component) List to a generic (T) List, is this possible? how?
I'm using Unity and C#, but I would like to know in general how one would do this.
        List<Component> compList = new List<Component>();
        foreach(GameObject obj in objects)   // objects is List<GameObject>
        {
            var retrievedComp = obj.GetComponent(typeof(T));
            if(retrievedComp != null)
                compList.Add(retrievedComp);
        }

        List<T> newList = new List<T>(compList as IEnumerable<T>); // ERROR HERE

        foreach(T n in newList)
            Debug.Log(n);

thanks!
I assume that is the issue, I'm getting this runtime error...
ArgumentNullException: Argument cannot be null.
Parameter name: collection
System.Collections.Generic.List`1[TestPopulateClass].CheckCollection (IEnumerable`1 collection)
System.Collections.Generic.List`1[TestPopulateClass]..ctor (IEnumerable`1 collection)
DoPopulate.AddObjectsToList[TestPopulate] (System.Reflection.FieldInfo target) (at Assets/Editor/ListPopulate/DoPopulate.cs:201)
System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture)
Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation.
System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture)
System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters)
DoPopulate.OnGUI () (at Assets/Editor/ListPopulate/DoPopulate.cs:150)
System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture)

A: Have you tried
    List<T> newList = compList.OfType<T>().Select(x=>x).ToList()

A: Most likley cased by the fact that T and Component are different types: List<Component> compList and compList as IEnumerable<T> (this one will be null since compList is IEnumerable<Component> not IEnumerable<T>).
I think you want:
    List<T> compList = new List<T>(); // +++ T instead of GameObject
    foreach(GameObject obj in objects)   // objects is List<GameObject>
    {
        // ++++ explict cast to T if GetComponent does not return T
        var retrievedComp = (T)obj.GetComponent(typeof(T));
        if(retrievedComp != null)
            compList.Add(retrievedComp);
    }

    List<T> newList = new List<T>(compList as IEnumerable<T>); // ERROR HERE

    foreach(T n in newList)
        Debug.Log(n);


text:
Q: List property inside a model is coming null while posting the model to controller I am creating a basic mvc3 application in which I am trying to post a complex model type with a list property (of model type) to my controller. But when I do so, that property is coming as null inside the model.
I have my model as follows:
public class EmployeeList
{
    public List<Employee> employeeList { get; set; }
}

And Employee is again a model :
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Controller Code is:
[HttpGet]
public ActionResult Index()
{
    EmployeeList em = new EmployeeList();
    em.employeeList = new List<Employee>() { new Employee(){}};
    return View(em);
}

[HttpPost]
public ActionResult Index([Bind(Prefix = "employeeList")]EmployeeList employeeList1)
{
    .......
}

And the Views are as follows:
Index.cshtml:-
@model test.Models.EmployeeList
@{
    ViewBag.Title = "Index";
 }

Index

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @id = "testForm" }))
{
    @Html.LabelFor(m => m.eid)
    @Html.EditorFor(m => m.eid)
    @Html.HiddenFor(m => m.eid)

    @Html.EditorFor(x => x.employeeList)

        <input type="submit" value="Post" />

}

And the editor template view is:
@model test.Models.Employee

@Html.LabelFor(model => model.Id)
@Html.TextBoxFor(model => model.Id)
@Html.HiddenFor(model => model.Id)

@Html.LabelFor(model => model.Name)
@Html.TextBoxFor(model => model.Name)
@Html.HiddenFor(model => model.Name)

On the browser I checked , the names and id's are generated as follows:
name="employeeList[0].Id", id="employeeList_0__Id"

name="employeeList[0].Name", id="employeeList_0__Name"

But when I post this EmployeeList model to controller, I get the employeeList as null.
Please help me if I am missing something.
Thanks in advance.

A: I think the mvc model binding might be getting confused. Try changing the name of your model's property from employeeList to ListOfEmployees. e.g.
public class EmployeeList
{
    public List<Employee> ListOfEmployees { get; set; }
}

[HttpPost]
public ActionResult Index([Bind(Prefix = "ListOfEmployees")]EmployeeList employeeList1)
{
    .......
}

@model test.Models.EmployeeList
@{
    ViewBag.Title = "Index";
 }

Index

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @id = "testForm" }))
{
    @Html.LabelFor(m => m.eid)
    @Html.EditorFor(m => m.eid)
    @Html.HiddenFor(m => m.eid)

    @Html.EditorFor(x => x.ListOfEmployees)

        <input type="submit" value="Post" />

}

A: As you have discovered, you need to remove the BindAttribute. To explain:
When you use [Bind(Prefix="employeeList")], you are telling the ModelBinder to strip "employeeList" from the beginning of the name of each property that's posted back, so instead of employeeList[0].Id and employeeList[0].Name (which is correct as your posting back class EmployeeList) you getting [0].Id and [0].Name (but class EmployeeList does not have properties Id and Name.
If you use the the attribute as you have, you would need to change your parameter to
public ActionResult Index([Bind(Prefix = "employeeList")]List<Employee> employeeList1)

which would bind correctly


text:
Q: Creating DIY ON/CHARGING switch for an Arduino Currently I'm using the newly released WEMO LOLIN32 (pictured below), and it's a great board, save for the lack of one thing, a power button.

Initially I was thinking of a simple ON/OFF switch that disconnects the battery, but I realized I need it to be able to charge a Li-Po battery while the device is powered down. Now since I'm charging a Li-Po I need to output 4.2V to the charger (at say 50-100+ mA or something comparable to the current from the battery terminal). Sadly as this is a new board I don't have much in the way of a spec sheet to guide me on the capabilities of each port.

Two questions

*

*Will I fry the board if I try to run power through analog out ports?

*Is there charging behavior that is built into Li-Po charging that I need to emulate on the analog out that I use?

A: Q2 is a mosfet used to disable power draw from VBAT when 5V or VUSB is present. Disconnect the trace from pin 3, and place a switch between pin 3 and the trace from VBAT.
Based on what I see on the schematic. This means it can still charge from 5V. But will only power the 3.3v regulator when the switch is on.
Edit: based on https://macsbug.wordpress.com/2017/05/08/battery-and-battery-interface-of-lolin32/ there are two revisions. The original uses a diode or bridge, while the newer uses a mosfet there. The same applies to either revision. Disconnect the VBAT from q2 or the diode bridge and insert a switch.
Edit 2: here https://macsbug.wordpress.com/2017/05/31/power-switch-to-wemos-lolin32/ they mod a power switch. Similar to what I suggested, this would also keep the board mostly off even of you use a usb or 5v power source. It will allow you to charge and have the board off, but not board on no charging.

A: I'm not certain you actually need to cut the power. As you stated in the comments, the board already supports charging, you just need to shut your application down when the switch is off. I'm sure this chip has a "sleep" mode you can put it into. Wire your switch into a digital input pin and use an interrupt to monitor its state. When the interrupt is triggered, you can stop your application and put it into low power mode.

A: *

*Yes, you will fry something if you try to run power through an I/O port on any microcontroller (and I don't see any analog outputs on the schematic, anyway.)

*The schematic and spec page indicates that the board has built-in battery charging capability. (see U5 on the schematic).


text:
Q: Recycle view row text overlaps on smaller devices I am building a simple row layout to add data dynamicly inside my recycle view, so i builded a a layout like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#cfcfcf">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:background="#ffffff"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/plantPhoto"
            android:layout_width="120dp"
            android:layout_height="100dp"
            android:layout_weight="1"
            android:background="#c7c7c7"
            android:padding="0dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="20"
            android:orientation="vertical">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                    android:id="@+id/plantName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:padding="15dp"
                    android:text="TextView"
                    android:textAppearance="?android:attr/textAppearanceSmall"
                    android:textColor="@color/emerald" />

                <ImageView
                    android:id="@+id/starIcon"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentEnd="true"
                    android:padding="15dp"
                    android:src="@drawable/ic_star" />

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:padding="15dp">

                <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                    android:id="@+id/data"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_toStartOf="@+id/cameraForbiden"
                    android:text="TextView"
                    android:textAppearance="?android:attr/textAppearanceSmall"
                    android:textColor="@color/base" />

                <ImageView
                    android:id="@+id/cameraForbiden"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentEnd="true"
                    android:src="@drawable/ic_no_photos" />

                <ImageView
                    android:id="@+id/userIcon"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"

                    android:gravity="left"
                    android:src="@drawable/ic_user" />

                <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                    android:id="@+id/password"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_toRightOf="@+id/userIcon"
                    android:layout_alignBottom="@+id/userIcon"
                    android:textAppearance="?android:attr/textAppearanceSmall"
                    android:text="Filipe"
                    android:textColor="@color/base" />

            </RelativeLayout>

        </LinearLayout>
    </LinearLayout>

the main problem on this approach is that when i check my solution on smaller devices the text at left orverlaps the text at right, one solution that i am searching is to decrease the content based on the device size, but didn't find that yet.
This is what i get on a Nexus 5 for example:

this is what i get on a smaller device:
any help with this guys?
Thank you very much

A: You can use Linear layout for this. You can assign weight to each item.
Try this code :
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#cfcfcf">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="10dp"
            android:background="#ffffff"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/plantPhoto"
                android:layout_width="120dp"
                android:layout_height="100dp"
                android:layout_weight="1"
                android:background="#c7c7c7"
                android:padding="0dp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="20"
                android:orientation="vertical">

                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:id="@+id/plantName"
                        android:layout_width="0dp"
                        android:layout_weight="1"
                        android:layout_height="wrap_content"
                        android:gravity="left"
                        android:padding="15dp"
                        android:text="TextView"
                        android:textAppearance="?android:attr/textAppearanceSmall"
                        android:textColor="@color/black" />

                    <ImageView
                        android:id="@+id/starIcon"
                        android:layout_width="0dp"
                        android:layout_weight="0.5"
                        android:layout_height="wrap_content"
                        android:padding="15dp"
                        android:src="@drawable/ic_art_track_black_24dp" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:padding="15dp"
                    android:orientation="horizontal">

                    <ImageView
                        android:id="@+id/cameraForbiden"
                        android:layout_width="0dp"
                        android:layout_weight="1"
                        android:layout_height="wrap_content"
                        android:src="@drawable/ic_art_track_black_24dp" />

                    <TextView
                        android:id="@+id/data"
                        android:layout_width="0dp"
                        android:layout_weight="2.5"
                        android:layout_height="wrap_content"
                        android:text="TextView"
                        android:textAppearance="?android:attr/textAppearanceSmall"
                        android:textColor="@color/black" />

                    <TextView
                        android:id="@+id/password"
                        android:layout_width="0dp"
                        android:layout_weight="2"
                        android:textAlignment="viewEnd"
                        android:layout_height="wrap_content"
                        android:layout_toRightOf="@+id/userIcon"
                        android:layout_alignBottom="@+id/userIcon"
                        android:textAppearance="?android:attr/textAppearanceSmall"
                        android:text="Filipe"
                        android:textColor="@color/black" />

                    <ImageView
                        android:id="@+id/userIcon"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1.5"
                        android:gravity="left"
                        android:src="@drawable/ic_art_track_black_24dp" />

                </LinearLayout>

            </LinearLayout>
        </LinearLayout>
</LinearLayout>


text:
Q: How does a class loader find a class ClassLoader c //imagine this is a valid object
c.loadClass(String className, boolean resolveIt);

It is the className parameter which is confusing me. I have written the java file to a folder, and compiled it using reflection. I am unsure therfore how I point to the correct file and what naming convention i use for the className.
The documentation sayjust says the name of the class, but how is it supposed to know where it is?
Thanks

A: The point of a ClassLoader is precisely to know how to search for class files given a class name. The javadoc says:

Given the binary name of a class, a class loader should attempt to
  locate or generate data that constitutes a definition for the class. A
  typical strategy is to transform the name into a file name and then
  read a "class file" of that name from a file system.

So, you'll have to make your ClassLoader translate the class name to some location where the byte-code of the class will be found. URLClassLoader does that by transforming the class name into a path, and looking up that path in the various jars and directories at which the URLs point.

A: This is the very reason why you write a classloader in the first place: it is just a mechanism to map class names to (binary) classes in memory. Where the classloader gets the data is its very own business.
For example, an URLClassLoader will consult the class path and see if it can find a file that contains the named class.


text:
Q: determining the end of user char input c++ i want to proccess user input which is a line of string. with string library it's just easy as cin >> mystring; , but for performance reasons, i'd like to process a character at a time without saving previous characters or using any kind of arrays. so i wrote this code:
char myc;
while(cin >> myc){
   dosomething(myc);
}

but after writing a line of string as input and hitting enter, it processes input characters and still waits for more input characters to come.
i also used cin.eof() and while(myc) but none of them worked.

A: You have to check for line break but you can't do it with std::istream::operator>> because it is formatted read and skips newline. Use
char myc;
while ((myc = cin.get()) != '\n')
   dosomething(myc);
}

A: To read a stream character-wise use std::basic_istream<CharT,Traits>::get function:
for(char c; std::cin.get(c);) {
    std::cout << c;
}


text:
Q: Simple circuit to give a pulse to a IC pin once? I have an IC that is activated when pulsing a pin high, the pin should be keep floating after the pulse. The circuit is powered using a battery, and that IC then wake up everything else (Regulator, MCU, etc).
I'm looking for something like this:
Battery -> Pulse to the pin -> IC wakes up -> IC wakes up everything else
I'm trying to guess how to do that in simple terms, I mean without adding even more complexity to the circuit.
I have tried bridging the pin to the + of the battery manually for a moment (< 1 sec) and it works, but only after removing the + from the pin.
So the question is: How do I create a brief pulse using simple components? It is possible?

A: The difficult bit is keeping the pin 'floating' afterwards. I offer this as a possible solution.

When the circuit is switched on the voltage across C1 cannot change immediately so that the negative terminal is pulled up to the supply voltage (leading edge). R1 gives a path for the capacitor to charge and the voltage across R1 will fall with time. After 1 CR time constant this voltage will be approximately 1/3 of the supply.
Q1 will initially be turned ON but as the capacitor charges the voltage across R1 falls. Q1 will be turned OFF after a short period of time.
The diode is in there for when the power is switched off.
When Q1 is turned ON Q2 is also turned ON as the voltage at its gate will fall near to 0 across R2. This will pull up the RESET pin to the positive rail for the short time period set by C1 R1.
After Q1 (and Q2) are turned OFF there is no connection to the RESET and so the pin will be floating.


text:
Q: Different response on NodeJS and Postman I want to write a script with nodejs that gets a set of rules from http://hl7.org/fhir. For example, when I do this request on Postman (http://hl7.org/fhir/address-use) I get a valid JSON response:

However, when I use the nodejs code below which is generated by Postman, I get an html as response.
var http = require("http");

var options = {
  "method": "GET",
  "hostname": "hl7.org",
  "port": "80",
  "path": "/fhir/address-use",
  "headers": {
    "content-type": "application/json",
    "accept": "application/json"
  }
};

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });
});

req.end();

If you try to go to the url in your browser, it says that the url was moved to another page, but Postman gets the correct results anyway. I also tried to get the url that it moved, but it returns html response also.
How can I make my script work just as Postman?
EDIT:
I tried request package as recommended in another question. Here is the code:
var request = require("request");

var options = { method: 'GET',
  url: 'http://hl7.org:80/fhir/address-use',
  headers:
   {
     accept: 'application/json',
     'content-type': 'application/json' } };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});

But the result didn't change. It gets the same html response.


text:
Q: How to upgrade Nativescript app to version 6? Recently I tried to upgrade my nativescript5.1.1 app to nativescript6 and I am getting the following error:

ERROR in ./tools/preinstall.js
Module not found: Error: Can't resolve 'child_process' in '/Users/saiful/Documents/Workspaces/test-App/app/tools'
@ ./tools/preinstall.js 3:13-37
@ . sync (?<!\bApp_Resources\b.)\.(xml|css|js|(?<!\.d\.)ts|(?<!\b_[\w-]*\.)scss)$*
@ ./app.js


text:
Q: Generate new SSH Key in GIT GUI Actually, I have generated a SSH Key using GIT GUI. But I would like to modify the existing SSH Key. I don't see any options for modifying the existing key.
Can anyone tell me how to modify the existing SSH Key?

A: To modify the existing default ssh key, you don't need to gui.
Make sure your <git>\usr\bin is in %PATH% and type:
ssh-keygen -t rsa -C "key for xxx access" -q -P ""

That will propose to override your %HOME%\.ssh\id_rsa(.pub) (with %HOME% generally set to %USERPROFILE%)


text:
Q: i18n vue is not working when changing locale, using rules in text field of vuetify Using Vuei18n and Vuetify make me confuse this point
This is my code (I noted the weird thing in-line):
<v-form @submit.prevent="login" v-model="valid" ref="form">
  <v-text-field
    prepend-icon="person"
    name="login"
    :label="$t('Login')" <-- This line is still translated automatically
    type="email"
    v-model="email"
    :rules="[v => !!v || $t('E-mail is required')]" <-- This line is not translated automatically
  ></v-text-field>
  ...
</v-form>

How can I translate automatically the message under the input form?

A: Create a computed emailRules,
computed: {
    emailRules() {
      return [
        v => !!v || $t('E-mail is required')
      ];
    }
  },

Then modify your line :rules in your "v-text-field"
:rules="emailRules"

A: I think vuetify takes the message when rule has just to fail.
I did this mixin based on update rules when locale has changed, in order to refresh rules message.

import Vue from 'vue'

export default Vue.extend({
  data: () => ({
    formActive: true,
  }),
  computed: {
    requiredRules() {
      return this.formActive
        ? [(val: string) => !!val || this.$t('errors.requiredField')]
        : []
    },
  },
  methods: {
    updateLocale() {
      this.formActive = false
      this.$nextTick(() => {
        this.formActive = true
      })
    },
  },
})

A:          <v-select
              :items="getAllPriceGrups"
              item-text="name"
              @input="getPrices"
              v-model="priceG"
              filled
              :rules="rulesRequired($t('global.needToFillOut'))"
              return-object
          ></v-select>

 methods: {
    rulesRequired(role) {
      return [value => !!value || role];
    },
}

This works for me!

A: The solution of SteDeshain from this open github issue works for me:
template:
<v-text-field
    v-model="userState.username"
    :rules="[rules.required, rules.mail]"
>
    <template #message="{ message }">
        {{ $t(message) }}
    </template>
</v-text-field>

js:
data () {
  return {
    show1: false,
    rules: {
      required: v => !!v || 'rules.notEmpty',
      mail: v=> /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,6})$/.test(v) || 'rules.mail'
    }
  };
},