text:
Q: Unable to set the height dynamically to textarea I've a textarea where the height of the textarea will increase dynamically based on the length of the text goes inside. Once it reaches the height of 200px the scoll appears. Somehow, I am unable decrease the height when I delete the text after scroll appears. The height remains constant even though the content is not fully occupied.
I am trying to match with the textarea(dynamic) present in https://www.intercom.com/ chat.
HTML & JS
  <div class="container">
      <textarea placeholder="Text goes here..." onkeydown="expand(this)" onkeyup="expand(this)"></textarea>
    </div>
    <script>
      function expand(element) {
        if (element.scrollHeight < 200) {
          element.style.height = "0px";
          element.style.height = (element.scrollHeight) + "px";
        } else {
          element.style.height = "200px";
          element.style.overflowY = "auto";
        }
      }

    </script>

CSS
.container {
  min-height: 16px;
  max-height: 200px;
  width: 300px;
}

.container textarea {
  max-height: none;
  max-width: none;
  min-height: 0;
  min-width: 0;
  color: #565867;
  background-color: #f4f7f9;
  resize: none;
  //border: none;
  overflow: hidden;
  font-size: 14px;
  width: 100%;
  height: 100%;
}

Fiddle here

A: Change the following code to make it work
.container {
  min-height:18px;
  max-height: 200px;
  width: 300px;
}

into
.container {
  height:18px;
  max-height: 200px;
  width: 300px;
}


text:
Q: Make a div offset based on middle of window width? Basically, I have the code:

        text here

CSS:
#footer { line-height:125px; margin:0 auto; width:500px;height:100%; text-align:center;color:#ECECEC; }

It works lovely on one computer, then if I load it on another the text is offset even further to the left or right depending on monitor/resolution.
How can I set it so it's centered but hovered over/under the image to an offset just right of the image?
EDIT
Small Screen:
Large Screen:
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>stuff here</title>

stuff here

            dasdasdasd dsad dasdasdas dsadsad ssdasdasd.

            dasdsa dasdasd dasdasdasd dasdsadsad .

A: You need to set position: relative; on the footer if you want the text to be positioned absolute in relation to the footer.
DEMO
Or you can remove all the positioning and the enormous line-height
DEMO

A: You can use the image as a background-image instead. Then it's much easier to position the text
HTML

text here

CSS
#footer {
    line-height:125px;
    margin:0 auto;
    width:500px;
    height:100px;
    text-align:center;
    color:#ECECEC;
    background-image: url(http://i.imgur.com/nx8pHGH.png);
    background-repeat: no-repeat;
}

See JSFiddle

redpajama_set_name: RedPajamaStackExchange


text:
Q: Workflow limits in response to API calls Are there limitations on the number of workflow rules that can be triggered simultaneously for my org?
Here's the situation.  My company is running as Unlimited with between 100 - 200 users.  My manager is trying to come up with a way to simulate recurring scheduled tasks for a custom object in Salesforce.  Before we put it into play, I'm trying to determine if we'll run into any Salesforce limits that will cause trouble.
Here's what we're trying to do:

*

*I will write an external script that accesses Salesforce via the API.

*

*Every hour, this script checks a checkbox on every records of a custom object.

*Our Salesforce declarative interface guy will set up a workflow on these records that is triggered by the change in state of the same checkbox:

*

*One workflow action unchecks the checkbox so that my script can re-check again it in an hour.

*He will add other workflow actions to schedule time-based actions for email notifications, update fields, etc...

There are thousands of records which this will apply to.
I've read through the Salesforce Limits Quick Reference Guide [PDF] and searched through this forum and others, but I haven't found a conclusive answer.  I'm fairly new to Salesforce, and I've had a lot of trouble trying to decipher the Salesforce documentation.
Also, are there any recommendations for a better way to implement recurring tasks?  I've seen a little info on scheduled APEX, but I haven't looked into it much.  I know there are limits involved there as well.
Thanks!
Update:  Solution in the comments on Doug B's answer.

A: welcome to the forum.
I fear that your approach is over-complicated. And you are introducing a system integration (to call in on the API) and issues of scaling and performance if you are trying to update a potentially large number of target records.
Without knowing the full ins and outs of your requirements, I'd suggest you look at.

*

*Scheduled Apex. You write an apex job, and schedule it to run every hour. It first finds records that match your entry criteria, then it executes your business logic (e.g. email).

*Time based workflow. No code required. Set up a workflow, e.g. if a record hasn't had the "salesman" field filled in within two days, set the status to escalated or something like that.

*If it really is exactly recurring tasks you want, well you can setup recurring tasks in Salesforce. You could set these up programmatically too. Have a trigger code which runs whenever one of your records is created/updated and if it meets your criteria then create a task.
Hope this gives you something to think about.


text:
Q: AWS-SAM: How to re use a Route53 domain instead of re creating it? I am developing an HTTP API. I need to use a custom domain with this. I already have the domain, and I generated the certificate from the AWS Certificate manager as well. My domain DNS is in Amazon Route53.
Now I am trying to attach this custom domain to my HTTP API. I also need to set the base path. I am using AWS-SAM template and below is what I tried.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  aws-restapi

  Sample SAM Template for aws-restapi

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 5
    VpcConfig:
        SecurityGroupIds:
          - sg-041f24sd125s51e8e
        SubnetIds:
          - subnet-05265b2d

Parameters:
  FirebaseProjectId:
    Type: String

  DomainName:
    Type: String
    Default: api.example.com

Resources:

  AuthGatewayHttpApi:
    Type: AWS::Serverless::HttpApi
    Properties:
      Domain:
        DomainName: !Ref DomainName
        CertificateArn: arn:aws:acm:us-east-1:xxxx:certificate/xxxxx-xxxx-xxxx-xxxx-xxxxx
        Route53:
          HostedZoneId: Z096752626aDO8HB8C6
      Auth:
        Authorizers:
          FirebaseAuthorizer:
            IdentitySource: $request.header.Authorization
            JwtConfiguration:
              audience:
                - !Ref FirebaseProjectId
              issuer: !Sub https://securetoken.google.com/${FirebaseProjectId}
        DefaultAuthorizer: FirebaseAuthorizer

  AuthFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: aws-restapi/
      Handler: source/testfile.lambdaHandler
      Runtime: nodejs14.x
      Events:
        Gateway:
          Type: HttpApi
          Properties:
            ApiId: !Ref AuthGatewayHttpApi
            Path: /hello
            Method: get

This template builds fine but when deploying it throws the following error.
CREATE_FAILED                      AWS::Route53::RecordSetGroup       RecordSetGroupf015792d8d

[Tried to create resource record set [name='api.example.com.',type='A'] but it already exists]

Well, the error says the truth, I have the domain already in place. I do not want to create the domain or a certificate again, I just want to use them here.
How can I get this done? also how can I set the basePath so i can access like api.example.com/products ?

A: You can't reuse this DomainName if it is pointing to a server or other AWS service like AWS Amplify. You can reuse this domain (or subdomain) only if it is already being used by API Gateway. So, if you can delete the DNS register, I recommend you to create it again with AWS SAM or create a different subdomain. If the subdomain is already being used by API Gateway, then you can create an AWS::ApiGatewayV2::ApiMapping resource.
Creating the DNS Record with AWS SAM
In this case you can simply define the BasePath attribute of the Domain:
AuthGatewayHttpApi:
    Type: AWS::Serverless::HttpApi
    Properties:
      Domain:
        BasePath:
          - products
        DomainName: !Ref DomainName
        CertificateArn: arn:aws:acm:us-east-1:xxxx:certificate/xxxxx-xxxx-xxxx-xxxx-xxxxx
        Route53:
          HostedZoneId: Z096752626aDO8HB8C6
      Auth:
        Authorizers:
          FirebaseAuthorizer:
            IdentitySource: $request.header.Authorization
            JwtConfiguration:
              audience:
                - !Ref FirebaseProjectId
              issuer: !Sub https://securetoken.google.com/${FirebaseProjectId}
        DefaultAuthorizer: FirebaseAuthorizer

Creating an ApiMapping for an existing DomainName
In this case you won't define the Domain properties, it is only necessary to create the AWS::ApiGatewayV2::ApiMapping resource.
AuthGatewayHttpApi:
    Type: AWS::Serverless::HttpApi
    Properties:
      Auth:
        Authorizers:
          FirebaseAuthorizer:
            IdentitySource: $request.header.Authorization
            JwtConfiguration:
              audience:
                - !Ref FirebaseProjectId
              issuer: !Sub https://securetoken.google.com/${FirebaseProjectId}
        DefaultAuthorizer: FirebaseAuthorizer

AuthGatewayProductsMapping: # Creates the mapping for Reporting V1
    Type: AWS::ApiGatewayV2::ApiMapping
    Properties:
      ApiId: !Ref AuthGatewayHttpApi
      ApiMappingKey: products
      DomainName: !Ref DomainName
      Stage: Prod


text:
Q: Importing package from parallel or higher order directory in Python 3.6+ My python project is structured as follows
In order to user logr.py of comUtil package from dataPreparation package one has to tweak its sys path as follows
import sys
sys.path.append('../')
import comUtil.logr as logg
Now the question is

*

*Is this an accepted practice and are there any drawbacks for such usage ?

*What are other alternatives and possibly better ?

A: One solution could be to set the path till dataIngestionTool. Because this is your project's root directory.
And then import files as:
from dataIngestionTool.comUtil.logr import *

or
from dataIngestionTool.comUtil import logr

A: *

*sys.path.append('../') permanently appends this path to the list. Now, if you are going to import a_random_module for example in driver.py, the package manager will also start looking for a_random_module in the parent directory of driver.py.

*I would suggest something like this to add a certain path to sys:
import sys
import os
def append_specific_dir_to_sys_path():
    current_dir = os.getcwd()
    parent_dir = current_dir.split('/')[:-1]
    import_dir = '/'.join(parent_dir) + '/comUtil/'
    sys.path.append(import_dir)
append_specific_dir_to_sys_path()


text:
Q: Facebook account linking, can anyone give small example code? I'm very frustated, I can't figure out how to link accounts using the account_link button, it's making my life so hard, I posted this question before, and I thought I had understood how but I just didn't, it's driving me crazy.
Can someone please post a sample code of how to achieve this?
You get on you account linking url the GET parameters:
$token = $_GET['account_linking_token'];
$uri = $_GET['redirect_uri'];

Then you type in your credentials in the log in.
User: user
Password: pass

Click login.
You go and verify credentials, if they are correct, you link the account:
THIS IS THE SMALL BASIC EXAMPLE CODE I NEED
Then, if account linked succesfully, I redirect to the uri:
redirect($uri.'&authorization_code=myauthorizationtoken');

After this, I can retrieve PSID with the API.
Can somebody help me out please?

A: Check this out : Account Linking Failed
Use messaging_account_linking subscription for your Facebook developer application.

A: Your problem is that you do not understand what account linking really means. Account linking means that you should ask this current messenger user to login on your platform thereby linking the messenger account to the user account on your platform.
The flow is just an implementation of OAUTH 2.0. Please read it up to really understand what's going on.
Your job is to just

