问:
PIL Image.fromstring from PyOpengl buffer has the wrong size
I use PyOpenGL to draw a 2D Image. Then I want to use the Python Imaging Library (PIL) to store this image to disk. I use GLUT to display the image which works perfectly. But when I use PIL to store the image it extracts the wrong clipping. It has the wrong size.

Here is a minimal example which reproduces the effect and I also attach the output to make it more clear without running some code.

```<code>from OpenGL.GL import *
from OpenGL.GLUT import *
from PIL import Image

width, height = 640, 480

def DrawStuff():
    poly1 = [(0,0), (640,0), (0,480)]
    color = (0.5, 0.4, 0.3, 0.8)
    glClear(GL_COLOR_BUFFER_BIT)
    glPushMatrix()
    glLineWidth(5.0)

    glColor4f(*color)
    glBegin(GL_POLYGON)
    glVertex2f(poly1[0][0], poly1[0][1])
    glVertex2f(poly1[1][0], poly1[1][1])
    glVertex2f(poly1[2][0], poly1[2][1])
    glVertex2f(poly1[0][0], poly1[0][1])
    glEnd() # GL_POLYGON

    glPopMatrix()
    glPixelStorei(GL_PACK_ALIGNMENT, 1)
    data = glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE)
    image = Image.fromstring("RGBA", (width, height), data)
    image.show()
    image.save('out.png', 'PNG')
    glutSwapBuffers()

# glut initialization
glutInit(sys.argv)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA)
glutCreateWindow("Draw Polygons")
glutInitWindowSize(width, height)

# set the function to draw
glutDisplayFunc(DrawStuff)

# enable the alpha blending
glEnable(GL_BLEND)
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

# prepare for 2D drawing
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, width, height, 0, 0, 1)
glDisable(GL_DEPTH_TEST)
glMatrixMode(GL_MODELVIEW)

# start the mainloop
glutMainLoop ()
</code>```

this is how it looks int the GLUT window and how it is supposed to look like

and this is how the saved image looks like

答: You should consider that in OpenGL the coordinate system starts at different place than in PIL. Look at this.</p>

Body:
I use PyOpenGL to draw a 2D Image. Then I want to use the Python Imaging Library (PIL) to store this image to disk. I use GLUT to display the image which works perfectly. But when I use PIL to store the image it extracts the wrong clipping. It has the wrong size.

Here is a minimal example which reproduces the effect and I also attach the output to make it more clear without running some code.

from OpenGL.GL import *
from OpenGL.GLUT import *
from PIL import Image

width, height = 640, 480

def DrawStuff():
    poly1 = [(0,0), (640,0), (0,480)]
    color = (0.5, 0.4, 0.3, 0.8)
    glClear(GL_COLOR_BUFFER_BIT)
    glPushMatrix()
    glLineWidth(5.0)

    glColor4f(*color)
    glBegin(GL_POLYGON)
    glVertex2f(poly1[0][0], poly1[0][1])
    glVertex2f(poly1[1][0], poly1[1][1])
    glVertex2f(poly1[2][0], poly1[2][1])
    glVertex2f(poly1[0][0], poly1[0][1])
    glEnd() # GL_POLYGON

    glPopMatrix()
    glPixelStorei(GL_PACK_ALIGNMENT, 1)
    data = glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE)
    image = Image.fromstring("RGBA", (width, height), data)
    image.show()
    image.save('out.png', 'PNG')
    glutSwapBuffers()

# glut initialization
glutInit(sys.argv)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA)
glutCreateWindow("Draw Polygons")
glutInitWindowSize(width, height)

# set the function to draw
glutDisplayFunc(DrawStuff)

# enable the alpha blending
glEnable(GL_BLEND)
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

# prepare for 2D drawing
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, width, height, 0, 0, 1)
glDisable(GL_DEPTH_TEST)
glMatrixMode(GL_MODELVIEW)

# start the mainloop
glutMainLoop ()

this is how it looks int the GLUT window and how it is supposed to look like

and this is how the saved image looks like


来源: stackexchange

问:
React Display Data in React Table
i have to display the Data coming from Async function in a Table. but it will only 4 Line displayed.
enter image description here

i excpected 6 Line. please check the Result in Console.log(result) => enter image description here

my code :

```<code>mychange = async () => {
    // Use IPC API to query Electron's main thread and run this method
    const result = await window.api.getNetworkInterfaces()
    var myliste = [];

    console.log(result)
    for (const [key, value] of Object.entries(result)) {
        var entryNumber = 0;
        var i =0;
        //console.log(value.lenght)
        value.forEach(entry => {
          console.log(entry.lenght)

          myliste[i]={ id: i, selected: false, name: key, email: entry.family,phone:entry.address};
            i++;
        })
    }
  ;
    this.setState({
        List:myliste
    })

  }
</code>```

can someone help to lose the probleme ?

expected result :
enter image description here

答:
There is a bug in your program. You are replacing your item in the second iteration of Object.entries(result). Your index i is reset to 0 after an iteration.

A suggested fix is the following, by putting the variable i outside the loop.

    var i =0;
    for (const [key, value] of Object.entries(result)) {
        value.forEach(entry => {
            myliste[i] = { id: i, selected: false, name: key, email: entry.family, phone: entry.address };
            i++;
        })
    }
```

ContentLicense: CC BY-SA 4.0

Title: React Display Data in React Table

Body:
i have to display the Data coming from Async function in a Table. but it will only 4 Line displayed.
enter image description here

i excpected 6 Line. please check the Result in Console.log(result) => enter image description here

my code :

mychange = async () => {
    // Use IPC API to query Electron's main thread and run this method
    const result = await window.api.getNetworkInterfaces()
    var myliste = [];

    console.log(result)
    for (const [key, value] of Object.entries(result)) {
        var entryNumber = 0;
        var i =0;
        //console.log(value.lenght)
        value.forEach(entry => {
          console.log(entry.lenght)

          myliste[i]={ id: i, selected: false, name: key, email: entry.family,phone:entry.address};
            i++;
        })
    }
  ;
    this.setState({
        List:myliste
    })

  }

can someone help to lose the probleme ?

expected result :
enter image description here


问:
Get what x% of an element is
I'm trying to set the margins of an HTML element to be x% of its size. Tried using margin-bottom: 50% or margin-bottom: 50vm but it gets x% of the screen size.

Code:

#task_box {
  margin-bottom: 1%;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="task_box">
<input type="text" id="task_box">
<input type="text" id="task_box"></code>```

I want to set this to the task_box object.

答:
it helps to solve the problem

.task_box {
  margin-bottom: calc(100% - 50%);
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" class="task_box">
<input type="text" class="task_box">
<input type="text" class="task_box"></code>```

Title: Get what x% of an element is

Body:
I'm trying to set the margins of an HTML element to be x% of its size. Tried using margin-bottom: 50% or margin-bottom: 50vm but it gets x% of the screen size.

Code:

#task_box {
  margin-bottom: 1%;
  display: block;
}

<input type="text" id="task_box">
<input type="text" id="task_box">
<input type="text" id="task_box">

I want to set this to the task_box object.

Body:
it helps to solve the problem

.task_box {
  margin-bottom: calc(100% - 50%);
  display: block;
}

<input type="text" class="task_box">
<input type="text" class="task_box">
<input type="text" class="task_box">


问:
IPv6 Network is unreachable (os error 101)
Trying to create tcp socket connection between via an Ipv6 address, I get Network is unreachable (os error 101)
As a binding local address is used fe80::850***.
Probably it's because of fe80*** is local ipv6 address generated by OS. Is there a way to provide correct configuration for system to make a call via IPv6?</p>

答:
Short answer:

Your IPv6 connectivity is not setup correctly. This is most probably no configuration problem on your machine, but on the gateway router.

Long answer:

You get a "Network is unreachable" error because your operating system does not know how to reach the destination address. Usually it maintains a table called the routing table, where it looks up which network path leads to which ip subnet. It seems that in your case, there are several things missing.

Your interface probably has no configured non-link-local (fe80::/64) address

There is no routing table entry for the destination address range

In the IPv4 world these missing things are usually resolved by a DHCP server. In the IPv6 world, there are two possible configuration options. Either DHCPv6 is used or the IPv6 Stateless Address Autoconfiguration is used. It seems that neither is setup in your network. Note that correctly setting up one of these requires you to have administrative access to your gateway router.


问:
How can I get username and password from SharedPreferences in Android?
I am trying to recover the username and password to be able to start a session.
These are the users of the sharedPreferences.

```<code><?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="admin">1234</string>
    <string name="user">user0987</string>
</map>
</code>```

And this is the method

```<code>login.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        SharedPreferences sp1 = MainActivity.this.getSharedPreferences("data", Context.MODE_PRIVATE);
        String user = sp1.getString(userInput.getText().toString(), "User not found");
        String pass = sp1.getString(passwordInput.getText().toString(), "Password is not correct");

        if(user.equals(userInput.getText().toString()){
            Toast.makeText(MainActivity.this, "User Exists", Toast.LENGTH_SHORT).show();
        } else{
            Toast.makeText(MainActivity.this, "User not found", Toast.LENGTH_SHORT).show();
        }

    }
});
</code>```

This is the code that puts data in SharedPreferences

```<code>register.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        String user = userInput.getText().toString();
        String pass = passwordInput.getText().toString();

        if(user.isEmpty()){
            error.show();
        } else if (pass.isEmpty()){
            error2.show();
        } else{
            SharedPreferences sp=getSharedPreferences("data", Context.MODE_PRIVATE);
            SharedPreferences.Editor Ed=sp.edit();
            Ed.putString(user,pass);
            Ed.commit();
            Toast.makeText(MainActivity.this, "Register completed", Toast.LENGTH_SHORT).show();
        }

    }
});
</code>```

答:
You need to add keys for saving for data in SharedPreferences editor.

Currently you are using entered username as key, It can be change according to entered data in edittext, because user will not enter same username every time, but for saving and getting data to/from SharedPreferences we need a specific key.

You can add keys for saving user name and password like following code:

```<code> SharedPreferences sp=getSharedPreferences("data", Context.MODE_PRIVATE);
 SharedPreferences.Editor ed=sp.edit();
 ed.putString("user",user);
 ed.putString("pass",pass);
 ed.commit();
