问:
Plone 4.0.5 unified installer failing on Ubuntu 11.04 (natty) with zip/zlib error
I am a Plone newbie and am trying to install Plone 4.0.5 on Ubuntu 11.04 Natty using the Unified Installer.

I unpack the installer and run the ./install.sh zeo as root and I get the following error:

```
ZEO Cluster Install selected

Detailed installation log being written to /tmp/Plone-4.0.5-UnifiedInstaller/install.log

Root install method chosen. Will install for use by system user plone

Installing Plone 4.0.5 at /usr/local/Plone

User 'plone' already exists. No need to create it.
Skipping libjpeg build
Skipping zlib build
Skipping readline build
Installing Python 2.6.6. This takes a while...
Traceback (most recent call last):
  File "", line 1, in
LookupError: unknown encoding: zip
Python zlib support is missing; something went wrong in the zlib or python build.

Installation has failed.
See the detailed installation log at /tmp/Plone-4.0.5-UnifiedInstaller/install.log
to determine the cause.
```

I have installed these ubuntu packages too:

```
apt-get install zlib1g zlib1g-dev zlibc libghc6-zlib-dev zlibc
```

The install.log is quite big - I'm just including mentions of zlib here:

```
Starting at Tue May 17 14:12:46 SAST 2011
configure: WARNING: unrecognized options: --with-readline, --with-zlib, --disable-tk, --with-cxx
...
Failed to find the necessary bits to build these modules:
_bsddb             _sqlite3           _tkinter
bsddb185           dbm                gdbm
sunaudiodev        zlib
To find the necessary bits, look in setup.py in detect_modules() for the module's name.

Failed to build these modules:
crypt              nis
...
```

I can't find a setup.py in the installation files.

Any ideas what I should do or what I should be looking for?

Thank you.

答:
Works fine for me - but then I built it on a maverick system, then upgraded to natty.

Prereqs that I have that look necessary for you:

```<code>zlib1g-dev (which you have)
python-gdbm
libgdbm3
libsqlite3-0 (hard to imagine you would not have that)
python-tk
</code>```

bsddb & sunaudio are both part of the system python2.6 - you could try building with that (aptitude install python2.6, if necessary)

Body:
I am a Plone newbie and am trying to install Plone 4.0.5 on Ubuntu 11.04 Natty using the Unified Installer.

I unpack the installer and run the ./install.sh zeo as root and I get the following error:

ZEO Cluster Install selected

Detailed installation log being written to /tmp/Plone-4.0.5-UnifiedInstaller/install.log

Root install method chosen. Will install for use by system user plone

Installing Plone 4.0.5 at /usr/local/Plone

User 'plone' already exists. No need to create it.
Skipping libjpeg build
Skipping zlib build
Skipping readline build
Installing Python 2.6.6. This takes a while...
Traceback (most recent call last):
  File "", line 1, in
LookupError: unknown encoding: zip
Python zlib support is missing; something went wrong in the zlib or python build.

Installation has failed.
See the detailed installation log at /tmp/Plone-4.0.5-UnifiedInstaller/install.log
to determine the cause.

I have installed these ubuntu packages too:

apt-get install zlib1g zlib1g-dev zlibc libghc6-zlib-dev zlibc

The install.log is quite big - I'm just including mentions of zlib here:

Starting at Tue May 17 14:12:46 SAST 2011
configure: WARNING: unrecognized options: --with-readline, --with-zlib, --disable-tk, --with-cxx
...
Failed to find the necessary bits to build these modules:
_bsddb             _sqlite3           _tkinter
bsddb185           dbm                gdbm
sunaudiodev        zlib
To find the necessary bits, look in setup.py in detect_modules() for the module's name.

Failed to build these modules:
crypt              nis
...

I can't find a setup.py in the installation files.

Any ideas what I should do or what I should be looking for?

Thank you.

Body:
Works fine for me - but then I built it on a maverick system, then upgraded to natty.

Prereqs that I have that look necessary for you:

zlib1g-dev (which you have)
python-gdbm
libgdbm3
libsqlite3-0 (hard to imagine you would not have that)
python-tk

bsddb & sunaudio are both part of the system python2.6 - you could try building with that (aptitude install python2.6, if necessary)


来源: stackexchange

问:
Connect css fonts locally
I searched on the Internet how to connect fonts to the site, with a link to a local file, but could not find a complete answer anywhere. Please explain by points and in full what needs to be done to connect fonts to HTML and CSS files.</p>

答:
you can use this css to add your personalized fonts

@font-face {

```<code> font-family:'Your Font Name Here';

 src:url('path-to-your-font.ttf') format('truetype');
</code>```

}

Good Luck.

ContentLicense: CC BY-SA 4.0

Title: Connect css fonts locally

Body:
you can use this css to add your personalized fonts

@font-face {

 font-family:'Your Font Name Here';

 src:url('path-to-your-font.ttf') format('truetype');

}

Good Luck.


问:
Is it safe to reuse Faraday connection objects?
Is it safe to reuse Faraday connection objects, or is it better to recreate them every time?</p>

```<code>def connection
  @connection ||= Faraday.new('http://example.com') do |conn|
    conn.request :url_encoded
    # more configuration
  end
end
</code>```

答:
https://github.com/lostisland/faraday/blob/52e30bf8e8d79159f332088189cb7f7e536d1ba1/lib/faraday/connection.rb#L502

connection.get .post and all other methods duplicates params etc here.
It means each request shares nothing with each other and the parent Connection object.

It's safe to reuse.

ContentLicense: CC BY-SA 3.0

Body:
Is it safe to reuse Faraday connection objects, or is it better to recreate them every time?

def connection
  @connection ||= Faraday.new('http://example.com') do |conn|
    conn.request :url_encoded
    # more configuration
  end
end


问:
Wrong configuration in htaccess redirects from subfolder to main domain
I got website on subfolder https://lofty-tibiabot.com/new/

and when I want go to https://lofty-tibiabot.com/new/wp-admin

I have noticed when I put https://lofty-tibiabot.com/new/wp-admin/index.php it works correctly

it redirects me to https://lofty-tibiabot.com/wp-admin

what i have to do with that?

here is htaccess from https://lofty-tibiabot.com

```<code>Options -MultiViews +FollowSymlinks -Indexes

#
# If mod_security is enabled, attempt to disable it.
# - Note, this will work on the majority of hosts but on
#   MediaTemple, it is known to cause random Internal Server
#   errors. For MediaTemple, please remove the block below
#
<IfModule mod_security.c>
  # Turn off mod_security filtering.
  SecFilterEngine Off

  # The below probably isn't needed, but better safe than sorry.
  SecFilterScanPOST Off
</IfModule>

 RewriteEngine on
  RewriteBase /

#
# MyBB "search engine friendly" URL rewrites
# - Note, for these to work with MyBB please make sure you have
#   the setting enabled in the Admin CP and you have this file
#   named .htaccess
#
  <IfModule mod_rewrite.c>
  RewriteRule ^([^&]*)&(.*)$ https://lofty-tibiabot.com/$1?$2 [L,QSA,R=301]

  #RewriteCond %{HTTPS} off
  #RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

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

  RewriteRule ^forum-([0-9]+)\.html$ forumdisplay.php?fid=$1 [L,QSA]
  RewriteRule ^forum-([0-9]+)-page-([0-9]+)\.html$ forumdisplay.php?fid=$1&page=$2 [L,QSA]

  RewriteRule ^thread-([0-9]+)\.html$ showthread.php?tid=$1 [L,QSA]
  RewriteRule ^thread-([0-9]+)-page-([0-9]+)\.html$ showthread.php?tid=$1&page=$2 [L,QSA]
  RewriteRule ^thread-([0-9]+)-lastpost\.html$ showthread.php?tid=$1&action=lastpost [L,QSA]
  RewriteRule ^thread-([0-9]+)-nextnewest\.html$ showthread.php?tid=$1&action=nextnewest [L,QSA]
  RewriteRule ^thread-([0-9]+)-nextoldest\.html$ showthread.php?tid=$1&action=nextoldest [L,QSA]
  RewriteRule ^thread-([0-9]+)-newpost\.html$ showthread.php?tid=$1&action=newpost [L,QSA]
  RewriteRule ^thread-([0-9]+)-post-([0-9]+)\.html$ showthread.php?tid=$1&pid=$2 [L,QSA]

  RewriteRule ^post-([0-9]+)\.html$ showthread.php?pid=$1 [L,QSA]

  RewriteRule ^announcement-([0-9]+)\.html$ announcements.php?aid=$1 [L,QSA]

  RewriteRule ^user-([0-9]+)\.html$ member.php?action=profile&uid=$1 [L,QSA]

  RewriteRule ^calendar-([0-9]+)\.html$ calendar.php?calendar=$1 [L,QSA]
  RewriteRule ^calendar-([0-9]+)-year-([0-9]+)-month-([0-9]+)\.html$ calendar.php?calendar=$1&year=$2&month=$3 [L,QSA]
  RewriteRule ^calendar-([0-9]+)-year-([0-9]+)-month-([0-9]+)-day-([0-9]+)\.html$ calendar.php?action=dayview&calendar=$1&year=$2&month=$3&day=$4 [L,QSA]
  RewriteRule ^calendar-([0-9]+)-week-(n?[0-9]+)\.html$ calendar.php?action=weekview&calendar=$1&week=$2 [L,QSA]

  RewriteRule ^event-([0-9]+)\.html$ calendar.php?action=event&eid=$1 [L,QSA]

  # Google SEO workaround for search.php highlights:
# Make this rule the first rewrite rule in your .htaccess!
RewriteRule ^([^&]*)&(.*)$ https://lofty-tibiabot.com/$1?$2 [L,QSA,R=301]

# Google SEO 404:
ErrorDocument 404 /misc.php?google_seo_error=404

# Google SEO Sitemap:
RewriteRule ^sitemap\-([^./]+)\.xml$ misc.php?google_seo_sitemap=$1 [L,QSA,NC]

# Google SEO URL Forums:
RewriteRule ^Forum\-([^./]+)$ forumdisplay.php?google_seo_forum=$1 [L,QSA,NC]

# Google SEO URL Threads:
RewriteRule ^Thread\-([^./]+)$ showthread.php?google_seo_thread=$1 [L,QSA,NC]

# Google SEO URL Announcements:
RewriteRule ^Announcement\-([^./]+)$ announcements.php?google_seo_announcement=$1 [L,QSA,NC]

# Google SEO URL Users:
RewriteRule ^User\-([^./]+)$ member.php?action=profile&google_seo_user=$1 [L,QSA,NC]

# Google SEO URL Calendars:
RewriteRule ^Calendar\-([^./]+)$ calendar.php?google_seo_calendar=$1 [L,QSA,NC]

# Google SEO URL Events:
RewriteRule ^Event\-([^./]+)$ calendar.php?action=event&google_seo_event=$1 [L,QSA,NC]

# Google SEO workaround for search.php highlights:
# Make this rule the first rewrite rule in your .htaccess!
RewriteRule ^([^&]*)&(.*)$ https://lofty-tibiabot.com/$1?$2 [L,QSA,R=301]

  <IfModule mod_env.c>
    SetEnv SEO_SUPPORT 1
  </IfModule>
</IfModule>

#
# If Apache is compiled with built in mod_deflade/GZIP support
# then GZIP Javascript, CSS, HTML and XML so they're sent to
# the client faster.
#
<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE application/javascript text/css text/html text/xml
</IfModule>

# Note: You are able to choose a different name in the Admin CP. If you've done that you need to change it here too
<Files "error.log">
  Order Deny,Allow
  Deny from all
</Files>
</code>```