*

*Redirect the user to a login screen on your part and get the user's PSID using the endpoint provided by the documentation.

*Save the PSID and (optional) account linking token to the user's data model.

*Generate an authorization code(this is part of the OAUTH 2 flow)

*Redirect back to messenger.


text:
Q: How to control flow of steps in task scheduler As we know in SQL job agent, we can manage the control of steps
for ex:-
lets a job has following steps:-
step 1
step 2
step 3
step 4

we can control the flow as if step1 is success go to step 2 else go to step 4
Can something like this be done in task schedule?
because in task schduler, i did not find any option to perform this functionality
Any help in this regard?

A: As detailed in this MSDN blog post, you can chain tasks together by setting up a custom event trigger and use the XPath Filter editor to target events indicating that the previous task completed:

The TaskName value is the path to the task in Task Scheduler, so if you want to trigger on a task called "Task01", placed in the root folder of the task scheduler library, value should be "\Task01"
Unfortunately, the New-ScheduledTaskTrigger cmdlet doesn't support custom event log based triggers, so the only way to automate deployment of such a task is to:

*

*Create it "by hand"

*Export it

*Update the XML if necessary

*Import on target machine

Step 2-4 can be accomplished programmatically with Export-ScheduledTask, the [xml] type accelerator and schtasks /create /xml


text:
Q: What's special about the circle problem? Let $K$ be a number field, and let
$$\zeta_{K}(s):= \sum_{0
\neq I \text{ ideal of }O_K} \frac{1}{N_{K/\mathbb{Q}}(I)^s} = \sum_{n \ge 1} \frac{a_n}{n^s}$$
be the Dedekind zeta function of $K$. The quantity $s_K(x):=\sum_{n \le x} a_n$ counts ideals of $O_K$ of norm up to $x$.
$\zeta_K$ is analytic in $s\ge 1$ apart from a simple pole at $s=1$, with residue given by the class number formula. The Wiener-Ikehara theorem implies:
$$s_K(x) \sim c_{K} x$$
as $x\to \infty$, where $c_K$ is given by the class number formula.
Let $E_K(x):=s_K(x) - c_K x$.
When $K=\mathbb{Q}(i)$, the problem of studying $E_K$ is known as the Gauss circle problem. Proving $E_K(x) = O(x^{1/2})$ is easy, but it is believed that $E_K(x) = O_{\varepsilon}(x^{1/4 + \varepsilon})$.

*

*What is known about $E_K(x)$ for general number fields (conditionally and unconditionally)? What is the heuristic for that?

*What distinguishes the case $K=\mathbb{Q}(i)$ from other cases? (Apart from the elementary geometric interpretation)

A: There is nothing special about the circle problem (except of course that it goes back to Gauss)!  The problem for number fields has been extensively investigated, and goes back to Landau.  If the number field has degree $k$, then the problem is quite analogous to the error term in the $k$-divisor problem.  One expects that the remainder term should be on the scale of $O(x^{\frac{k-1}{2k}+\epsilon})$, and an $\Omega$ result of this flavor is known.  Regarding $O$-results, less is known and for large $k$ the best may still be $1-2/(k+1)$ (the analog of the $1/3$ exponent in the usual circle and divisor problems).   You can look at Chapter XII in Titchmarsh's book (and Heath-Brown's notes) for the $k$-divisor problem, and also look at Vaughan or Nowak for more information and other references.  For example, Vaughan notes that for cubic fields the exponent $43/96$ is known in the $O$-result, and is due to Muller.


text:
Q: Place map above another view Swift UI I want the map to be above the bottom-slider always Whenever the bottom-slider move up the map go with it and adjust always stay above it.
This is my code, Btw I started a swift today
 var body: some View {
ZStack(alignment: Alignment.top) {
        MapView()
     // From here I want the MapView which is google maps above the SlideOverCard
        SlideOverCard {
            VStack {
                Text("Whatever")
                    .font(.headline)

            }.frame(width: 1000)
        }
    }
    .edgesIgnoringSafeArea(.vertical)
}

A: You can give either .zIndex or change the order of views in ZStack(the latest will be the top-most)
A)
ZStack(alignment: Alignment.top) {
        MapView().zIndex(1)         // by default all views has 0
        SlideOverCard {

B)
ZStack(alignment: Alignment.top) {
        SlideOverCard {
            // ... other code here
        }
        MapView()      // will be above
}


text:
Q: When displaying MDI child, the child form is cut off at the top I have a problem with a Winforms application written in VS2012(C#).
I am posting it here after lots of research and attempts with no luck.
I have 2 MDI child forms and one parent form which I use to switch between them.
After loading child1 the 1st time, the MDI form looks like it was pushed up and the top part of it is hidden and cannot be seen; this problem is resolved after the 2nd click.
This is the source of child1 which is the same code for child2
public partial class Child1 : Form
{
    public Child1()
    {
        InitializeComponent();
        panel1.Dock = DockStyle.Top;
        StationFormUtils.SetPanelHeaderDefinitions(panel1);
    }

    private void Child_Load(object sender, EventArgs e)
    {
        //removes the child bar
        this.MaximizeBox = false;
    }
}

public static void SetPanelHeaderDefinitions(Panel panel)
{
    panel.Size = new System.Drawing.Size(BaseClass.StationTableWidth, BaseClass.StationHeaderHeight);
    panel.BackgroundImage = global::TestMdi.Properties.Resources.StationHeaderStrip;
    panel.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Tile;
}

And this is the source code for the parent:
public partial class Form1 : Form
{
    private Child1 ChildMainFrm1 = new Child1();
    private Child2 ChildMainFrm2 = new Child2();
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ChildMainFrm1.MdiParent = this;
        ChildMainFrm1.WindowState = FormWindowState.Maximized;
        ChildMainFrm1.Show();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        ChildMainFrm2.MdiParent = this;
        ChildMainFrm2.WindowState = FormWindowState.Maximized;
        ChildMainFrm2.Show();
    }
}

Does anyone know what am I doing wrong or what am I missing?


text:
Q: Create column o difference between two pandas DF I have firstDF:
rs     Chr      MapInfo         Name       SourceSeq
1       A1       B1              C1          D1
2       A2       B2              C2          D2
3       A3       B3              C3          D3
4       A4       B4              C4          D4
5       A5       B5              C5          D5

And secondDF:
Chr       MapInfo     Name    SourceSeq       Unnamed: 0       rs
 1          A1          B1        C1             D1            E1
 4          A4          B4        C4             D4            E4
 8          A8          B8        C8             D8            E8
 10         A10         B10       C10            D10           E10

I need to create a new data frame contains only rows from secondDF which does not exist in first:
newDF:
Chr       MapInfo     Name    SourceSeq       Unnamed: 0       rs
8          A8          B8        C8             D8            E8
10         A10         B10       C10            D10           E10

I want filter it by Name. What will be better way to do that?
I trough about a fullouter merge but the cols are different and honestly I don't know how to do it proper.
Second, think was a loop but it's not efficient.
And last I tried do ith by:
new= secondDF[~firstDF.Name.isin(secondDF.name)]

but i got:

IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match

Can someone give me advice about that task?

A: Solution is change mask - compare secondDF.Name by column from firstDF, from sample data it is MapInfo column, in real data seems Name column for boolean mask with same size and index values like secondDF, because is filtered secondDF DataFrame:
new= secondDF[~secondDF.Name.isin(firstDF.MapInfo)]
print (new)
   Chr MapInfo Name SourceSeq Unnamed: 0   rs
2    8      A8   B8        C8         D8   E8
3   10     A10  B10       C10        D10  E10


text:
Q: Setting Working Directory using knitr::opts_knit I am trying to use the code below to change the working directory in R markdown (using the R setup chunk). However, this doesn't seem to be working. The output from getwd() after running this chunk remains as the directory containing the R script. I've never had this issue before; any ideas of where I'm going wrong? Thank you!
```{r setup}
library(foreach)
library(stringr)
library(rmarkdown)
library(knitr)

knitr::opts_knit$set(root.dir = normalizePath('/Users/chantal/Documents/PhD/Projects/'))
getwd()
```

A: Based on this answer I believe that if you check getwd() in the next chunk, you should see that the working directory has changed. This is something I tried and it appears to corroborate Tomas' comment.
---
title: "test"
author: "Roman Luštrik"
date: "`r Sys.Date()`"
output: html_document
---

```{r setup, include=TRUE}
knitr::opts_knit$set(echo = TRUE, root.dir = normalizePath("/home/romunov/Downloads"))
getwd()
```

```{r}
getwd()
```


text:
Q: regular expression in freemarker to check if first character in a string is lower case I am using freemarker to generate a Java class. I am stuck to convert a first character of a string to lower case.
Following is what i tryed but no luck :(
    <#function methodName attName >
      <#if attName?length > 1 >
        <#if  attrName(0)?matches([a-z])>
          <#return attName>
       </#if>
      </#if>
    </#function>

Thanks.

A: Try uncap_first:
${"Test"?uncap_first} yields test


text:
Q: Probability that minimum of two numbers is less than 4 Suppose I have to choose two numbers from set $$S=\{1,2,3,4,5,6 \}$$ without a replacement , then what is the probability that minimum of two is less than $4$?
I made two groups for this problem $A= \{1,2,3 \}$ and $B=\{4,5,6 \}$
.There are two possibilities , either both are from $A$ or one from $A$ and one from $B$ to satisfy our requirement. Hence
$$P(E)=\frac{3}{6}.\frac{2}{5} + \frac{3}{6}.\frac{3}{5}$$
but answer is incorrect. Help?

A: The probability $P$(minimum is $ \lt 4)$ is
$1 - P($ minimum is $\geq 4 ) = 1 - P($ both choices are from $A$ $)$.
The probability that both choices are from $A$ is $\frac{3}{6} \cdot \frac{2}{5}=\frac{1}{5}$.
Thus, the probability you're looking for is $\frac{4}{5}$.

A: We have $\binom{6}{2}$ possibilities, but $\binom{3}{2}$ of them are not what we want, more precisely, those events that 2 elements are chosen from $\{4,5,6\}$, hence, $P(E)=\frac{\binom{6}{2}-\binom{3}{2}}{\binom{6}{2}}$.

A: It is easy as P.I.E.. Use the Principle of Inclusion and Exclusion.
$$\begin{align}
\mathsf P(\min(X,Y) < 4) & = \mathsf P(X < 4)+\mathsf P(Y < 4)- \mathsf P(X< 4 \cap Y< 4)
\\ &= \frac 3 6 + \frac 3 6 - \frac 3 6\cdot\frac 2 5
\\ & = \frac 4 5
\end{align}$$
Or you can use the Law of Complements
$$\begin{align}
\mathsf P(\min(X,Y) < 4) & = 1- \mathsf P(X \geq 4 \cap Y\geq 4)
\\ &= 1 - \frac 3 6\cdot\frac 2 5
\\ & = \frac 4 5
\end{align}$$
Or by your method (the Law of Total Probability), but remembering that there are two ways for one pick to be in A and the other in B.
$$\begin{align}
\mathsf P(\min(X,Y) < 4) & = \mathsf P(X < 4 \cap Y\geq 4)+\mathsf P(X \geq 4 \cap Y< 4) + \mathsf P(X< 4\cap Y< 4)
\\ & = \frac 3 6\cdot\frac 3 5 +\frac 3 6\cdot\frac 3 5 +\frac 3 6\cdot\frac 2 5
\\ & = \frac 4 5
\end{align}$$

A: The error with your approach is that "One from $A$ and one from $B$" has two ways of happening: $A$ then $B$, or $B$ then $A$. So you need to multiply your calculation of this case by 2.
$$P(E) = \frac{3}{6} \cdot \frac{2}{5} + 2 \cdot \frac{3}{6} \cdot \frac{3}{5} = \frac{4}{5}$$


text:
Q: How to zoom in and out on a stage in libgdx Scene2d? I am making a 2d game using libgdx and am adding hexagon shaped actors to a group which is then added to a stage. For a normal camera you can use camera.zoom in the render method to zoom in and out along with camera.translate to pan around the world.
I have been getting the camera used by the stage using stage.getCamera() and I can still call stage.getcamera().translate however there is no stage.getCamera().zoom option.
Here is my code:
//import statements

public class HexGame implements ApplicationListener{

private Stage stage;

private Texture hexTexture;
private Group hexGroup;

private int screenWidth;
private int screenHeight;

@Override
public void create() {

    hexTexture = new Texture(Gdx.files.internal("hex.png"));

    screenHeight = Gdx.graphics.getHeight();
    screenWidth = Gdx.graphics.getWidth();

    stage = new Stage(new ScreenViewport());

    hexGroup = new HexGroup(screenWidth,screenHeight,hexTexture);

    stage.addActor(hexGroup);
}

@Override
public void dispose() {
    stage.dispose();
    hexTexture.dispose();
}

@Override
public void render() {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();

    handleInput();
    stage.getCamera().update();

}

private void handleInput() {

    if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
        stage.getCamera().translate(-3, 0, 0);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
        stage.getCamera().translate(3, 0, 0);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
        stage.getCamera().translate(0, -3, 0);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.UP)) {
        stage.getCamera().translate(0, 3, 0);
    }

    //This is the part that doesn't work
    /*
    if (Gdx.input.isKeyPressed(Input.Keys.Z)) {
        stage.getCamera().zoom += 0.02;
    }
    */

    }

@Override
public void resize(int width, int height) {
    stage.getViewport().update(width, height);
}

@Override
public void pause() {
}

@Override
public void resume() {
}

}