</code>```

For getting data

```<code>SharedPreferences sp1 = getSharedPreferences("data", Context.MODE_PRIVATE);
String userName = sp1.getString("user", "User not found");
String password = sp1.getString("pass", "Password is not correct");
</code>```

For more info regarding  Sharedpref check Official documentation for Save key-value data using SharedPreferences

Body:
I am trying to recover the username and password to be able to start a session.
These are the users of the sharedPreferences.

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="admin">1234</string>
    <string name="user">user0987</string>
</map>

And this is the method

login.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        SharedPreferences sp1 = MainActivity.this.getSharedPreferences("data", Context.MODE_PRIVATE);
        String user = sp1.getString(userInput.getText().toString(), "User not found");
        String pass = sp1.getString(passwordInput.getText().toString(), "Password is not correct");

        if(user.equals(userInput.getText().toString()){
            Toast.makeText(MainActivity.this, "User Exists", Toast.LENGTH_SHORT).show();
        } else{
            Toast.makeText(MainActivity.this, "User not found", Toast.LENGTH_SHORT).show();
        }

    }
});

This is the code that puts data in SharedPreferences

register.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        String user = userInput.getText().toString();
        String pass = passwordInput.getText().toString();

        if(user.isEmpty()){
            error.show();
        } else if (pass.isEmpty()){
            error2.show();
        } else{
            SharedPreferences sp=getSharedPreferences("data", Context.MODE_PRIVATE);
            SharedPreferences.Editor Ed=sp.edit();
            Ed.putString(user,pass);
            Ed.commit();
            Toast.makeText(MainActivity.this, "Register completed", Toast.LENGTH_SHORT).show();
        }

    }
});

Body:
You need to add keys for saving for data in SharedPreferences editor.

Currently you are using entered username as key, It can be change according to entered data in edittext, because user will not enter same username every time, but for saving and getting data to/from SharedPreferences we need a specific key.

You can add keys for saving user name and password like following code:

 SharedPreferences sp=getSharedPreferences("data", Context.MODE_PRIVATE);
 SharedPreferences.Editor ed=sp.edit();
 ed.putString("user",user);
 ed.putString("pass",pass);
 ed.commit();

For getting data

SharedPreferences sp1 = getSharedPreferences("data", Context.MODE_PRIVATE);
String userName = sp1.getString("user", "User not found");
String password = sp1.getString("pass", "Password is not correct");

For more info regarding  Sharedpref check Official documentation for Save key-value data using SharedPreferences


问:
Getting key from values present in a dictionary of dictionaries
I have a dictionary of dictionaries, like given below:

```<code>{
   "dev": {
      "project_id": "dev_project_id",
      "secret_id": "dev_secret_id",
      "secret_project_id": "dev_secret_project_id",
      "service_account_email": "dev_service_account_email@gmail.com",
      "email_list": ["dev_email@gmail.com"],
      "core_func_path":"dev/core_func.py",
      "secret_id_email": "dev_secret_id_email"
   },
   "prod": {
      "project_id": "prod_project_id",
      "secret_id": "prod_secret_id",
      "secret_project_id": "prod_secret_project_id",
      "service_account_email": "prod_service_account_email@gmail.com",
      "email_list": ["prod_email_list@gmail.com"],
      "core_func_path":"prod/core_func.py",
      "secret_id_email": "prod_secret_id_email"
   }
}
</code>```

And I need to extract key when a specific project_id is provided.

Till now, I have this code, which can get values from a dictionary, however, it is failing for a dictionary of dictionaries.

```<code>check_project_id='dev_project_id'
curr_dir = Path(os.path.dirname(os.path.abspath(__file__)))
    default_config_dir = os.fspath(Path(curr_dir.parent.parent, 'config').resolve())
    constants_path = str(default_config_dir)+'/config.json'
    with open(constants_path, 'r') as f:
        std_config = json.load(f)
        for val in std_config.values():
            if(val['project_id']==check_project_id):
                print(list(std_config.keys())[list(std_config.values()).index(check_project_id)])
</code>```

Is there any way I can implement this?

答:
So if I understand correctly, std_config is your dictionary of dictionaries. Just use the items call on the dictionary to be able to extract the key that matches your criteria.

```<code>for k, v in std_config.items():
    if v["project_id"] == check_project_id:
        print(k)

> dev
</code>```

Body:
I have a dictionary of dictionaries, like given below:

{
   "dev": {
      "project_id": "dev_project_id",
      "secret_id": "dev_secret_id",
      "secret_project_id": "dev_secret_project_id",
      "service_account_email": "dev_service_account_email@gmail.com",
      "email_list": ["dev_email@gmail.com"],
      "core_func_path":"dev/core_func.py",
      "secret_id_email": "dev_secret_id_email"
   },
   "prod": {
      "project_id": "prod_project_id",
      "secret_id": "prod_secret_id",
      "secret_project_id": "prod_secret_project_id",
      "service_account_email": "prod_service_account_email@gmail.com",
      "email_list": ["prod_email_list@gmail.com"],
      "core_func_path":"prod/core_func.py",
      "secret_id_email": "prod_secret_id_email"
   }
}

And I need to extract key when a specific project_id is provided.

Till now, I have this code, which can get values from a dictionary, however, it is failing for a dictionary of dictionaries.

check_project_id='dev_project_id'
curr_dir = Path(os.path.dirname(os.path.abspath(__file__)))
    default_config_dir = os.fspath(Path(curr_dir.parent.parent, 'config').resolve())
    constants_path = str(default_config_dir)+'/config.json'
    with open(constants_path, 'r') as f:
        std_config = json.load(f)
        for val in std_config.values():
            if(val['project_id']==check_project_id):
                print(list(std_config.keys())[list(std_config.values()).index(check_project_id)])

Is there any way I can implement this?

Body:
So if I understand correctly, std_config is your dictionary of dictionaries. Just use the items call on the dictionary to be able to extract the key that matches your criteria.

for k, v in std_config.items():
    if v["project_id"] == check_project_id:
        print(k)

> dev


问:
relation "mains_shop" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "mains_shop"
I am Building a Webapp and I am stuck on an Error.

What i am trying to do

I am making a GeoDjango app using Gdal , OSGeo , Postgresql , Postgis. All of them are successfuly installed.

Tutorial :- I am following this Tutorial

When i try to open the Shop panel in Django Admin then it is keep showing me

relation "mains_shop" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "mains_shop"

And when i delete it and migrate again

then it shows

ValueError: String input unrecognized as WKT EWKT, and HEXEWKB.

But deleting migrations is solving ValueError .

models.py

```<code>class Shop(models.Model):
    name = models.CharField(max_length=100)
    location = models.PointField()
    address = models.CharField(max_length=100)
    city = models.CharField(max_length=50)
</code>```

admin.py

```<code>@admin.register(Shop)
class ShopAdmin(OSMGeoAdmin):
    list_display = ('name', 'location')