here is htaccess from https://lofty-tibiabot.com/new/

```<code># BEGIN WordPress
# The directives (lines) between `BEGIN WordPress` and `END WordPress` are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /new/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /new/index.php [L]
</IfModule>
# END WordPress
</code>```

答: Have you changed your website address from database? Please try first with that.</p>

Body:
I got website on subfolder https://lofty-tibiabot.com/new/

and when I want go to https://lofty-tibiabot.com/new/wp-admin

I have noticed when I put https://lofty-tibiabot.com/new/wp-admin/index.php it works correctly

it redirects me to https://lofty-tibiabot.com/wp-admin

what i have to do with that?

here is htaccess from https://lofty-tibiabot.com

Options -MultiViews +FollowSymlinks -Indexes

#
# If mod_security is enabled, attempt to disable it.
# - Note, this will work on the majority of hosts but on
#   MediaTemple, it is known to cause random Internal Server
#   errors. For MediaTemple, please remove the block below
#
<IfModule mod_security.c>
  # Turn off mod_security filtering.
  SecFilterEngine Off

  # The below probably isn't needed, but better safe than sorry.
  SecFilterScanPOST Off
</IfModule>

 RewriteEngine on
  RewriteBase /

#
# MyBB "search engine friendly" URL rewrites
# - Note, for these to work with MyBB please make sure you have
#   the setting enabled in the Admin CP and you have this file
#   named .htaccess
#
  <IfModule mod_rewrite.c>
  RewriteRule ^([^&]*)&(.*)$ https://lofty-tibiabot.com/$1?$2 [L,QSA,R=301]

  #RewriteCond %{HTTPS} off
  #RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

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

  RewriteRule ^forum-([0-9]+)\.html$ forumdisplay.php?fid=$1 [L,QSA]
  RewriteRule ^forum-([0-9]+)-page-([0-9]+)\.html$ forumdisplay.php?fid=$1&page=$2 [L,QSA]

  RewriteRule ^thread-([0-9]+)\.html$ showthread.php?tid=$1 [L,QSA]
  RewriteRule ^thread-([0-9]+)-page-([0-9]+)\.html$ showthread.php?tid=$1&page=$2 [L,QSA]
  RewriteRule ^thread-([0-9]+)-lastpost\.html$ showthread.php?tid=$1&action=lastpost [L,QSA]
  RewriteRule ^thread-([0-9]+)-nextnewest\.html$ showthread.php?tid=$1&action=nextnewest [L,QSA]
  RewriteRule ^thread-([0-9]+)-nextoldest\.html$ showthread.php?tid=$1&action=nextoldest [L,QSA]
  RewriteRule ^thread-([0-9]+)-newpost\.html$ showthread.php?tid=$1&action=newpost [L,QSA]
  RewriteRule ^thread-([0-9]+)-post-([0-9]+)\.html$ showthread.php?tid=$1&pid=$2 [L,QSA]

  RewriteRule ^post-([0-9]+)\.html$ showthread.php?pid=$1 [L,QSA]

  RewriteRule ^announcement-([0-9]+)\.html$ announcements.php?aid=$1 [L,QSA]

  RewriteRule ^user-([0-9]+)\.html$ member.php?action=profile&uid=$1 [L,QSA]

  RewriteRule ^calendar-([0-9]+)\.html$ calendar.php?calendar=$1 [L,QSA]
  RewriteRule ^calendar-([0-9]+)-year-([0-9]+)-month-([0-9]+)\.html$ calendar.php?calendar=$1&year=$2&month=$3 [L,QSA]
  RewriteRule ^calendar-([0-9]+)-year-([0-9]+)-month-([0-9]+)-day-([0-9]+)\.html$ calendar.php?action=dayview&calendar=$1&year=$2&month=$3&day=$4 [L,QSA]
  RewriteRule ^calendar-([0-9]+)-week-(n?[0-9]+)\.html$ calendar.php?action=weekview&calendar=$1&week=$2 [L,QSA]

  RewriteRule ^event-([0-9]+)\.html$ calendar.php?action=event&eid=$1 [L,QSA]

  # Google SEO workaround for search.php highlights:
# Make this rule the first rewrite rule in your .htaccess!
RewriteRule ^([^&]*)&(.*)$ https://lofty-tibiabot.com/$1?$2 [L,QSA,R=301]

# Google SEO 404:
ErrorDocument 404 /misc.php?google_seo_error=404

# Google SEO Sitemap:
RewriteRule ^sitemap\-([^./]+)\.xml$ misc.php?google_seo_sitemap=$1 [L,QSA,NC]

# Google SEO URL Forums:
RewriteRule ^Forum\-([^./]+)$ forumdisplay.php?google_seo_forum=$1 [L,QSA,NC]

# Google SEO URL Threads:
RewriteRule ^Thread\-([^./]+)$ showthread.php?google_seo_thread=$1 [L,QSA,NC]

# Google SEO URL Announcements:
RewriteRule ^Announcement\-([^./]+)$ announcements.php?google_seo_announcement=$1 [L,QSA,NC]

# Google SEO URL Users:
RewriteRule ^User\-([^./]+)$ member.php?action=profile&google_seo_user=$1 [L,QSA,NC]

# Google SEO URL Calendars:
RewriteRule ^Calendar\-([^./]+)$ calendar.php?google_seo_calendar=$1 [L,QSA,NC]

# Google SEO URL Events:
RewriteRule ^Event\-([^./]+)$ calendar.php?action=event&google_seo_event=$1 [L,QSA,NC]

# Google SEO workaround for search.php highlights:
# Make this rule the first rewrite rule in your .htaccess!
RewriteRule ^([^&]*)&(.*)$ https://lofty-tibiabot.com/$1?$2 [L,QSA,R=301]

  <IfModule mod_env.c>
    SetEnv SEO_SUPPORT 1
  </IfModule>
</IfModule>

#
# If Apache is compiled with built in mod_deflade/GZIP support
# then GZIP Javascript, CSS, HTML and XML so they're sent to
# the client faster.
#
<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE application/javascript text/css text/html text/xml
</IfModule>

# Note: You are able to choose a different name in the Admin CP. If you've done that you need to change it here too
<Files "error.log">
  Order Deny,Allow
  Deny from all
</Files>

here is htaccess from https://lofty-tibiabot.com/new/

# BEGIN WordPress
# The directives (lines) between `BEGIN WordPress` and `END WordPress` are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /new/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /new/index.php [L]
</IfModule>
# END WordPress


问:
Difference between Convert.ToString() and .ToString()
What is the difference between Convert.ToString() and .ToString()?

I found many differences online, but what's the major difference?

答:
Convert.Tostring() basically just calls the following value == null ? String.Empty: value.ToString()

(string)variable will only cast when there is an implicit or explicit operator on what you are casting

ToString() can be overriden by the type (it has control over what it does), if not it results in the name of the type

Obviously if an object is null, you can't access the instance member ToString(), it will cause an exception


问:
how to use regular expression for this below stuff in php
I have a database of more than 70000 records and its primary key value started from 1 single digit.

So I want user have to type nm0000001 instead of 1 in url.And in code part I have to discard the rest of the value except 1.

But my problem is i want this type of things having 9 letters in the string and the pattern is like this

```<code>1    - nm0000001
9    - nm0000009
10   - nm0000010
2020 - nm0002020
</code>```

And from the above pattern i want only the digits like 1,9,10,2020 in php.

答:
Assuming the value is received in the URL as a querystring parameter, that is, passed via $_GET['id'] or some other name than id:

```<code>// Trim the "nm" off the front
$pk = substr($_GET['id'],2);
// And parse out an integer value.
$id = intval($pk);
</code>```

Body:
I have a database of more than 70000 records and its primary key value started from 1 single digit.

So I want user have to type nm0000001 instead of 1 in url.And in code part I have to discard the rest of the value except 1.

But my problem is i want this type of things having 9 letters in the string and the pattern is like this

1    - nm0000001
9    - nm0000009
10   - nm0000010
2020 - nm0002020

And from the above pattern i want only the digits like 1,9,10,2020 in php.

Body:
Assuming the value is received in the URL as a querystring parameter, that is, passed via $_GET['id'] or some other name than id:

// Trim the "nm" off the front
$pk = substr($_GET['id'],2);
// And parse out an integer value.
$id = intval($pk);


问:
how to merge recursive array with replace value
img here

I want result array looklike this
 please help I stuck at this array for a while please

```<code>foreach($x as $key => $value){
    foreach ($y[$key] as $key2 => $value2){

        if($x[$key] == $y[$key][$key2]){
            $z[$key][$key2] = $value2;
        }else{
            $z[$key][$key2] = $value1;
        }
    }
}
</code>```

答:
```<code>loop through both the array
array 1, array 2
foreach ($array2 as $value)
{
$array3 =$value;
if($value == ""){
$array3 =$value;
}
}
</code>```

Body:
img here

I want result array looklike this
 please help I stuck at this array for a while please

foreach($x as $key => $value){
    foreach ($y[$key] as $key2 => $value2){

        if($x[$key] == $y[$key][$key2]){
            $z[$key][$key2] = $value2;
        }else{
            $z[$key][$key2] = $value1;
        }
    }
}


问:
Using Function to generate numbers
```<code>def generate(num):
    res = 0
    for i in str(num):
       res = res + int(i)
    return res + num
</code>```

I was looking at someone's code for generating numbers and I don't understand why he used 'str(num)' to iterate i to num. Then he translates the str(i) again to int(i).

What is the intention behind this? Why can we not create

```<code>def generate(num):
    res = 0
    for i in num:
       res = res + i
    return res + num
</code>```

from the beginning?

Thanks

答:
This code snippet,

```<code>def generate(num):
    res = 0
    for i in str(num):
       res = res + int(i)
    return res + num
</code>```

assumes num is a numerical value and adds the individual digits of a given number to produce res and then it adds that res to the the number itself,
So, when you call generate(123) it adds (1 + 2 + 3) + 123 which produces 129

The second code snippet raises and error when num is a numerical value.

Hope it helps!

Title: Using Function to generate numbers

Body:
def generate(num):
    res = 0
    for i in str(num):
       res = res + int(i)
    return res + num

I was looking at someone's code for generating numbers and I don't understand why he used 'str(num)' to iterate i to num. Then he translates the str(i) again to int(i).

What is the intention behind this? Why can we not create

def generate(num):
    res = 0
    for i in num:
       res = res + i
    return res + num

from the beginning?

Thanks

Body:
This code snippet,

def generate(num):
    res = 0
    for i in str(num):
       res = res + int(i)
    return res + num