Any help is appreciated, and if there is anything else wrong with my code please let me know, I'm new to libgdx. Thanks

A: Zoom is available in OrthographicCamera class and by default Stage class create a OrthographicCamera
/** Creates a stage with a {@link ScalingViewport} set to {@link Scaling#stretch}. The stage will use its own {@link Batch}
     * which will be disposed when the stage is disposed. */
    public Stage () {
        this(new ScalingViewport(Scaling.stretch, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), new OrthographicCamera()),
            new SpriteBatch());
        ownsBatch = true;
    }

So what you need is to cast your camera to OrthographicCamera:
((OrthographicCamera)stage.getCamera()).zoom += 0.02f;


text:
Q: Fastest way of checking if a number is within a range What is the easiest way of checking if a number is within a range, besides
if (Enumerable.Range(1,100).Contains(number))
//true

if (x >= 1 && x <= 100)
//true

these ways? Something perhaps more effective?

A: There's nothing more efficient than the second option. You could write an extension:
public static class NumberExtensions
{
    public static bool IsWithinRange<T>(this T number, T rangeStart, T rangeEnd) where T : IComparable<T>
    {
        return number.CompareTo(rangeStart) >= 0 && number.CompareTo(rangeEnd) <= 0;
    }
}

Now the code is readable and efficient:
if (x.IsWithinRange(1, 100))
{

}

A: The first (LINQ) option is horribly inefficient. The second option (just check with inequality operators) is fine. In the general case when you have multiple ranges, you can use the new switch improvements:
    switch(number)
    {
        case var n when n >= 1 && n <= 100:
            // ...
            break;
        case var n when n > 100:
            // ...
            break;
        default:
            // ...
            break;
    }


text:
Q: How to redirect System.out to Play Logger? So I have a library that I am using in my project that uses System.out for logging and I want all of my logging to be standardized in the play logger (play.Logger). So, I was wondering if there is a way of redirecting the System.out to the Play Logger say at the debug level?
Maybe by changing System.out to use a different stream?
Notes:
My Play logger is configured to use the following appenders:
ch.qos.logback.core.ConsoleAppender
ch.qos.logback.core.FileAppender

I think the library only calls System.out.println(String)

A: Use following snippet:
    System.setOut(new PrintStream(new OutputStream() {
        StringBuilder sb = new StringBuilder();

        @Override
        public void write(int b) throws IOException {
            if (b == '\n') {
                writeStringToActualLogger(sb.toString());
                sb = new StringBuilder();
            } else {
                sb.append((char) b);
            }
        }
    }));

Keep in mind that it only works with ASCII.
You have to implement writeStringToActualLogger to write string to your logger.


text:
Q: In LuaLaTeX, how do I pass the content of an environment to Lua verbatim? In LuaLaTeX, how would I go about capturing the content of an environment for (verbatim) processing by Lua? For example, consider something like
\begin{foobar}
  Hello {World}
\end{foobar}

I'd like to be able to take the content of the environment and pass it to Lua, as in
foobar("  Hello {World}\n")

(and Lua would then eventually pass the processed version back to LaTeX, but I can presumably handle that).

A: A bit late to the party, but this fix to https://tex.stackexchange.com/users/243/topskip's answer does the job:
in response to question in comments:
In topskip's answer Hello World is still written to the pdf file, which is not typically what one would want.  So I've taken his answer and made the change that if the line read does not contain "\end{foobar}" then nothing is returned to the tex interpreter, but if it does contain "\end{foobar}" it gets spit back (via the nil return value) to the tex interpreter which then ends the foobar environment.  If the "\end{foobar}" line would not get returned then tex would never end the environment, which is clearly not what you want.
The example is still imperfect in that it doesn't give the desired result if there is text before "\end{foobar}" on the same line.
\documentclass{article}
\usepackage{luacode}
\begin{luacode*}
do
  local mybuf = ""
  function readbuf( buf )
   print("buf=" .. buf)
    i,j = string.find(buf,"\\end{foobar}")
    print(i,j)
    if i==nil then
     mybuf = mybuf .. buf .. "\n"
     print("[" .. mybuf .. "]")
     return ""
    else
    return nil
    end
   end

  function startrecording()
    luatexbase.add_to_callback('process_input_buffer', readbuf, 'readbuf')
  end

  function stoprecording()
    luatexbase.remove_from_callback('process_input_buffer', 'readbuf')
    local buf_without_end = mybuf:gsub("\\end{foobar}\n","")
    print(string.format("Lua: %s", buf_without_end))
  end
end
\end{luacode*}

\begin{document}
  \newenvironment{foobar}{\directlua{startrecording()}}{\directlua{stoprecording()}}
\begin{foobar}
    Hello {World}
\end{foobar}

\end{document}

A: Start the "recording" mode when you enter \begin{foobar} and end it when you close the environment. That way you get the pure buffer contents.
\documentclass{article}
\usepackage{luacode}
\begin{luacode*}
do
  local mybuf = ""
  function readbuf( buf )
    mybuf = mybuf .. buf .. "\n"
  end
  function startrecording()
    luatexbase.add_to_callback('process_input_buffer', readbuf, 'readbuf')
  end

  function stoprecording()
    luatexbase.remove_from_callback('process_input_buffer', 'readbuf')
    local buf_without_end = mybuf:gsub("\\end{foobar}\n","")
    print(string.format("Lua: %q", buf_without_end))
  end
end
\end{luacode*}
\begin{document}
  \newenvironment{foobar}{\directlua{startrecording()}}{\directlua{stoprecording()}}
\begin{foobar}
    Hello {World}
\end{foobar}

\end{document}

A: In ConTeXt, you can simply use buffers for this.
\def\startfoobar
    {\definebuffer[foobar][startfoobar][stopfoobar]}