</code>```

settings.py

```<code>INSTALLED_APPS = [

   'django.contrib.gis',
]

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': '-------',
        'USER': '-------',
        'PASSWORD': '-------',
        'HOST': 'localhost',
        'PORT': '',
    }
}
</code>```

What have i tried

First time when error appears then i think that GDal would not installed then I reinstalled it and it successfully installed.

I have reinstalled PostGis .

I have also seen many answers but nothing worked for me.

I have applied migrations many times.

I also tried python manage.py migrate --fake.

I don't know what am i doing wrong.

Any help would be appreciated.

Thank You in Advance.

答:
I know this is not the best solution but it works for me.
This problem occurred to me after I removed my tables in database manually.

my solution:

first of all I removed all of the migration files related to the model which showed in error log. ( you should remove migrations related to Shop model)

change the name of models. (you can change it to Shop2)

run makemigrations and migrate command

change model names back. (change it to Shop again)

make migrations and migrate again

after these steps the problem fixed for me.
also after these step you can delete all new migration files and make migrations again to have only one migration file.

Body:
I am Building a Webapp and I am stuck on an Error.

What i am trying to do

I am making a GeoDjango app using Gdal , OSGeo , Postgresql , Postgis. All of them are successfuly installed.

Tutorial :- I am following this Tutorial

When i try to open the Shop panel in Django Admin then it is keep showing me

relation "mains_shop" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "mains_shop"

And when i delete it and migrate again

then it shows

ValueError: String input unrecognized as WKT EWKT, and HEXEWKB.

But deleting migrations is solving ValueError .

models.py

class Shop(models.Model):
    name = models.CharField(max_length=100)
    location = models.PointField()
    address = models.CharField(max_length=100)
    city = models.CharField(max_length=50)

admin.py

@admin.register(Shop)
class ShopAdmin(OSMGeoAdmin):
    list_display = ('name', 'location')

settings.py

INSTALLED_APPS = [

   'django.contrib.gis',
]

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': '-------',
        'USER': '-------',
        'PASSWORD': '-------',
        'HOST': 'localhost',
        'PORT': '',
    }
}

What have i tried

First time when error appears then i think that GDal would not installed then I reinstalled it and it successfully installed.

I have reinstalled PostGis .

I have also seen many answers but nothing worked for me.

I have applied migrations many times.

I also tried python manage.py migrate --fake.

I don't know what am i doing wrong.

Any help would be appreciated.

Thank You in Advance.


问:
Dynamic Heroicons import with Next.js
I'm using heroicons in my Next.js project and since it currently doesn't support dynamic imports (by passing icon name to component) I created my own component.

// HeroIcon.tsx
import * as SolidIcons from '@heroicons/react/solid';
import * as OutlineIcons from '@heroicons/react/outline';

interface Props {
  icon: string;
  color?: string;
  size?: number;
  outline?: boolean;
}

export const HeroIcon = (props: Props): JSX.Element => {
  const { icon, color, size, outline = false } = props;

  const { ...icons } = outline ? OutlineIcons : SolidIcons;

  // @ts-ignore
  const Icon: JSX.Element = icons[icon];

  const classes = [
    `${color ? color : 'text-black'}`,
    `h-${size ? size : 6}`,
    `w-${size ? size : 6}`
  ];

  return (
    // @ts-ignore
    <Icon className={classes.join(' ')} />
  );
};
```
<p>and I can later use it as such:</p>
<pre class="lang-js prettyprint-override"><code><HeroIcon icon='CogIcon' color='text-blue-600' size={6} outline />
</code>```

While it works on my development server:

the moment I build the project with npm run build and start it with npm start I'm getting this result instead:

and on mobile devices, icons are not visible at all.

The page is pre-rendered with SSG and uses both getStaticPaths and getStaticProps.

Any idea what might be the reason?

答:
This code is the problem

  const classes = [
    `${color ? color : 'text-black'}`,
    `h-${size ? size : 6}`,
    `w-${size ? size : 6}`
  ];
```
<p>If you want to change Tailwind CSS styles dynamically, write your code like this instead.</p>
<pre class="lang-js prettyprint-override"><code>  const classes = [
    `${color ? color : 'text-black'}`,
    size ? 'h-12' : 'h-6',
    size ? 'w-12' : 'w-6',
  ];
</code>```

This is due to how Purge CSS works, and Tailwind CSS uses Purge CSS under the hood to optimize your Tailwind CSS classes for production.

Sadly, you cannot write your class like h-{x}, since Tailwind CSS is purged at build time and h-{x} does not evaluate to valid Tailwind CSS class.

Reference

https://v2.tailwindcss.com/docs/optimizing-for-production#writing-purgeable-html

Title: Dynamic Heroicons import with Next.js

Body:
I'm using heroicons in my Next.js project and since it currently doesn't support dynamic imports (by passing icon name to component) I created my own component.

// HeroIcon.tsx
import * as SolidIcons from '@heroicons/react/solid';
import * as OutlineIcons from '@heroicons/react/outline';

interface Props {
  icon: string;
  color?: string;
  size?: number;
  outline?: boolean;
}

export const HeroIcon = (props: Props): JSX.Element => {
  const { icon, color, size, outline = false } = props;

  const { ...icons } = outline ? OutlineIcons : SolidIcons;

  // @ts-ignore
  const Icon: JSX.Element = icons[icon];

  const classes = [
    `${color ? color : 'text-black'}`,
    `h-${size ? size : 6}`,
    `w-${size ? size : 6}`
  ];

  return (
    // @ts-ignore
    <Icon className={classes.join(' ')} />
  );
};

and I can later use it as such:

<HeroIcon icon='CogIcon' color='text-blue-600' size={6} outline />

While it works on my development server:

the moment I build the project with npm run build and start it with npm start I'm getting this result instead:

and on mobile devices, icons are not visible at all.

The page is pre-rendered with SSG and uses both getStaticPaths and getStaticProps.

Any idea what might be the reason?

Body:
This code is the problem

  const classes = [
    `${color ? color : 'text-black'}`,
    `h-${size ? size : 6}`,
    `w-${size ? size : 6}`
  ];

If you want to change Tailwind CSS styles dynamically, write your code like this instead.

  const classes = [
    `${color ? color : 'text-black'}`,
    size ? 'h-12' : 'h-6',
    size ? 'w-12' : 'w-6',
  ];

This is due to how Purge CSS works, and Tailwind CSS uses Purge CSS under the hood to optimize your Tailwind CSS classes for production.

Sadly, you cannot write your class like h-{x}, since Tailwind CSS is purged at build time and h-{x} does not evaluate to valid Tailwind CSS class.

Reference

https://v2.tailwindcss.com/docs/optimizing-for-production#writing-purgeable-html


问:
INSERT 6000 Rows - best practice
I have a PHP script that calls an API method that can easily return 6k+ results.

I use PEAR DB_DataObject to write each row in a foreach loop to the DB.

The above script is batch processing 20 users at a time - and although some will only have a few results from the API others will have more. Worst case is that all have 1000's of results.

The loop to call the API seems to be ok, batches of 20 every 5 minutes works fine. My only concern is 1000's of mysql INSERTs for each user (with a long pause between each user for fresh API calls)

Is there a good way to do this? Or am I doing it a good way?!

答:
Well, the fastest way to do it would be to do one insert statement with lots of values, like this:

```<code>INSERT INTO mytable (col1, col2) VALUES ( (?,?), (?,?), (?,?), ...)
</code>```

But that would probably require ditching the DB_DataObject method you are using now.  You'll just have to weigh the performance benefits of doing it that way vs. the "ease of use" benefits of using DB_DataObject.

ContentLicense: CC BY-SA 2.5

Title: INSERT 6000 Rows - best practice

Body:
Well, the fastest way to do it would be to do one insert statement with lots of values, like this:

INSERT INTO mytable (col1, col2) VALUES ( (?,?), (?,?), (?,?), ...)

But that would probably require ditching the DB_DataObject method you are using now.  You'll just have to weigh the performance benefits of doing it that way vs. the "ease of use" benefits of using DB_DataObject.

OwnerDisplayName: Eric P


问:
How to replace path in file in docker container with perl or sed
I am working on automation script that can set some parameters in docker container. I want to replace path path.repo: /var/backups with path.repo: /var/log/elasticsearch in yaml file in container so I use commands below:

```<code>old_path=/var/backups
new_path=/var/log/elasticsearch

docker exec elk sed -i '0,/${old_path}/s//${new_path}/' /etc/elasticsearch/elasticsearch.yml
</code>```

or

```<code>docker exec elk sed -i -E 's/^([^ ]*\s+)(\/var\/backups)(\s.*)/\1\2\/var\/log\/elasticsearch\3/' /etc/elasticsearch/elasticsearch.yml
</code>```

None of them is working. When I log in docker container and opening the yml file, it still remains same. Am I doing something wrong maybe with docker commands?
I also tried:

```<code>perl -i -p -e's{"/var/backups"}{/var/log/elasticsearch' /etc/elasticsearch/elasticsearch.yml
</code>```

Thanks in advance

答:
A problem with your first attempt is that setting variables in your local shell doesn't expose them inside your docker container (and using single quotes around your arguments prevents your local shell from expanding them)...and even if you were to substitute the variable values in that expression, the / characters in your path would muck with your sed command. The simplest solution here is probably something like this:

```<code>docker exec elk sed -i 's|/var/backups|/var/log/elasticsearch|' /etc/elasticsearch/elasticsearch.yml
</code>```

Note the use of | instead of / as the sed expression delimiter to avoid conflicts with the path separators. That only works with the s command, so if you really need to limit the scope of those changes with a search expression you'll need something like:

```<code>docker exec elk sed -i '0,/\/var\/backups/ s|/var/backups|/var/log/elasticsearch|' /etc/elasticsearch/elasticsearch.yml
</code>```

That's pretty much the equivalent of your first example.

Having said that, editing content inside a running container is generally considered an anti-pattern: your best course of action is almost always to generate a new image with the changes baked in by using an appropriate Dockerfile.

Body:
I am working on automation script that can set some parameters in docker container. I want to replace path path.repo: /var/backups with path.repo: /var/log/elasticsearch in yaml file in container so I use commands below:

old_path=/var/backups
new_path=/var/log/elasticsearch

docker exec elk sed -i '0,/${old_path}/s//${new_path}/' /etc/elasticsearch/elasticsearch.yml

or

docker exec elk sed -i -E 's/^([^ ]*\s+)(\/var\/backups)(\s.*)/\1\2\/var\/log\/elasticsearch\3/' /etc/elasticsearch/elasticsearch.yml

None of them is working. When I log in docker container and opening the yml file, it still remains same. Am I doing something wrong maybe with docker commands?
I also tried:

perl -i -p -e's{"/var/backups"}{/var/log/elasticsearch' /etc/elasticsearch/elasticsearch.yml

Thanks in advance

Body:
A problem with your first attempt is that setting variables in your local shell doesn't expose them inside your docker container (and using single quotes around your arguments prevents your local shell from expanding them)...and even if you were to substitute the variable values in that expression, the / characters in your path would muck with your sed command. The simplest solution here is probably something like this:

docker exec elk sed -i 's|/var/backups|/var/log/elasticsearch|' /etc/elasticsearch/elasticsearch.yml

Note the use of | instead of / as the sed expression delimiter to avoid conflicts with the path separators. That only works with the s command, so if you really need to limit the scope of those changes with a search expression you'll need something like:

docker exec elk sed -i '0,/\/var\/backups/ s|/var/backups|/var/log/elasticsearch|' /etc/elasticsearch/elasticsearch.yml

That's pretty much the equivalent of your first example.

Having said that, editing content inside a running container is generally considered an anti-pattern: your best course of action is almost always to generate a new image with the changes baked in by using an appropriate Dockerfile.


问:
How to size a SingleChildScrollView dynamically inside a Column?
I'm having a bit of a problem with Flutter's widget placement. Here's the code:

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;
  final _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        controller: _scrollController,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              controller: _scrollController,
              child: DataTable(
                //Rows and columns filled with random data
                columns: const <DataColumn>[
                  DataColumn(
                    label: Text(
                      'Name',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Age',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Role',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Name',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Age',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Role',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                ],
                rows: const <DataRow>[
                  DataRow(
                    cells: <DataCell>[
                      DataCell(Text('Sarah')),
                      DataCell(Text('19')),
                      DataCell(Text('Student')),
                      DataCell(Text('Sarah')),
                      DataCell(Text('19')),
                      DataCell(Text('Student')),
                    ],
                  ),
                  DataRow(
                    cells: <DataCell>[
                      DataCell(Text('Janine')),
                      DataCell(Text('43')),
                      DataCell(Text('Professor')),
                      DataCell(Text('Sarah')),
                      DataCell(Text('19')),
                      DataCell(Text('Student')),
                    ],
                  ),
                  DataRow(
                    cells: <DataCell>[
                      DataCell(Text('William')),
                      DataCell(Text('27')),
                      DataCell(Text('Associate Professor')),
                      DataCell(Text('Sarah')),
                      DataCell(Text('19')),
                      DataCell(Text('Student')),
                    ],
                  ),
                ],
              ),
            ),
            //How to make this widget be at the bottom?
            const Text('This widget should be at the bottom'),
          ],
        ),
      ),
    );
  }
}
</code>```