assumes num is a numerical value and adds the individual digits of a given number to produce res and then it adds that res to the the number itself,
So, when you call generate(123) it adds (1 + 2 + 3) + 123 which produces 129

The second code snippet raises and error when num is a numerical value.

Hope it helps!


问:
Align a div to the bottom of its parent div while maintaining the parent height of 100VH and not using fixed positioning
Here is my fiddle: https://jsfiddle.net/cwverdkt/.

I am trying to keep "hello" in the center and the photo of the dog on the bottom left. I need the main div to be 100vh and not relative because I am going to implement parallax scrolling and I can't have the dog always be on the bottom.

I have tried:

```<code>#photo{
  bottom: 0;
}
</code>```

and

```<code>#photo{
  display: inline-block;
  align-self: flex-end;
}
</code>```

and

.bottom-aligner {
  display: inline-block;
  height: 100%;
  vertical-align: bottom;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bottom-aligner">
  <div id="dog">
    <img src="http://i.imgur.com/FleWUfc.png" />
  </div>
</div></code>```

The last one sort of worked except it cropped the photo of the dog.

Here's a screenshot of what I want to make it look like:

答:
Make the dog image as a background of the #photo element to create a parallax scroll effect.

#slide3{
background-color: #fff;
color: #333333;
overflow: hidden;
margin: 0 auto;
background-size: cover;
height: 100vh;
}

#hello{
 display: table;
 margin: 0 auto;
 width:100px;
}

#photo{
  height: 100%;
  overflow-y: scroll;
  background-image: url(http://i.imgur.com/FleWUfc.png);
  background-repeat: no-repeat;
  background-size: 50%;
  background-position: center bottom;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="slide3">
  <div id=photo>
    <img src = "https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_256,w_256,f_auto,q_auto:eco/w3j8mozntf75fcku9zlr" id = "hello">
    <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras commodo sit amet tellus ut volutpat. Vestibulum sagittis commodo ultrices. Nunc ullamcorper urna sit amet lobortis posuere. Mauris viverra, leo ut hendrerit hendrerit, turpis lorem porttitor sem, ac tincidunt eros tortor et orci. Praesent aliquam est ac nisl dignissim, quis ullamcorper augue consectetur. Vestibulum ultricies sodales dictum. Nam et tortor vel ante dapibus ornare id sit amet turpis. Pellentesque metus magna, auctor vitae egestas sed, lobortis vitae magna. Quisque at lacus leo. Donec sodales erat et semper feugiat. Donec convallis, diam nec auctor facilisis, sem leo vestibulum enim, eu gravida mi sapien in elit. Donec et magna vel est malesuada sollicitudin. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla pulvinar tempus mi, eu porttitor enim mattis eu. Interdum et malesuada fames ac ante ipsum primis in faucibus.
    </p>
    <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras commodo sit amet tellus ut volutpat. Vestibulum sagittis commodo ultrices. Nunc ullamcorper urna sit amet lobortis posuere. Mauris viverra, leo ut hendrerit hendrerit, turpis lorem porttitor sem, ac tincidunt eros tortor et orci. Praesent aliquam est ac nisl dignissim, quis ullamcorper augue consectetur. Vestibulum ultricies sodales dictum. Nam et tortor vel ante dapibus ornare id sit amet turpis. Pellentesque metus magna, auctor vitae egestas sed, lobortis vitae magna. Quisque at lacus leo. Donec sodales erat et semper feugiat. Donec convallis, diam nec auctor facilisis, sem leo vestibulum enim, eu gravida mi sapien in elit. Donec et magna vel est malesuada sollicitudin. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla pulvinar tempus mi, eu porttitor enim mattis eu. Interdum et malesuada fames ac ante ipsum primis in faucibus.
    </p>
    <div id = "dog">
      <img src = "http://i.imgur.com/FleWUfc.png"/>
    </div>
  </div>
 </div></code>```

Body:
Here is my fiddle: https://jsfiddle.net/cwverdkt/.

I am trying to keep "hello" in the center and the photo of the dog on the bottom left. I need the main div to be 100vh and not relative because I am going to implement parallax scrolling and I can't have the dog always be on the bottom.

I have tried:

#photo{
  bottom: 0;
}

and

#photo{
  display: inline-block;
  align-self: flex-end;
}

and

.bottom-aligner {
  display: inline-block;
  height: 100%;
  vertical-align: bottom;
}

The last one sort of worked except it cropped the photo of the dog.

Here's a screenshot of what I want to make it look like:

Body:
Make the dog image as a background of the #photo element to create a parallax scroll effect.

#slide3{
background-color: #fff;
color: #333333;
overflow: hidden;
margin: 0 auto;
background-size: cover;
height: 100vh;
}

#hello{
 display: table;
 margin: 0 auto;
 width:100px;
}

#photo{
  height: 100%;
  overflow-y: scroll;
  background-image: url(http://i.imgur.com/FleWUfc.png);
  background-repeat: no-repeat;
  background-size: 50%;
  background-position: center bottom;
}

<div id="slide3">
  <div id=photo>
    <img src = "https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_256,w_256,f_auto,q_auto:eco/w3j8mozntf75fcku9zlr" id = "hello">
    <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras commodo sit amet tellus ut volutpat. Vestibulum sagittis commodo ultrices. Nunc ullamcorper urna sit amet lobortis posuere. Mauris viverra, leo ut hendrerit hendrerit, turpis lorem porttitor sem, ac tincidunt eros tortor et orci. Praesent aliquam est ac nisl dignissim, quis ullamcorper augue consectetur. Vestibulum ultricies sodales dictum. Nam et tortor vel ante dapibus ornare id sit amet turpis. Pellentesque metus magna, auctor vitae egestas sed, lobortis vitae magna. Quisque at lacus leo. Donec sodales erat et semper feugiat. Donec convallis, diam nec auctor facilisis, sem leo vestibulum enim, eu gravida mi sapien in elit. Donec et magna vel est malesuada sollicitudin. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla pulvinar tempus mi, eu porttitor enim mattis eu. Interdum et malesuada fames ac ante ipsum primis in faucibus.
    </p>
    <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras commodo sit amet tellus ut volutpat. Vestibulum sagittis commodo ultrices. Nunc ullamcorper urna sit amet lobortis posuere. Mauris viverra, leo ut hendrerit hendrerit, turpis lorem porttitor sem, ac tincidunt eros tortor et orci. Praesent aliquam est ac nisl dignissim, quis ullamcorper augue consectetur. Vestibulum ultricies sodales dictum. Nam et tortor vel ante dapibus ornare id sit amet turpis. Pellentesque metus magna, auctor vitae egestas sed, lobortis vitae magna. Quisque at lacus leo. Donec sodales erat et semper feugiat. Donec convallis, diam nec auctor facilisis, sem leo vestibulum enim, eu gravida mi sapien in elit. Donec et magna vel est malesuada sollicitudin. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla pulvinar tempus mi, eu porttitor enim mattis eu. Interdum et malesuada fames ac ante ipsum primis in faucibus.
    </p>
    <div id = "dog">
      <img src = "http://i.imgur.com/FleWUfc.png"/>
    </div>
  </div>
 </div>


问:
Surprising or wrong benchmarks of Where(predicate).FirstOrDefault() vs FirstOrDefault(predicate)?
I know this question has been asked a lot by people and some even say

So, first(FirstOrDefault(predicate)) one is better in terms of performance1

and I get it, I also think that one more method call should be slightly slower, its just intuition that I have. Nevertheless, I decided to run some benchmarks in order to prove my right and boy little did I know.

This is what I had as results of running my benchmarks:

```<code>BenchmarkDotNet=v0.12.0, OS=Windows 10.0.18363
Intel Core i7-3630QM CPU 2.40GHz (Ivy Bridge), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.1.101
  [Host]     : .NET Core 3.1.1 (CoreCLR 4.700.19.60701, CoreFX 4.700.19.60801), X64 RyuJIT
  Job-XMZTSC : .NET Framework 4.8 (4.8.4121.0), X64 RyuJIT
Runtime=.NET 4.7.2

Method                            N      Mean         Error      StdDev    Ratio    RatioSD
WherePlusFirstOrDefaultArray    10000   31.44 us    0.288 us    0.270 us    0.40    0.00
FirstOrDefaultArray             10000   78.47 us    0.679 us    0.635 us    1.00    0.00
WherePlusFirstOrDefaultList     10000   54.27 us    1.070 us    1.099 us    0.69    0.02
FirstOrDefaultList              10000   100.84 us   1.722 us    1.611 us    1.29    0.02
WherePlusFirstOrDefaultArray    100000  325.41 us   4.840 us    4.527 us    0.39    0.01
FirstOrDefaultArray             100000  829.85 us   16.513 us   15.446 us   1.00    0.00
WherePlusFirstOrDefaultList     100000  558.10 us   5.507 us    5.151 us    0.67    0.01
FirstOrDefaultList              100000  1,026.93 us 17.648 us   16.508 us   1.24    0.02
WherePlusFirstOrDefaultArray    1000000 3,255.46 us 9.615 us    7.507 us    0.40    0.01
FirstOrDefaultArray             1000000 8,134.15 us 108.425 us  101.420 us  1.00    0.00
WherePlusFirstOrDefaultList     1000000 5,477.63 us 70.584 us   66.024 us   0.67    0.01
FirstOrDefaultList              1000000 9,987.54 us 64.239 us   60.089 us   1.23    0.02
</code>```

Not only Where(predicate).FirstOrDefault() was faster, but at what margin.

This is my benchmark code using BenchmarkDotNet

```<code>[SimpleJob(RuntimeMoniker.Net472)]
public class Benchmarks
{
    private int[] _array;
    private List<int> _list;

    [Params(10000, 100000, 1000000)]
    public int N;

    [GlobalSetup]
    public void Setup()
    {
        _array = new int[N];
        _list = new List<int>(N);

        _array = Enumerable
            .Repeat(0, N - 1).ToArray();
        _list = Enumerable
            .Repeat(0, N - 1).ToList();

        _array[N - 2] = 7;
        _list[N - 2] = 7;
    }

    [Benchmark]
    public int WherePlusFirstOrDefaultArray()
    {
        var seven = _array.Where(n => n == 7).FirstOrDefault();

        return seven;
    }

    [Benchmark(Baseline = true)]
    public int FirstOrDefaultArray()
    {
        var seven = _array.FirstOrDefault(n => n == 7);

        return seven;
    }

    [Benchmark]
    public int WherePlusFirstOrDefaultList()
    {
        var seven = _list.Where(n => n == 7).FirstOrDefault();

        return seven;
    }

    [Benchmark]
    public int FirstOrDefaultList()
    {
        var seven = _list.FirstOrDefault(n => n == 7);

        return seven;
    }
}
</code>```

Since I was stunned from the results leaving me with no other choice but to ask you guys what am I doing wrong or am I missing something?

EDIT:

I added benchmarks for array vs list structure to the guys thinking it might be because of the List.

EDIT2:
 The saga continues and I think I am closer to the answer. Adding hardware counter to my benchmark yielded following interesting results:

```<code>BenchmarkDotNet=v0.12.0, OS=Windows 10.0.18363
Intel Core i7-3630QM CPU 2.40GHz (Ivy Bridge), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.1.101
  [Host]     : .NET Core 3.1.1 (CoreCLR 4.700.19.60701, CoreFX 4.700.19.60801), X64 RyuJIT
  Job-ZTIMEH : .NET Framework 4.8 (4.8.4121.0), X64 RyuJIT
Runtime=.NET 4.7.2

Method                             N     Mean        Error      StdDev     Ratio    RatioSD CacheMisses/Op  BranchMispredictions/Op
WherePlusFirstOrDefaultArray    1000000 3.222 ms    0.0224 ms   0.0210 ms    0.39     0.01      885                  327
FirstOrDefaultArray             1000000 8.166 ms    0.1992 ms   0.1863 ms   1.00      0.00     1,795                 810
WherePlusFirstOrDefaultList     1000000 5.564 ms    0.1066 ms   0.1228 ms   0.68      0.02     1,051                 503
FirstOrDefaultList              1000000 10.161 ms   0.1816 ms   0.1699 ms   1.24      0.03     3,451                1,442
</code>```

For some reason, I can't still explain to myself why FirstOrDefault(predicate) method is yielding 2 to 3 times more branch mispredictions and ofc cache misses than Where(predicate).FirstOrDefault(), surely this has to play a bit part in the results I am observing previously.

Also, one curious thing, if you look at FirstOrDefaultArray and FirstOrDefaultList results and compare them you will see that list is 24% slower, but assemblies generated by these methods are identical to me: https://www.diffchecker.com/WSjAQlet (I stripped memory addresses of the instructions.)

答:
This one really got me interested, so I did a bit more digging, and the answer looks to be related to that when FirstOrDefault is called on a Where results, the predicate executes under a WhereArrayIterator or a WhereEnumerableIterator depending on the source type.

When FirstOrDefault(predicate) is used, it is iterating directly against the source array.

The difference?

FirstOrDefault(predicate)

```<code>public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
        if (source == null) throw Error.ArgumentNull("source");
        if (predicate == null) throw Error.ArgumentNull("predicate");
        foreach (TSource element in source) {
            if (predicate(element)) return element;
        }
        return default(TSource);
    }
</code>```

vs. WhereArrayIterator's MoveNext

```<code>public override bool MoveNext() {
            if (state == 1) {
                while (index < source.Length) {
                    TSource item = source[index];
                    index++;
                    if (predicate(item)) {
                        current = item;
                        return true;
                    }
                }
                Dispose();
            }
            return false;
        }

public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source) {
        if (source == null) throw Error.ArgumentNull("source");
        IList<TSource> list = source as IList<TSource>;
        if (list != null) {
            if (list.Count > 0) return list[0];
        }
        else {
            using (IEnumerator<TSource> e = source.GetEnumerator()) {
                if (e.MoveNext()) return e.Current;
            }
        }
        return default(TSource);
    }
</code>```

The key difference is that the WhereIterator classes both use while loops to iterate through the enumerable/array where the FirstOrDefault(predicate) is using foreach. Over larger sets, foreach is notably slower than while or for loops, so I suspect this will explain a good share of the variance.

Source above pulled from source reference: https://referencesource.microsoft.com/#system.core/System/Linq/Enumerable.cs,709a06a6b65427d6
and
https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,8087366974af11d2

Regarding the original assumption that Where(predicate).FirstOrDefault() might be assumed to be slower than FirstOrDefault(predicate) due to the extra method call, this can be disproved by the following test:

```<code>    [Test]
    public void Test()
    {
        var data = new[] { 0, 0, 7, 0 };
        var test1 = data.FirstOrDefault(isSeven);
        var test2 = data.Where(isSeven).FirstOrDefault();
    }

    private bool isSeven(int val)
    {
        return val == 7;
    }
</code>```

with a breakpoint inside the isSeven method. In both cases the predicate is only called 3 times where one might assume that it is "executed" in the Where(predicate) call which would result in 4 calls, but it is only executed when FirstOrDefault() wants to iterated through the iterator, triggering MoveNext() on the WhereEnumerator.

Body:
I know this question has been asked a lot by people and some even say

So, first(FirstOrDefault(predicate)) one is better in terms of performance1

and I get it, I also think that one more method call should be slightly slower, its just intuition that I have. Nevertheless, I decided to run some benchmarks in order to prove my right and boy little did I know.

This is what I had as results of running my benchmarks:

BenchmarkDotNet=v0.12.0, OS=Windows 10.0.18363
Intel Core i7-3630QM CPU 2.40GHz (Ivy Bridge), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.1.101
  [Host]     : .NET Core 3.1.1 (CoreCLR 4.700.19.60701, CoreFX 4.700.19.60801), X64 RyuJIT
  Job-XMZTSC : .NET Framework 4.8 (4.8.4121.0), X64 RyuJIT
Runtime=.NET 4.7.2

Method                            N      Mean         Error      StdDev    Ratio    RatioSD
WherePlusFirstOrDefaultArray    10000   31.44 us    0.288 us    0.270 us    0.40    0.00
FirstOrDefaultArray             10000   78.47 us    0.679 us    0.635 us    1.00    0.00
WherePlusFirstOrDefaultList     10000   54.27 us    1.070 us    1.099 us    0.69    0.02
FirstOrDefaultList              10000   100.84 us   1.722 us    1.611 us    1.29    0.02
WherePlusFirstOrDefaultArray    100000  325.41 us   4.840 us    4.527 us    0.39    0.01
FirstOrDefaultArray             100000  829.85 us   16.513 us   15.446 us   1.00    0.00
WherePlusFirstOrDefaultList     100000  558.10 us   5.507 us    5.151 us    0.67    0.01
FirstOrDefaultList              100000  1,026.93 us 17.648 us   16.508 us   1.24    0.02
WherePlusFirstOrDefaultArray    1000000 3,255.46 us 9.615 us    7.507 us    0.40    0.01
FirstOrDefaultArray             1000000 8,134.15 us 108.425 us  101.420 us  1.00    0.00
WherePlusFirstOrDefaultList     1000000 5,477.63 us 70.584 us   66.024 us   0.67    0.01
FirstOrDefaultList              1000000 9,987.54 us 64.239 us   60.089 us   1.23    0.02

Not only Where(predicate).FirstOrDefault() was faster, but at what margin.

This is my benchmark code using BenchmarkDotNet

[SimpleJob(RuntimeMoniker.Net472)]
public class Benchmarks
{
    private int[] _array;
    private List<int> _list;

    [Params(10000, 100000, 1000000)]
    public int N;

    [GlobalSetup]
    public void Setup()
    {
        _array = new int[N];
        _list = new List<int>(N);

        _array = Enumerable
            .Repeat(0, N - 1).ToArray();
        _list = Enumerable
            .Repeat(0, N - 1).ToList();

        _array[N - 2] = 7;
        _list[N - 2] = 7;
    }

    [Benchmark]
    public int WherePlusFirstOrDefaultArray()
    {
        var seven = _array.Where(n => n == 7).FirstOrDefault();

        return seven;
    }

    [Benchmark(Baseline = true)]
    public int FirstOrDefaultArray()
    {
        var seven = _array.FirstOrDefault(n => n == 7);

        return seven;
    }

    [Benchmark]
    public int WherePlusFirstOrDefaultList()
    {
        var seven = _list.Where(n => n == 7).FirstOrDefault();

        return seven;
    }

    [Benchmark]
    public int FirstOrDefaultList()
    {
        var seven = _list.FirstOrDefault(n => n == 7);

        return seven;
    }
}

Since I was stunned from the results leaving me with no other choice but to ask you guys what am I doing wrong or am I missing something?

EDIT:

I added benchmarks for array vs list structure to the guys thinking it might be because of the List.

EDIT2:
 The saga continues and I think I am closer to the answer. Adding hardware counter to my benchmark yielded following interesting results:

BenchmarkDotNet=v0.12.0, OS=Windows 10.0.18363
Intel Core i7-3630QM CPU 2.40GHz (Ivy Bridge), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.1.101
  [Host]     : .NET Core 3.1.1 (CoreCLR 4.700.19.60701, CoreFX 4.700.19.60801), X64 RyuJIT
  Job-ZTIMEH : .NET Framework 4.8 (4.8.4121.0), X64 RyuJIT
Runtime=.NET 4.7.2

Method                             N     Mean        Error      StdDev     Ratio    RatioSD CacheMisses/Op  BranchMispredictions/Op
WherePlusFirstOrDefaultArray    1000000 3.222 ms    0.0224 ms   0.0210 ms    0.39     0.01      885                  327
FirstOrDefaultArray             1000000 8.166 ms    0.1992 ms   0.1863 ms   1.00      0.00     1,795                 810
WherePlusFirstOrDefaultList     1000000 5.564 ms    0.1066 ms   0.1228 ms   0.68      0.02     1,051                 503
FirstOrDefaultList              1000000 10.161 ms   0.1816 ms   0.1699 ms   1.24      0.03     3,451                1,442

For some reason, I can't still explain to myself why FirstOrDefault(predicate) method is yielding 2 to 3 times more branch mispredictions and ofc cache misses than Where(predicate).FirstOrDefault(), surely this has to play a bit part in the results I am observing previously.

Also, one curious thing, if you look at FirstOrDefaultArray and FirstOrDefaultList results and compare them you will see that list is 24% slower, but assemblies generated by these methods are identical to me: https://www.diffchecker.com/WSjAQlet (I stripped memory addresses of the instructions.)

Body:
This one really got me interested, so I did a bit more digging, and the answer looks to be related to that when FirstOrDefault is called on a Where results, the predicate executes under a WhereArrayIterator or a WhereEnumerableIterator depending on the source type.

When FirstOrDefault(predicate) is used, it is iterating directly against the source array.

The difference?

FirstOrDefault(predicate)

public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
        if (source == null) throw Error.ArgumentNull("source");
        if (predicate == null) throw Error.ArgumentNull("predicate");
        foreach (TSource element in source) {
            if (predicate(element)) return element;
        }
        return default(TSource);
    }

vs. WhereArrayIterator's MoveNext

public override bool MoveNext() {
            if (state == 1) {
                while (index < source.Length) {
                    TSource item = source[index];
                    index++;
                    if (predicate(item)) {
                        current = item;
                        return true;
                    }
                }
                Dispose();
            }
            return false;
        }

public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source) {
        if (source == null) throw Error.ArgumentNull("source");
        IList<TSource> list = source as IList<TSource>;
        if (list != null) {
            if (list.Count > 0) return list[0];
        }
        else {
            using (IEnumerator<TSource> e = source.GetEnumerator()) {
                if (e.MoveNext()) return e.Current;
            }
        }
        return default(TSource);
    }

The key difference is that the WhereIterator classes both use while loops to iterate through the enumerable/array where the FirstOrDefault(predicate) is using foreach. Over larger sets, foreach is notably slower than while or for loops, so I suspect this will explain a good share of the variance.

Source above pulled from source reference: https://referencesource.microsoft.com/#system.core/System/Linq/Enumerable.cs,709a06a6b65427d6
and
https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,8087366974af11d2