\def\stopfoobar
    {\ctxlua{userdata.luafunction(buffers.getcontents('foobar'))}

The function userdata.luafunction will then receive the contents of the environment.
See the ConTeXt wiki for more examples.


text:
Q: Can't run flutter build from Jenkins I tried to run a flutter build from jenkins using the following pipeline code :
pipeline {
    agent any

    stages {
        stage('build') {
            steps {
                bat 'C:\\path_to_doc\\flutter_dev\\flutter\\bin\\flutter.bat build web -t "C:\\path_to_doc\\lib\\src\\main\\main.dart"'
            }
        }
    }
    post{
        always {
            archiveArtifacts artifacts: 'C:\\path_to_doc\\build\\web\\index.html', fingerprint: true, followSymlinks: false
        }
    }
}

I got this error in jenkins :

I tried to write the flutter build code in a bat file in the root of my flutter project, and then execute this file on the pipeline code, got the same error.
What is the correct way to proceed to avoid this error ?

A: Jenkins has a habit of reverting to the initial workspace directory for each separate command. Try setting the directory after your steps{ line:
dir('C:\\path_to_doc\\flutter_dev\\flutter\\bin\\') {
    bat 'flutter.bat build web -t "C:\\path_to_doc\\lib\\src\\main\\main.dart"'
}

This will ensure that your script will run in this location. So if your pubspec.yaml is in this location, it should be able to find it. In any case, this is a problem with the directory, so if this doesn't work, some manual debugging would be necessary to see what went wrong.


text:
Q: I cant add a data into the sql via EF (Non static method requires a target) In my MVC project, Im tryna add a bike to my db, but i cannot.
Here's my code:
public override ServiceResult New(Bike entity)
    {
        var bike = repository.Select(x => x.Brand == entity.Brand && x.Model == entity.Model);
            if (bike.Any())
            {
                return new ServiceResult(ServiceResultCode.Generic, "This bike is already exists.");
            }
                return base.New(entity);
    }

And let me show you other connected classes and maybe you'll get that where the wrong part is.
Here is my GenericRepository class.
 public virtual IEnumerable<T> Select(Expression<Func<T, bool>> Filter = null)
    {
        if (Filter != null)
        {
            return _dbSet.Where(Filter);
        }
        return _dbSet;
    }

when i press the add button. It's like "Dude stop, you dont know what you're trying!" Like a guardian. Maybe a little help?

A: First up, if this is your first foray into Entity Framework, start simple before trying to delve into things like repository patterns. IMHO while a repository pattern is very useful for isolating your domain from your logic to test that logic, the Generic repository pattern is an anti-pattern.  Immediately the first problem is returning IEnumerable<T>, to maintain the benefit of EF with Linq expressions, repositories should return IQueryable<T>.
public virtual IEnumerable<T> Select(Expression<Func<T, bool>> Filter = null)
{
   if (Filter != null)
       return _dbSet.Where(Filter);
   return _dbSet;
}

vs.
public virtual IQueryable<T> Select(Expression<Func<T, bool>> Filter = null)
{
   if (Filter != null)
       return _dbSet.Where(Filter);
   return _dbSet;
}

Both methods appear to work, but they do two completely different things. Both methods will triggered a deferred execution for the query when you execute the .Any() statement, however when you return IEnumerable<T>, the query will execute as effectively a SELECT * FROM [T] where if you return IQueryable<T> the query will execute as a SELECT CASE WHEN EXISTS essentially running a query to just return whether a row exists or not. Any operation you use, the first example will always be doing a SELECT * where the second has the opportunity to generate more efficient and precise queries.
To start narrowing down the root of your problem though, start simple with just the DbContext and the entities. Generally it's not a good idea to pass entities around between client and server as it exposes your schema and generally passes more information than the client needs to display. It also leads to lazy load hits when serializing or potentially errors/#null data with cyclic references or if lazy loading is disabled to get around these problems. Data coming from a client should also never be trusted, so any code that might attach a passed in entity set state to Modified and save to the database risks harmful data injection attacks.
But looking at your original example, start by reducing it down to the simplest possible thing without getting dug right in to repositories and inheritance:
public override ServiceResult New(Bike entity)
{
    using (var context = new ApplicationContext())
    {
        var bikeExists = context.Bikes.Any(x => x.Brand = entity.Brand
            && x.Model == entity.Model);
        if (bikeExists)
            return new ServiceResult(ServiceResultCode.Generic, "This bike is already exists.");

        var newBike = new Bike
        {
            Brand = entity.Brand,
            Model = entity.Model,
            // Copy over only data you trust after validating it.
        };
        context.Bikes.Add(newBike);
        context.SaveChanges();
        return new ServiceResult(ServiceResultCode.Success, "Bike added.");
    }
}

If that works, then re-factor to reintroduce common base class functionality, repositories, etc. This will help identify where/what elements are tripping you up. Writing code to best practices is something I recommend that developers re-factor code towards rather than try to write from scratch especially when starting out with unfamiliar technologies. Often the attempts to write efficient code make problems harder to identify and fix. The end goal would be to reintroduce a repository, a unit of work, and a view model for communication between client and server. It would end up looking something like:
public override ServiceResult New(NewBikeViewModel newBike)
{
    using (var contextScope = ContextScopeFactory.Create())
    {
        var bikeExists = BikeRepository.Bikes.Any(x => x.Brand = newBike.Brand
            && x.Model == newBike.Model);
        if (bikeExists)
            return new ServiceResult(ServiceResultCode.Generic, "This bike is already exists.");

        var bike = BikeRepository.Create(newBike.Brand, newBike.Model);
        // Can fill in any optional details from the view model into bike here.
        contextScope.SaveChanges();
        return new ServiceResult(ServiceResultCode.Success, "Bike added.");
    }
}

NewBikeViewModel represents a model from the view containing the data to identify a new bike. I utilize a Unit of Work pattern called Mehdime DbContextScope which coordinates a context scope between business logic (controllers) and repositories. The repository locates it's scope (throwing an exception if you call it outside of one) and uses that to get the DbContext. Context Scopes or Units of Work are nice because they form a boundary for committing changes. The issue with something like a DbContext being injected and limited to a lifetime scope such as the request is that it is all or nothing for everything. Any change that attempts to commit in the context and fails remains associated to that context and will prevent that context from saving anything else. The BikeRepository is not a Generic repository, it is a repository that services bikes. This includes retrieving data, but also creating data. It serves as a factory for Bikes to ensure that all required information is passed in. It is also in the position to ensure that any references to other entities can be set up to ensure that a new Bike is always returned in a complete enough state. Create takes parameters for all required fields/references. Any optional data can be filled in afterwards before the changes are saved.   This is only an example of the patterns I use, the key thing is to start with the simplest thing then move towards the target structure you want to adopt.


text:
Q: A property of uncountable almost disjoint families Let $\mathcal{A}$ be an uncountable almost disjoint family (not necessarily maximal) of infinite subsets of $\mathbb{N}$. Denote by $\mathcal{A}_{\subseteq}=\{ B\subseteq\mathbb{N}:|B|=\omega \wedge \exists A\in\mathcal{A}(B\subseteq A) \}$.
Question 1: Must there exist a $B\in\mathcal{A}_{\subseteq}$ such that for any $n$, $\{C\in\mathcal{A}:|C\cap B|\geq n\}$ is uncountable?
If this is true, then:
Question 1':  Must there exist a $B\in\mathcal{A}_{\subseteq}$ such that for any $n$, $\{C\in\mathcal{A}:B\upharpoonright n\subset C\}$ is uncountable? (By $B\upharpoonright n$, I mean the first $n$ elements of $B$ listed in increasing order.)
I don't have an intuition as to whether this should be true or false, but the question stems from the observation that for any uncountable family $\mathcal{A}$ of subsets of $\mathbb{N}$, there is an $n\in\mathbb{N}$ such that $\{A\in\mathcal{A}:n\in A\}$ is uncountable.
EDIT: As seen in the solutions below, the passage to $\mathcal{A}_{\subseteq}$ is unnecessary.
EDIT: In light of the positive answer to the questions above, I'll add an additional question that I am interested in.
Question 2: Must there be a sequence $(A_n)_{n\in\omega}$ of distinct elements of $\mathcal{A}$ (or elements of $\mathcal{A}_{\subseteq}$ which are below pairwise distinct elements of $\mathcal{A}$) such that for any $n$, $\{B\in\mathcal{A}:\forall i\leq n(A_i\upharpoonright n\subset B)\}$ (or $\{B\in\mathcal{A}:\forall i\leq n(A_i\upharpoonright n-i\subset B)\}$) is uncountable. (Again, $A \upharpoonright n$ means the first $n$ elements of $A$ listed in increasing order, it does not mean the elements of $A$ below $n$ here.)

A: Yes to both: Just take a condensation point $A$ of $\mathcal{A}$. This means every clopen neighborhood of $A$ contains uncountably many members of $\mathcal{A}$.

A: For any finite $M\subset {\mathbb N}$ which is contained in at most countably many sets from  $\mathcal{A}$ we just remove them all out from  $\mathcal{A}$ . Now any finite subset of any of our sets is contained in uncountably many sets.


text:
Q: Azure AD: I need to change a Company wide setting, but apparently that's impossible? I need to change a setting in Azure to allow for Email Verification. MS documentation states that I have to get into azure's powershell and run Set-MsolCompanySettings -AllowEmailVerifiedUsers. I found this, however, to be apparently impossible?
In order to do this, I have to use before: Connect-MsolService, which gives me this error:

Connect-MsolService: Could not load file or assembly
'System.IdentityModel, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'. The system cannot find the file
specified.

And from what I read, Azure's Powershell does not allow for this?? How am I supposed to run that command?
Thanks in advance, any clue is welcome at this point

A: We have did a repro in our local environment, below statements are based on the repro analysis.
I have tried connecting to msolservice & successfully  enabled the company setting " AllowEmailVerifiedUsers" in my local machine that is running with PowerShell version 5.1
Set-MsolCompanySettings -AllowEmailVerifiedUsers $true

Here is the output

I have tried running the same company  setting cmdlet in PowerShell core version 7 it is failing with same error that you have mentioned above.

Based on this GitHub , we understood that currently MSOnline module version v1 is too old and it is not supported in PowerShell core 7.
We would suggest you use the PowerShell version 5.1 to enable company setting using MsolOnline module.


text:
Q: Trouble 301 redirecting pages from old Wix site to new site My client's original site was built on Wix, and I have designed and built a new one on a new server.
I'm trying to 301 redirect some pages from the old site to their counterparts on the new one, and it doesn't seem to want to work properly, as each old URL simply goes straight to the home page.
Example case:
old URL: example.com/#!clients/c1pen
new URL: example.com/stay-with-us
I have the redirect set out like so in .htaccess:
Redirect 301 /#!clients/c1pen /stay-with-us
Can anyone shed some light on this for me?

A: Hash-location (http://someurl/#hash-location) typically adresses an anchor in a html page and is not visible to the server rewrite rules. Consequently the matcher #!clients/c1pen does never match. See 'hash' url rewrite in .htaccess


text:
Q: C - Replace "No such file or directory" message I'm trying to make a shell that whenever it can't execute a command it says "Error executing binary: -nameOfBinary-". But the thing is that it always gives me the message "No such file or directory".
Heres part of my code:
void handle_SIGINT() {
  write(STDOUT_FILENO,line,strlen(line));
  printf("\n");
  struct sigaction handler;
  handler.sa_handler = handle_SIGINT;
  sigaction(SIGINT, &handler, NULL);
}

void runcommand(char* argv[]) {
  int p =fork();
  if(p==0) {
    struct sigaction handler;
    handler.sa_handler = SIG_IGN;
    sigaction(SIGINT, &handler, NULL);
    execvp(argv[0],argv);
    perror("Error executing binary");
    exit(1);
  } else {
    wait(NULL);
  }

}
With the code as it is it always gives me the message "Error executing binary: No such file or directory" which is close to what I want!
How can I fix it?
Thanks in advance!

A: The function perror() prints the string you supply, a colon and a space, and then adds the string corresponding to the current value of errno (ENOENT or 'No such file or directory' in your case) and a newline.  If that's not the message you want, you have to write and call your own error reporting function.
You can cheat and simply use:
perror(argv[0]);

which will give you something like:
name-of-binary: No such file or directory

or you can write your own:
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void err_syserr(const char *fmt, ...)
{
    int errnum = errno;
    va_list args;
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    if (errnum != 0)
        fprintf(stderr, "%d: %s\n", errnum, strerror(errnum));
    putc('\n', stderr);
    exit(EXIT_FAILURE);
}

and then call it:
err_syserr("Error executing binary: %s: ", argv[0]);

Since the function calls exit(), it could be decorated with _Noreturn to indicate that it does not return, and you don't need the exit(1); in the calling code.
There are those who argue that printing the error number as well as the message is A Bad Thing™ but (as you can guess) I don't agree for most of the work I do.  It might matter in web-facing code, but this isn't likely to be web-facing code.


text:
Q: How to close any application with close sign symbol in javascript function back(){

  document.getElementById("xbox").addEventListener("click",closePage);

    function closePage(){
        window.close()
    }
}

i am using this code for closing the application which i have connected to html page in button "oncliick="back()" "
I was trying to close the application with above code but it is getting close but on second click of the mouse . and i want it to be close on first click of mouse.


text:
Q: Ubuntu: Resize the root LVM(2?) partition I have an Ubuntu virtual machine running in VirtualBox 2.2.4, and I created it on an 8gb virtual disk which is too small.
So, I am trying to increase the size of the disk.  So far, I have done this:

*

*Created a new larger virtual disk

*Added the 2nd disk to the machine

*Used CloneZilla to clone the first disk onto the 2nd disk

*Removed the first disk

*Booted up off the 2nd (larger disk)

But now I'm still stuck with an 8gb partition on my new 100gb virtual disk.
Whats the easiest path from here to having a 100gb partition? :) I gather GPart can resize partitions, but it doesn't seem to support LVM2 partitions, which mine seems to be.
thx

*

*Alex

A: In general, here's how to resize LVM volumes:
Let's say /mountpoint is on /dev/VolGroup00/mountpoint. You can find this out by checking out /etc/fstab or by running mount -l.
You may also need to resize the actual Physical Volume, depending on your setup. Use pvdisplay to find out if it's big enough, and use pvresize (much like lvresize below) if necessary.
umount /mountpoint
lvresize -L +<HOW MUCH BIGGER> /dev/VolGroup00/mountpoint
e2fsck -f /dev/VolGroup00/mountpoint
resize2fs /dev/VolGroup00/mountpoint <TOTAL SIZE>
mount /mountpoint

This amounts to umounting, resizing the underlying LVM, then resizing the actual ext3 partition.
A few things to be careful of:

*

*Obviously playing with / will be different from a data partition. You may need a boot disk such as Sysrescuecd instead of Doing It Live. Also see Kristof's comment below -- you may actually be able to do this without unmounting /.

*lvresize has a few different syntax options, and reducing a logical volume will probably harm the overlaying partition. Consult your local man pages for more information.

A: There was one (and only one) way I found to do this and I tried a myriad.
First, clone the ubuntu guest VM in virtualbox by right-clicking it and going to "clone". Once the clone is finished then extend the cloned vdi by using (On the host OS)
VBoxManage modifyhd "name_of_cloned_vdi" --resize "size_of_new_root_partition_in_MB"
Then - follow the steps in this post to the letter (he refers to VMware as a platform but ignore that)
http://blog.campodoro.org/?p=36
This will create another lvm exactly equivalent in size to the extra space you have added and tack it onto the end of the existing one.
Once you have checked all is good, then you can delete the original VM and promote your clone!
No need to mess about with fdisk and worry about deleting or screwing up the wrong partition.
I must have broken about 4 cloned OS's until I found this solution!

A: I just did this and had the same question you had, but instead of creating a new LVM and adding it to the volume group, the OCD side of me wanted to resize my current LVM and thus keeping a single partition in the name of simplicity. Note: I don't believe this is possible if the free space does not immediately follow the partition you are resizing!
In order to do so you'll need a tool that can delete and create partition tables. Since I use GPT this meant I needed gdisk. You will also need to do this with the partition unmounted, so you may want to boot to an Ubuntu LiveCD and run this from there.
The following steps in bold are for an example LVM /dev/mms/root on device /dev/sda, where I wanted to expand partition /dev/sda3 to occupy my newfound free space.
NOTE: These are potentially very destructive, so make sure your inputs are correct!

*

*gdisk /dev/sda (make sure to enter the correct device! ) This brings you into gdisk where you can then perform the following steps in order

*

*p  -- prints out your current partition information (for reference)

*d  -- for deleting a partition table

*3  -- the device number representing the partition table you wish to delete (important!)

*n  -- for creating a partition table

*3 -- the device number representing the partition table you wish to create (you'll probably want to use the same as you deleted in step 3)

*p  -- prints out your current partition info (again for reference, compare it to what you started with!)

*w  -- saves your changes to disk (are you sure?!)

*pvresize /dev/sda3 -- you may have to reboot prior to doing this so your OS recognizes the new partition size

*pvdisplay -- prints out your current info (it should show that it's using the full space now!)

*lvresize -l +100%FREE /dev/mms/root -- resizes my LVM to occupy 100% of my newfound space

*e2fsck -f /dev/mms/root -- performs an integrity check

*resize2fs -p /dev/mms/root -- resizes the file system to occupy your full LVM

After doing the above and restarting into the resized OS, everything worked as expected and I had all of my additional freespace at my disposal!
Additional references which I used to figure this all out:
http://www.jethrocarr.com/2012/08/10/gdisk-oh-glorious-gdisk/
http://people.virginia.edu/~ll2bf/docs/quickref/lvm.html

A: See a related answer here.
(excerpt)
Resizing physical volume:
pvresize --verbose --test /dev/md0

Resizing logical volume:
lvresize --verbose -L <SIZE> --test /dev/VG1/LV1

And finally, resizing ext3 FS:
resize2fs /dev/VG1/LV1

A: Note that you don't actually need to use a clone tool like CloneZilla here, you can put a partition on the new virtual disk (optional) then initialize that (or the virtual disk itself) into LVM using the pvcreate command. Then use vgextend to add that to the volume group supporting your logical volume, then use vgreduce to remove the original virtual disk from the volume group. This will perform a migration, and it can be done live while the logical volume is in use, this is the beauty of storage virtualization. Once it's finished you just need to extend the logical volume as above, which could also be done live with more modern filesystems than ext3.

A: I. If your virtual HDD has a fixed size, you cannot make it bigger. In this case you have to clone it first.
(1) Clone the HDD over the VB GUI: File -> Virtual Media Manager... -> [tab] Hard Drives -> select your HDD -> [button] Next -> [button] Next -> select "Dynamically allocated" on the step "Storage on physical hard drive"-> ...
or on the command line:
# VBoxManage clonehd "/path/to/the/HDD.vdi" "/path/to/the/HDD_NEW.vdi"

(2) Add the new HDD to the list of the known HDDs.
(3) In the VB machine settings remove the old HDD from the VDI list under the Controller and add the new on instead.
II. Resize the HDD
(1) Resize the new HDD.
# VBoxManage modifyhd 463c7bd4-9b9c-4cf8-bee4-e14e10c0d462 --resize 25600

You get the key with the VBoxManage list hdds command.
III. Add new allocated space.
(1)  Add a GParted ISO as new medium under Machine Settings -> Storage -> [rightclick] Controller IDE -> Add CD / DVD Device -> ... and select the Live CD/DVD checkbox.
(2) Start the VM and add the not allocated free space to your work partition.
(3) Stop the VM.
(4) Detach the GParted ISO.
Enjoy! :)

A: Check out this other serverfault question's answer, How do you increase a KVM guest's disk space?. The technique used to increase the LVM partition in this KVM guest is similar to what you're trying to accomplish.

A: When resizing LV2 partition, this reference helped me a lot:
http://people.virginia.edu/~ll2bf/docs/quickref/lvm.html
Notice, that you don't need to use any live cd, you may do the resize on the mounted, live system, resizing on the fly.


text:
Q: XSRF and double submit cookie JWT alternative - is this implementation safe? I was looking into HTTP security for my REST API and I was hoping to make it more secure by using the Double Submit Cookie pattern but I'm pretty sure that I'm actually doing something similar already (totally by accident).
This is my flow:

*

*Client makes a POST request to server with username and password.

*Server responds with a JWT token.

*Client saves the token into a cookie.

*On subsequent requests the client reads the token cookie and places the token into the Authorization header (I'm pretty sure that this step is equivelent to the double cookie submit technique).

*The server authenticates the user based on a valid token in the authorization header.

Now this isn't 100% equivelent as the server isn't checking that the cookie and HTTP header match (this would be trivial to add if I needed to).
Is what I have so far sufficient to block a XSRF attack or should I go with adding a XSRF-TOKEN cookie too?

A: I think you might be secure against XSRF attacks, but the way it sounds, you are not secure against XSS attacks. For protection against XSS attacks you need to also store a secret in a HttpOnly cookie.


text:
Q: "getAvailableIDs()" in TimeZone class of Android is not supporting 'SystemV' and many abbreviated TimeZones
For compatibility with JDK 1.1.x, some other three-letter time zone
  IDs (such as "PST", "CTT", "AST") are also supported.

This is what Android Developer Document for TimeZone says . But the method getAvailableIds() is not returning those abbreviations . Which means TimeZone class in Android is not supporting such abbreviations.
Following timezones ids are not supported by Android whereas they are supported in JDK 1.8 :

SystemV/AST4
  SystemV/AST4ADT
  SystemV/CST6
  SystemV/CST6CDT
  SystemV/EST5
  SystemV/EST5EDT
  SystemV/HST10
  SystemV/MST7
  SystemV/MST7MDT
  SystemV/PST8
  SystemV/PST8PDT
  SystemV/YST9
  SystemV/YST9YDT
  US/Pacific-New
  ACT
  AET
  AGT
  ART
  AST
  BET
  BST
  CAT
  CNT
  CST
  CTT
  EAT
  ECT
  IET
  IST
  JST
  MIT
  NET
  NST
  PLT
  PNT
  PRT
  PST
  SST
  VST

Why is it so ?


text:
Q: OutOfMemoryError , Google Direction API (ANDROID) I was using my google maps app successfully and it works perfectly fine from all respect. but when i tried to get direction from two too far distance places it crashed and gave a OutOfMemoryError to me.

*

*The places for which i was getting direction is-
Source      - magadan russia
Destination - cape point south africa

*My Logcat
Throwing OutOfMemoryError "Failed to allocate a 28 byte allocation with 0 free bytes and 0B until OOM" (recursive case)
04-06 16:42:41.423 4871-4871/com.afixi.prasenjeetpati.googleapi E/art: "main" prio=5 tid=1 Runnable
04-06 16:42:41.423 4871-4871/com.afixi.prasenjeetpati.googleapi E/art:   | group="main" sCount=0 dsCount=0 obj=0x744132c0 self=0xb8a7efc0
04-06 16:42:41.423 4871-4871/com.afixi.prasenjeetpati.googleapi E/art:   | sysTid=4871 nice=0 cgrp=default sched=0/0 handle=0xb6fb4ec8
04-06 16:42:41.423 4871-4871/com.afixi.prasenjeetpati.googleapi E/art:   | state=R schedstat=( 13237478608 1327768343 8667 ) utm=1243 stm=80 core=2 HZ=100
04-06 16:42:41.423 4871-4871/com.afixi.prasenjeetpati.googleapi E/art:   | stack=0xbe1b7000-0xbe1b9000 stackSize=8MB
04-06 16:42:41.423 4871-4871/com.afixi.prasenjeetpati.googleapi E/art:   | held mutexes= "mutator lock"(shared held)
04-06 16:42:41.423 4871-4871/com.afixi.prasenjeetpati.googleapi E/art:     at java.lang.AbstractStringBuilder.toString(AbstractStringBuilder.java:636)
04-06 16:42:41.423 4871-4871/com.afixi.prasenjeetpati.googleapi E/art:     at java.lang.StringBuilder.toString(StringBuilder.java:663)
04-06 16:42:41.423 4871-4871/com.afixi.prasenjeetpati.googleapi E/art:     at com.mediatek.anrappmanager.MessageLogger.println(SourceFile:83)
04-06 16:42:41.423 4871-4871/com.afixi.prasenjeetpati.googleapi E/art:     at android.os.Looper.loop(Looper.java:155)
04-06 16:42:41.423 4871-4871/com.afixi.prasenjeetpati.googleapi E/art:     at android.app.ActivityThread.main(ActivityThread.java:5532)
04-06 16:42:41.423 4871-4871/com.afixi.prasenjeetpati.googleapi E/art:     at java.lang.reflect.Method.invoke!(Native method)
04-06 16:42:41.423 4871-4871/com.afixi.prasenjeetpati.googleapi E/art:     at java.lang.reflect.Method.invoke(Method.java:372)
04-06 16:42:41.423 4871-4871/com.afixi.prasenjeetpati.googleapi E/art:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
04-06 16:42:41.423 4871-4871/com.afixi.prasenjeetpati.googleapi E/art:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)

*I tried the url in the web to check if it is working or not , but it gave result and worked fine. but have a lots and lots of data.

*The app i have designed was working fine but i have never checked with such long distances (25684 km by google maps app).

*Anyone who is thinking how i was parsing the json data into my app . i have taken my directionparsing from thistutorial. i provided the parsing class here because i think this is where the problem is.
My Research
I have followed this , this , this and this SO links but not found much info to solve my problem.
Any suggestion please .


text:
Q: Unit testing http service on Angular 5 I'm pretty confused about how to test a data service, there's just way too many possibilities and it's overwhelming.
I have this simple service:
@Injectable()
export class DataService {

  constructor(private _http: HttpClient) { }

  getData<T>(path: string): Observable<T> {
    return this._http.get<T>(path);
  }

}

I want to test that calling getData<number> will, infact, return a data type of number.
The angular testing guide  frustratingly shows several ways (use testbed, use beforeEach, use jasmine without testBed) and I've tried all of them but not with much success.
How do I do this please? I have so far failed to even get as far as calling the getData. I want to be able to mock the Http, emit mock return values (like in jasmine.spy.and.returnValue(mockData)) and verify that dataService is OK
I've got this in my data.service.spec.ts:
describe('DataService', () => {

  beforeEach(() => {

    TestBed.configureTestingModule({
      imports: [
        HttpClientModule
      ],
      providers: [
        DataService,
        HttpClient
      ]
    });

  });

  // This was auto generated, and works
  it('should be created', inject([DataService], (service: DataService) => {
    expect(service).toBeTruthy();
  }));

  // I added this, but doesn't work
  describe('When getData() is called', () => {

    it('should return an observable of type T', inject([DataService], (service: DataService) => {

      service.getData<number>('mock-url')
        .subscribe(data => {
          expect(typeof(data)).toBe('number');
        });

    }));

  });

});

When I say it doesn't work... the second test passes! but it shouldn't. I can see the real request go out on dev console to the (invalid) url, and that errors out as expected, but the test just passes...
So I guess, my question is simply, in Angular 5, how do I mock my backend service and unit test it please?

A: try to test it like this using flush method
 inject(
  [HttpTestingController, DataService],
  (httpMock: HttpTestingController, service: DataService) =>{
     const mockResponse = 5;
     const mock-url = '...';

     service.getData<number>('mock-url').subscribe(data => {
        expect(data).toEqual(mockResponse);
         expect(typeof(data)).toBe('number');
    });

    const mockRequest = httpMock.expectOne((req: HttpRequest<any>) => req.url === mock-url); //get your request here

    expect(mockRequest.request.method).toBe('GET');

    mockRequest.flush(mockResponse);
   })


text:
Q: Generic "is null" predicate I wrote this generic predicate:
private static <T> Predicate<T> isNull(){
    return Objects::isNull;
}

But I can't use it in combination with other predicates like this:
private static Predicate<String> isEmpty(){
    return string -> string.isEmpty();
}

Because this snippet will not compile (expects Predicate< String> in or operation):
isNull().or(isEmpty())

Any idea to solve it? Thanks!

A: Since isNull() is generic, and the compiler cannot infer the generic parameter when combined like that, you need to explicitly specify the type parameter.
To do that, you must qualify with the class name, e.g. Test:
Test.<String>isNull().or(isEmpty())

Full example:
public class Test {
    public static void main(String[] args) {
        Predicate<String> isNullOrEmpty = Test.<String>isNull().or(isEmpty());
        System.out.println(isNullOrEmpty.test(null));   // true
        System.out.println(isNullOrEmpty.test(""));     // true
        System.out.println(isNullOrEmpty.test("Foo"));  // false
    }
    private static <T> Predicate<T> isNull(){
        return Objects::isNull;
    }
    private static Predicate<String> isEmpty(){
        return string -> string.isEmpty();
    }
}

You can also resolved it by assigning each part to a variable:
Predicate<String> isNull = isNull(); // String is inferred from assignment operator
Predicate<String> isEmpty = isEmpty();
Predicate<String> isNullOrEmpty = isNull.or(isEmpty);

Or just the first part:
Predicate<String> isNull = isNull();
Predicate<String> isNullOrEmpty = isNull.or(isEmpty());

A: Well in our project we have a small work-around for this:
private static <T> Predicate<T> allOr(Predicate<T> ... predicates) {
    return Arrays.stream(predicates).reduce(Predicate::or).orElse(x -> true);
}

And using it with:
Predicate<String> both = allOr(isEmpty(), isNull());

A: When you call isNull(), there is no context to infer what the actual type of T be.
isNull().or(..) here expects a Predicate<? super Object> and hence you cannot pass a Predicate<String> to it.
Flipping them will work (isEmpty().or(isNull()))
isEmpty() now returns a Predicate<String> and isEmpty.or(..) expects a Predicate<? super String> and so you can pass a Predicate<Object>
But this is not what you want as you want to do the null check before checking if empty (Thanks to Slaw@ for pointing this out. Was focusing on making it compile that I didn't pay attention to the meaning/semantic of it).
You can give compiler the clue what the type T is by writing
<YourClassName>.<String>isNull().or(isEmpty());

A: Specifically for String, what you might just be looking for is a single Predicate like this -
private static Predicate<String> isNullOrEmpty() {
    return s -> s == null || s.isEmpty();
}

This can be further used as
List<String> strings = Arrays.asList("", "one", "two", null, "three");
strings.stream().filter(isNullOrEmpty()).forEach(System.out::println);
// ofcourse the above would print "null" and is less useful

Or with the capability of Predicate.not in Java11, the more intuitive way and seemingly useful would be -
List<String> strings = Arrays.asList("", "one", "two", null, "three");
strings.stream().filter(Predicate.not(isNullOrEmpty)).forEach(System.out::println);
// this would print one, two and three


text:
Q: zsh: command not found: mockgen - golang 1.18 - macOS Monterrey I'm new to go. Currently I'm using zsh terminal in macOS, just followed the instructions pointed out here https://github.com/golang/mock when installing go mock. However when trying to execute a mockgen command I keep seeing zsh: command not found: mockgen and when navigating in the terminal to my $GOPATH/bin i see mockgen inthere, so I don't know if there's anything else needed.

These are the variables I have configured in my /.zshrc file:
#GO path
export GOPATH="$HOME/Documents/study_projects/go"
export GOBINPATH="$GOPATH/bin"

Idk if GOBINPATH is a proper name for this $GOPATH/bin variable to be exported to the PATH also, aso pointed out in https://github.com/golang/mock (mockgen/gomock)  installation instructions. Does anyone of you know what else is needed here, do I need an additional configuration for this mockgen command to work with zsh?
Thank you!

A: *

*Make sure run below for go 1.16+
go install github.com/golang/mock/mockgen@v1.6.0

*Add users/[your_login]/go/bin to .zshrc path

A: add export PATH=$PATH:$(go env GOPATH)/bin in .zshrc and try again.


text:
Q: Netscaler - Passtrough SAML Auth We have the following Situation.
Public reachable SSO Portal based on Microsoft ADFS (sso.company.com)
Public reachable Citrix Netscaler (netscaler.company.com)
Private WebServer (web.company.com)  - Not reachable from the internet.
We managed to authenticate against the Netscaler portal with ADFS.
Also we can authenticate against the WebServer inside our Network with ADFS.
Our problem is now to configure Netscaler in a way that we also can use the SSO Login to web.company.com from outside via Netscaler.
I hope that's somewhat clear.

A: I assume you are using SAML and not OAUTH (shouldn't make a difference):
Is SSO for web.company.com SAML based?

*

*if not then the NS can't help you since SAML does not hold a password by default.

*if it is using SAML then just configure the new endpoint in your IDP and everything will be transparent

A: The anove answer is incorrect. Netscaler can indeed do this and i have done it several times.
You need to use Kerberos Constrained Delegation on backend and SAML/OIDC on Front End. With Kerberos Constrained Delegation you are allowed to impersionate another user without having the password.


text:
Q: How can I always bring the application to front when opening a new file? Running in a GNOME 3.28.0/Wayland desktop. If I right-click on a text file and select "Open with other application", the application I choose is brought to the front when it launches. However, if I repeat the process (the application is already running), the new text file is opened in a new tab, but the application remains in the back.
This happens for both Text Editor and Geany.
How can I ensure that when I open a file, the application it is opened in is always brought to the front?


text:
Q: Why doesn't the execve command in C on macOS allow the 'which' command to work? Why does the execve command in C on macOS not allow the 'which' command to work? It works on non-Mac devices.
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main()
{
    int fd;
    char cmd[] = "/bin/cat";
    char cmd1[] = "/usr/bin/which";
    char *s[]={"which","ls",NULL};
    if (execve(cmd1, s, NULL) == -1)
        perror("oops ur wrong!!");
}

Expected output
 clang-7 -pthread -lm -o main main.c
 ./main
/bin/ls


but on a Mac, it returns nothing.

A: macOS
The code works.  It doesn't work well, but it does work.
Given the null PATH in the environment (because you've used execve() and provided NULL as the environment), /usr/bin/which can't find ls — it has nowhere to look for it because PATH is not set.
On my machine (a MacBook Pro running macOS Big Sur 11.7.1 — it's a work machine and the company IT is behind the times), /usr/bin/which is a universal binary with two architectures.  If I run /usr/bin/which ozymandias on the command line, there is no output (I don't have a command ozymandias anywhere), but the exit status is 1 (failure).  That's an odd implementation — not reporting an error — but it works within its limits.
You can see this effect with:
$ (unset PATH; /usr/bin/which ls)
$ echo $?
1
$

If you use execv() instead of execve() and remove the , NULL from the argument list, the output is /bin/ls and the exit status is 0.
Linux
Just for comparison, on a RHEL 7.4 machine, I get different results:
$ which -a which
which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'
    /usr/bin/alias
    /usr/bin/which
/usr/bin/which
$ file /usr/bin/which
/usr/bin/which: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.32, BuildID[sha1]=317ba624d2914607bf9246993446803a977fbc18, stripped
$ /usr/bin/which which
/usr/bin/which
$ (unset PATH; /usr/bin/which which)
/usr/bin/which: no which in ((null))
$ /usr/bin/which ozymandias
/usr/bin/which: no ozymandias in (/work2/jleffler/bin:/u/jleffler/bin:/usr/perl/v5.34.0/bin:/usr/gcc/v12.2.0/bin:/usr/local/bin:/usr/bin:/usr/sbin)
$ /usr/bin/which --help
Usage: /usr/bin/which [options] [--] COMMAND [...]
Write the full path of COMMAND(s) to standard output.

  --version, -[vV] Print version and exit successfully.
  --help,          Print this help and exit successfully.
  --skip-dot       Skip directories in PATH that start with a dot.
  --skip-tilde     Skip directories in PATH that start with a tilde.
  --show-dot       Don't expand a dot to current directory in output.
  --show-tilde     Output a tilde for HOME directory for non-root.
  --tty-only       Stop processing options on the right if not on tty.
  --all, -a        Print all matches in PATH, not just the first
  --read-alias, -i Read list of aliases from stdin.
  --skip-alias     Ignore option --read-alias; don't read stdin.
  --read-functions Read shell functions from stdin.
  --skip-functions Ignore option --read-functions; don't read stdin.

Recommended use is to write the output of (alias; declare -f) to standard
input, so that which can show aliases and shell functions. See which(1) for
examples.

If the options --read-alias and/or --read-functions are specified then the
output can be a full alias or function definition, optionally followed by
the full path of each command used inside of those.

Report bugs to <which-bugs@gnu.org>.
$

PATH sanitized — radically shortened.
The which command reports an error when it can't find the command.  It is a standalone executable on this Linux machine, and the which alias feeds it the aliases so it can report on them.  The -a option reports on all the things that could be known as which (the second which in which -a which).

A: I found that adding the envp(path argument in main) to the arguments made it work
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main(int argv, char *argc[],char *envp[])
{
    int fd;
    char cmd1[] = "/usr/bin/which";
    char *s[] = {"which", "ls", NULL};
    if (execve(cmd1, s, envp) == -1)
        perror("oops ur wrong!!");
}

thanks anyways


text:
Q: Python Loops, Functions, Etc I made a miler per gallon program and I have it all working there's just a few things I would like to add that i'm not too sure how. The things i'm trying to add are when entering a number 0 or negative when it asks you for how many miles were driven and how many gallons of gas were used it will give you an error that says "Please enter a number greater then 0" and has them re-enter the number. Another thing i'm trying to do is loop it so the same questions will be asked 4 times and each time it will print out their information that is being calculated in the code as if there are 4 cars you can check the MPG each time the program is ran.
Another thing I was wondering is if I wanted to have this same code but in functions how would I go about this? The different functions would be like main ( ), printWelcome ( ), getMiles ( ) , getGallons ( ) , calcMpg ( ), printMpg ( ), and rateMpg ( ).
This is what I currently have:
print ('Miles Per Gallon Program')
print ('\n')

milesDrove = float( input( "How many miles were driven?" ) )
gallonsOfGasUsed = float(input( "How many gallons of gas were used?" ) )
milesPerGallon = milesDrove / gallonsOfGasUsed
print ('\n')
print("The MPG is: " + str(milesPerGallon) )

if milesPerGallon < 12:
    print ("Poor mpg")
elif milesPerGallon < 19:
    print ("Fair mpg")
elif milesPerGallon < 26:
    print ("Good mpg")
else:
    print ("Excellent mpg.")\

Thank you!

A: def printWelcome():
    print ('Welcome to the Miles per Gallon program')
def getMiles():
    miles = float(input('Enter the miles you have drove: '))
    return miles
def getGallons():
    gallons = float(input('Enter the gallons of gas you used: '))
    return gallons
def printMpg(milespergallon):
    print ('Your MPG is: ', str(milespergallon))
def calcMpg(miles, gallons):
    mpg = miles / gallons
    return mpg
def rateMpg(mpg):
    if mpg < 12:
        print ("Poor mpg")
    elif mpg < 19:
         print ("Fair mpg")
    elif mpg < 26:
         print ("Good mpg")
    else:
         print ("Excellent mpg")
if __name__ == '__main__':
    printWelcome()
    print('\n')
    miles = getMiles()
    if miles <= 0:
        print('The number of miles cannot be negative or zero. Enter a positive number')
        miles = getMiles()
    gallons = getGallons()
    if gallons <= 0:
        print('The gallons of gas used has to be positive')
        gallons = getGallons()
    print('\n')
    mpg = calcMpg(miles, gallons)
    printMpg(mpg)
    print('\n')
    rateMpg(mpg)

The loop to repeat the above process can be put inside main(), where the function starts. It will ask to enter the numbers n times for n cars and will calculate, rate and mpg for all inputs

A: If you want to get an input from the user, and retry if the input was not validated is as simple as declaring an initial invalid value and looping until the user inputs a valid value:
milesDrove = -1
while milesDrove <= 0:
   try:
       milesDrove = float( input( "How many miles were driven?" ) )
       if milesDrove <= 0:
           print("Please enter a number greater then 0")
   except:
       print("Please enter a number greater then 0")

Given the basic level of your questions I asume you just started a python course at your college/school. In the example above i used exception handling, because the call to float() can raise an exception if the input is not a number (the user can never be trusted, but depends on what level of validation you are confortable with).
Looping N times:

for i in range(4):
    print("Calculate the MPG for car #%d" % i + 1)
    milesDrove = float( input( "How many miles were driven?" ) )
    gallonsOfGasUsed = float(input( "How many gallons of gas were used?" ) )
    milesPerGallon = milesDrove / gallonsOfGasUsed
    print ('\n')
    print("The MPG is: " + str(milesPerGallon) )

    if milesPerGallon < 12:
        print ("Poor mpg")
    elif milesPerGallon < 19:
        print ("Fair mpg")
    elif milesPerGallon < 26:
        print ("Good mpg")
    else:
        print ("Excellent mpg.")\

Finally, regarding your question about functions, having functions that do all their job in one line is kind of overkill. In your case, most of them will just return a single value. In general, although the python interpreter will run your code even if its not inside a function(this is not c or java, we don´t really need a main function) usually people declare the starting point of their scripts as follows:
if __name__ == "__main__":
    do_stuff()

Deciding when to declare a function or not can be difficult to a beginer. As a general rule you should declare a function whenever that piece of code is called multiple times form other parts of your code or if the work that is done by such function is very well defined (for instance a function that calculates the fibonnaci sum)


text:
Q: Android How to get system's installed locales Is there any way to get System installed locales from the Android device. I tried with getAvailableLocales () from android Get Available locales, but it is not working for devices like Asus, Carbon, Lava, Intex.
For example, if I call getAvailableLocales() in Nexus device I am able to get locales which is there in Settings-> Language&Input -> Language
But if I do same on any Carbon device, instead of getting languages from  Settings-> Language&Input -> Language, I get a different list.
I want only the  installed list of languages in the device, not every language supported by OS.

A: If you want system supported locales, use
Locale.getAvailableLocales()

If you want system supported and device enabled locales
Resources.getSystem().getAssets().getLocales()

By using the first one, you cannot be sure about if all locales are supported by that device. Cause they all came in with that Android ROM.
But the latter one is always a sure shot.
Cause it gives only what all the locales(fonts) installed for that particular device. These locales(fonts) are placed by that device manufacturer.
I explained more it in here

A: The Locale.getAvailableLocales() method is the generic 'base' set of locales. From the documentation:

Most locale-sensitive classes offer their own getAvailableLocales method, which should be preferred over this general purpose method.

Emphasis mine.
You can get the locales available for a specific use-case by querying the getAvailableLocales() method on the appropriate class. Specifically:

*

*BreakIterator.getAvailableLocales()

*Collator.getAvailableLocales()

*DateFormat.getAvailableLocales()

*DateFormatSymbols.getAvailableLocales()

*DecimalFormatSymbols.getAvailableLocales()

*NumberFormat.getAvailableLocales()

*Calendar.getAvailableLocales()


text:
Q: Mircrosoft - first last (organization) naming to avoid send errors More and more common in organisations is to use "first last (organization)" naming conventions in teams/outlook etc. to avoid sending email to the wrong person with autocomplete.
My problem is how to do this, in AD, in outlook, in 365, in exchange?
Pls help
Best
/Peter

A: I solved this today. In Azure AD I changed users name from "first last" to "first last (organization)"  It seems to work.
Best/Peter


text:
Q: Reading big raster getting warnings using GDAL Python I am trying to use GDAL Python API to deal with some big raster, and when I read these rasters into Python, I get warnings like that:
Warning 1: TIFFFetchNormalTag:ASCII value for tag "GeoASCIIParams" contains null byte in value; value incorrectly truncated during reading due to implementation limitations
Warning 1: TIFFReadDirectory:Sum of Photometric type-related color channels and ExtraSamples doesn't match SamplesPerPixel. Defining non-color channels as ExtraSamples.
Warning 1: TIFFFetchNormalTag:ASCII value for tag "GeoASCIIParams" contains null byte in value; value incorrectly truncated during reading due to implementation limitations
Warning 1: TIFFReadDirectory:Sum of Photometric type-related color channels and ExtraSamples doesn't match SamplesPerPixel. Defining non-color channels as ExtraSamples.

Do anybody encounter problems like this? Why did this thing happen?
The raster I use is about 2.2G for one raster, and the raster' format is TIFF.the warnings don't affect the later use of the data, it is still an annoying issue, I want to know how to fix this.

A: You can suppress the warnings (as long as you're sure there's no real issue with your data) with gdal.PushErrorHandler('CPLQuietErrorHandler').  If you do this any errors will also not get printed, so make sure you tell GDAL to raise a Python exception when an error occurs with gdal.UseExceptions().
E.g.
# Stop GDAL printing both warnings and errors to STDERR
gdal.PushErrorHandler('CPLQuietErrorHandler')

# Make GDAL raise python exceptions for errors (warnings won't raise an exception)
gdal.UseExceptions()

A: The first warning means that the value of GeoASCIIParams tag is not read as it was written because the original image is having NULL character in the value of the tag. NULL can be used as a delimiter between strings http://freeimage.sourceforge.net/fnet/html/A633E9A9.htm but obviously GDAL takes just the first string.
The second error means that the writer that created the TIFF file has written the metadata wrong. Perhaps the metadata tells that image is of RGB type without extra samples (bands) but actually the image has four bands and GDAL considers it as RGBA. By doing that GDAL at least doesn not drop a band but it may make a wrong guess about the role of the extra band which is not necessarily alpha but could contain data as well (for example RGB+Near Infrared).


text:
Q: How to pass request body data in type POST using Datatable for Serverside pagination using Javascript I am trying to implement ServerSide pagination using Datatable for AJAX POST request
here is my Javascript Code, if I use JSON.stringify for data field then api won't hit
$('#tripboard_table').DataTable({
    proccessing: true,
    serverSide: true,
    ajax: {
        "url": "http://localhost:5000/api/v1/trip/get-trip-list",
        "contentType": "application/json; charset=utf-8",
        "type": "POST",
        "dataType": "json",
        "data": {
            "driver_id": "",
            "franchise_id": login_data.franchise_id,
            "page_no": 0,
            "page_size": 10
        }
    },
    columns: [
        { "data": "" },
        { "data": "reference_number" },
        { "data": "consignor_name" },
        { "data": "consignee_name" },
        { "data": "from_city" },
        { "data": "to_city" },
        { "data": "status" },
        { "data": "route_name" },
        { "data": "vehicle_number" },
        { "data": "driver_name" },
        { "data": "pickup_date" },
        { "data": "scheduled_delivery_date" },
        { "data": "total_money_allocated" },
        { "data": "total_money_released" }
    ]

});

if we remove JSON.stringify function from data and passed data as it is then api gets hit and showing error alert that

DataTables warning: table id=tripboard_table - Ajax error. For more
information about this error, please see http://datatables.net/tn/7

and no data is inserted in table.
In console it shows

Method Not Allowed
The method is not allowed for the requested URL.

Please suggest solution for this..

A: Use this for adding to existing request of data table
function (d) {
                d.driver_id = "";
                d.franchise_id = login_data.franchise_id;
                d.page_no = 0;
                d.page_size = 10;
                return d;
            }

https://datatables.net/manual/server-side#Sent-parameters
$('#tripboard_table').DataTable({
        proccessing: true,
        serverSide: true,
        ajax: {
            "url": "http://localhost:5000/api/v1/trip/get-trip-list",
            "contentType": "application/json; charset=utf-8",
            "type": "POST",
            "dataType": "json",
            "data": function (d) {
                d.driver_id = "";
                d.franchise_id = login_data.franchise_id;
                d.page_no = 0;
                d.page_size = 10;
                return JSON.stringify(d)
                });
            }
        },
        columns: [
            { "data": "" },
            { "data": "reference_number" },
            { "data": "consignor_name" },
            { "data": "consignee_name" },
            { "data": "from_city" },
            { "data": "to_city" },
            { "data": "status" },
            { "data": "route_name" },
            { "data": "vehicle_number" },
            { "data": "driver_name" },
            { "data": "pickup_date" },
            { "data": "scheduled_delivery_date" },
            { "data": "total_money_allocated" },
            { "data": "total_money_released" }
        ]

    });


text:
Q: For a given precision, what is the maximum value for which a float32 will give the same result as a float64? With numpy, I'm trying to understand what is the maximum value that can be downcasted from float64 to float32 with a loss on accuracy less or equal to 0.001.
Since I could not find a simple explanation online, I quickly came up with this piece of code to test :
result = {}
for j in range(1,1000):
    for i in range (1, 1_000_000):
        num = i + j/1000
        x=np.array([num],dtype=np.float32)
        y=np.array([num],dtype=np.float64)
        if abs(x[0]-y[0]) > 0.001:
            result[j] = i
            break

Based on the results, it seems any positive value <32768 can be safely downcasted from float64 to float32 with an acceptable loss on accuracy (given the criteria of <=0.001)
Is this correct ?
Could someone explain the math behind ?
Thanks a lot

A: Assuming IEEE 754 representation, float32 has a 24-bit significand precision, while float64 has a 53-bit significand precision (except for "denormal" numbers).
In order to represent a number with an absolute error of at most 0.001, you need at least 9 bits to the right of the binary point, which means the numbers are rounded off to the nearest multiple of 1/512, thus having a maximum representation error of 1/1024 = 0.0009765625 < 0.001.
With 24 significant bits in total, and 9 to the right of the binary point, that leaves 15 bits to the left of the binary point, which can represent all integers less than 215 = 32768, as you have experimentally determined.
However, there are some numbers higher than this threshold that still have an error less than 0.001.  As Eric Postpischil pointed out in his comment, all float64 values between 32768.0 and 32768.001 (the largest being exactly 32768+137438953/237), which the float32 conversion rounds down to exactly 32768.0, meet your accuracy requirement.  And of course, any number that happens to be exactly representable in a float32 will have no representation error.


text:
Q: How to work with spherical surface plot in existing coordinate system? I would like to draw a spherical surface plot following the example 3.6.2 from the tikz-3D plot documentation. I managed to draw the sphere I want, but I couldn't include the plot into my 3D graph in which the other stuff is plotted in. The current state looks like this:
The code I wrote to get this example:
\documentclass[a4paper, 12pt]{report}
\usepackage{tikz} %Vektorgrafiken
\usepackage{pgfplots}
\usepackage{amsmath}
\usepackage{tikz}
\usepackage{xcolor}
\usepackage{tikz-3dplot}

\begin{document}
\begin{figure}
\centering
\begin{tikzpicture}[x={(-30:1cm)}, y={(30:1cm)}, z={(90:1cm)}, scale=1.0,
    >=stealth,
    inner sep=0pt, outer sep=2pt,
    axis/.style={thick,->},
    wave/.style={thick,color=#1,smooth},
    polaroid/.style={fill=black!60!white, opacity=0.3},
    ]

\coordinate (O) at (0, 0, 0);
\draw[axis] (6.28, 0,   0) -- +(5.72, 0,   0) node [right] {z};
\draw[axis] (O) -- +(0,  -2.5, 0) node [left] {x};
\draw[axis] (O) -- +(0,  0,   2) node [above] {y};
\draw[thick,dashed] (-2,0,0) -- (6.28, 0,   0);

\draw[thick,dashed] (8.72, -2,  0) -- (8.72, 2,  0);

\tdplotsetmaincoords{60}{140}
\begin{scope}[x = {10}, y = {1}, z = {1}, scale=2,line join=bevel,tdplot_main_coords,%
    fill opacity=.5]
\tdplotsetpolarplotrange{0}{180}{0}{180}
\tdplotsphericalsurfaceplot[parametricfill]{72}{24}%
    {1}{black}{180}%
{\draw[axis] (O) -- + (0,2,0) node[anchor=north east]{$z$};}%
  {\draw[axis] (O) -- +  (2.5 ,0 ,0) node[anchor=north west]{$x$};}%
    {\draw[axis] (O) -- +(0,  0,   2)  node[anchor=south]{$y$};}%
\end{scope}
\end{tikzpicture}
\end{figure}
\end{document}

The questions I have are:

*

*Why are the x axis of the coordinate systems not aligned?

*How do i transfer the sphere into the coordinate system I first defined?

*How do I move the sphere along the z axis to the point of the crossing line?

*How can I make the sphere completely transparent?


text:
Q: Having issue in Downloading Google Documents using .NET? I have created sample web application for access google drive APIs.

*

*Enabled google drive documents APIsusing my google account.

*Downloaded credential.json file and included inside the project.

*Uploaded one document to my google drive with these below code

UserCredential credential;
string[] scopes = new string[] { DriveService.Scope.Drive,
                    DriveService.Scope.DriveAppdata,
                    DriveService.Scope.DriveFile,
                    DriveService.Scope.DriveMetadataReadonly,
                    DriveService.Scope.DriveReadonly,
                    DriveService.Scope.DriveScripts
};

using (var stream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "credentials.json", FileMode.Open, FileAccess.ReadWrite))
{
  string credPath = AppDomain.CurrentDomain.BaseDirectory + "token.json";
  credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
 }

DriveService driveService = new DriveService(new BaseClientService.Initializer()
{
 HttpClientInitializer = credential,
ApplicationName = ApplicationName,
 });

FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream(fileName,                                            System.IO.FileMode.Open))
{
   request = driveService.Files.Create(fileMetadata, stream, mimeType);
   request.Fields = "id";
   request.Upload();
}

file = request.ResponseBody;

*Download file stream

 var request = service.Files.Get(fileId);
                    var stream = new System.IO.MemoryStream();

                    request.MediaDownloader.ProgressChanged +=
                        (IDownloadProgress progress) =>
                        {
                            switch (progress.Status)
                            {
                                case DownloadStatus.Downloading:
                                    {
                                        break;
                                    }
                                case DownloadStatus.Completed:
                                    {
                                        var bytearray = stream.ToArray();
                                     System.IO.File.WriteAllBytes(SavedLocation, bytearray );
                                        break;
                                    }
                                case DownloadStatus.Failed:
                                    {
                                        break;
                                    }
                            }
                        };
                    request.Download(stream);

But file stream is not properly download in random cases.
Refer Link: https://developers.google.com/drive/api/v3/manage-downloads#downloading_google_documents
How can achieve this?


text:
Q: How do I input filepath by sys.stdin in python? I wrote a simple py by using sys.stdin
import sys
for line in sys.stdin:
  print "hello" + line

While I need to import filepath as import to execute in my function.
When I use sys.stdin and run it into command line.
    ~$ python metrics.py
    /Users/glange/graphs/Building768.0.json
    ctrl+D
    IOError: [Errno 2] No such file or directory:
    '/Users/glange/graphs/Building768.0.json\n'

I enter the filepath then ctrl+D. It cannot be run. It seems When I finished the filepath I need enter a new line to ctrl+D. And the path becomes \n in the end.
How can I fix that?

A: You can use .rstrip() to remove the new line character
print "hello" + line.rstrip()


text:
Q: Html  tag strange displaying Why is the
 tag displaying so strange? How to fix it?

HomeController:
namespace MvcApplication4.Controllers
{
public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        List<Department> department = new List<Department>();
        department.Add(new Department { Computers = new List<Computer> { new Computer { ID = 1 }, new Computer { ID = 2 } }, Employees = new List<Employee> { new Employee { Number = 1, Text = "Jhon" }, new Employee { Number = 2, Text = "Conorrrrrrrrrrrr" }, new Employee { Number = 3, Text = "Nick" } } });
        department.Add(new Department { Computers = new List<Computer> { new Computer { ID = 1 }, new Computer { ID = 2 }, new Computer { ID = 3} }, Employees = new List<Employee> { new Employee { Number = 1, Text = "David" } } });
        return View(new IndexViewModel { Department = department });
    }
}
public class IndexViewModel
{
    public IEnumerable<Department> Department { get; set; }

}

public class Department
{
    public IEnumerable<Employee> Employees { get; set; }

    public IEnumerable<Computer> Computers { get; set; }
}

public class Computer
{
    public int ID {get;set;}
}
public class Employee
{
    public string Text { get; set; }

    public int Number { get; set; }
}
}

Index.cshtml:
@model MvcApplication4.Controllers.IndexViewModel
@{
    ViewBag.Title = "Index";
}

Index

@foreach(var department in Model.Department)
{

        @foreach (var computer in department.Computers)
        {

                    @computer.ID

        }

        @foreach (var employee in department.Employees)
        {

                    @employee.Text

                    @employee.Number

        }

}

A: You should clear the float. Otherwise if the hr is directly after a floating table, it will be displayed to its right.

Or, preferably, put
hr {clear:left;}

in your stylesheet.


text:
Q: Using srcset in Vuetify My webp images are not loading in Safari and Edge, so I want to use srcset to use the png variant instead if the browser can't load the webp file. Currently this is how I define my image:
  <img
    :srcset="`${require('../../assets/art/blob-right-side.webp')} ${require('../../assets/art/blob-right-side.png')}`"
    :src="require('../../assets/art/blob-right-side.webp')"
    class="hidden-sm-and-down"
    height="500"
    width="217"
    style="position: absolute; top: 300vh; right: 0;"
  />

But my browser (Chrome) returns the following errors:

Failed parsing 'srcset' attribute value since it has an unknown descriptor.
Dropped srcset candidate
"/images/blob-bottom-desktop.webp?92a59c3833d65ecd5913e9d37354bcc8"

Can anyone explain to me why this isn't working? I can't find much information about it.

A: Possible you missed comma between values
:srcset="`${require('../../assets/art/blob-right-side.webp')}, ${require('../../assets/art/blob-right-side.png')}`"

And I don't see any rules for resolution switching
:srcset="`${require('../../assets/art/blob-right-side.webp')}, ${require('../../assets/art/blob-right-side.png')}` 1.5x"