I have a DataTable and a Text widget, wrapped with a Column and two SingleChilScrollViews in order to have bidirectional scrolling (the table is larger than the screen). I want to place the Text widget on the bottom of the screen. Tinkering with the code, I can do it pretty easily by giving the Column widget a parent Container, and fixing its size to my screen. However, how would I go about sizing it dynamically? I've tried using MediaQuery but the result was not that accurate. This "fix" can be found below:

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;
  final _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        controller: _scrollController,
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                controller: _scrollController,
                child: DataTable(
                  //Rows and columns filled with random data
                  columns: const <DataColumn>[
                    DataColumn(
                      label: Text(
                        'Name',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Age',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Role',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Name',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Age',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Role',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                  ],
                  rows: const <DataRow>[
                    DataRow(
                      cells: <DataCell>[
                        DataCell(Text('Sarah')),
                        DataCell(Text('19')),
                        DataCell(Text('Student')),
                        DataCell(Text('Sarah')),
                        DataCell(Text('19')),
                        DataCell(Text('Student')),
                      ],
                    ),
                    DataRow(
                      cells: <DataCell>[
                        DataCell(Text('Janine')),
                        DataCell(Text('43')),
                        DataCell(Text('Professor')),
                        DataCell(Text('Sarah')),
                        DataCell(Text('19')),
                        DataCell(Text('Student')),
                      ],
                    ),
                    DataRow(
                      cells: <DataCell>[
                        DataCell(Text('William')),
                        DataCell(Text('27')),
                        DataCell(Text('Associate Professor')),
                        DataCell(Text('Sarah')),
                        DataCell(Text('19')),
                        DataCell(Text('Student')),
                      ],
                    ),
                  ],
                ),
              ),
              //How to make this widget be at the bottom?
              const Text('This widget should be at the bottom'),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

Any ideas or suggestions on how to tackle this issue? Thanks.

EDIT

Using the text in the bottomNavigationBar of the Scaffold works as well, however it doens't seem an appropriate solution.

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;
  final _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: ListView(
        children: [
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: DataTable(
              //Rows and columns filled with random data
              columns: const <DataColumn>[
                DataColumn(
                  label: Text(
                    'Name',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Age',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Role',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Name',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Age',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Role',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
              ],
              rows: const <DataRow>[
                DataRow(
                  cells: <DataCell>[
                    DataCell(Text('Sarah')),
                    DataCell(Text('19')),
                    DataCell(Text('Student')),
                    DataCell(Text('Sarah')),
                    DataCell(Text('19')),
                    DataCell(Text('Student')),
                  ],
                ),
                DataRow(
                  cells: <DataCell>[
                    DataCell(Text('Janine')),
                    DataCell(Text('43')),
                    DataCell(Text('Professor')),
                    DataCell(Text('Sarah')),
                    DataCell(Text('19')),
                    DataCell(Text('Student')),
                  ],
                ),
                DataRow(
                  cells: <DataCell>[
                    DataCell(Text('William')),
                    DataCell(Text('27')),
                    DataCell(Text('Associate Professor')),
                    DataCell(Text('Sarah')),
                    DataCell(Text('19')),
                    DataCell(Text('Student')),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
      bottomNavigationBar: const Text('Is at the bottom - doesnt seem right'),
    );
  }
}
</code>```

答:
I found a more elegant solution while tinkering with my code and the provided answers. I wrapped the Scaffold's body in a Column and used 2 expanded widgets: one for my bottom widget and another one for the ScrollViews and Table. Here's the final body:</p>
```<code>  body: Column(
    children: [
      Expanded(
        flex: 9,
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          controller: _scrollController,
          child: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            controller: _scrollController,
            child: DataTable(
              columns: _controller.columns,
              rows: _controller.rows,
            ),
          ),
        ),
      ),
      Expanded(
        child: Total(_controller.total),
      ),
    ],
  ),
</code>```

Body:
I'm having a bit of a problem with Flutter's widget placement. Here's the code:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;
  final _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        controller: _scrollController,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              controller: _scrollController,
              child: DataTable(
                //Rows and columns filled with random data
                columns: const <DataColumn>[
                  DataColumn(
                    label: Text(
                      'Name',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Age',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Role',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Name',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Age',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Role',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                ],
                rows: const <DataRow>[
                  DataRow(
                    cells: <DataCell>[
                      DataCell(Text('Sarah')),
                      DataCell(Text('19')),
                      DataCell(Text('Student')),
                      DataCell(Text('Sarah')),
                      DataCell(Text('19')),
                      DataCell(Text('Student')),
                    ],
                  ),
                  DataRow(
                    cells: <DataCell>[
                      DataCell(Text('Janine')),
                      DataCell(Text('43')),
                      DataCell(Text('Professor')),
                      DataCell(Text('Sarah')),
                      DataCell(Text('19')),
                      DataCell(Text('Student')),
                    ],
                  ),
                  DataRow(
                    cells: <DataCell>[
                      DataCell(Text('William')),
                      DataCell(Text('27')),
                      DataCell(Text('Associate Professor')),
                      DataCell(Text('Sarah')),
                      DataCell(Text('19')),
                      DataCell(Text('Student')),
                    ],
                  ),
                ],
              ),
            ),
            //How to make this widget be at the bottom?
            const Text('This widget should be at the bottom'),
          ],
        ),
      ),
    );
  }
}

I have a DataTable and a Text widget, wrapped with a Column and two SingleChilScrollViews in order to have bidirectional scrolling (the table is larger than the screen). I want to place the Text widget on the bottom of the screen. Tinkering with the code, I can do it pretty easily by giving the Column widget a parent Container, and fixing its size to my screen. However, how would I go about sizing it dynamically? I've tried using MediaQuery but the result was not that accurate. This "fix" can be found below:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;
  final _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        controller: _scrollController,
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                controller: _scrollController,
                child: DataTable(
                  //Rows and columns filled with random data
                  columns: const <DataColumn>[
                    DataColumn(
                      label: Text(
                        'Name',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Age',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Role',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Name',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Age',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Role',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                  ],
                  rows: const <DataRow>[
                    DataRow(
                      cells: <DataCell>[
                        DataCell(Text('Sarah')),
                        DataCell(Text('19')),
                        DataCell(Text('Student')),
                        DataCell(Text('Sarah')),
                        DataCell(Text('19')),
                        DataCell(Text('Student')),
                      ],
                    ),
                    DataRow(
                      cells: <DataCell>[
                        DataCell(Text('Janine')),
                        DataCell(Text('43')),
                        DataCell(Text('Professor')),
                        DataCell(Text('Sarah')),
                        DataCell(Text('19')),
                        DataCell(Text('Student')),
                      ],
                    ),
                    DataRow(
                      cells: <DataCell>[
                        DataCell(Text('William')),
                        DataCell(Text('27')),
                        DataCell(Text('Associate Professor')),
                        DataCell(Text('Sarah')),
                        DataCell(Text('19')),
                        DataCell(Text('Student')),
                      ],
                    ),
                  ],
                ),
              ),
              //How to make this widget be at the bottom?
              const Text('This widget should be at the bottom'),
            ],
          ),
        ),
      ),
    );
  }
}

Any ideas or suggestions on how to tackle this issue? Thanks.

EDIT

Using the text in the bottomNavigationBar of the Scaffold works as well, however it doens't seem an appropriate solution.

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;
  final _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: ListView(
        children: [
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: DataTable(
              //Rows and columns filled with random data
              columns: const <DataColumn>[
                DataColumn(
                  label: Text(
                    'Name',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Age',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Role',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Name',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Age',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Role',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
              ],
              rows: const <DataRow>[
                DataRow(
                  cells: <DataCell>[
                    DataCell(Text('Sarah')),
                    DataCell(Text('19')),
                    DataCell(Text('Student')),
                    DataCell(Text('Sarah')),
                    DataCell(Text('19')),
                    DataCell(Text('Student')),
                  ],
                ),
                DataRow(
                  cells: <DataCell>[
                    DataCell(Text('Janine')),
                    DataCell(Text('43')),
                    DataCell(Text('Professor')),
                    DataCell(Text('Sarah')),
                    DataCell(Text('19')),
                    DataCell(Text('Student')),
                  ],
                ),
                DataRow(
                  cells: <DataCell>[
                    DataCell(Text('William')),
                    DataCell(Text('27')),
                    DataCell(Text('Associate Professor')),
                    DataCell(Text('Sarah')),
                    DataCell(Text('19')),
                    DataCell(Text('Student')),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
      bottomNavigationBar: const Text('Is at the bottom - doesnt seem right'),
    );
  }
}

Body:
I found a more elegant solution while tinkering with my code and the provided answers. I wrapped the Scaffold's body in a Column and used 2 expanded widgets: one for my bottom widget and another one for the ScrollViews and Table. Here's the final body:

  body: Column(
    children: [
      Expanded(
        flex: 9,
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          controller: _scrollController,
          child: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            controller: _scrollController,
            child: DataTable(
              columns: _controller.columns,
              rows: _controller.rows,
            ),
          ),
        ),
      ),
      Expanded(
        child: Total(_controller.total),
      ),
    ],
  ),


问:
Function empty object check

I need help this task
You have to implement function that will
Check that object is empty.
Object considered to be empty when it has no properties or all its properties are false (I.e. 0, “”, false …)

check object for presence: {},0, “”, symbol(“key”), null, 5,[].

答:
You can use something like this.
This will just loop through the object and check if any value exist and if it does it will just return false else it will return true.

function isEmpty(obj) {
  for (let key in obj) {
     if(!!obj[key]) return false;
   }
   return true;
}
```

Title: Function empty object check


问:
Angular6 Can't use ternary operator in ngClass with multiple entries
I'm trying to add multiple classes by ngClass, and I'm confused as to why I can't use ternary operator here.

```<code><div [ngClass]="{'otherClass': otherFlag, classFlag ? 'class--true': 'class--false'}>
</code>```

I get the following error:

```<code>Parser Error: Missing expected } at column 37 in [{'otherClass': otherFlag, classFlag ? 'class--true': 'class--false'}]
</code>```

I'm aware I can do the following:

```<code><div [ngClass]="{
'otherClass': otherFlag,
'class--true': classFlag,
'class--false': !classFlag
}">
</code>```

Just trying to understand why I can't use ternary operator here (or maybe I'm doing it wrong). I would appreciate the help in understanding this.

Edit: Thank you for both answers. I mostly understood it thanks to Bryan's answer, but both were helpful.

答:
You can't use ternary operator this way because the value of ngClass is a JavaScript object and your class name is used as a key of the object. The ternary operator can only be used for values, not for keys.

You can do this in a JSON:

{
 "key": condition ? value : otherValue
}
```
<p>But you <strong>can't</strong> do that:</p>
<pre class="lang-js prettyprint-override"><code>{
 condition ? "key" : "otherKey": value
}
</code>```

To do what you want to do you have to use [class] instead of [ngCLass]. Like that:

```

Body:
I'm trying to add multiple classes by ngClass, and I'm confused as to why I can't use ternary operator here.

I get the following error:

Parser Error: Missing expected } at column 37 in [{'otherClass': otherFlag, classFlag ? 'class--true': 'class--false'}]

I'm aware I can do the following:

Just trying to understand why I can't use ternary operator here (or maybe I'm doing it wrong). I would appreciate the help in understanding this.

Edit: Thank you for both answers. I mostly understood it thanks to Bryan's answer, but both were helpful.

Body:
You can't use ternary operator this way because the value of ngClass is a JavaScript object and your class name is used as a key of the object. The ternary operator can only be used for values, not for keys.

You can do this in a JSON:

{
 "key": condition ? value : otherValue
}

But you can't do that:

{
 condition ? "key" : "otherKey": value
}

To do what you want to do you have to use [class] instead of [ngCLass]. Like that:

<div [class]="classFlag ? 'class--true' : 'class--false'">


问:
How do you create a news archive in umbraco?
I'm trying to create a news archive in umbraco, where it would display a list of news pages organised by month. Each page would display a listing of the news items of that month.

I've followed the tutorial for creating news items, but I'm not sure how to create an archive. There doesn't seem to be any references to do this online either. Surely it's a common use case for the CMS.

Anyone have any ideas (preferably in razorscript if coding is required)?

答:
The most obvious solution in Umbraco would be to arrange your folder structure in the 'Content' section to match how you want the site to arrange items and then use simple xsl transformations to build the index pages.

Code two templates ('Settings' section), one to show the index for each month and another to display the individual article.

So a folder structure like:

```<code>> Content
> |--Home
>     |--2011
>         |--01 January
>             |--News article 1
>             |--News article 2
>             |--News article 3
>             |--News article 4
>         |--02 February
>             |--News article 5
>             |--News article 6
>             |--News article 7
</code>```

Then use some simple xsl added as a macro to the index template (similar to the following) to run round the news articles (I got this from umbNewsListItems.xslt which I think came from the news sample site):

```<code><xsl:template match="/">

<!-- The fun starts here -->

<div class="newsList">
<xsl:for-each select="$currentPage/* [@isDoc and string(umbracoNaviHide) != '1']">
  <xsl:sort select="@updateDate" order="ascending" />
   <h3 class="headline"> <a href="{umbraco.library:NiceUrl(@id)}">
      <xsl:value-of select="@nodeName"/>
    </a>
  </h3>
  <small class="meta">Posted: <xsl:value-of select="umbraco.library:LongDate(@updateDate, true(), ' - ')"/></small><br/>
  <p class="introduction">
    <xsl:value-of select="umbraco.library:ReplaceLineBreaks(introduction)" disable-output-escaping="yes"/>
  </p>

</xsl:for-each>
  </div>

</xsl:template>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The most obvious solution in Umbraco would be to arrange your folder structure in the 'Content' section to match how you want the site to arrange items and then use simple xsl transformations to build the index pages.

Code two templates ('Settings' section), one to show the index for each month and another to display the individual article.

So a folder structure like:

> Content
> |--Home
>     |--2011
>         |--01 January
>             |--News article 1
>             |--News article 2
>             |--News article 3
>             |--News article 4
>         |--02 February
>             |--News article 5
>             |--News article 6
>             |--News article 7

Then use some simple xsl added as a macro to the index template (similar to the following) to run round the news articles (I got this from umbNewsListItems.xslt which I think came from the news sample site):

<xsl:template match="/">

<!-- The fun starts here -->

<div class="newsList">
<xsl:for-each select="$currentPage/* [@isDoc and string(umbracoNaviHide) != '1']">
  <xsl:sort select="@updateDate" order="ascending" />
   <h3 class="headline"> <a href="{umbraco.library:NiceUrl(@id)}">
      <xsl:value-of select="@nodeName"/>
    </a>
  </h3>
  <small class="meta">Posted: <xsl:value-of select="umbraco.library:LongDate(@updateDate, true(), ' - ')"/></small><br/>
  <p class="introduction">
    <xsl:value-of select="umbraco.library:ReplaceLineBreaks(introduction)" disable-output-escaping="yes"/>
  </p>

</xsl:for-each>
  </div>

</xsl:template>


问:
Mysql query to get distinct row with column having null and duplicate values
So I have a weird situation in which I have a table like this :

```<code>mysql> select * from test;
+-------+------+
| name  | sal  |
+-------+------+
| agent | 1000 |
| agent | 2000 |
| NULL  | 3000 |
| NULL  | 4000 |
| smith | 5000 |
| smith | 6000 |
| neo   | 7000 |
+-------+------+
</code>```

I want to return a data set which looks like this :

```<code>+-------+------+
| name  | sal  |
+-------+------+
| agent | 1000 |
| NULL  | 3000 |
| NULL  | 4000 |
| smith | 5000 |
| neo   | 7000 |
+-------+------+
</code>```

Meaning I want to fetch unique rows wherever name is duplicated, but fetch all rows as it is when name is null or is not duplicated.

I have written this query below in order to achieve that and it works fine. But I want to optimize it.

```<code>select *
from test
where sal in (
                select sal from (
                        select min(sal) as sal
                        from test
                        group by name
                    union
                        select sal
                        from test where name is null
                ) t
order by sal);
</code>```

Queries for creating this sample data -

```<code>create table test (name text, sal int);
insert into test values ('agent',1000);
insert into test values ('agent',2000);
insert into test values (null,3000);
insert into test values (null,4000);
insert into test values ('smith',5000);
insert into test values ('smith',6000);
insert into test values ('neo',7000);
</code>```

Can anyone help me with that? I know that we shouldn't use IN to fetch data because that will increase the query time a lot in production.

Any help is appreciated!

答:
You can try to use two queries with UNION ALL one is for name which value is null, another one writes MIN aggregate function by name with name isn't NULL.

Query #1

```<code>SELECT *
FROM (
  SELECT name,sal
  FROM test
  WHERE name IS NULL
  UNION ALL
  SELECT name,min(sal)
  FROM test
  WHERE name IS NOT NULL
  group by name
)t1
ORDER BY sal;
</code>```

name
sal

agent
1000

3000

4000

smith
5000

neo
7000

View on DB Fiddle

Note

You can try to create an index on name column which might help you improve the query performance

Body:
So I have a weird situation in which I have a table like this :

mysql> select * from test;
+-------+------+
| name  | sal  |
+-------+------+
| agent | 1000 |
| agent | 2000 |
| NULL  | 3000 |
| NULL  | 4000 |
| smith | 5000 |
| smith | 6000 |
| neo   | 7000 |
+-------+------+

I want to return a data set which looks like this :

+-------+------+
| name  | sal  |
+-------+------+
| agent | 1000 |
| NULL  | 3000 |
| NULL  | 4000 |
| smith | 5000 |
| neo   | 7000 |
+-------+------+

Meaning I want to fetch unique rows wherever name is duplicated, but fetch all rows as it is when name is null or is not duplicated.

I have written this query below in order to achieve that and it works fine. But I want to optimize it.

select *
from test
where sal in (
                select sal from (
                        select min(sal) as sal
                        from test
                        group by name
                    union
                        select sal
                        from test where name is null
                ) t
order by sal);

Queries for creating this sample data -

create table test (name text, sal int);
insert into test values ('agent',1000);
insert into test values ('agent',2000);
insert into test values (null,3000);
insert into test values (null,4000);
insert into test values ('smith',5000);
insert into test values ('smith',6000);
insert into test values ('neo',7000);

Can anyone help me with that? I know that we shouldn't use IN to fetch data because that will increase the query time a lot in production.

Any help is appreciated!

Body:
You can try to use two queries with UNION ALL one is for name which value is null, another one writes MIN aggregate function by name with name isn't NULL.

Query #1

SELECT *
FROM (
  SELECT name,sal
  FROM test
  WHERE name IS NULL
  UNION ALL
  SELECT name,min(sal)
  FROM test
  WHERE name IS NOT NULL
  group by name
)t1
ORDER BY sal;

name
sal

agent
1000

3000

4000

smith
5000

neo
7000

View on DB Fiddle

Note

You can try to create an index on name column which might help you improve the query performance


问:
Automapper ProjectTo maps the subTypes also which not required while using OData
I have Implemented ODATA and Automapper and facing 2 problems.

1 problem:

If I am using the Data Layer Models, It is giving me correct result:

```<code>[EnableQuery]
 public IQueryable<Student> GetStudentTest()
 {
   return _studentService.RetrieveStudent();
 }
</code>```

and the expected result is correct where enrollments and Studentaddress is null:

```<code>studentId : 1
firstName : "Captain"
firMiddleName : "Cool"
lastName : "Marvel"
enrollmentDate : "2021-12-28T06:52:52.743"
enrollments : null
studentAddresses : null
</code>```

But When I use the Automapper and DTO:

```<code>[EnableQuery]
public IQueryable<StudentsDTO> GetStudent()
{
 return _mapper.ProjectTo<StudentsDTO>(_studentService.RetrieveStudent());
}
</code>```

The result is wrong that is it gives me result with enrollment and results:

```<code>[
    {
        "studentId": 1,
        "firstName": "Captain",
        "firMiddleName": "Cool",
        "lastName": "Marvel",
        "enrollmentDate": "2021-12-28T06:52:52.743",
        "enrollments": [
            {
                "enrollmentId": 1,
                "courseId": 1,
                "studentId": 1,
                "grade": 1,
                "course": {
                    "courseId": 1,
                    "title": "Course1",
                    "credits": 5,
                    "enrollments": null
                },
                "student": null
            }
        ],
        "studentAddresses": [
            {
                "addressId": 1,
                "houseNumber": "5/133",
                "city": "Lucknow",
                "state": "UttarPradesh",
                "studentId": 1,
                "students": null
            }
        ]
    }
]
</code>```

2 Problem:

Using OData and Automapper with the query like $expand within $expand:

```<code>/api/v1/GetEnrollments?$expand=Student($expand=StudentAddresses),Course
</code>```

The ProjectTo of automapper doesnt able to bind the data to subtypes as mentioned studentAddresses.

The answers and suggestions will be much appreciated.
odata automapper

答:
I recently wrote about this, though the question is unrelated, the reasoning is the same: OData accent-insensitive filter

Queryable Extensions

ProjectTo must be the last call in the chain. ORMs work with entities, not DTOs. So apply any filtering and sorting on entities and, as the last step, project to DTOs.

The reason that the 2nd example doesn't work is that the data has already been enumerated into memory, before the $expand clause was applied, calling $expand or Include on the in-memory collection will not result in any additional call to the database to retrieve the missing data.

Instead we need to use an additional package: AutoMapper.Extensions.ExpressionMapping that will give us access to the UseAsDataSource extension method.

UseAsDataSource

Mapping expressions to one another is a tedious and produces long ugly code.

UseAsDataSource().For() makes this translation clean by not having to explicitly map expressions. It also calls ProjectTo() for you as well, where applicable.

This changes your implementation to the following which should allow the EnableQueryAttribute to correctly apply the QueryOptions on the request to the underlying IQueryable<T> expression.

```<code>[EnableQuery]
public IQueryable<StudentsDTO> GetStudent()
{
    return _studentService.RetrieveStudent().UseAsDataSource().For<StudentsDTO>());
}
</code>```

NOTE:

The implementation of _studentService.RetrieveStudent() can still affect this execution, especially the how $expand might be applied. If it returns an IEnumerable<T> that is simply wrapped in an IQueryable<T> using the [AsQueryable()][3] extension then the results might not be as you expect, but it would not help to speculate in this post how to resolve this.

Body:
I have Implemented ODATA and Automapper and facing 2 problems.

1 problem:

If I am using the Data Layer Models, It is giving me correct result:

[EnableQuery]
 public IQueryable<Student> GetStudentTest()
 {
   return _studentService.RetrieveStudent();
 }

and the expected result is correct where enrollments and Studentaddress is null:

studentId : 1
firstName : "Captain"
firMiddleName : "Cool"
lastName : "Marvel"
enrollmentDate : "2021-12-28T06:52:52.743"
enrollments : null
studentAddresses : null

But When I use the Automapper and DTO:

[EnableQuery]
public IQueryable<StudentsDTO> GetStudent()
{
 return _mapper.ProjectTo<StudentsDTO>(_studentService.RetrieveStudent());
}

The result is wrong that is it gives me result with enrollment and results:

[
    {
        "studentId": 1,
        "firstName": "Captain",
        "firMiddleName": "Cool",
        "lastName": "Marvel",
        "enrollmentDate": "2021-12-28T06:52:52.743",
        "enrollments": [
            {
                "enrollmentId": 1,
                "courseId": 1,
                "studentId": 1,
                "grade": 1,
                "course": {
                    "courseId": 1,
                    "title": "Course1",
                    "credits": 5,
                    "enrollments": null
                },
                "student": null
            }
        ],
        "studentAddresses": [
            {
                "addressId": 1,
                "houseNumber": "5/133",
                "city": "Lucknow",
                "state": "UttarPradesh",
                "studentId": 1,
                "students": null
            }
        ]
    }
]

2 Problem:

Using OData and Automapper with the query like $expand within $expand:

/api/v1/GetEnrollments?$expand=Student($expand=StudentAddresses),Course

The ProjectTo of automapper doesnt able to bind the data to subtypes as mentioned studentAddresses.

The answers and suggestions will be much appreciated.
odata automapper

Body:
I recently wrote about this, though the question is unrelated, the reasoning is the same: OData accent-insensitive filter

Queryable Extensions

ProjectTo must be the last call in the chain. ORMs work with entities, not DTOs. So apply any filtering and sorting on entities and, as the last step, project to DTOs.

The reason that the 2nd example doesn't work is that the data has already been enumerated into memory, before the $expand clause was applied, calling $expand or Include on the in-memory collection will not result in any additional call to the database to retrieve the missing data.

Instead we need to use an additional package: AutoMapper.Extensions.ExpressionMapping that will give us access to the UseAsDataSource extension method.

UseAsDataSource

Mapping expressions to one another is a tedious and produces long ugly code.

UseAsDataSource().For() makes this translation clean by not having to explicitly map expressions. It also calls ProjectTo() for you as well, where applicable.

This changes your implementation to the following which should allow the EnableQueryAttribute to correctly apply the QueryOptions on the request to the underlying IQueryable<T> expression.

[EnableQuery]
public IQueryable<StudentsDTO> GetStudent()
{
    return _studentService.RetrieveStudent().UseAsDataSource().For<StudentsDTO>());
}

NOTE:

The implementation of _studentService.RetrieveStudent() can still affect this execution, especially the how $expand might be applied. If it returns an IEnumerable<T> that is simply wrapped in an IQueryable<T> using the [AsQueryable()][3] extension then the results might not be as you expect, but it would not help to speculate in this post how to resolve this.


问:
Xcode @IBDesignable Button Background Color Not Rendering In Storyboard
Trying to show the button background color in the storyboard, the following code renders the border width and radius correctly but background doesn't show. In the simulator, the button's background color is rendered correctly.

```<code>import UIKit

let colorSunset = #colorLiteral(red: 0.9693382382, green: 0.5568749309, blue: 0, alpha: 1)

@IBDesignable class PrimaryButtonA: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        buttonA()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        buttonA()
    }

    func buttonA() {
        self.layer.cornerRadius = 10
        self.layer.borderWidth = 5
        self.layer.backgroundColor = colorSunset.cgColor
    }

}
</code>```

Code Screenshot

Storyboard Screenshot

Simulator Screenshot

Xcode doesn't show any errors but there is a warning which is unrelated and is about the button's fixed width and height and the text will be clipped.

Thanks in advance for the help.

答: There is no solution to this. This problem occurs because some times storyboard does not recognize IBDesignables. When you restart your XCode sometimes it gets recognized and sometimes it doesn't.</p>

Body:
Trying to show the button background color in the storyboard, the following code renders the border width and radius correctly but background doesn't show. In the simulator, the button's background color is rendered correctly.

import UIKit

let colorSunset = #colorLiteral(red: 0.9693382382, green: 0.5568749309, blue: 0, alpha: 1)

@IBDesignable class PrimaryButtonA: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        buttonA()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        buttonA()
    }

    func buttonA() {
        self.layer.cornerRadius = 10
        self.layer.borderWidth = 5
        self.layer.backgroundColor = colorSunset.cgColor
    }

}

Code Screenshot

Storyboard Screenshot

Simulator Screenshot

Xcode doesn't show any errors but there is a warning which is unrelated and is about the button's fixed width and height and the text will be clipped.

Thanks in advance for the help.


问:
How to Draw Right Angled Triangle progress I can Fill It percentage wise
I need to draw something like this in the UI , And Unable to draw it in image View, Can anyone help me achieve this kind of design?

答:
An example of custom view in Java. This requires a triangle image in drawable folder.

public final class DrawTest extends View implements SeekBar.OnSeekBarChangeListener
{
    private final Bitmap bitmap;
    private final Paint paint;
    private final Rect src;
    private final Rect dst;
    private SeekBar seekBar;
    private int width, height;
    private final int imgWidth, imgHeight;

    public final DrawTest(final Context context)
    {
        this(context, null);
    }

    public final DrawTest(final Context context, final AttributeSet attrs)
    {
        this(context, attrs, -1);
    }

    public final DrawTest(final Context context, final AttributeSet attrs, final int defStyleAttr)
    {
        this(context, attrs, defStyleAttr, -1);
    }

    public final DrawTest(final Context context, final AttributeSet attrs, final int defStyleAttr, final int defStyleRes)
    {
        super(context, attrs, defStyleAttr, defStyleRes);

        src = new Rect();
        dst = new Rect();
        paint = new Paint();

        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.triangle);
        imgWidth = bitmap.getWidth();
        imgHeight = bitmap.getHeight();
    }

    @Override
    protected void onSizeChanged(final int w, final int h, final int oldw, final int oldh)
    {
        super.onSizeChanged(w, h, oldw, oldh);

        width = w;
        height = h;

        src.set(0, 0, imgWidth, imgHeight);
        dst.set(0, 0, w, h);

        seekBar = getRootView().findViewById(R.id.SeekBar);
        seekBar.setOnSeekBarChangeListener(this);
        seekBar.setMax(100);
        seekBar.setProgress(100);
    }

    public final int getWidth(final int percentage, final int width)
    {
        return (int)((width / 100F) * percentage);
    }

    @Override
    public final void onProgressChanged(final SeekBar seekBar, final int progress, boolean fromUser)
    {
        src.set(0, 0, getWidth(progress, imgWidth), height);
        dst.set(0, 0, getWidth(progress, width), height);
        invalidate();
    }
    @Override
    public final void onStartTrackingTouch(final SeekBar seekBar)
    {}
    @Override
    public final void onStopTrackingTouch(final SeekBar seekBar)
    {}

    @Override
    protected final void onDraw(final Canvas canvas)
    {
        super.onDraw(canvas);
        canvas.drawBitmap(bitmap, src, dst, paint);
    }
}
```


答:
Please try to use next code when you retrieve data from SP:

```<code>SharedPreferences sp1 = MainActivity.this.getSharedPreferences("data", Context.MODE_PRIVATE);
String pass = sp1.getString(userInput.getText().toString(), null);
if (pass != null) {
    Toast.makeText(MainActivity.this, "User Exists", Toast.LENGTH_SHORT).show();
} else{
    Toast.makeText(MainActivity.this, "User not found", Toast.LENGTH_SHORT).show();
}
</code>```

You are saving data in form of "user:pasword", so you need to get it the same way, using user name as the key.

Title: How can I get username and password from SharedPreferences in Android?

Body:
I am trying to recover the username and password to be able to start a session.
These are the users of the sharedPreferences.

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="admin">1234</string>
    <string name="user">user0987</string>
</map>

And this is the method

login.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        SharedPreferences sp1 = MainActivity.this.getSharedPreferences("data", Context.MODE_PRIVATE);
        String user = sp1.getString(userInput.getText().toString(), "User not found");
        String pass = sp1.getString(passwordInput.getText().toString(), "Password is not correct");

        if(user.equals(userInput.getText().toString()){
            Toast.makeText(MainActivity.this, "User Exists", Toast.LENGTH_SHORT).show();
        } else{
            Toast.makeText(MainActivity.this, "User not found", Toast.LENGTH_SHORT).show();
        }

    }
});

This is the code that puts data in SharedPreferences

register.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        String user = userInput.getText().toString();
        String pass = passwordInput.getText().toString();

        if(user.isEmpty()){
            error.show();
        } else if (pass.isEmpty()){
            error2.show();
        } else{
            SharedPreferences sp=getSharedPreferences("data", Context.MODE_PRIVATE);
            SharedPreferences.Editor Ed=sp.edit();
            Ed.putString(user,pass);
            Ed.commit();
            Toast.makeText(MainActivity.this, "Register completed", Toast.LENGTH_SHORT).show();
        }

    }
});

Body:
Please try to use next code when you retrieve data from SP:

SharedPreferences sp1 = MainActivity.this.getSharedPreferences("data", Context.MODE_PRIVATE);
String pass = sp1.getString(userInput.getText().toString(), null);
if (pass != null) {
    Toast.makeText(MainActivity.this, "User Exists", Toast.LENGTH_SHORT).show();
} else{
    Toast.makeText(MainActivity.this, "User not found", Toast.LENGTH_SHORT).show();
}

You are saving data in form of "user:pasword", so you need to get it the same way, using user name as the key.


问:
Outlook email render has issues
In my node js app I send an email. I take that html content from db as a string and replace some variables with dynamic values and send it as mail. When the mail comes to gmail, it looks perfect. But it's ruined in outlook.

This is my html content coming from database.

```<code><html>
   <body>
      <table border="0" cellspacing="0" cellpadding="0" style="max-width:600px">
         <tbody>
            <tr height="15"></tr>
            <tr>
               <td>
                  <table bgcolor="#007bff" width="100%">
                     <tbody>
                        <tr>
                           <td height="45px" colspan="3"></td>
                        </tr>
                        <tr>
                           <td width="30"></td>
                           <td style="font-size:24px;color:#ffffff;line-height:1">###emailSubject###</td>
                           <td width="30"></td>
                        </tr>
                        <tr td height="20px" colspan="3"></tr>
                     </tbody>
                  </table>
               </td>
            </tr>
            <tr>
               <td>
                  <table bgcolor="#FAFAFA" width="100%">
                     <tbody>
                        <tr height="15px">
                           <td width="15px" rowspan="5"></td>
                           <td></td>
                           <td width="15px" rowspan="5"></td>
                        </tr>
                        <tr>
                           <td>
                              <table bgcolor="#FAFAFA" width="100%" cellspacing="0" cellpadding="0">
                                 <tbody>
                                    <tr height="15px">
                                       <td width="20px" rowspan="5"></td>
                                       <td></td>
                                       <td width="20px" rowspan="3"></td>
                                    </tr>
                                    <tr>
                                       <td>
                                          <p>Hi team,</p>
                                          <p>Please find below details of the new request for ###widgetTitle###</p>
                                          <p><strong style="font-size:12px;font-weight:bold">Customer Name: </strong>###customerName###</p>
                                          <p><strong style="font-size:12px;font-weight:bold">Email Address : </strong>###email###</p>
                                          <p><strong style="font-size:12px;font-weight:bold">Contact Number: </strong>###contactNumber###</p>
                                          <p><strong style="font-size:12px;font-weight:bold">Requirement : </strong>###requirement###</p>
                                          <p>Location</p>
                                          <p><strong style="font-size:12px;font-weight:bold">Customer Address : </strong> ###customerAddress###</p>
                                          <p><strong style="font-size:12px;font-weight:bold">Longitude : </strong> ###longitude###</p>
                                          <p><strong style="font-size:12px;font-weight:bold">Latitude : </strong> ###latitude###</p>
                                          </p></p>
                                          <p>Marketing Agent Details</p>
                                          <p><strong style="font-size:12px;font-weight:bold">MA ID : </strong>###maId###</p>
                                          <p><strong style="font-size:12px;font-weight:bold">Name : </strong>###fullName###</p>
                                          <p><strong style="font-size:12px;font-weight:bold">Contact Number : </strong>###maContact###</p>
                                          <p><strong style="font-size:12px;font-weight:bold">Email : </strong>###maEmail###</p>
                                          <p>Contact the  team for more information.</p>
                                          <p><strong style="font-size:12px;font-weight:bold">Email address:</strong> sample email (Biz Hrs)</p>
                                          <p><b><i>This is an auto generated email sent by the Project name : do not reply or forward this email. </i></b></p>
                                          <p>Thank You,</p>
                                          <p>Team Project name</p>
                                       </td>
                                    </tr>
                                    <tr height="30px"></tr>
                                 </tbody>
                              </table>
                           </td>
                        </tr>
                        <tr height="30px"></tr>
                     </tbody>
                  </table>
               </td>
            </tr>
            <tr height="15"></tr>
         </tbody>
      </table>
   </body>