Regarding the original assumption that Where(predicate).FirstOrDefault() might be assumed to be slower than FirstOrDefault(predicate) due to the extra method call, this can be disproved by the following test:

    [Test]
    public void Test()
    {
        var data = new[] { 0, 0, 7, 0 };
        var test1 = data.FirstOrDefault(isSeven);
        var test2 = data.Where(isSeven).FirstOrDefault();
    }

    private bool isSeven(int val)
    {
        return val == 7;
    }

with a breakpoint inside the isSeven method. In both cases the predicate is only called 3 times where one might assume that it is "executed" in the Where(predicate) call which would result in 4 calls, but it is only executed when FirstOrDefault() wants to iterated through the iterator, triggering MoveNext() on the WhereEnumerator.


答: There's absolutely no use for regular expressions in this -- use sprintf("nm%07d", ...) to format and just substr and a cast to int to parse.

Title: how to use regular expression for this below stuff in php


问:
How to verify the status of an EC2 instance launched from a newly created AMI?
How to check if an EC2 instance is up and running/one particular service is up or down using boto3. The instance is created from a newly created AMI. </p>

答:
You can uses the following Instance:

```<code>ec2 = boto3.resource('ec2')

instance = ec2.Instance('instance_id')

print(instance.image_id)
</code>```

Compare instance.image_id to the id of image you expect.

To check if instance is already running, use EC2.Waiter.InstanceRunning waiter.

Body:
You can uses the following Instance:

ec2 = boto3.resource('ec2')

instance = ec2.Instance('instance_id')

print(instance.image_id)

Compare instance.image_id to the id of image you expect.

To check if instance is already running, use EC2.Waiter.InstanceRunning waiter.


问:
Neovim colorscheme does not look right when using nvim inside tmux
I'm trying to use vim-material theme from https://github.com/kaicataldo/material.vim

Below is what happens when i run neovim in tmux

Below is what it should look like

What i've tried so far:

in my .tmux.conf
I tried both

```<code>set -g default-terminal "screen-256color"
</code>```

and

```<code>set -g default-terminal "xterm-256color"
</code>```

I also tried

```<code>TERM=screen-256color-bce tmux
</code>```

I am able to echo $TERM with proper results here. but i've also tried setting them manually with export TERM=xterm-256color or export TERM=screen-256color before i open nvim

This is what I have in my init.vim

```<code>let g:material_theme_style = 'ocean'
colorscheme material
set background=dark
set t_Co=256
set termguicolors
</code>```

i've tried setting and unsetting these.
unsetting termguicolors was the worst, the theme just didnt work and it gave me default vim look

I also run tmux as tmux -2 i should also mention i kill tmux sessions after changing anything in my tmux.conf to make sure it reflects

the versions of related apps and os

```<code>nvim v0.4.3
tmux 3.0a
iTerm2 3.3.9
macOS mojave 10.14.6
</code>```

EDIT:

I've since tried clearing all tmux plugins and nvim plugins only leaving the default-terminal in my tmux config

Here's what's left on my init.vim file

```<code>call plug#begin('~/.config/nvim/plugged')

Plug 'kaicataldo/material.vim'
call plug#end()

set termguicolors
let g:material_theme_style = 'default'
colorscheme material
</code>```

I also tried downloading an older version of tmux. 2.5, still no luck.

I deleted all my tmux plugins and nvim plugins and reinstalled material.vim so i'm sure nothing is conflicting in the plugins somehow

答:
FOUND THE SOLUTION . this article helped me:
 https://cyfyifanchen.com/neovim-true-color/</p>

```<code>set-default colorset-option -ga terminal-overrides ",xterm-256color:Tc"
</code>```

Body:
I'm trying to use vim-material theme from https://github.com/kaicataldo/material.vim

Below is what happens when i run neovim in tmux

Below is what it should look like

What i've tried so far:

in my .tmux.conf
I tried both

set -g default-terminal "screen-256color"

and

set -g default-terminal "xterm-256color"

I also tried

TERM=screen-256color-bce tmux

I am able to echo $TERM with proper results here. but i've also tried setting them manually with export TERM=xterm-256color or export TERM=screen-256color before i open nvim

This is what I have in my init.vim

let g:material_theme_style = 'ocean'
colorscheme material
set background=dark
set t_Co=256
set termguicolors

i've tried setting and unsetting these.
unsetting termguicolors was the worst, the theme just didnt work and it gave me default vim look

I also run tmux as tmux -2 i should also mention i kill tmux sessions after changing anything in my tmux.conf to make sure it reflects

the versions of related apps and os

nvim v0.4.3
tmux 3.0a
iTerm2 3.3.9
macOS mojave 10.14.6

EDIT:

I've since tried clearing all tmux plugins and nvim plugins only leaving the default-terminal in my tmux config

Here's what's left on my init.vim file

call plug#begin('~/.config/nvim/plugged')

Plug 'kaicataldo/material.vim'
call plug#end()

set termguicolors
let g:material_theme_style = 'default'
colorscheme material

I also tried downloading an older version of tmux. 2.5, still no luck.

I deleted all my tmux plugins and nvim plugins and reinstalled material.vim so i'm sure nothing is conflicting in the plugins somehow

Body:
FOUND THE SOLUTION . this article helped me:
 https://cyfyifanchen.com/neovim-true-color/

set-default colorset-option -ga terminal-overrides ",xterm-256color:Tc"


问:
Delete and list out the all models and deployment service from Azure Machine Learning Service using python
How to get all models and deployment service from Azure Machine Learning Service and how to delete it using python.

Is there any way to list, delete all models and deployment services from Azure ML Service using python?

答:
The Model Class has methods to help you accomplish this task. Check out delete and list methods.

Sample code:

```<code>from azureml.core import Workspace
ws = Workspace.get(name="your_workspace_name",
           subscription_id='your_subscription_id',
           resource_group='your_resource_group')

from azureml.core import Model
for model in Model.list(ws):
    print('name:', model.name, '\nversion:', model.version, '\n')
Model(ws, name = 'model_name', version = 'model_version').delete()

from azureml.core import Webservice
for webservice in Webservice.list(ws):
    print('name:', webservice.name)
Webservice(ws, name = 'webservice').delete()
</code>```

Thanks.

Body:
The Model Class has methods to help you accomplish this task. Check out delete and list methods.

Sample code:

from azureml.core import Workspace
ws = Workspace.get(name="your_workspace_name",
           subscription_id='your_subscription_id',
           resource_group='your_resource_group')

from azureml.core import Model
for model in Model.list(ws):
    print('name:', model.name, '\nversion:', model.version, '\n')
Model(ws, name = 'model_name', version = 'model_version').delete()

from azureml.core import Webservice
for webservice in Webservice.list(ws):
    print('name:', webservice.name)
Webservice(ws, name = 'webservice').delete()

Thanks.


问:
from Eclipse to Android phone
I have made a program on eclipse. But how can I get the program from eclipse to my phone? I have a cable because it probably wont make a QR code like appinventor does huh. How do i install my app on there? </p>

答:
You need to set up your machine and phone for running and debugging from eclipse.  It involves getting the phone's usb driver on your machine, and setting up the phone for usb debugging.

Read this Using Hardware Devices | Android Developer Guide

Title: from Eclipse to Android phone


问:
Does pandas ExcelFile parse all sheets on initialization? (and can it be avoided)
I have a series of large (and poorly formatted) excel spreadsheets that I am trying to process with pandas. Each excel file contains 50-60 sheets, and I am only interested in a subset of the sheets, within each file.