</html>
</code>```

This is the mail I got in my gmail.

This is what I got in my outlook.

I read about it a little and as I learned this has happened in outlook most of the time. But I couldn't find any solution that works in my case.

How can I solve this? Please help.

答:
The Outlooks on Windows use Word as a rendering engine. And they're not very good at rendering HTML. There are a few things in your code that are problematic in Outlook:

max-width:600px is only supported since the latest version (Outlook 2019). It is better to set a fixed width (width:600px) and add a max-width:100%.

There are straight code errors in your code (like

) that would probably make Outlook trippy.

Using empty cells and rows for spacing is not a good idea. (And I think the values of your rowspan is incorrect.) Better use padding on a .

Here’s a quick rewrite of your code with Outlook in mind.

<!DOCTYPE html>

   <meta charset="UTF-8" />
   <title>###emailSubject###</title>
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no, date=no, address=no, email=no, url=no" />

###emailSubject###

Hi team,

Please find below details of the new request for ###widgetTitle###

Customer Name: ###customerName###

Email Address : ###email###

Contact Number: ###contactNumber###

Requirement : ###requirement###

Location

Customer Address :  ###customerAddress###

Longitude :  ###longitude###

Latitude :  ###latitude###

Marketing Agent Details

MA ID : ###maId###

Name : ###fullName###

Contact Number : ###maContact###

Email : ###maEmail###

Contact the Marketplace team for more information.

Email address: support.marketplace@dialog.lk (Biz Hrs)

This is an auto generated email sent by the Marketplace : do not reply or forward this email.

Thank You,

Team Marketplace

```

If you want to learn more about email coding, I wrote Email Coding Guidelines to help you on the right track.

Title: Outlook email render has issues

Body:
In my node js app I send an email. I take that html content from db as a string and replace some variables with dynamic values and send it as mail. When the mail comes to gmail, it looks perfect. But it's ruined in outlook.

This is my html content coming from database.

                           ###emailSubject###

Hi team,

Please find below details of the new request for ###widgetTitle###

Customer Name: ###customerName###

Email Address : ###email###

Contact Number: ###contactNumber###

Requirement : ###requirement###

Location

Customer Address :  ###customerAddress###

Longitude :  ###longitude###

Latitude :  ###latitude###

Marketing Agent Details

MA ID : ###maId###

Name : ###fullName###

Contact Number : ###maContact###

Email : ###maEmail###

Contact the  team for more information.

Email address: sample email (Biz Hrs)

This is an auto generated email sent by the Project name : do not reply or forward this email.

Thank You,

Team Project name

This is the mail I got in my gmail.

This is what I got in my outlook.

I read about it a little and as I learned this has happened in outlook most of the time. But I couldn't find any solution that works in my case.

How can I solve this? Please help.

Body:
The Outlooks on Windows use Word as a rendering engine. And they're not very good at rendering HTML. There are a few things in your code that are problematic in Outlook:

max-width:600px is only supported since the latest version (Outlook 2019). It is better to set a fixed width (width:600px) and add a max-width:100%.

There are straight code errors in your code (like <tr td height="20px" colspan="3"></tr>) that would probably make Outlook trippy.

Using empty cells and rows for spacing is not a good idea. (And I think the values of your rowspan is incorrect.) Better use padding on a <td>.

Here’s a quick rewrite of your code with Outlook in mind.

<!DOCTYPE html>
<html lang="en" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head></head>
<head>
   <meta charset="UTF-8" />
   <title>###emailSubject###</title>
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no, date=no, address=no, email=no, url=no" />
   <!--[if mso]>
   <xml>
   <o:OfficeDocumentSettings>
      <o:PixelsPerInch>96</o:PixelsPerInch>
   </o:OfficeDocumentSettings>
   </xml>
   <![endif]-->
</head>
<body style="padding:0; margin:0; -webkit-text-size-adjust:none; text-size-adjust:none; background:#fff;">
   <div lang="en" style="background:#fff;">
      <table border="0" cellspacing="0" cellpadding="0" align="center" style="margin:0 auto; width:600px; max-width:100%;">
         <tr>
            <td style="padding:15px;">
                <table border="0" cellspacing="0" cellpadding="0" style="width:100%; background:#007bff;">
                  <tr>
                     <td style="padding:45px 30px 20px;">
                        <h1 style="margin:0; font:bold 24px/24px sans-serif; color:#fff;">###emailSubject###</h1>
                     </td>
                  </tr>
               </table>
               <table border="0" cellspacing="0" cellpadding="0" style="width:100%; background:#fafafa;">
                  <tr>
                     <td style="padding:30px 35px 50px; font:16px/1.25 sans-serif;">
                        <p>Hi team,</p>
                        <p>Please find below details of the new request for ###widgetTitle###</p>
                        <p><strong style="font-size:12px;">Customer Name: </strong>###customerName###</p>
                        <p><strong style="font-size:12px;">Email Address : </strong>###email###</p>
                        <p><strong style="font-size:12px;">Contact Number: </strong>###contactNumber###</p>
                        <p><strong style="font-size:12px;">Requirement : </strong>###requirement###</p>
                        <p>Location</p>
                        <p><strong style="font-size:12px;">Customer Address : </strong> ###customerAddress###</p>
                        <p><strong style="font-size:12px;">Longitude : </strong> ###longitude###</p>
                        <p><strong style="font-size:12px;">Latitude : </strong> ###latitude###</p>
                        <p>Marketing Agent Details</p>
                        <p><strong style="font-size:12px;">MA ID : </strong>###maId###</p>
                        <p><strong style="font-size:12px;">Name : </strong>###fullName###</p>
                        <p><strong style="font-size:12px;">Contact Number : </strong>###maContact###</p>
                        <p><strong style="font-size:12px;">Email : </strong>###maEmail###</p>
                        <p>Contact the Marketplace team for more information.</p>
                        <p><strong style="font-size:12px;">Email address:</strong> support.marketplace@dialog.lk (Biz Hrs)</p>
                        <p><b><i>This is an auto generated email sent by the Marketplace : do not reply or forward this email. </i></b></p>
                        <p>Thank You,</p>
                        <p>Team Marketplace</p>
                     </td>
                  </tr>
               </table>
            </td>
         </tr>
      </table>
   </div>