I have tried to read the entire spreadsheet as an pd.ExcelFile object, so I can use the sheet_names attribute to parse particular sheets (and I don't know the names of each sheet ahead of time). This works - but seems exceptionally slow (close to a minute for each ~30mb excel file).

I can only assume this is because each sheet is being parsed as the pd.ExcelFile object is being initialised (...could be wrong?). If so, is there a way to prevent this behaviour?  - I really only want to get the sheet names, and then parse the specific sheets from there.

Thanks in advance!

答: to best of my knowledge pandas uses xlrd or similar engine to open and parse the excel file. xlrd is the default engine. When you open an excel file using xlrd it defaults to loading all sheets. Thus pandas presumably does as well. You might have better luck opening the excel files using xlrd, setting on_demand kwarg to True, and then defining the df after pulling in data using xlrd. </p>


问:
Pythonic way of not printing a error message up
I am trying to suppress a error/warning in my log while calling a library. Assume i have this code

```<code>        try:
            kazoo_client.start()
        except:
            pass
</code>```

This is calling a zookeeper client which throws some exception which bubble up, now i don't want the warn/error in my logs when i call kazoo_client.start() is there a way to get this suppressed when you call the client

答:
I would like to suggest a more generic approach, which can be used in general.
I leave you an example of how to create an decorator who ignore errors.

```<code>import functools

# Use the Decorator Design Pattern

def ignore_error_decorator(function_reference):
    @functools.wraps(function_reference)  # the decorator inherits the original function signature
    def wrapper(*args):
        try:
            result = function_reference(*args)  # execute the function
            return result  # If the function executed correctly, return
        except Exception as e:
            pass  # Default ignore; You can also log the error or do what ever you want

    return wrapper  # Return the wrapper reference

if __name__ == '__main__':
    # First alternative to use. Compose the decorator with another function
    def my_first_function(a, b):
        return a + b

    rez_valid = ignore_error_decorator(my_first_function)(1, 3)
    rez_invalid = ignore_error_decorator(my_first_function)(1, 'a')
    print("Alternative_1 valid: {result}".format(result=rez_valid))
    print("Alternative_1 invalid: {result}".format(result=rez_invalid)) # None is return by the exception bloc

    # Second alternative. Decorating a function
    @ignore_error_decorator
    def my_second_function(a, b):
        return a + b

    rez_valid = my_second_function(1, 5)
    rez_invalid = my_second_function(1, 'a')
    print("Alternative_2 valid: {result}".format(result=rez_valid))
    print("Alternative_2 invalid: {result}".format(result=rez_invalid))  # None is return by the exception bloc
</code>```

Getting back to your problem, using my alternative you have to run

```<code>ignore_error_decorator(kazoo_client.start)()
</code>```

Body:
I am trying to suppress a error/warning in my log while calling a library. Assume i have this code

        try:
            kazoo_client.start()
        except:
            pass

This is calling a zookeeper client which throws some exception which bubble up, now i don't want the warn/error in my logs when i call kazoo_client.start() is there a way to get this suppressed when you call the client

Body:
I would like to suggest a more generic approach, which can be used in general.
I leave you an example of how to create an decorator who ignore errors.

import functools

# Use the Decorator Design Pattern

def ignore_error_decorator(function_reference):
    @functools.wraps(function_reference)  # the decorator inherits the original function signature
    def wrapper(*args):
        try:
            result = function_reference(*args)  # execute the function
            return result  # If the function executed correctly, return
        except Exception as e:
            pass  # Default ignore; You can also log the error or do what ever you want

    return wrapper  # Return the wrapper reference

if __name__ == '__main__':
    # First alternative to use. Compose the decorator with another function
    def my_first_function(a, b):
        return a + b

    rez_valid = ignore_error_decorator(my_first_function)(1, 3)
    rez_invalid = ignore_error_decorator(my_first_function)(1, 'a')
    print("Alternative_1 valid: {result}".format(result=rez_valid))
    print("Alternative_1 invalid: {result}".format(result=rez_invalid)) # None is return by the exception bloc

    # Second alternative. Decorating a function
    @ignore_error_decorator
    def my_second_function(a, b):
        return a + b

    rez_valid = my_second_function(1, 5)
    rez_invalid = my_second_function(1, 'a')
    print("Alternative_2 valid: {result}".format(result=rez_valid))
    print("Alternative_2 invalid: {result}".format(result=rez_invalid))  # None is return by the exception bloc

Getting back to your problem, using my alternative you have to run

ignore_error_decorator(kazoo_client.start)()


问:
strcpy function not working properly
Please consider the below code.

```<code>#include<stdio.h>
#include<string.h>
void main()
{
    char a[6], b[6];

    strcpy(a,"rajeev");
    printf("print A:");
    for(int i=0;i<strlen(a);i++)
    {
         printf("%c",a[i]);
    }

    strcpy(b,a);
    printf("print B:");
    for(int i=0;i<strlen(b);i++)
    {
        printf("%c",b[i]);
    }

    printf("trying to print A again");
    for(int i=0;i<strlen(a);i++)
    {
        printf("%c",a[i]);
    }
</code>```

While running this program,in the "trying to print A again" section prints nothing, and the strlen(a) will be 0.  That means the source array will be empty.

Can you please help me to understand the phenomena behind this?
But, change the declaration of a[6] to char* a=malloc(6) works properly.

答:
The array you defined  char a[6], b[6] don't have enough space to fit the string you are trying to store.

Kindly remember that every array in C has a null byte \0 at the end.

You can fix it by giving enough space to the array:

```<code>char a[7], b[7];
</code>```

Title: strcpy function not working properly

Body:
Please consider the below code.

#include<stdio.h>
#include<string.h>
void main()
{
    char a[6], b[6];

    strcpy(a,"rajeev");
    printf("print A:");
    for(int i=0;i<strlen(a);i++)
    {
         printf("%c",a[i]);
    }

    strcpy(b,a);
    printf("print B:");
    for(int i=0;i<strlen(b);i++)
    {
        printf("%c",b[i]);
    }

    printf("trying to print A again");
    for(int i=0;i<strlen(a);i++)
    {
        printf("%c",a[i]);
    }

While running this program,in the "trying to print A again" section prints nothing, and the strlen(a) will be 0.  That means the source array will be empty.

Can you please help me to understand the phenomena behind this?
But, change the declaration of a[6] to char* a=malloc(6) works properly.

Body:
The array you defined  char a[6], b[6] don't have enough space to fit the string you are trying to store.

Kindly remember that every array in C has a null byte \0 at the end.

You can fix it by giving enough space to the array:

char a[7], b[7];


问:
Edit post taxonomy before post will be saved to database
Scenario: I have a plugin that scraping another website and creating wordpress posts. I can't edit the plugin. But what I want is editting the taxonomy(tags) before it will be saved to the database.

Code idea:

```<code>function taxonomy_edit( $data , $postarr ) {

    // Get tags (array)
    $taxonomies = $data['tags_input'];

        // Here will be some array edit

    // Editted taga (array)
    $data['tags_input'] = $taxonomies;

    return $data;
}

add_filter( 'wp_insert_post_data' , 'taxonomy_edit' , 99, 2);
</code>```

Is there a way to edit a taxonomy before saving it to the database for the first time?

答: The better way is to create new taxonomy first when you are importing new post and then assign that post to that taxonomy. </p>

Body:
Scenario: I have a plugin that scraping another website and creating wordpress posts. I can't edit the plugin. But what I want is editting the taxonomy(tags) before it will be saved to the database.

Code idea:

function taxonomy_edit( $data , $postarr ) {

    // Get tags (array)
    $taxonomies = $data['tags_input'];

        // Here will be some array edit

    // Editted taga (array)
    $data['tags_input'] = $taxonomies;

    return $data;
}

add_filter( 'wp_insert_post_data' , 'taxonomy_edit' , 99, 2);

Is there a way to edit a taxonomy before saving it to the database for the first time?


答:
To check if an EC2 instance is up or down:

```<code>import sys
import boto3

ec2 = boto3.client('ec2')
if sys.argv[1] == 'ON':
    response = ec2.monitor_instances(InstanceIds=['INSTANCE_ID'])
else:
    response = ec2.unmonitor_instances(InstanceIds=['INSTANCE_ID'])
print(response)
</code>```

To check the health of an instance:

```<code># Boto 2.x
for status in ec2_connection.get_all_instance_statuses():
    print(status)

# Boto 3
for status in ec2.meta.client.describe_instance_status()['InstanceStatuses']:
    print(status)
</code>```

For more details refer to:
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/migrationec2.html

https://boto3.amazonaws.com/v1/documentation/api/latest/guide/ec2-example-managing-instances.html

Update: (To check if particular service in EC2 is running or not)

You can publish a custom metric to CloudWatch in the form of a "heart beat".

Have a small script running via cron on your server checking the process list to see whether my_service is running and if it is, make a put-metric-data call to CloudWatch.

The metric could be as simple as pushing the number "1" to your custom metric in CloudWatch.

Set up a CloudWatch alarm that triggers if the average for the metric falls below 1

Make the period of the alarm be >= the period that the cron runs e.g. cron runs every 5 minutes, make the alarm trigger if it sees the average is below 1 for two 5 minute periods.

Make sure you also handle the situation in which the metric is not published (e. g. cron fails to run or whole machine dies). you would want to setup an alert in case the metric is missing. (see here:AWS Cloudwatch heartbeat alarm)

Be aware that the custom metric will add an additional cost of 50c to your AWS bill (not a big deal for one metric - but the equation changes drastically if you want to push hundred/thousands of metrics - i.e. good to know it's not free as one would expect)

You have to create a topic in SNS (Simple Notification Service) service in AWS. There you have to define your email under SNS on which you will receive the notification.

References:

Use cloudwatch to determine if linux service is running

AWS Cloudwatch Heartbeat Alarm

Title: How to verify the status of an EC2 instance launched from a newly created AMI?

Body: How to check if an EC2 instance is up and running/one particular service is up or down using boto3. The instance is created from a newly created AMI.

Body:
To check if an EC2 instance is up or down:

import sys
import boto3

ec2 = boto3.client('ec2')
if sys.argv[1] == 'ON':
    response = ec2.monitor_instances(InstanceIds=['INSTANCE_ID'])
else:
    response = ec2.unmonitor_instances(InstanceIds=['INSTANCE_ID'])
print(response)

To check the health of an instance:

# Boto 2.x
for status in ec2_connection.get_all_instance_statuses():
    print(status)

# Boto 3
for status in ec2.meta.client.describe_instance_status()['InstanceStatuses']:
    print(status)

For more details refer to:
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/migrationec2.html

https://boto3.amazonaws.com/v1/documentation/api/latest/guide/ec2-example-managing-instances.html

Update: (To check if particular service in EC2 is running or not)

You can publish a custom metric to CloudWatch in the form of a "heart beat".

Have a small script running via cron on your server checking the process list to see whether my_service is running and if it is, make a put-metric-data call to CloudWatch.

The metric could be as simple as pushing the number "1" to your custom metric in CloudWatch.

Set up a CloudWatch alarm that triggers if the average for the metric falls below 1

Make the period of the alarm be >= the period that the cron runs e.g. cron runs every 5 minutes, make the alarm trigger if it sees the average is below 1 for two 5 minute periods.

Make sure you also handle the situation in which the metric is not published (e. g. cron fails to run or whole machine dies). you would want to setup an alert in case the metric is missing. (see here:AWS Cloudwatch heartbeat alarm)

Be aware that the custom metric will add an additional cost of 50c to your AWS bill (not a big deal for one metric - but the equation changes drastically if you want to push hundred/thousands of metrics - i.e. good to know it's not free as one would expect)

You have to create a topic in SNS (Simple Notification Service) service in AWS. There you have to define your email under SNS on which you will receive the notification.

References:

Use cloudwatch to determine if linux service is running

AWS Cloudwatch Heartbeat Alarm


问:
How to calculate the percentage of different values in same column and group by month of current year?
I want to take the percentage of only SLA's in the sla_osla table and group them by all the months of current year

Here is my table

http://sqlfiddle.com/#!9/179518/2

I have tried the following query

```<code>    SELECT MONTH(service_date),((nums/(count(*)))*100) AS perc
      FROM orders CROSS JOIN (SELECT MONTH(service_date) AS months, COUNT(*) AS
   nums FROM orders WHERE YEAR(service_date) = year(CURRENT_DATE()) AND sla_osla =
  'sla'
     GROUP BY MONTH(CURRENT_DATE())) table1
     WHERE YEAR(service_date) = YEAR(current_date) AND sla_osla IN ('sla','osla')
     GROUP BY MONTH(service_date)
</code>```

I want output like this

```<code>month percentage

    1       75%
    2       50%
</code>```

答:
http://sqlfiddle.com/#!9/179518/129</p>

```<code>SELECT MONTH(service_date) month, CONCAT(FORMAT(SUM(sla_osla='sla')/COUNT(*)*100,0),'%') percentage FROM orders WHERE YEAR(CURDATE())=YEAR(service_date) GROUP BY MONTH(service_date);
</code>```

Body:
I want to take the percentage of only SLA's in the sla_osla table and group them by all the months of current year

Here is my table

http://sqlfiddle.com/#!9/179518/2

I have tried the following query

    SELECT MONTH(service_date),((nums/(count(*)))*100) AS perc
      FROM orders CROSS JOIN (SELECT MONTH(service_date) AS months, COUNT(*) AS
   nums FROM orders WHERE YEAR(service_date) = year(CURRENT_DATE()) AND sla_osla =
  'sla'
     GROUP BY MONTH(CURRENT_DATE())) table1
     WHERE YEAR(service_date) = YEAR(current_date) AND sla_osla IN ('sla','osla')
     GROUP BY MONTH(service_date)

I want output like this

month percentage

    1       75%
    2       50%

Body:
http://sqlfiddle.com/#!9/179518/129

SELECT MONTH(service_date) month, CONCAT(FORMAT(SUM(sla_osla='sla')/COUNT(*)*100,0),'%') percentage FROM orders WHERE YEAR(CURDATE())=YEAR(service_date) GROUP BY MONTH(service_date);


问:
Dynamic Column configuration in ag-grid
I am trying to load table data dynamically in ag-grid. All column will be listed in sidebar(ToolPanel) check boxes and if user click on any unchecked box then a request will be sent to server and get data for that column and merge into the grid.

I am not sure this can be done with the ag-grid sideBar.
I am thinking of capturing the click event in sideBar but can not found any relevant document.

Please let me know if there is any solution for this.

答:
If you are expecting any event from ag-grid, I think columnVisible might help you.

Have a look at this live example: https://plnkr.co/edit/KpFQp84rZvJgY2gjKRar?p=preview

Uncheck any column and then check.

```<code><AgGridReact
   ...
   onColumnVisible={this.onColumnVisible}
/>
</code>```

```<code>  onColumnVisible = params => {
    console.log(params);
    if (params.visible) {
      const colId = params.column.colId;
      alert(colId);
      // you could identify here, which column was checked
      // load data from server for that column
      // make sure you also retrieve ID and then associate the column data with appropriate row, i.e.
     this.yourHttpSvc.getColData(colId).subscribe(response => {
        // iterate through response & rowData appropriately
        this.stats.rowData[key][colId] = response[key][colId];
     })
    }
  }
</code>```

Hope this helps!

Title: Dynamic Column configuration in ag-grid

Body:
If you are expecting any event from ag-grid, I think columnVisible might help you.

Have a look at this live example: https://plnkr.co/edit/KpFQp84rZvJgY2gjKRar?p=preview

Uncheck any column and then check.

<AgGridReact
   ...
   onColumnVisible={this.onColumnVisible}
/>

  onColumnVisible = params => {
    console.log(params);
    if (params.visible) {
      const colId = params.column.colId;
      alert(colId);
      // you could identify here, which column was checked
      // load data from server for that column
      // make sure you also retrieve ID and then associate the column data with appropriate row, i.e.
     this.yourHttpSvc.getColData(colId).subscribe(response => {
        // iterate through response & rowData appropriately
        this.stats.rowData[key][colId] = response[key][colId];
     })
    }
  }

Hope this helps!


问:
Convert Firebase Data To Formated Google Sheet

I need to Store ApplyForCompany Data in Google Sheet.
Can anyone help me to solve out this problem?

Thank You.

答:
I have solved this question following of below link

Data To Formated Google Sheet


问:
Alternative to fgets()?
Description:

Obtain output from an executable

Note:

Will not compile, due to fgets() declaration

Question:

What is the best alternative to fgets, as fgets requires char *?

Is there a better alternative?

Illustration:

```<code>void Q_analysis (const char *data)
{
string buffer;
size_t found;
found = buffer.find_first_of (*data);

FILE *condorData = _popen ("condor_q", "r");
while (fgets (buffer.c_str(), buffer.max_size(), condorData) != NULL)
{
    if (found == string::npos)
    {
        Sleep(2000);
    } else {
        break;
    }
}
return;
}
</code>```

答:
Try the boost library - I believe it has a function to create an fstream from a FILE*

or you could use fileno() to get a standard C file handle from the FILE, then use fstream::attach to attach a stream to that file.  From there you can use getline(), etc.  Something like this:

```<code>FILE *condorData = _popen ("condor_q", "r");
std::ifstream &stream = new std::ifstream();
stream.attach(_fileno(condorData));
</code>```

ContentLicense: CC BY-SA 2.5

Title: Alternative to fgets()?

Body:
Description:

Obtain output from an executable

Note:

Will not compile, due to fgets() declaration

Question:

What is the best alternative to fgets, as fgets requires char *?

Is there a better alternative?

Illustration:

void Q_analysis (const char *data)
{
string buffer;
size_t found;
found = buffer.find_first_of (*data);

FILE *condorData = _popen ("condor_q", "r");
while (fgets (buffer.c_str(), buffer.max_size(), condorData) != NULL)
{
    if (found == string::npos)
    {
        Sleep(2000);
    } else {
        break;
    }
}
return;
}

Body:
Try the boost library - I believe it has a function to create an fstream from a FILE*

or you could use fileno() to get a standard C file handle from the FILE, then use fstream::attach to attach a stream to that file.  From there you can use getline(), etc.  Something like this:

FILE *condorData = _popen ("condor_q", "r");
std::ifstream &stream = new std::ifstream();
stream.attach(_fileno(condorData));

OwnerDisplayName: Eric P


问:
jqgrid set datatype to jon- gets xml instead
I'm trying to set up jqgrid with JSON data.

my problem is that the data returned from my service is in xml format.

I've tracked the request sent by the grid in firebug, and here's what it says:

```<code>Request Headers
Host    localhost
User-Agent  Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1
Accept  application/json, text/javascript, */*; q=0.01
Accept-Language en-gb,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive  115
Connection  keep-alive
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With    XMLHttpRequest
Referer http://localhost/sample/sampleUserSearchPage.htm
Content-Length  60
Cookie  ASP.NET_SessionId=yfx42t45b0nidn45yztqzsun
</code>```

notice the Content-Type field.

I've compared this to another jQuery.ajax request I was making, and I noticed that the only difference was in the Content-Type field. on the other request (which returned json), the Content-Type was application/json; charset=UTF-8;

i think that's the problem, but i couldn't find on the jqgrid docs how to change that.

attached is my jquery code:

```<code>$("#grid").jqGrid({
        url: 'SampleScriptService.asmx/GetGridData',
        datatype: "json",
        mtype: "POST",
        jsonReader : { root: "rows" },
        colNames: ['Username', 'Full Name', 'Monitor?', 'Schedule?', 'Reports?', 'Administrator?', 'Password'],
        colModel: [
            { name: 'username', key: true, index: 'id', jsonmap: 'Username' },
            { name: 'fullname', index: 'invdate', width: 90 , jsonmap: 'FullName' },
            { name: 'ismonitor', index: 'name', width: 100, jsonmap: 'IsMonitor' },
            { name: 'isschedule', index: 'amount', width: 80, jsonmap: 'IsSchedule' },
            { name: 'isreports', index: 'tax', width: 80, jsonmap: 'IsReports' },
            { name: 'isadministrator', index: 'total', width: 80, jsonmap: 'IsAdministrator' },
            { name: 'password', index: 'note', width: 150, jsonmap: 'Password' }
             ],
        rowNum: 10,
        viewrecords: true,
        caption: "Simple data manipulation",
    });
</code>```

and the web service method:

```<code>[WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public GridData GetGridData(int page, int rows, /*string sixd,*/ string sord)
        {
            var arr= new UsersController().SearchUsers("", 10, 0).ToArray(); //this returns an array of User objects.
            GridData retVal = new GridData() { page = 1, records = 6, total = 34, rows = arr };

            return retVal;
        }
</code>```

答:
Probably the main problem which you have: you should add additional parameters to jqGrid:

```<code>ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {return JSON.stringify(postData);}
</code>```

Then the request from jqGrid will require JSON data. You can for example download the old demo project or read more information here.

Body:
I'm trying to set up jqgrid with JSON data.

my problem is that the data returned from my service is in xml format.

I've tracked the request sent by the grid in firebug, and here's what it says:

Request Headers
Host    localhost
User-Agent  Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1
Accept  application/json, text/javascript, */*; q=0.01
Accept-Language en-gb,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive  115
Connection  keep-alive
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With    XMLHttpRequest
Referer http://localhost/sample/sampleUserSearchPage.htm
Content-Length  60
Cookie  ASP.NET_SessionId=yfx42t45b0nidn45yztqzsun

notice the Content-Type field.

I've compared this to another jQuery.ajax request I was making, and I noticed that the only difference was in the Content-Type field. on the other request (which returned json), the Content-Type was application/json; charset=UTF-8;

i think that's the problem, but i couldn't find on the jqgrid docs how to change that.

attached is my jquery code:

$("#grid").jqGrid({
        url: 'SampleScriptService.asmx/GetGridData',
        datatype: "json",
        mtype: "POST",
        jsonReader : { root: "rows" },
        colNames: ['Username', 'Full Name', 'Monitor?', 'Schedule?', 'Reports?', 'Administrator?', 'Password'],
        colModel: [
            { name: 'username', key: true, index: 'id', jsonmap: 'Username' },
            { name: 'fullname', index: 'invdate', width: 90 , jsonmap: 'FullName' },
            { name: 'ismonitor', index: 'name', width: 100, jsonmap: 'IsMonitor' },
            { name: 'isschedule', index: 'amount', width: 80, jsonmap: 'IsSchedule' },
            { name: 'isreports', index: 'tax', width: 80, jsonmap: 'IsReports' },
            { name: 'isadministrator', index: 'total', width: 80, jsonmap: 'IsAdministrator' },
            { name: 'password', index: 'note', width: 150, jsonmap: 'Password' }
             ],
        rowNum: 10,
        viewrecords: true,
        caption: "Simple data manipulation",
    });

and the web service method:

[WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public GridData GetGridData(int page, int rows, /*string sixd,*/ string sord)
        {
            var arr= new UsersController().SearchUsers("", 10, 0).ToArray(); //this returns an array of User objects.
            GridData retVal = new GridData() { page = 1, records = 6, total = 34, rows = arr };

            return retVal;
        }

Body:
Probably the main problem which you have: you should add additional parameters to jqGrid:

ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {return JSON.stringify(postData);}

Then the request from jqGrid will require JSON data. You can for example download the old demo project or read more information here.


问:
How to extract schema from XML variable using XQuery
Technologies: T-SQL, XML, XQuery

I have an XML @variable in a database table which has a schema section and data section. I would only like to extra only the schema section and create a XML Schema Collection for it. It appears XQuery would be the quickest way. How do I specify the starting tag and ending tag in the following file (I only want to extract everything between <xs:schema xmlns and </xs:schema>?

```<code>CREATE FUNCTION [etl].[ufn_GetXmlSchema]
(
    @DataLakeBlobId uniqueidentifier
)
RETURNS xml
AS
BEGIN
    DECLARE  @XmlSchema xml
        ,@XmlData xml

    SET @XmlSchema = ( SELECT [XmlData]
                    FROM [landing].[v_tbForm] WITH (NOLOCK)
                    WHERE [DataLakeBlobId] = @DataLakeBlobId
                 )

    --RETURN @XmlSchema.query('</xs:schema>')-- missing matching begin tag
    --RETURN @XmlSchema.query('<xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="NewDataSet">')-- Expected end tag 'xs:schema'
    RETURN @XmlSchema.query('<xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="NewDataSet"></xs:schema>')-- nothing in between was returned
END
GO

SELECT [etl].[ufn_GetXmlSchema]('A257667D-C3AA-471C-9F82-91FA35181833')
</code>```

Any help is appreciated.

答:
While waiting for a real scenario, here is a good jump start for you. As end result, it creates an XML Schema Collection named dbo.StateAndCities.

SQL

```<code>USE tempdb;
GO

-- DDL and sample data population, start
IF EXISTS (SELECT * FROM sys.xml_schema_collections
                    WHERE name = N'StateAndCities'
                    AND schema_id = SCHEMA_ID(N'dbo'))
DROP XML SCHEMA COLLECTION dbo.StateAndCities;

DECLARE @tbl TABLE (
   ID INT IDENTITY PRIMARY KEY
   , state CHAR(2)
   , city VARCHAR(30)
);
INSERT INTO @tbl (state, city)
VALUES
('FL', 'Miami')
, ('CA', 'Los Angeles')
, ('TX', 'Austin');
-- DDL and sample data population, end

DECLARE @xml XML
    , @XSD XML;

-- Generate XML plus embedded XSD schema
SET @xml = (SELECT NULL,
(
    SELECT *
    FROM @tbl AS [row]
    FOR XML AUTO, ELEMENTS, TYPE, XMLSCHEMA('MyURI'))
    FOR XML PATH(''), TYPE, ROOT('root')
);

-- just to see, XML plus embedded XSD schema
SELECT @xml;

-- retrive just XSD
;WITH xmlnamespaces ('http://www.w3.org/2001/XMLSchema' AS xsd)
SELECT @xsd = (SELECT @xml.query('/root/xsd:schema'));

-- just to see, XSD schema
SELECT @xsd AS xsd;

-- create schema collection
CREATE XML SCHEMA COLLECTION dbo.StateAndCities AS @xsd;
</code>```

Body:
Technologies: T-SQL, XML, XQuery

I have an XML @variable in a database table which has a schema section and data section. I would only like to extra only the schema section and create a XML Schema Collection for it. It appears XQuery would be the quickest way. How do I specify the starting tag and ending tag in the following file (I only want to extract everything between <xs:schema xmlns and </xs:schema>?

CREATE FUNCTION [etl].[ufn_GetXmlSchema]
(
    @DataLakeBlobId uniqueidentifier
)
RETURNS xml
AS
BEGIN
    DECLARE  @XmlSchema xml
        ,@XmlData xml

    SET @XmlSchema = ( SELECT [XmlData]
                    FROM [landing].[v_tbForm] WITH (NOLOCK)
                    WHERE [DataLakeBlobId] = @DataLakeBlobId
                 )

    --RETURN @XmlSchema.query('</xs:schema>')-- missing matching begin tag
    --RETURN @XmlSchema.query('<xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="NewDataSet">')-- Expected end tag 'xs:schema'
    RETURN @XmlSchema.query('<xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="NewDataSet"></xs:schema>')-- nothing in between was returned
END
GO

SELECT [etl].[ufn_GetXmlSchema]('A257667D-C3AA-471C-9F82-91FA35181833')

Any help is appreciated.

Body:
While waiting for a real scenario, here is a good jump start for you. As end result, it creates an XML Schema Collection named dbo.StateAndCities.

SQL

USE tempdb;
GO

-- DDL and sample data population, start
IF EXISTS (SELECT * FROM sys.xml_schema_collections
                    WHERE name = N'StateAndCities'
                    AND schema_id = SCHEMA_ID(N'dbo'))
DROP XML SCHEMA COLLECTION dbo.StateAndCities;

DECLARE @tbl TABLE (
   ID INT IDENTITY PRIMARY KEY
   , state CHAR(2)
   , city VARCHAR(30)
);
INSERT INTO @tbl (state, city)
VALUES
('FL', 'Miami')
, ('CA', 'Los Angeles')
, ('TX', 'Austin');
-- DDL and sample data population, end

DECLARE @xml XML
    , @XSD XML;

-- Generate XML plus embedded XSD schema
SET @xml = (SELECT NULL,
(
    SELECT *
    FROM @tbl AS [row]
    FOR XML AUTO, ELEMENTS, TYPE, XMLSCHEMA('MyURI'))
    FOR XML PATH(''), TYPE, ROOT('root')
);

-- just to see, XML plus embedded XSD schema
SELECT @xml;

-- retrive just XSD
;WITH xmlnamespaces ('http://www.w3.org/2001/XMLSchema' AS xsd)
SELECT @xsd = (SELECT @xml.query('/root/xsd:schema'));

-- just to see, XSD schema
SELECT @xsd AS xsd;

-- create schema collection
CREATE XML SCHEMA COLLECTION dbo.StateAndCities AS @xsd;


问:
How to export variables declared in .then() function
I am creating angular application with the single spa. when we integrate single spa feature with the existing angular application, it creates it's new main file and considers that while starting the application. Now, my concern is I am using some async operation and providing that while starting the app like below in the main.js file:

```<code>resolveAsyncServices([
    {
        provide: XYZ,
        useFactory: () => XYZ.getUserLocale()
    },
    {
        provide: ABC,
        useFactory: (ABCData: Locale) => LocaleServiceNg.getUserTimezone(ABCData),
        deps: [PQR]
    },

])
  .then((providers: Array<StaticProvider>) => {
        platformBrowserDynamic(providers)
            .bootstrapModule(AppModule);
    })
    .catch(console.error);
</code>```

when single spa loads its private main file to the app it looks like below:

```<code>const lifecycles = singleSpaAngular({
  bootstrapFunction: singleSpaProps => {
    singleSpaPropsSubject.next(singleSpaProps);
    return platformBrowserDynamic().bootstrapModule(AppModule);
  },
  template: '<app-root />',
  Router,
  NgZone: NgZone,
  AnimationEngine: AnimationEngine,
});

export const bootstrap = lifecycles.bootstrap;
export const mount = lifecycles.mount;
export const unmount = lifecycles.unmount;
</code>```

i wanted to consider my resolveAsyncServices function with the help of single spa loader file. So for that I am trying below code:

```<code>resolveAsyncServices([
    {
        provide: XYZ,
        useFactory: () => XYZ.getUserLocale()
    },
    {
        provide: ABC,
        useFactory: (ABCData: Locale) => LocaleServiceNg.getUserTimezone(ABCData),
        deps: [PQR]
    },

])
  .then((providers: Array<StaticProvider>) => {
       const lifecycles = singleSpaAngular({
       bootstrapFunction: singleSpaProps => {
          singleSpaPropsSubject.next(singleSpaProps);
          return platformBrowserDynamic(providers).bootstrapModule(AppModule);
       },
       template: '<ct-root />',
       Router,
       NgZone: NgZone,
       AnimationEngine: AnimationEngine,
  });

  export const bootstrap = lifecycles.bootstrap;
  export const mount = lifecycles.mount;
  export const unmount = lifecycles.unmount;
})
.catch(console.error);
</code>```

but it is giving me errors on last export lines. So, now How do i export the methods so that it can be considered by angular.

答:
You cannot export things in a .then() function.  It's too late as the module exports have already been returned before the .then() handler ever runs.

As of the current state of node.js, exports have to be synchronous and anything in a .then() function is not synchronous.  Usually the solution is to export a promise or to export a function that one can call to get a promise and the caller can then use .then() to get the value they want from that promise.

There are people working on asynchronous module loading that will allow asynchronously retrieved exports, but that's not here yet.

Body:
I am creating angular application with the single spa. when we integrate single spa feature with the existing angular application, it creates it's new main file and considers that while starting the application. Now, my concern is I am using some async operation and providing that while starting the app like below in the main.js file:

resolveAsyncServices([
    {
        provide: XYZ,
        useFactory: () => XYZ.getUserLocale()
    },
    {
        provide: ABC,
        useFactory: (ABCData: Locale) => LocaleServiceNg.getUserTimezone(ABCData),
        deps: [PQR]
    },

])
  .then((providers: Array<StaticProvider>) => {
        platformBrowserDynamic(providers)
            .bootstrapModule(AppModule);
    })
    .catch(console.error);

when single spa loads its private main file to the app it looks like below:

const lifecycles = singleSpaAngular({
  bootstrapFunction: singleSpaProps => {
    singleSpaPropsSubject.next(singleSpaProps);
    return platformBrowserDynamic().bootstrapModule(AppModule);
  },
  template: '<app-root />',
  Router,
  NgZone: NgZone,
  AnimationEngine: AnimationEngine,
});

export const bootstrap = lifecycles.bootstrap;
export const mount = lifecycles.mount;
export const unmount = lifecycles.unmount;

i wanted to consider my resolveAsyncServices function with the help of single spa loader file. So for that I am trying below code:

resolveAsyncServices([
    {
        provide: XYZ,
        useFactory: () => XYZ.getUserLocale()
    },
    {
        provide: ABC,
        useFactory: (ABCData: Locale) => LocaleServiceNg.getUserTimezone(ABCData),
        deps: [PQR]
    },

])
  .then((providers: Array<StaticProvider>) => {
       const lifecycles = singleSpaAngular({
       bootstrapFunction: singleSpaProps => {
          singleSpaPropsSubject.next(singleSpaProps);
          return platformBrowserDynamic(providers).bootstrapModule(AppModule);
       },
       template: '<ct-root />',
       Router,
       NgZone: NgZone,
       AnimationEngine: AnimationEngine,
  });

  export const bootstrap = lifecycles.bootstrap;
  export const mount = lifecycles.mount;
  export const unmount = lifecycles.unmount;
})
.catch(console.error);

but it is giving me errors on last export lines. So, now How do i export the methods so that it can be considered by angular.


问:
Visualising two very different distributions in one plot
This is more of a "how would you do it" than a "how to do it" question.

I have two groups, "a" and "b". "b" consists of responses that are normally distributed, more or less, bounded between 0-1. "a", however, is mostly 1-s.

The process that generated the data is a questionnaire. People in group "b" made mistakes, people in group "a" mostly figured it out.

How do I visualise these data side by side? Boxplots are messed up because the median of one of the groups is basically 1. Violin plots mess up the widths.

Here is a reproducible example with the rough idea.

```<code>library(tidyverse)

d = tibble(
  val= c(
    rnorm(100, mean = 0.5, sd = 0.25),
    rnorm(5, mean = 0.5, sd = 0.25),
    rep(1, 95)
  ),
  var = c(
    rep('a', 100), rep('b', 100)
  )
) %>%
  filter(
    val >= 0,
    val <= 1
         )

d %>%
  ggplot(aes(x = var, y = val)) +
  geom_jitter() +
  geom_violin()

# No.

d %>%
  ggplot(aes(x = var, y = val)) +
  geom_boxplot()

# No-no.

</code>```

答: Thanks y'all. I don't think there's a perfect answer to this, but I will go with multiple posters and, during write-up, discuss the oddities of the data and speculate on the process responsible in detail.</p>

Body:
This is more of a "how would you do it" than a "how to do it" question.

I have two groups, "a" and "b". "b" consists of responses that are normally distributed, more or less, bounded between 0-1. "a", however, is mostly 1-s.

The process that generated the data is a questionnaire. People in group "b" made mistakes, people in group "a" mostly figured it out.

How do I visualise these data side by side? Boxplots are messed up because the median of one of the groups is basically 1. Violin plots mess up the widths.

Here is a reproducible example with the rough idea.

library(tidyverse)

d = tibble(
  val= c(
    rnorm(100, mean = 0.5, sd = 0.25),
    rnorm(5, mean = 0.5, sd = 0.25),
    rep(1, 95)
  ),
  var = c(
    rep('a', 100), rep('b', 100)
  )
) %>%
  filter(
    val >= 0,
    val <= 1
         )

d %>%
  ggplot(aes(x = var, y = val)) +
  geom_jitter() +
  geom_violin()

# No.

d %>%
  ggplot(aes(x = var, y = val)) +
  geom_boxplot()

# No-no.


问:
What is the difference between a normal executable jar vs building jar using izpack
What is the difference between a normal executable jar vs building jar using izpack ?

a) Does it have pre-build configurable wizards?
b) Advantages over the traditional executable jars?

I have build executable jars via eclipse, intellij and it works perfectly in any OS and it is platform independent as well.

Thanks.

答:
As the first line on their official site says...

Easily make installers that work seamlessly on Microsoft Windows™, Linux™, Solaris™ and Mac OS X™.

http://izpack.org/