</body>
</html>

If you want to learn more about email coding, I wrote Email Coding Guidelines to help you on the right track.


问:
Get what x% of an element is
I'm trying to set the margins of an HTML element to be x% of its size. Tried using margin-bottom: 50% or margin-bottom: 50vm but it gets x% of the screen size.

Code:

#task_box {
  margin-bottom: 1%;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="task_box">
<input type="text" id="task_box">
<input type="text" id="task_box"></code>```

I want to set this to the task_box object.

答:
I think the only way to do this is using JS.

const taskBoxes = document.querySelectorAll(".task_box");

taskBoxes.forEach(taskBox => {
  var height = taskBox.offsetHeight;
  var marginBottom = height / 2;
  taskBox.style.marginBottom = marginBottom + 'px';
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.task_box {
  display: block;
}</code>```

<input type="text" class="task_box">
<input type="text" class="task_box">
<input type="text" class="task_box">```

Title: Get what x% of an element is

Body:
I'm trying to set the margins of an HTML element to be x% of its size. Tried using margin-bottom: 50% or margin-bottom: 50vm but it gets x% of the screen size.

Code:

#task_box {
  margin-bottom: 1%;
  display: block;
}

<input type="text" id="task_box">
<input type="text" id="task_box">
<input type="text" id="task_box">

I want to set this to the task_box object.

Body:
I think the only way to do this is using JS.

const taskBoxes = document.querySelectorAll(".task_box");

taskBoxes.forEach(taskBox => {
  var height = taskBox.offsetHeight;
  var marginBottom = height / 2;
  taskBox.style.marginBottom = marginBottom + 'px';
});

.task_box {
  display: block;
}

<input type="text" class="task_box">
<input type="text" class="task_box">
<input type="text" class="task_box">