问:
HTML Problems in Wordpress with Aweber
I am setting up my website in Wordpress and I have a pretty annoying problem.

I have a great sitebar with some widgets. When I don't implement my newsletter box (which is an Aweber script - look below), it look's great. However, when I implement it, it seems like the HTML is going wrong.

However, when I place the newsletter box as the lowest of the widgets, it also looks great. Problem is, I need to place the newsletter higher so I get more leads.

Graphical example:

When the newsletter box is in the bottom (and everything looks great):
http://i52.tinypic.com/2w6gb3c.jpg

When the newsletter box is where it shuld be (and everything looks horrible): http://i56.tinypic.com/no6ntd.jpg

My question therefore is: How in the world do I solve this issue? I have tried fixing the HTML lists and it doesn't seem like a missing closing tag.. And the HTML seems valid.

Technical Information

The Aweber Script is:

```<code><script type="text/javascript" src="http://forms.aweber.com/form/42/XXX.js"></script>
</code>```

This refer to a HTML form which looks like:

```<code><!-- AWeber Web Form Generator 3.0 -->
<style type="text/css">
#af-form-1560005742 .af-body .af-textWrap{width:98%;display:block;float:none;}
#af-form-1560005742 .af-body a{color:#700909;text-decoration:underline;font-style:normal;font-weight:normal;}
#af-form-1560005742 .af-body input.text, #af-form-1560005742 .af-body textarea{background-color:#FFFFFF;border-color:#BD965A;border-width:1px;border-style:solid;color:#000000;text-decoration:none;font-style:normal;font-weight:normal;font-size:12px;font-family:Verdana, sans-serif;}
#af-form-1560005742 .af-body input.text:focus, #af-form-1560005742 .af-body textarea:focus{background-color:#FFFAD6;border-color:#030303;border-width:1px;border-style:solid;}
#af-form-1560005742 .af-body label.previewLabel{display:block;float:none;text-align:left;width:auto;color:#000000;text-decoration:none;font-style:normal;font-weight:normal;font-size:12px;font-family:Verdana, sans-serif;}
#af-form-1560005742 .af-body{padding-bottom:15px;padding-top:15px;background-repeat:repeat-y;background-position:center left;background-image:url("http://forms.aweber.com/images/forms/memo/khaki/body.png");color:#000000;font-size:12px;font-family:Verdana, sans-serif;}
#af-form-1560005742 .af-footer{padding-bottom:45px;padding-top:1px;padding-right:34px;padding-left:34px;background-color:transparent;background-repeat:no-repeat;background-position:bottom left;background-image:url("http://forms.aweber.com/images/forms/memo/khaki/footer.png");border-width:1px;border-bottom-style:none;border-left-style:none;border-right-style:none;border-top-style:none;color:#000000;font-size:12px;font-family:Verdana, sans-serif;}
#af-form-1560005742 .af-header{padding-bottom:1px;padding-top:20px;padding-right:34px;padding-left:34px;background-color:transparent;background-repeat:no-repeat;background-position:top left;background-image:url("http://forms.aweber.com/images/forms/memo/khaki/header.png");border-width:1px;border-bottom-style:none;border-left-style:none;border-right-style:none;border-top-style:none;color:#8A1F0A;font-size:16px;font-family:Verdana, sans-serif;}
#af-form-1560005742 .af-quirksMode .bodyText{padding-top:2px;padding-bottom:2px;}
#af-form-1560005742 .af-quirksMode{padding-right:32px;padding-left:34px;}
#af-form-1560005742 .af-standards .af-element{padding-right:32px;padding-left:34px;}
#af-form-1560005742 .bodyText p{margin:1em 0;}
#af-form-1560005742 .buttonContainer input.submit{background-image:url("http://forms.aweber.com/images/auto/gradient/button/900.png");background-position:top left;background-repeat:repeat-x;background-color:#790000;border:1px solid #790000;color:#FFFFFF;text-decoration:none;font-style:normal;font-weight:normal;font-size:14px;font-family:Verdana, sans-serif;}
#af-form-1560005742 .buttonContainer input.submit{width:auto;}
#af-form-1560005742 .buttonContainer{text-align:left;}
#af-form-1560005742 body,#af-form-1560005742 dl,#af-form-1560005742 dt,#af-form-1560005742 dd,#af-form-1560005742 h1,#af-form-1560005742 h2,#af-form-1560005742 h3,#af-form-1560005742 h4,#af-form-1560005742 h5,#af-form-1560005742 h6,#af-form-1560005742 pre,#af-form-1560005742 code,#af-form-1560005742 fieldset,#af-form-1560005742 legend,#af-form-1560005742 blockquote,#af-form-1560005742 th,#af-form-1560005742 td{float:none;color:inherit;position:static;margin:0;padding:0;}
#af-form-1560005742 button,#af-form-1560005742 input,#af-form-1560005742 submit,#af-form-1560005742 textarea,#af-form-1560005742 select,#af-form-1560005742 label,#af-form-1560005742 optgroup,#af-form-1560005742 option{float:none;position:static;margin:0;}
#af-form-1560005742 div{margin:0;}
#af-form-1560005742 fieldset{border:0;}
#af-form-1560005742 form,#af-form-1560005742 textarea,.af-form-wrapper,.af-form-close-button,#af-form-1560005742 img{float:none;color:inherit;position:static;background-color:none;border:none;margin:0;padding:0;}
#af-form-1560005742 input,#af-form-1560005742 button,#af-form-1560005742 textarea,#af-form-1560005742 select{font-size:100%;}
#af-form-1560005742 p{color:inherit;}
#af-form-1560005742 select,#af-form-1560005742 label,#af-form-1560005742 optgroup,#af-form-1560005742 option{padding:0;}
#af-form-1560005742 table{border-collapse:collapse;border-spacing:0;}
#af-form-1560005742 ul,#af-form-1560005742 ol{list-style-image:none;list-style-position:outside;list-style-type:disc;padding-left:40px;}
#af-form-1560005742,#af-form-1560005742 .quirksMode{width:275px;}
#af-form-1560005742.af-quirksMode{overflow-x:hidden;}
#af-form-1560005742{background-color:transparent;border-color:transparent;border-width:1px;border-style:none;}
#af-form-1560005742{overflow:hidden;}
.af-body .af-textWrap{text-align:left;}
.af-body input.image{border:none!important;}
.af-body input.submit,.af-body input.image,.af-form .af-element input.button{float:none!important;}
.af-body input.text{width:100%;float:none;padding:2px!important;}
.af-body.af-standards input.submit{padding:4px 12px;}
.af-clear{clear:both;}
.af-element label{text-align:left;display:block;float:left;}
.af-element{padding:5px 0;}
.af-form-wrapper{text-indent:0;}
.af-form{text-align:left;margin:auto;}
.af-header,.af-footer{margin-bottom:0;margin-top:0;padding:10px;}
.af-quirksMode .af-element{padding-left:0!important;padding-right:0!important;}
.lbl-right .af-element label{text-align:right;}
body {
}
</style>
<form method="post" class="af-form-wrapper" action="http://www.aweber.com/scripts/addlead.pl" target="_new" >
<div style="display: none;">
<input type="hidden" name="meta_web_form_id" value="XXX" />
<input type="hidden" name="meta_split_id" value="" />
<input type="hidden" name="listname" value="youfirmnet" />
<input type="hidden" name="redirect" value="http://www.youfirm.net/wait-you-are-not-done-yet/" id="XXX" />

<input type="hidden" name="meta_adtracking" value="XXXX" />
<input type="hidden" name="meta_message" value="1" />
<input type="hidden" name="meta_required" value="email" />

<input type="hidden" name="meta_tooltip" value="" />
</div>
<div id="af-form-1560005742" class="af-form"><div id="af-header-XXX" class="af-header"><div class="bodyText"><p><span class="Apple-style-span" style="font-size: 18px;"><strong>Quality Newsletter:</strong></span></p>
<p><span class="Apple-style-span" style="font-size: 13px;">I write when I've something <em>important to share</em>. <strong>No</strong> daily emails and <strong>no</strong> spam. </span><span class="Apple-style-span" style="font-size: 13px;"><strong>By signing up</strong>, you will receive my *MUST READ* e-book: How the world of business is changing.</span></p></div></div>
<div id="af-body-XXX" class="af-body af-standards">
<div class="af-element">
<label class="previewLabel" for="awf_field-23759938">Email: </label>
<div class="af-textWrap"><input class="text" id="awf_field-XX" type="text" name="email" value="" tabindex="500"  />
</div><div class="af-clear"></div>
</div>
<div class="af-element buttonContainer">
<input name="submit" class="submit" type="submit" value="Submit" tabindex="501" />
<div class="af-clear"></div>
</div>
</div>
<div id="af-footer-XX" class="af-footer"><div class="bodyText"><p> </p></div></div>
</div>
<div style="display: none;"><img src="http://forms.aweber.com/form/displays.htm?id=jKxsDAwMrOwsTA==" alt="" /></div>
</form>
<script type="text/javascript">
    <!--
    (function() {
        var IE = /*@cc_on!@*/false;
        if (!IE) { return; }
        if (document.compatMode && document.compatMode == 'BackCompat') {
            if (document.getElementById("af-form-X")) {
                document.getElementById("af-form-XX").className = 'af-form af-quirksMode';
            }
            if (document.getElementById("af-body-x")) {
                document.getElementById("af-body-x").className = "af-body inline af-quirksMode";
            }
            if (document.getElementById("af-header-x")) {
                document.getElementById("af-header-x").className = "af-header af-quirksMode";
            }
            if (document.getElementById("af-footer-x")) {
                document.getElementById("af-footer-X").className = "af-footer af-quirksMode";
            }
        }
    })();
    -->
</script>

<!-- /AWeber Web Form Generator 3.0 -->
</code>```

The HTML on the UGLY version:

```<code><div class="sidebar_widgets">

            <ul>

            <li id="categories-3" class="widget widget_categories"><h2 class="widgettitle">Blog Categories</h2><div class="widget_inner">       <ul>
    <li class="cat-item cat-item-4"><a href="http://www.youfirm.net/category/cro/" title="When you have used either resources or money to attract visitors, you need to make money of these visitors. This category is all about how to convert the visitors into buyers.">Conversion Rate Optimization</a> (5)
</li>
    <li class="cat-item cat-item-12"><a href="http://www.youfirm.net/category/experiments/" title="In this category a variety of experiments I've performed myself is shown.">Experiments</a> (1)
</li>
    <li class="cat-item cat-item-11"><a href="http://www.youfirm.net/category/business/" title="This category covers some general advice and ideas. There are loads of different ideas you can use in your business - no matter what you are doing.">General Advice</a> (7)
</li>
    <li class="cat-item cat-item-5"><a href="http://www.youfirm.net/category/gettingvisitors/" title="Getting a large amount of visitors is essential to any business - offline and online. In this category I cover new ideas and methods to get visitors. If you are looking for search engine optimization help, look under YouFirm Articles.">Getting Visitors</a> (5)
</li>
    <li class="cat-item cat-item-9"><a href="http://www.youfirm.net/category/question-and-answers/" title="When people ask me questions using the Free advice page, I answer those questions. In this category you will see the questions asked and my answers to them.">Question and Answers</a> (7)
</li>
    <li class="cat-item cat-item-3"><a href="http://www.youfirm.net/category/upsell/" title="To make more money, up-selling is very important. Getting customers will often be expensive, so when you have customers, it is essential you make money up-selling them. This is what makes the difference: Get customers to buy again and get them to buy more.">Upselling</a> (3)
</li>
    <li class="cat-item cat-item-8"><a href="http://www.youfirm.net/category/website-feedback/" title="When people ask me about website feedback using the Free advice page, I tend to give some feedback! Here is some of the feedback posted.">Website Feedback</a> (2)
</li>
        </ul>
</div></li><li id="text-4" class="widget widget_text">          <div class="textwidget"><script type="text/javascript" src="http://forms.aweber.com/form/42/1560005742.js"></script></div>
        </div></li><li id="text-9" class="widget widget_text"><h2 class="widgettitle">YouFirm Membership</h2><div class="widget_inner">         <div class="textwidget"><b>This is the best I can offer</b>. This is my premium membership program which offers "how to" information. It covers how to get massive traffic, high conversions and generate massive up-sell.<br/><br/>

<a href="http://www.YouFirm.net/university" onclick="javascript:_gaq.push(['_trackEvent','outbound-widget','http://www.YouFirm.net']);" style="color:#9d080d; text-decoration: underline; font-weight:bold;">Read more about YouFirm University here</a>.</div>
        </div></li>     <li id="recent-posts-3" class="widget widget_recent_entries">       <h2 class="widgettitle">Recent Posts</h2><div class="widget_inner">     <ul>
                <li><a href="http://www.youfirm.net/2011/08/is-social-media-really-for-anyone/" title="Is social media really for anyone?">Is social media really for anyone?</a></li>
                <li><a href="http://www.youfirm.net/2011/08/buying-visitors-from-fiverr/" title="Buying visitors from Fiverr">Buying visitors from Fiverr</a></li>
                <li><a href="http://www.youfirm.net/2011/08/do-the-unexpected/" title="Do the Unexpected">Do the Unexpected</a></li>
                <li><a href="http://www.youfirm.net/2011/08/qr-codes-and-their-potential-exciting-designs/" title="QR Codes and their potential – Exciting designs">QR Codes and their potential – Exciting designs</a></li>
                <li><a href="http://www.youfirm.net/2011/08/using-professional-newsletter-managers/" title="Using Professional Newsletter Managers">Using Professional Newsletter Managers</a></li>
                <li><a href="http://www.youfirm.net/2011/08/q-is-it-easy-to-outrank-wikipedia-amazon-and-alike-in-google/" title="Q: Is it easy to outrank Wikipedia, Amazon and alike in Google?">Q: Is it easy to outrank Wikipedia, Amazon and alike in Google?</a></li>
                <li><a href="http://www.youfirm.net/2011/08/310/" title="More and More Elderly People">More and More Elderly People</a></li>
                <li><a href="http://www.youfirm.net/2011/08/getting-started-with-linkbuilding/" title="Getting started with linkbuilding">Getting started with linkbuilding</a></li>
                <li><a href="http://www.youfirm.net/2011/08/what-are-personas-and-how-to-use-them/" title="What Are Personas and How to Use Them">What Are Personas and How to Use Them</a></li>
                </ul>
        </div></li><li id="text-8" class="widget widget_text"><h2 class="widgettitle">Who is behind YouFirm?</h2><div class="widget_inner">         <div class="textwidget">My name is Lars Holdgaard and I am a full time entrepreneur. Read all <a href="http://www.youfirm.net/about/"  style="color:#9d080d; text-decoration: underline; font-weight:bold;">about me here</a>.<br/><br/>

<img src="http://i51.tinypic.com/24pe6gl.jpg" alt="Lars Holdgaard" title="Lars Holdgaard" width="150px" /></div>
        </div></li>         </ul>

        </div>

    </div>

    </div>
</code>```

Full CSS:
http://www.youfirm.net/wp-content/themes/SereneLiteTheme/style.css

答:
I'm posting the solution, the right way. So you can accept it if it worked out fine for you.

```<code><li id="text-4" class="widget widget_text">
  <div class="textwidget"><script type="text/javascript" src="http://forms.aweber.com/form/42/1560005742.js"></script></div>
  </div>
</li>
</code>```

The issue is that ending
 tag, its inside the
 tag with ID='text-4'. So that might you find it quickly just look for the element with that id and remove the last closing div tag from it.

so it would look like this:

```<code><li id="text-4" class="widget widget_text">
  <div class="textwidget"><script type="text/javascript" src="http://forms.aweber.com/form/42/1560005742.js"></script></div>
</li>
</code>```

Also, i encourage you to use http://validator.w3.org/ to find more errors in your page.

Title: HTML Problems in Wordpress with Aweber

Body:
I am setting up my website in Wordpress and I have a pretty annoying problem.

I have a great sitebar with some widgets. When I don't implement my newsletter box (which is an Aweber script - look below), it look's great. However, when I implement it, it seems like the HTML is going wrong.

However, when I place the newsletter box as the lowest of the widgets, it also looks great. Problem is, I need to place the newsletter higher so I get more leads.

Graphical example:

When the newsletter box is in the bottom (and everything looks great):
http://i52.tinypic.com/2w6gb3c.jpg

When the newsletter box is where it shuld be (and everything looks horrible): http://i56.tinypic.com/no6ntd.jpg

My question therefore is: How in the world do I solve this issue? I have tried fixing the HTML lists and it doesn't seem like a missing closing tag.. And the HTML seems valid.

Technical Information

The Aweber Script is:

This refer to a HTML form which looks like:

<form method="post" class="af-form-wrapper" action="http://www.aweber.com/scripts/addlead.pl" target="_new" >

<input type="hidden" name="meta_web_form_id" value="XXX" />
<input type="hidden" name="meta_split_id" value="" />
<input type="hidden" name="listname" value="youfirmnet" />
<input type="hidden" name="redirect" value="http://www.youfirm.net/wait-you-are-not-done-yet/" id="XXX" />

<input type="hidden" name="meta_adtracking" value="XXXX" />
<input type="hidden" name="meta_message" value="1" />
<input type="hidden" name="meta_required" value="email" />

<input type="hidden" name="meta_tooltip" value="" />

Quality Newsletter:

I write when I've something important to share. No daily emails and no spam. By signing up, you will receive my *MUST READ* e-book: How the world of business is changing.

Email:

<input class="text" id="awf_field-XX" type="text" name="email" value="" tabindex="500"  />

<input name="submit" class="submit" type="submit" value="Submit" tabindex="501" />

</form>

The HTML on the UGLY version:

Blog Categories

Conversion Rate Optimization (5)

Experiments (1)

General Advice (7)

Getting Visitors (5)

Question and Answers (7)

Upselling (3)

Website Feedback (2)

YouFirm Membership

This is the best I can offer. This is my premium membership program which offers "how to" information. It covers how to get massive traffic, high conversions and generate massive up-sell.

Read more about YouFirm University here.

Recent Posts

Is social media really for anyone?

Buying visitors from Fiverr

Do the Unexpected

QR Codes and their potential – Exciting designs

Using Professional Newsletter Managers

Q: Is it easy to outrank Wikipedia, Amazon and alike in Google?

More and More Elderly People

Getting started with linkbuilding

What Are Personas and How to Use Them

Who is behind YouFirm?

My name is Lars Holdgaard and I am a full time entrepreneur. Read all about me here.

Full CSS:
http://www.youfirm.net/wp-content/themes/SereneLiteTheme/style.css

Body:
I'm posting the solution, the right way. So you can accept it if it worked out fine for you.

<li id="text-4" class="widget widget_text">
  <div class="textwidget"><script type="text/javascript" src="http://forms.aweber.com/form/42/1560005742.js"></script></div>
  </div>
</li>

The issue is that ending </div> tag, its inside the <li> tag with ID='text-4'. So that might you find it quickly just look for the element with that id and remove the last closing div tag from it.

so it would look like this:

<li id="text-4" class="widget widget_text">
  <div class="textwidget"><script type="text/javascript" src="http://forms.aweber.com/form/42/1560005742.js"></script></div>
</li>

Also, i encourage you to use http://validator.w3.org/ to find more errors in your page.


来源: stackexchange

问:
`part:` modifier in node import statement
I came across this code in a javascript / Node project but can't find any explanation online as to what it is and how it works.

import PatchEvent, {set, unset} from 'part:@sanity/form-builder/patch-event';
```

答:
Looks like this syntax is specific to sanity.io's platform and isn't proper node / javascript syntax

https://www.sanity.io/docs/parts

ContentLicense: CC BY-SA 4.0


问:
When does Servlets read or write actual data
I was testing a Client Server Application to know when does a Servlet actually receives / writes a data to a Client.

The test setup has a client Java program which reads a file and POSTs the file to a Servlet.

Only after the client finishes writing the whole file (4 MB) data to socket the server starts reading that data. Similarly, when a Servlet sends a response using PrintWriter, the response reaches the client only when the doPost(...) method in the Servlet returns. Thorought the testing Tomcat memory didn't increase atall...

When does the Servlet Connection / Session gets established? Why does the Servlet coudn't read the data immediately when the client writes first few bytes of data to socket?

答:
That's just the way it works. The container will not invoke the servlet until the entire request is received from the client. Doing it any other way would imply any number of unforeseeable consequences. For starters, you would have to put manual completion checks in all your servlets, which would just add unnecessary boiler-plate code.

If you want to be able to react to HTTP requests from the moment they start being received, you will have to write your own socket program, binding and listening on a port and handling the input yourself.

Output is another matter. The output stream buffers all servlet output, but you can invoke flushBuffer() on the ServletResponse at any time to force it to send all currently buffered content. A warning about this though, once you start sending data to the client, the response is considered "committed". This is because of the HTTP protocol that requires certain pieces of information to come in a certain order. Headers, for instance, must be sent first, meaning that once you "commit" the response, headers and cookies can't be added by the server application anymore. The container will always call flushBuffer() (or flush() on the ServletOutputStream) after the servlet has finished executing.

ContentLicense: CC BY-SA 3.0


问:
First time login to Apache Airflow asks for username and password, what is the username and password?
I've just installed Apache Airflow, and I'm launching the webserver for the first time, and it asks me for username and password, I haven't set any username or password.

Can you let me know what is the default username and password for airflow?

答:
I installed AF from hub.docker.com and ran it

```<code>docker run -dit --name af --rm -p 8080:8080 apache/airflow standalone
</code>```

In this case defaul user is "admin" but password shows nowhere and stores in 'standalone_admin_password.txt'. To see the password run:

```<code>docker exec af cat standalone_admin_password.txt
</code>```

Body:
I installed AF from hub.docker.com and ran it

docker run -dit --name af --rm -p 8080:8080 apache/airflow standalone

In this case defaul user is "admin" but password shows nowhere and stores in 'standalone_admin_password.txt'. To see the password run:

docker exec af cat standalone_admin_password.txt


问:
Filter values as per std deviation for individual column
I am working on a requirement where I need to assign particular value to NaN based on the variable upper, which is my upper range of standard deviation
Here is a sample code-

```<code>    data = {'year': ['2014','2014','2015','2014','2015','2015','2015','2014','2015'],
        'month':['Hyundai','Toyota','Hyundai','Toyota','Hyundai','Toyota','Hyundai','Toyota',"Toyota"],
        'make': [23,34,32,22,12,33,44,11,21]
       }
    df = pd.DataFrame.from_dict(data)
    df=pd.pivot_table(df,index='month',columns='year',values='make',aggfunc=np.sum)
    upper=df.mean() + 3*df.std()
</code>```

This is just the sample data, the real data is huge, based on upper's value for every year, I need to filter the year column accordingly.

Sample I/P's:-

df-

upper std dev-

Desired O/P-

Based on the upper std deviation values in individual year, it should convert value as NaN if the value<upper.
Eg 2014 has upper=138, so only in 2014's column, if value<upper, convert it to NaN.
2014's upper value is only applicable in 2014 itself, and the same goes for 2015.

答:
IIUC use DataFrame.lt for compare Dataframe by Series and then set NaNs if match by DataFrame.mask:

```<code>print (df.lt(upper))
year     2014  2015
month
Hyundai  True  True
Toyota   True  True
</code>```

```<code>df = df.mask(df.lt(upper))
print (df)
year     2014  2015
month
Hyundai   NaN   NaN
Toyota    NaN   NaN
</code>```

Body:
I am working on a requirement where I need to assign particular value to NaN based on the variable upper, which is my upper range of standard deviation
Here is a sample code-

    data = {'year': ['2014','2014','2015','2014','2015','2015','2015','2014','2015'],
        'month':['Hyundai','Toyota','Hyundai','Toyota','Hyundai','Toyota','Hyundai','Toyota',"Toyota"],
        'make': [23,34,32,22,12,33,44,11,21]
       }
    df = pd.DataFrame.from_dict(data)
    df=pd.pivot_table(df,index='month',columns='year',values='make',aggfunc=np.sum)
    upper=df.mean() + 3*df.std()

This is just the sample data, the real data is huge, based on upper's value for every year, I need to filter the year column accordingly.

Sample I/P's:-

df-

upper std dev-

Desired O/P-

Based on the upper std deviation values in individual year, it should convert value as NaN if the value<upper.
Eg 2014 has upper=138, so only in 2014's column, if value<upper, convert it to NaN.
2014's upper value is only applicable in 2014 itself, and the same goes for 2015.

Body:
IIUC use DataFrame.lt for compare Dataframe by Series and then set NaNs if match by DataFrame.mask:

print (df.lt(upper))
year     2014  2015
month
Hyundai  True  True
Toyota   True  True

df = df.mask(df.lt(upper))
print (df)
year     2014  2015
month
Hyundai   NaN   NaN
Toyota    NaN   NaN


问:
How to compare large text files?
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

```<code>mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT
</code>```

file_2looks like this:

```<code>mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT
</code>```

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!

答:
Indeed, that could take a while. You have to make 1,200.000,000 line comparisions.
There are several possibilities to speed that up by an order of magnitute:

One would be to sort file2 and do kind of a binary search on file level.
Another approach: compute a checksum of each line, and search that. Depending on average line length, the file in question would be much smaller and you really can do a binary search if you store the checksums in a fixed format (i.e. a long)

The number of lines you read at once from file_1 does not matter, however. This is micro-optimization in the face of great complexity.

Title: How to compare large text files?

Body:
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT

file_2looks like this:

mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!


问:
How to get AuthorizationCode for RequestAuthorizationCodeTokenAsync
I am implementing IdentityServer. I need to use RequestAuthorizationCodeTokenAsync to get a token that can be passed to UserInfo endpoint. So I have a code like this:

```<code>var client = new HttpClient();
var tokenResponse = await client.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest
{
    Address = _discoveryDocument.TokenEndpoint,
    ClientId = ConfigurationManager.AppSettings["ClientId"],
    ClientSecret = ConfigurationManager.AppSettings["ClientSecret"],
    Code = "code",

});
</code>```

My client is authenticated successfully and redirected. So how do I get the AuthorizationCode from this redirect so I can pass as Code to the RequestAuthorizationCodeTokenAsync. I have setup my startup.cs like this:

```<code>services.AddAuthentication(options =>
{
    options.DefaultScheme = "cookie";
    options.DefaultChallengeScheme = "oidc";
})
.AddCookie("cookie")
.AddOpenIdConnect("oidc", options =>
{
    options.Authority = ConfigurationManager.AppSettings["AuthorityUrl"];
    options.ClientId = ConfigurationManager.AppSettings["ClientId"];
    options.ClientSecret = ConfigurationManager.AppSettings["ClientSecret"];
    options.RequireHttpsMetadata = false;
    options.GetClaimsFromUserInfoEndpoint = true;

    options.ResponseType = "code";
    options.UsePkce = true;
    options.ResponseMode = "query";

    options.Scope.Add("openid");
    options.Scope.Add("profile");
    options.Scope.Add("ois");
    options.SaveTokens = true;

});
</code>```

I know the Authorization request is supposed to return an Authorization code (i guess in a calback URL) but I have no idea how to get it.

I have tried using:

```<code>Microsoft.Extensions.Primitives.StringValues code;
Microsoft.Extensions.Primitives.StringValues state;

this.Request.Query.TryGetValue("code", out code);
this.Request.Query.TryGetValue("state", out state);
</code>```

but the code is null.

Please help.

Thanks

答:
Simply read the response:

```<code>if (tokenResponse.IsError)
{
    throw new Exception("...");
}
string token = tokenResponse.AccessToken;
</code>```

And I guess you are passing your actual code in the code parameter.

If you are using Cookies and OpenIdConnect handlers you don't need to call IdentityServer. The handler does it for you. Your app should be authenticated when you return from the Identity Provider.

As you configured your handler with SaveTokens = true, your tokens (access_token, refresh_token and id_token) are saved in your cookie.

If you need the access your tokens you can use the extension method HttpContext.GetTokenAsync(string token):

```<code>var accessToken = await HttpContext.GetTokenAsync("access_token");
var isToken = await HttpContext.GetTokenAsync("id_token");
var refreshToken = await HttpContext.GetTokenAsync("refresh_token");
</code>```

Body:
I am implementing IdentityServer. I need to use RequestAuthorizationCodeTokenAsync to get a token that can be passed to UserInfo endpoint. So I have a code like this:

var client = new HttpClient();
var tokenResponse = await client.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest
{
    Address = _discoveryDocument.TokenEndpoint,
    ClientId = ConfigurationManager.AppSettings["ClientId"],
    ClientSecret = ConfigurationManager.AppSettings["ClientSecret"],
    Code = "code",

});

My client is authenticated successfully and redirected. So how do I get the AuthorizationCode from this redirect so I can pass as Code to the RequestAuthorizationCodeTokenAsync. I have setup my startup.cs like this:

services.AddAuthentication(options =>
{
    options.DefaultScheme = "cookie";
    options.DefaultChallengeScheme = "oidc";
})
.AddCookie("cookie")
.AddOpenIdConnect("oidc", options =>
{
    options.Authority = ConfigurationManager.AppSettings["AuthorityUrl"];
    options.ClientId = ConfigurationManager.AppSettings["ClientId"];
    options.ClientSecret = ConfigurationManager.AppSettings["ClientSecret"];
    options.RequireHttpsMetadata = false;
    options.GetClaimsFromUserInfoEndpoint = true;

    options.ResponseType = "code";
    options.UsePkce = true;
    options.ResponseMode = "query";

    options.Scope.Add("openid");
    options.Scope.Add("profile");
    options.Scope.Add("ois");
    options.SaveTokens = true;

});

I know the Authorization request is supposed to return an Authorization code (i guess in a calback URL) but I have no idea how to get it.

I have tried using:

Microsoft.Extensions.Primitives.StringValues code;
Microsoft.Extensions.Primitives.StringValues state;

this.Request.Query.TryGetValue("code", out code);
this.Request.Query.TryGetValue("state", out state);

but the code is null.

Please help.

Thanks

Body:
Simply read the response:

if (tokenResponse.IsError)
{
    throw new Exception("...");
}
string token = tokenResponse.AccessToken;

And I guess you are passing your actual code in the code parameter.

If you are using Cookies and OpenIdConnect handlers you don't need to call IdentityServer. The handler does it for you. Your app should be authenticated when you return from the Identity Provider.

As you configured your handler with SaveTokens = true, your tokens (access_token, refresh_token and id_token) are saved in your cookie.

If you need the access your tokens you can use the extension method HttpContext.GetTokenAsync(string token):

var accessToken = await HttpContext.GetTokenAsync("access_token");
var isToken = await HttpContext.GetTokenAsync("id_token");
var refreshToken = await HttpContext.GetTokenAsync("refresh_token");


问:
Python program to convert infix to prefix notation
I keep on getting an IndexError: list index out of range, return self.data[-1] # the last element in the list; I think I know what is causing this but I have no clue how to fix it

Here is the Stack Class I used:

```<code>class Stack:
    # LIFO Stack implementation using a Python list as underlying storage.
    def __init__(self):
        self.data =[]

    def __len__(self):
        return len(self.data)

    def is_empty(self):
        return len(self.data)==0

    def push(self, e):
        self.data.append(e)

    def top(self):
        return self.data[-1]

    def pop(self):
        return self.data.pop()
</code>```

And the corresponding code I made:

```<code>def operatorpriority(x):
    if x == "+" or x == "-":
        return 1
    elif x == "*" or x == "/":
        return 2
    else:
        return 3
    return 0

def polishnotation(A):
    # Converts Infix to Prefix Notation
    stack = Stack()
    stack.push(')')
    A = A + '('
    output = ""
    for i in range(len(A)-1, -1, -1):
        print(i)
        if A[i].isnumeric() == True:
            output+=A[i]
        elif A[i] == ")":
            stack.push(A[i])
        elif A[i] == "-" or A[i] == "+" or A[i] == "*" or A[i] == "/" or A[i] == "^":
            if A[i] == "^":
                while operatorpriority(A[i]) <= operatorpriority(stack.top()):
                    output+=stack.pop()
            else:
                while operatorpriority(A[i]) < operatorpriority(stack.top()):
                    output+=stack.pop()
            stack.push(A[i])
        elif A[i] == "(":
            while stack.is_empty()== False:
                if stack.top() != "(":
                    output+=stack.pop()
                stack.pop()
    while stack.is_empty()== False:
        output+=stack.pop()
    print(output)

</code>```

InfixInput = input("Input infix notation: ")

polishnotation(InfixInput)

Sample Input:

(a+b)*(c-d)

Expected Output:

*+ab-cd

答:
You have A = A + '('.  That adds at the wrong end.  Just do A = '('+A+')' and skip the extra push.

You are giving ')' the same priority as '^'.   In operatorpriority, your else: should be elif x =='^':.

In your elif A[i] == "(" clause, you are popping until '('.  That's the wrong type of parens.  And you don't break out of that loop until the stack is empty.  You need to break when you get to a ')'.

Your example shows (a+b)*(c+d), but your code only allows digits.  I haven't changed that.

This works:

```<code>class Stack:
    # LIFO Stack implementation using a Python list as underlying storage.
    def __init__(self):
        self.data =[]

    def __len__(self):
        return len(self.data)

    def is_empty(self):
        return len(self.data)==0

    def push(self, e):
        self.data.append(e)

    def top(self):
        return self.data[-1]

    def pop(self):
        return self.data.pop()

def operatorpriority(x):
    if x in "+-":
        return 1
    elif x in "*/":
        return 2
    elif x in "^":
        return 3
    return 0

def polishnotation(A):
    # Converts Infix to Prefix Notation
    stack = Stack()
    A = '(' + A + ')'
    output = ""
    for c in A[::-1]:
        print(c)
        if c.isnumeric():
            output+=c
        elif c == ")":
            stack.push(c)
        elif c in "+-*/^":
            if c == "^":
                while operatorpriority(c) <= operatorpriority(stack.top()):
                    output+=stack.pop()
            else:
                while operatorpriority(c) < operatorpriority(stack.top()):
                    output+=stack.pop()
            stack.push(c)
        elif c == "(":
            while not stack.is_empty():
                c1 = stack.pop()
                if c1 == ')':
                    break
                output+=c1
    while not stack.is_empty():
        output+=stack.pop()
    return output

print(polishnotation('(3+4)*(5+6)'))
</code>```

Body:
I keep on getting an IndexError: list index out of range, return self.data[-1] # the last element in the list; I think I know what is causing this but I have no clue how to fix it

Here is the Stack Class I used:

class Stack:
    # LIFO Stack implementation using a Python list as underlying storage.
    def __init__(self):
        self.data =[]

    def __len__(self):
        return len(self.data)

    def is_empty(self):
        return len(self.data)==0

    def push(self, e):
        self.data.append(e)

    def top(self):
        return self.data[-1]

    def pop(self):
        return self.data.pop()

And the corresponding code I made:

def operatorpriority(x):
    if x == "+" or x == "-":
        return 1
    elif x == "*" or x == "/":
        return 2
    else:
        return 3
    return 0

def polishnotation(A):
    # Converts Infix to Prefix Notation
    stack = Stack()
    stack.push(')')
    A = A + '('
    output = ""
    for i in range(len(A)-1, -1, -1):
        print(i)
        if A[i].isnumeric() == True:
            output+=A[i]
        elif A[i] == ")":
            stack.push(A[i])
        elif A[i] == "-" or A[i] == "+" or A[i] == "*" or A[i] == "/" or A[i] == "^":
            if A[i] == "^":
                while operatorpriority(A[i]) <= operatorpriority(stack.top()):
                    output+=stack.pop()
            else:
                while operatorpriority(A[i]) < operatorpriority(stack.top()):
                    output+=stack.pop()
            stack.push(A[i])
        elif A[i] == "(":
            while stack.is_empty()== False:
                if stack.top() != "(":
                    output+=stack.pop()
                stack.pop()
    while stack.is_empty()== False:
        output+=stack.pop()
    print(output)

InfixInput = input("Input infix notation: ")

polishnotation(InfixInput)

Sample Input:

(a+b)*(c-d)

Expected Output:

*+ab-cd

Body:
You have A = A + '('.  That adds at the wrong end.  Just do A = '('+A+')' and skip the extra push.

You are giving ')' the same priority as '^'.   In operatorpriority, your else: should be elif x =='^':.

In your elif A[i] == "(" clause, you are popping until '('.  That's the wrong type of parens.  And you don't break out of that loop until the stack is empty.  You need to break when you get to a ')'.

Your example shows (a+b)*(c+d), but your code only allows digits.  I haven't changed that.

This works:

class Stack:
    # LIFO Stack implementation using a Python list as underlying storage.
    def __init__(self):
        self.data =[]

    def __len__(self):
        return len(self.data)

    def is_empty(self):
        return len(self.data)==0

    def push(self, e):
        self.data.append(e)

    def top(self):
        return self.data[-1]

    def pop(self):
        return self.data.pop()

def operatorpriority(x):
    if x in "+-":
        return 1
    elif x in "*/":
        return 2
    elif x in "^":
        return 3
    return 0

def polishnotation(A):
    # Converts Infix to Prefix Notation
    stack = Stack()
    A = '(' + A + ')'
    output = ""
    for c in A[::-1]:
        print(c)
        if c.isnumeric():
            output+=c
        elif c == ")":
            stack.push(c)
        elif c in "+-*/^":
            if c == "^":
                while operatorpriority(c) <= operatorpriority(stack.top()):
                    output+=stack.pop()
            else:
                while operatorpriority(c) < operatorpriority(stack.top()):
                    output+=stack.pop()
            stack.push(c)
        elif c == "(":
            while not stack.is_empty():
                c1 = stack.pop()
                if c1 == ')':
                    break
                output+=c1
    while not stack.is_empty():
        output+=stack.pop()
    return output

print(polishnotation('(3+4)*(5+6)'))


问:
Issue when trying to interact with an API in Vuejs?
datalist.js

import axios from "axios";

export const datalist = () => {
  return axios.get("myapiurl/name...").then((response) => response);
};```
</div>
</div>
</p>
<p><strong>HelloWorld.vue</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
  <div>
    <div v-for="item in items" :key="item.DttID">
      <router-link
        :to="{
          name: 'UserWithID',
          params: { id: item.DepaD },
          query: { DepaD: item.DepaID },
        }"
      >
        <div class="bt-color">{{ item.DepaName }}</div>
      </router-link>
    </div>
    <br /><br /><br />
    <User />
  </div>
</template>

<script>
import User from "./User.vue";
import { datalist } from "./datalist";
export default {
  name: "HelloWorld",
  components: {
    User,
  },
  data() {
    return {
      items: datalist,
    };
  },
  mounted() {
    datalist().then((r) => {
      this.items = r.data;
    });
  },
};
</script></code>```

User.vue

<template>

      {{ item.Accv }}

</template>

```

Error with the code is,

[Vue warn]: Error in render: "TypeError: this.lists.filter is not a function"
TypeError: this.lists.filter is not a function

The above error i am getting in User.vue component in the line number '20'

From the api which is in, datalist.js file, i think i am not fetching data correctly. or in the list filter there is problem in User.vue?

答:
Try to change the following

HelloWorld.vue

```<code>data() {
  return {
    items: [],
  };
},
mounted() {
  datalist().then((r) => {
    this.items = r.data;
  });
},
</code>```

User.vue

```<code>data() {
  return {
    lists: []
  };
},
mounted() {
  datalist().then((r) => {
    this.lists = r.data;
  });
},
</code>```

At least this suppress the error, but i cant tell more based on your snippet since there are network issues :)

Body:
datalist.js

import axios from "axios";

export const datalist = () => {
  return axios.get("myapiurl/name...").then((response) => response);
};

HelloWorld.vue

<template>

      <router-link
        :to="{
          name: 'UserWithID',
          params: { id: item.DepaD },
          query: { DepaD: item.DepaID },
        }"
      >

{{ item.DepaName }}

      </router-link>

    <User />

</template>

User.vue

<template>

      {{ item.Accv }}

</template>

Error with the code is,

[Vue warn]: Error in render: "TypeError: this.lists.filter is not a function"
TypeError: this.lists.filter is not a function

The above error i am getting in User.vue component in the line number '20'

From the api which is in, datalist.js file, i think i am not fetching data correctly. or in the list filter there is problem in User.vue?

Body:
Try to change the following

HelloWorld.vue

data() {
  return {
    items: [],
  };
},
mounted() {
  datalist().then((r) => {
    this.items = r.data;
  });
},

User.vue

data() {
  return {
    lists: []
  };
},
mounted() {
  datalist().then((r) => {
    this.lists = r.data;
  });
},

At least this suppress the error, but i cant tell more based on your snippet since there are network issues :)


问:
Issue with Auth0/Nginx/Django redirect after login with Nginx Proxy
I am using nginx as a proxy to pass to my django app container. I can successfully access the main url but when it passes control back to the django app and logins in the django app container gives it the local url and it doesn't route back to the correct page.

The redirect uri comes in as http://app

site-enabled

```<code>upstream app{
    server 0.0.0.0:8888;
}

server {
    listen 8080;
    server_name app-dev.company.net;

    location / {
        # django running in uWSGI
        proxy_pass http://app;
        include uwsgi_params;
        uwsgi_read_timeout 300s;
        client_max_body_size 320m;
        sendfile on;
        proxy_read_timeout 1800;
        proxy_connect_timeout 1800;
        proxy_send_timeout 1800;
        send_timeout 1800;
    }
}
</code>```

docker-compose.yml

```<code>version: "3.9"
services:
  app:
    image: ecr/app
    container_name: django_app
    ports:
      - 8888
    env_file:
      - dev.env
    volumes:
      - staticfiles:/opt/app/static/
  nginx:
    build: ./nginx
    container_name: django_app
    volumes:
      - staticfiles:/opt/app/static/
    ports:
      - 8080:8080
    depends_on:
      - app
volumes:
  staticfiles:
</code>```

答:
Your docker-compose / nginx configuration file is full with little errors that could cause this kind of problem - so lets try to remove them.

delete the container names if not needed. This will make it easier to understand how to link from one container in another.

Where is your NGINX Dockerfile you need to do build ./nginx.

docker-compose

```<code>version: "3.9"
services:
  app:
    image: ecr/app
    ports:
      - 8888
    env_file:
      - dev.env
    volumes:
      - staticfiles:/opt/app/static/
  nginx:
    build: ./nginx
    volumes:
      - staticfiles:/opt/app/static/
    ports:
      - 8080:8080
    depends_on:
      - app
volumes:
  staticfiles:
</code>```

NGINX Configuration

You can not use 0.0.0.0 in your upstream block. Normally I use the service name. In your case app.  So please change that to server app:8888; and test it one more time.

Location Configuration

You are proxying http traffic to your django app container. There is no need to use uwsgi_read_timeout or include uwsgi_params. In your case a simple http proxy configuration would be enough. For example in all the things you have randomly added to the nginx configuration, one important proxy configuration is missing.

 proxy_pass http://django_app;
 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 proxy_set_header Host $host;
 proxy_redirect off;
```

Make sure your understand the directives you are using in the NGINX configuration as well as in the docker-compose file, clean up the config files and try again.

Body:
I am using nginx as a proxy to pass to my django app container. I can successfully access the main url but when it passes control back to the django app and logins in the django app container gives it the local url and it doesn't route back to the correct page.

The redirect uri comes in as http://app

site-enabled

upstream app{
    server 0.0.0.0:8888;
}

server {
    listen 8080;
    server_name app-dev.company.net;

    location / {
        # django running in uWSGI
        proxy_pass http://app;
        include uwsgi_params;
        uwsgi_read_timeout 300s;
        client_max_body_size 320m;
        sendfile on;
        proxy_read_timeout 1800;
        proxy_connect_timeout 1800;
        proxy_send_timeout 1800;
        send_timeout 1800;
    }
}

docker-compose.yml

version: "3.9"
services:
  app:
    image: ecr/app
    container_name: django_app
    ports:
      - 8888
    env_file:
      - dev.env
    volumes:
      - staticfiles:/opt/app/static/
  nginx:
    build: ./nginx
    container_name: django_app
    volumes:
      - staticfiles:/opt/app/static/
    ports:
      - 8080:8080
    depends_on:
      - app
volumes:
  staticfiles:

Body:
Your docker-compose / nginx configuration file is full with little errors that could cause this kind of problem - so lets try to remove them.

delete the container names if not needed. This will make it easier to understand how to link from one container in another.

Where is your NGINX Dockerfile you need to do build ./nginx.

docker-compose

version: "3.9"
services:
  app:
    image: ecr/app
    ports:
      - 8888
    env_file:
      - dev.env
    volumes:
      - staticfiles:/opt/app/static/
  nginx:
    build: ./nginx
    volumes:
      - staticfiles:/opt/app/static/
    ports:
      - 8080:8080
    depends_on:
      - app
volumes:
  staticfiles:

NGINX Configuration

You can not use 0.0.0.0 in your upstream block. Normally I use the service name. In your case app.  So please change that to server app:8888; and test it one more time.

Location Configuration

You are proxying http traffic to your django app container. There is no need to use uwsgi_read_timeout or include uwsgi_params. In your case a simple http proxy configuration would be enough. For example in all the things you have randomly added to the nginx configuration, one important proxy configuration is missing.

 proxy_pass http://django_app;
 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 proxy_set_header Host $host;
 proxy_redirect off;

Make sure your understand the directives you are using in the NGINX configuration as well as in the docker-compose file, clean up the config files and try again.


问:
Adding time stamp values to a table
I have lately started learning SQL,and as a part of my assignment,I was trying to solve this question:

The table structure which I have created is:

```<code>CREATE TABLE train (train_no int,date_of_dep date,time_of_dep timestamp,time_of_arrival timestamp)
</code>```

I am trying to insert a record for a train which will depart 33 minutes from now, and will arrive 115 minutes from current time.

This is the command I am trying to use:

```<code>INSERT INTO train VALUES(5,SYSDATE,TO_TIMESTAMP(SYSDATE+33/1440),TO_TIMESTAMP(SYSDATE+115/1440))
</code>```

On displaying the table, it is giving me this output:

Can anyone explain why am I not getting the required output?

答:
As there's no TIME datatype in Oracle, and as you need to collect information up to minutes (you certainly don't need fractional seconds; do you?), use DATE datatype as it contains both date and time information.

Also - although your task says that you do need it - you don't need date of departure; it is contained in time of departure.

Something like this:

```<code>SQL> CREATE TABLE train
  2  (
  3     train_no          INT,
  4     time_of_dep       DATE,
  5     time_of_arrival   DATE
  6  );

Table created.
</code>```

Insert a row; note that it is a good habit to specify all columns you're inserting into. You can add minutes the way you tried to, but - why wouldn't you use interval? It is easier to understand what you're doing:

```<code>SQL> INSERT INTO train (train_no, time_of_dep, time_of_arrival)
  2          VALUES (5,
  3                  SYSDATE + INTERVAL '33' MINUTE,
  4                  SYSDATE + INTERVAL '115' MINUTE);

1 row created.
</code>```

OK, so - what's being inserted?

```<code>SQL> SELECT SYSDATE, t.*
  2    FROM train t;

SYSDATE    TRAIN_NO TIME_OF_ TIME_OF_
-------- ---------- -------- --------
11.02.22          5 11.02.22 11.02.22
</code>```

Whoops! Not very useful. So - modify date format:

```<code>SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi';

Session altered.

SQL> SELECT SYSDATE, t.*
  2    FROM train t;

SYSDATE            TRAIN_NO TIME_OF_DEP      TIME_OF_ARRIVAL
---------------- ---------- ---------------- ----------------
11.02.2022 08:33          5 11.02.2022 09:05 11.02.2022 10:27

SQL>
</code>```

That looks better.

Alternatively, you could have used TO_CHAR function with desired format mask:

```<code>SQL> select train_no,
  2    to_char(time_of_dep    , 'dd.mm.yyyy hh24:mi') dep,
  3    to_char(time_of_arrival, 'dd.mm.yyyy hh24:mi') arr
  4  from train;

  TRAIN_NO DEP              ARR
---------- ---------------- ----------------
         5 11.02.2022 09:05 11.02.2022 10:27

SQL>
</code>```

[EDIT] If it must be a timestamp, you'd do the same:

```<code>SQL> CREATE TABLE train
  2  (
  3     train_no          INT,
  4     time_of_dep       timestamp,
  5     time_of_arrival   timestamp
  6  );

Table created.

SQL> INSERT INTO train (train_no, time_of_dep, time_of_arrival)
  2          VALUES (5,
  3                  systimestamp + INTERVAL '33' MINUTE,
  4                  systimestamp + INTERVAL '115' MINUTE);

1 row created.

SQL> SELECT SYSDATE, t.*
  2    FROM train t;

SYSDATE            TRAIN_NO TIME_OF_DEP               TIME_OF_ARRIVAL
---------------- ---------- ------------------------- -------------------------
11.02.2022 08:57          5 11.02.22 09:30:35,783378  11.02.22 10:52:35,783378

SQL>
</code>```

Title: Adding time stamp values to a table

Body:
I have lately started learning SQL,and as a part of my assignment,I was trying to solve this question:

The table structure which I have created is:

CREATE TABLE train (train_no int,date_of_dep date,time_of_dep timestamp,time_of_arrival timestamp)

I am trying to insert a record for a train which will depart 33 minutes from now, and will arrive 115 minutes from current time.

This is the command I am trying to use:

INSERT INTO train VALUES(5,SYSDATE,TO_TIMESTAMP(SYSDATE+33/1440),TO_TIMESTAMP(SYSDATE+115/1440))

On displaying the table, it is giving me this output:

Can anyone explain why am I not getting the required output?

Body:
As there's no TIME datatype in Oracle, and as you need to collect information up to minutes (you certainly don't need fractional seconds; do you?), use DATE datatype as it contains both date and time information.

Also - although your task says that you do need it - you don't need date of departure; it is contained in time of departure.

Something like this:

SQL> CREATE TABLE train
  2  (
  3     train_no          INT,
  4     time_of_dep       DATE,
  5     time_of_arrival   DATE
  6  );

Table created.

Insert a row; note that it is a good habit to specify all columns you're inserting into. You can add minutes the way you tried to, but - why wouldn't you use interval? It is easier to understand what you're doing:

SQL> INSERT INTO train (train_no, time_of_dep, time_of_arrival)
  2          VALUES (5,
  3                  SYSDATE + INTERVAL '33' MINUTE,
  4                  SYSDATE + INTERVAL '115' MINUTE);

1 row created.

OK, so - what's being inserted?

SQL> SELECT SYSDATE, t.*
  2    FROM train t;

SYSDATE    TRAIN_NO TIME_OF_ TIME_OF_
-------- ---------- -------- --------
11.02.22          5 11.02.22 11.02.22

Whoops! Not very useful. So - modify date format:

SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi';

Session altered.

SQL> SELECT SYSDATE, t.*
  2    FROM train t;

SYSDATE            TRAIN_NO TIME_OF_DEP      TIME_OF_ARRIVAL
---------------- ---------- ---------------- ----------------
11.02.2022 08:33          5 11.02.2022 09:05 11.02.2022 10:27

SQL>

That looks better.

Alternatively, you could have used TO_CHAR function with desired format mask:

SQL> select train_no,
  2    to_char(time_of_dep    , 'dd.mm.yyyy hh24:mi') dep,
  3    to_char(time_of_arrival, 'dd.mm.yyyy hh24:mi') arr
  4  from train;

  TRAIN_NO DEP              ARR
---------- ---------------- ----------------
         5 11.02.2022 09:05 11.02.2022 10:27

SQL>

[EDIT] If it must be a timestamp, you'd do the same:

SQL> CREATE TABLE train
  2  (
  3     train_no          INT,
  4     time_of_dep       timestamp,
  5     time_of_arrival   timestamp
  6  );

Table created.

SQL> INSERT INTO train (train_no, time_of_dep, time_of_arrival)
  2          VALUES (5,
  3                  systimestamp + INTERVAL '33' MINUTE,
  4                  systimestamp + INTERVAL '115' MINUTE);

1 row created.

SQL> SELECT SYSDATE, t.*
  2    FROM train t;

SYSDATE            TRAIN_NO TIME_OF_DEP               TIME_OF_ARRIVAL
---------------- ---------- ------------------------- -------------------------
11.02.2022 08:57          5 11.02.22 09:30:35,783378  11.02.22 10:52:35,783378

SQL>


问:
Typescript, Angular Material, get and set accessor must have the same datatype
After installing @angular/material version^13.1.1. I have a lot of Typescript errors (2307) :

'get' and 'set' accessor must have the same datatype.

I have used

```<code>ng add @angular/material
</code>```

example in \node_modules@angular\material\checkbox\checkbox.d.ts :

```<code>get disabled(): boolean;
set disabled(disabled: BooleanInput);
</code>```

My Typescript version : ~4.5.2.

As far as I can see this cannot be resolved changing a parameter in tsconfig.json.

答:
I was trying to implement 'Angular Material datepicker' and run the below commands -

```<code>npm install --save @angular/material @angular/cdk
npm install --save @angular/animations
npm i @angular/material-moment-adapter
npm i moment
</code>```

Then I have faced the same error (image) at the time of ng serve.

If we look closely at the error, then we found that the error was coming from only angular/cdk and angular/material. E.g. -

angular/cdk -

Error: node_modules/@angular/cdk/a11y/focus-trap/focus-trap.d.ts:141:9 - error
TS2380: 'get' and 'set' accessor must have the same type.
141     get enabled(): boolean;

angular/material -

Error: node_modules/@angular/material/datepicker/date-range-input.d.ts:48:9 - error
TS2380: 'get' and 'set' accessor must have the same type.
48     get required(): boolean;

This is due to version incompatibility.

package.json -

```<code>  "dependencies": {
    "@angular/animations": "^12.0.5",
    "@angular/cdk": "^13.2.2",
    "@angular/common": "~12.0.3",
    "@angular/compiler": "~12.0.3",
    "@angular/core": "~12.0.3",
    "@angular/forms": "~12.0.3",
    "@angular/material": "^13.2.2",
    "@angular/material-moment-adapter": "^13.2.2",
    "@angular/platform-browser": "~12.0.3",
    "@angular/platform-browser-dynamic": "~12.0.3",
    "@angular/router": "~12.0.3",
    "moment": "^2.29.1",
    "rxjs": "~6.6.0",
    "tslib": "^2.1.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.0.3",
    "@angular/cli": "~12.0.3",
    "@angular/compiler-cli": "~12.0.3",
    "@types/jasmine": "~3.6.0",
    "@types/node": "^12.11.1",
    "jasmine-core": "~3.7.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "typescript": "~4.2.3"
  }
</code>```

Solution -

Step 1 -

In my case, I was having:

```<code>"@angular/cdk": "^13.2.2",
"@angular/material": "^13.2.2"
</code>```

In package.json, change the version of cdk and material. Save -

```<code>"@angular/cdk": "~12.2.13",
"@angular/material": "~12.2.13"
</code>```

Info - check Angular Material website to get different/other
version.

Step 2 -

Delete node_modules folder and package-lock.json. Do npm install again.

Result -

Project running or working successfully and no error at the time of ng serve.

Body:
After installing @angular/material version^13.1.1. I have a lot of Typescript errors (2307) :

'get' and 'set' accessor must have the same datatype.

I have used

ng add @angular/material

example in \node_modules@angular\material\checkbox\checkbox.d.ts :

get disabled(): boolean;
set disabled(disabled: BooleanInput);

My Typescript version : ~4.5.2.

As far as I can see this cannot be resolved changing a parameter in tsconfig.json.

Body:
I was trying to implement 'Angular Material datepicker' and run the below commands -

npm install --save @angular/material @angular/cdk
npm install --save @angular/animations
npm i @angular/material-moment-adapter
npm i moment

Then I have faced the same error (image) at the time of ng serve.

If we look closely at the error, then we found that the error was coming from only angular/cdk and angular/material. E.g. -

angular/cdk -

Error: node_modules/@angular/cdk/a11y/focus-trap/focus-trap.d.ts:141:9 - error
TS2380: 'get' and 'set' accessor must have the same type.
141     get enabled(): boolean;

angular/material -

Error: node_modules/@angular/material/datepicker/date-range-input.d.ts:48:9 - error
TS2380: 'get' and 'set' accessor must have the same type.
48     get required(): boolean;

This is due to version incompatibility.

package.json -

  "dependencies": {
    "@angular/animations": "^12.0.5",
    "@angular/cdk": "^13.2.2",
    "@angular/common": "~12.0.3",
    "@angular/compiler": "~12.0.3",
    "@angular/core": "~12.0.3",
    "@angular/forms": "~12.0.3",
    "@angular/material": "^13.2.2",
    "@angular/material-moment-adapter": "^13.2.2",
    "@angular/platform-browser": "~12.0.3",
    "@angular/platform-browser-dynamic": "~12.0.3",
    "@angular/router": "~12.0.3",
    "moment": "^2.29.1",
    "rxjs": "~6.6.0",
    "tslib": "^2.1.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.0.3",
    "@angular/cli": "~12.0.3",
    "@angular/compiler-cli": "~12.0.3",
    "@types/jasmine": "~3.6.0",
    "@types/node": "^12.11.1",
    "jasmine-core": "~3.7.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "typescript": "~4.2.3"
  }

Solution -

Step 1 -

In my case, I was having:

"@angular/cdk": "^13.2.2",
"@angular/material": "^13.2.2"

In package.json, change the version of cdk and material. Save -

"@angular/cdk": "~12.2.13",
"@angular/material": "~12.2.13"

Info - check Angular Material website to get different/other
version.

Step 2 -

Delete node_modules folder and package-lock.json. Do npm install again.

Result -

Project running or working successfully and no error at the time of ng serve.


问:
What is the default mongod write concern in which version?
I could not find in mongodb's documentation what's the default write concern and how an "acknowledged write" is defined.
It seems that this have changed throughout the different mongodb versions as shows the v3.2 documentation for example:

In 3.2-versions earlier than 3.2.6, w: "majority" implies j: true if journaling is enabled. With earlier versions of MongoDB, w: majority" does not imply journaling.

Or:

Changed in version 3.0: Prior to MongoDB 3.0, w: "majority" refers to the majority of the replica set’s members.

Or:

Changed in version 2.6: In Master/Slave deployments, MongoDB treats w: "majority" as equivalent to w: 1. In earlier versions of MongoDB, w: "majority" produces an error in master/slave deployments.

Also, I'm wondering that "majority" refers to all voting nodes in v3.2 documentation :

Requests acknowledgment that write operations have propagated to the majority of voting nodes [1], including the primary.

Does this mean that even arbiters count since they are voting nodes? So, for example, if I have a replSet consisting of 2 data bearing nodes plus 1 arbiter, a write operation with write concern "majority" would succeed even if 1 data bearing node went down because the write was acknowledged by the remaining data bearing node and the arbiter, hence the majority?

答:
In MongoDB v5.0, the default writeConcern is w:majority.

In previous versions < v5.0, the default is writeConcern w:1


问:
Does GitLab's API provide a way to create issues based on issue templates?
I'm building a Python tool that can use GitLab issue templates to create issues. Does the API provide a way to do so?

I read the documentation and it seems not but maybe I missed something.

答:
I can only find "Using a URL with prefilled values", where the following URL is using a description template

```<code>https://gitlab.com/gitlab-org/gitlab/-/issues/new?
  issue[title]=Validate%20new%20concept&
  issuable_template=Feature%20Proposal%20-%20basic
</code>```

Calling that URL in your Python tool would use said template.

Body:
I can only find "Using a URL with prefilled values", where the following URL is using a description template

https://gitlab.com/gitlab-org/gitlab/-/issues/new?
  issue[title]=Validate%20new%20concept&
  issuable_template=Feature%20Proposal%20-%20basic

Calling that URL in your Python tool would use said template.


问:
C preprocessor: expand macro in a #warning
I would like to print a macro value (expand the macro) in the #warning directive.

For example, for the code:

```<code>#define AAA 17
#warning AAA = ???
</code>```

The desired compile-time output would be

```<code>warning: AAA = 17
</code>```

What do I use for ???, or, how do I augment the code?

答:
Another simple method is, especially when you are dealing with a Makefile project (like linux, u-boot, qemu, ..), you can see the pre-processed result of the file.

For example,

to see preprocessed file of arch/arm64/kernel/head.S,

you can do make arch/arm64/kernel/head.s. (small s).

to see preprocessed file of foo/bar/baz.c,

you can do make foo/bar/baz.i

The macros are all expanded to the final value.

Body:
I would like to print a macro value (expand the macro) in the #warning directive.

For example, for the code:

#define AAA 17
#warning AAA = ???

The desired compile-time output would be

warning: AAA = 17

What do I use for ???, or, how do I augment the code?


答:
If you want a simple approach: you can hash both of the files and compare the hash. But it's probably faster (especially if the files differ) to use your approach. About the memory consumption: just make sure you use enough memory, using no buffer for this kind a thing is a bad idea..

And all those answers about hashes, checksums etc: those are not faster. You have to read the whole file in both cases. With hashes/checksums you even have to compute something...

Title: How to compare large text files?


问:
How can I get the IP of the docker host on a Linux system from a docker container?
This question appears to have been asked many times, but the answers appear to be outdated, or just not work.

I'm on a Linux system without a RTC (a raspberry pi). My host runs an ntp daemon (ntpd), which checks the time online as soon as the host boots up, assuming it has internet, and sets the system clock.

The code inside my container needs to know if the host's system clock is accurate (has been updated since last boot).

On the host itself, this is very easy to do - use something like ntpdate -q 127.0.0.1. ntpdate connects to 127.0.0.1:123 over udp, and checks with the ntpd daemon if the clock is accurate (if it's been updated since last boot). This appears to be more difficult to do from within a container.

If I start up a container, and use docker container inspect NAME to see the container's IP, it shows me this:

```<code>"Gateway": "172.19.0.1",
"IPAddress": "172.19.0.6",
</code>```

If I run ntpdate -q 172.19.0.1 within the container, this works. Unfortunately, 172.19.0.1 isn't a permanent IP for the host. It that subnet is already taken when the container is starting up, the subnet will change, so hardcoding this IP is a bad idea. What I need is an environment variable that always reflects the proper IP for the host.

Windows and MacOS versions of docker appear to set the host.docker.internal hostname within containers, but Linux doesn't. Some people recommend setting this in the /etc/hosts file of the host, but then you're just hardcoding the IP, which again, can change.

I run my docker container with a docker-compose.yml file, and apparently, on new versions of docker, you can do this:

```<code>extra_hosts:
    - "host.docker.internal:host-gateway"
</code>```

I tried this, and this works. Sort of. Inside my container, host.docker.internal resolves to 172.17.0.1, which is IP of the docker0 interface on the host. While I can ping host.docker.internal from within the container, using ntpdate -q host.docker.internal or ntpdate -q 172.17.0.1 doesn't work.

Is there a way to make host.docker.internal resolve to the proper gateway IP of the host from within the container? In my example, 172.19.0.1.

Note: Yes, I can use code within the container to check what the container's gateway is with netstat or similar, but then I need to complicate my code, making it figure out the IP of the NTP server (the docker host). I can probably also pass the docker socket into the container, and try to get the docker host's IP through that, but that seems super hackey, and an unnecessary security issue.

答:
The best solution I've found is to use the ip command from the iproute2 package, look for the default route and use the gateway address for it.

```<code>ip route | awk '/default/ {print $3}'
</code>```

if you want it in an environment variable, you can set it in an entrypoint script with

```<code>export HOST_IP_ADDRESS=$(ip route | awk '/default/ {print $3}')
</code>```

Body:
This question appears to have been asked many times, but the answers appear to be outdated, or just not work.

I'm on a Linux system without a RTC (a raspberry pi). My host runs an ntp daemon (ntpd), which checks the time online as soon as the host boots up, assuming it has internet, and sets the system clock.

The code inside my container needs to know if the host's system clock is accurate (has been updated since last boot).

On the host itself, this is very easy to do - use something like ntpdate -q 127.0.0.1. ntpdate connects to 127.0.0.1:123 over udp, and checks with the ntpd daemon if the clock is accurate (if it's been updated since last boot). This appears to be more difficult to do from within a container.

If I start up a container, and use docker container inspect NAME to see the container's IP, it shows me this:

"Gateway": "172.19.0.1",
"IPAddress": "172.19.0.6",

If I run ntpdate -q 172.19.0.1 within the container, this works. Unfortunately, 172.19.0.1 isn't a permanent IP for the host. It that subnet is already taken when the container is starting up, the subnet will change, so hardcoding this IP is a bad idea. What I need is an environment variable that always reflects the proper IP for the host.

Windows and MacOS versions of docker appear to set the host.docker.internal hostname within containers, but Linux doesn't. Some people recommend setting this in the /etc/hosts file of the host, but then you're just hardcoding the IP, which again, can change.

I run my docker container with a docker-compose.yml file, and apparently, on new versions of docker, you can do this:

extra_hosts:
    - "host.docker.internal:host-gateway"

I tried this, and this works. Sort of. Inside my container, host.docker.internal resolves to 172.17.0.1, which is IP of the docker0 interface on the host. While I can ping host.docker.internal from within the container, using ntpdate -q host.docker.internal or ntpdate -q 172.17.0.1 doesn't work.

Is there a way to make host.docker.internal resolve to the proper gateway IP of the host from within the container? In my example, 172.19.0.1.

Note: Yes, I can use code within the container to check what the container's gateway is with netstat or similar, but then I need to complicate my code, making it figure out the IP of the NTP server (the docker host). I can probably also pass the docker socket into the container, and try to get the docker host's IP through that, but that seems super hackey, and an unnecessary security issue.

Body:
The best solution I've found is to use the ip command from the iproute2 package, look for the default route and use the gateway address for it.

ip route | awk '/default/ {print $3}'

if you want it in an environment variable, you can set it in an entrypoint script with

export HOST_IP_ADDRESS=$(ip route | awk '/default/ {print $3}')


问:
Integer contains linq c# but using using expressions
I want to create a dynamic filter for my repositories using linq expressions, I have other filters but i don't know how to make the next one using expressions: (the condition was taked from here)

```<code>var result = _studentRepotory.GetAll().Where(s =>
SqlFunctions.StringConvert((double)s.Id).Contains("91")).ToList();
</code>```

I have a method that receives the value of a property, the propertyName and the filter operator type (enum):

```<code>public static class Helper {
    public static Expression<Func<T, bool>> GetExpression<T>(object value, string propertyName, FilterOperatorType FilterType)
    {
        var parameter = Expression.Parameter(typeof(T));
        var property = ExpressionUtils.GetPropertyChild(parameter, propertyName);
        var constValue = Expression.Constant(value);

        BinaryExpression expresion = null;
        switch (FilterType)
        {
            case FilterOperatorType.Equal:
                expresion = Expression.Equal(property, constValue);
                break;
            case FilterOperatorType.Greater:
                expresion = Expression.GreaterThan(property, constValue);
                break;
            case FilterOperatorType.Less:
                expresion = Expression.LessThan(property, constValue);
                break;
            case FilterOperatorType.GreaterOrEqual:
                expresion = Expression.GreaterThanOrEqual(property, constValue);
                break;
            case FilterOperatorType.LessOrEqual:
                expresion = Expression.LessThanOrEqual(property, constValue);
                break;
        }

        var lambda = Expression.Lambda<Func<T, bool>>(expresion, parameter);
        return lambda;
    }
}
</code>```

So, I want to add a new opertator type Contains that will evaluate if an integer contains some digits, in the first block of code I do it, but I want to do it with linq expressions using generics.

At the end I wil have:

```<code>Expression<Func<Student, bool>> where = Helper.GetExpression<Student>("91", "Id",  FilterOperatorType.Contains);
var result = _studentRepotory.GetAll().Where(where).ToList();
</code>```

The query should return all the students when the Id contains the digits 91.

Please help me, and tell me if you understand.

答:
Here is a method. And you can search int columns as strings

https://gist.github.com/gnncl/e424adefc3e08b607beee8d638759492

Body:
I want to create a dynamic filter for my repositories using linq expressions, I have other filters but i don't know how to make the next one using expressions: (the condition was taked from here)

var result = _studentRepotory.GetAll().Where(s =>
SqlFunctions.StringConvert((double)s.Id).Contains("91")).ToList();

I have a method that receives the value of a property, the propertyName and the filter operator type (enum):

public static class Helper {
    public static Expression<Func<T, bool>> GetExpression<T>(object value, string propertyName, FilterOperatorType FilterType)
    {
        var parameter = Expression.Parameter(typeof(T));
        var property = ExpressionUtils.GetPropertyChild(parameter, propertyName);
        var constValue = Expression.Constant(value);

        BinaryExpression expresion = null;
        switch (FilterType)
        {
            case FilterOperatorType.Equal:
                expresion = Expression.Equal(property, constValue);
                break;
            case FilterOperatorType.Greater:
                expresion = Expression.GreaterThan(property, constValue);
                break;
            case FilterOperatorType.Less:
                expresion = Expression.LessThan(property, constValue);
                break;
            case FilterOperatorType.GreaterOrEqual:
                expresion = Expression.GreaterThanOrEqual(property, constValue);
                break;
            case FilterOperatorType.LessOrEqual:
                expresion = Expression.LessThanOrEqual(property, constValue);
                break;
        }

        var lambda = Expression.Lambda<Func<T, bool>>(expresion, parameter);
        return lambda;
    }
}

So, I want to add a new opertator type Contains that will evaluate if an integer contains some digits, in the first block of code I do it, but I want to do it with linq expressions using generics.

At the end I wil have:

Expression<Func<Student, bool>> where = Helper.GetExpression<Student>("91", "Id",  FilterOperatorType.Contains);
var result = _studentRepotory.GetAll().Where(where).ToList();

The query should return all the students when the Id contains the digits 91.

Please help me, and tell me if you understand.


问:
Change img via css if it is out the container
I've got a container for image and img inside.

Is there some way to change the img content if it's width becomes bigger than the container width via css? Maby image-set?

nav{;
    width: 100%;
    padding: 0;
    height:70px;
    display: flex;
    position: relative;
    border-bottom: 1px solid #b8bbc0;
}

.logo-container{
    display: inline-block;
    overflow: hidden;
    max-width: 25%;
    flex: 0 0  25%;
    -ms-flex: 0 0  25%;
    padding: 5px 0;
    margin: 5px 5px 5px 0;
    position: absolute;
    left: 5px;
}
.logo-helper{
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
.logo-container img{
    max-height:40px;
    margin: 5px;
    display: inline-block;
    content:   url(https://wilcity.com/wp-content/uploads/2018/12/sample-logo-design-png-3.png);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <nav>
    <div class="logo-container">
        <span class="helper"></span>
        <img>
    </div>
    </nav></code>```

答:
You cannot conditionally set any property in CSS because it is not a programming language.
You can do this in JavaScript.

```<code>var img = document.getElementById("my-img");
var container = document.getElementById("image-container");
if(img.style.width > container.style.width){
 img.src = "http://example.com/myimg.png"
</code>```

}

Body:
You cannot conditionally set any property in CSS because it is not a programming language.
You can do this in JavaScript.

var img = document.getElementById("my-img");
var container = document.getElementById("image-container");
if(img.style.width > container.style.width){
 img.src = "http://example.com/myimg.png"

}


问:
Is it possible to open IOS simulator while developing React-Native APP on Windows 10?
I am developing an application by using React-Native. My operating system is Windows 10. I want the application to be competible with both iOS and Android. I am using Expo for the development. In expo,

There are above choices, since I don't have an iOS simulator, the second choice gives an error. How can I install an iOS simulator to my computer?

答:
As of now, you can not create a simulator inside windows but there are many browser-based iOS stimulations available you can use them.

one of them is Appetize.io here It is free for use but you have to upload your app manually. There are many other options available. read here.


问:
ios15,WKWebView,UITextField crash
iOS15 system:
1.click UITextField crash
2.Click the second layer WebView to crash
log:

Incident Identifier: 4F61CB1C-53DB-4EFD-B38F-93B973BE5CCC
CrashReporter Key: 6fa29e4a6b7c708a032c474dff75ab04a89a6a5e Hardware
Model: iPhone12,5 Process: AppName [2986] Path:
/private/var/containers/Bundle/Application/***/AppName.app/AppName
Identifier: com.***** Version: 8.0.0 (1) Code Type: ARM-64 (Native)
Role: Foreground Parent Process: launchd [1] Coalition: com.*****
[1262] Date/Time: 2022-01-28 16:14:58.8262 +0800 Launch Time:
2022-01-28 16:14:41.9927 +0800 OS Version: iPhone OS 15.2.1 (19C63)
Release Type: User Baseband Version: 3.01.02 Report Version: 104
Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes:
0x0000000000000001, 0x00000001812e01ec Exception Note:
EXC_CORPSE_NOTIFY Termination Reason: SIGNAL 5 Trace/BPT trap: 5
Terminating Process: 888 handler [2986] Triggered by Thread: 0 Thread
0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed: 0
CoreFoundation 0x1812e01ec __NSI0 + 748 1 CoreFoundation 0x181333ad4
-[NSInvocation getArgument:atIndex:] + 148 2 Foundation 0x182b4f0dc _NSGetValueWithMethod + 220 3 Foundation 0x182b0ab2c -[NSObject(NSKeyValueCoding) valueForKey:] + 320 4 AccessibilityUtilities 0x196f8787c
__57-[NSObject(UIAccessibilitySafeCategory) safeValueForKey:]_block_invoke + 40 5 AccessibilityUtilities
0x196f87640 -[NSObject(UIAccessibilitySafeCategory)
_accessibilityPerformSafeValueKeyBlock:withKey:onClass:] + 96 6 AccessibilityUtilities 0x196f879a4
-[NSObject(UIAccessibilitySafeCategory) safeValueForKey:] + 240 7 UIKit 0x1f2042e38 -[UIViewControllerAccessibility
_accessibilityLoadAccessibilityInformation] + 144 8 UIAccessibility 0x198c430e0 -[UIAccessibilityInformationLoader
_loadAccessibilityInformationOnMainThread:] + 828 9 Foundation 0x182b15780 __NSFireTimer + 104 10 CoreFoundation 0x18136e318
[CFRUN IS_CALLING_OUT_TO A_TIMER_CALLBACK_FUNCTION] + 32 11
CoreFoundation 0x1812f2cf0 __CFRunLoopDoTimer + 1076 12
CoreFoundation 0x1812ed4ec __CFRunLoopDoTimers + 328 13
CoreFoundation 0x1812cbd08 __CFRunLoopRun + 1944 14 CoreFoundation
0x1812df468 CFRunLoopRunSpecific + 600 15 GraphicsServices
0x19ce6a38c GSEventRunModal + 164 16 UIKitCore 0x183c81088
-[UIApplication _run] + 1100 17 UIKitCore 0x1839ff958 UIApplicationMain + 2092 18 AppName 0x10060fed0 main + 352 19 dyld
0x105151aa4 start + 520 .......

答:
问题在avoidCrash中，
[AvoidCrash makeAllEffective];改成[AvoidCrash becomeEffective];不再全局捕获

发现崩溃在avoidCrashMethodSignatureForSelector:
这个方法里转发底层方法_navigationControllerContentInsetAdjustment时候崩溃

Title: ios15,WKWebView,UITextField crash


问:
Is there a way to check for a gitlab merge request approval status and then trigger the next stage in CI
I have a stage1 where it creates a merge request then after the merge request is approved by 3 approvers I manually trigger the stage2.
But, I want to find a way where I can check the merge request approval status created in stage1 and trigger the stage2 job automatically.</p>

答:
In order to achieve this we will use the Gitlab API and the jq package.
Firstly, let's define the jobs.

job_that_creates_mr is the job that creates the merge request and has to wait for 3 approvers before triggering the job_that_triggers_automatically_when_mr_approved

In job_that_creates_mr, I assume that you use the gitlab API for it and specifically https://docs.gitlab.com/ee/api/merge_requests.html#create-mr

```<code>POST /projects/:id/merge_requests
</code>```

In order to proceed we will need the merge request id, so adjust the way you create the mr, an example would be:

```<code>MERGE_REQUEST_IID=$(curl -XPOST -s --header "PRIVATE-TOKEN: <access_token>" "https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/merge_requests" --form "source_branch=<source_branch>" --form "target_branch=<target_branch>" --form "title=<mr_title>"  | jq '.iid')
</code>```

By piping the result to jq we get the merge request id

Next we need to the number of current approvers for the mr with iid that we found previously, to get this we will use https://docs.gitlab.com/ee/api/merge_request_approvals.html#merge-request-level-mr-approvals

```<code>GET /projects/:id/merge_requests/:merge_request_iid/approvals
</code>```

An example command would be:

```<code>NUMBER_OF_APPROVERS=$(curl -s --header "PRIVATE-TOKEN: <access_token>" https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/merge_requests/$MERGE_REQUEST_IID/approvals  | jq '.approved_by | length')
</code>```

Now a template gitlab-ci.yml would be:

```<code>stages:
  - run_after_approval
  - create_mr

job_that_triggers_automatically_when_mr_approved:
  stage: run_after_approval
  script:
    - echo 'I run automatically, even though it says manual'
  when: manual

job_that_creates_mr:
  stage: create_mr
  script:
    - apk add curl jq
    - |
      MERGE_REQUEST_IID=$(curl -XPOST -s --header "PRIVATE-TOKEN: <access_token>" "https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/merge_requests" --form "source_branch=<source_branch>" --form "target_branch=<target_branch>" --form "title=<mr_title>"  | jq '.iid')
      NUMBER_OF_APPROVERS=0
      while [[ $NUMBER_OF_APPROVERS -lt 3 ]]
      do
        NUMBER_OF_APPROVERS=$(curl -s --header "PRIVATE-TOKEN: <access_token" https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/merge_requests/$MERGE_REQUEST_IID/approvals  | jq '.approved_by | length')
        sleep 60
      done
      JOB_ID=$(curl -s --header "PRIVATE-TOKEN: <access_token>" "https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/pipelines/$CI_PIPELINE_ID/jobs" | jq '.[] | select(.name=="job_that_triggers_automatically_when_mr_approved") | .id')
      curl -XPOST --header "PRIVATE-TOKEN: <access_token" "https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/jobs/$JOB_ID/play"
</code>```

Note: In this example change job_that_triggers_automatically_when_mr_approved, with your job name

The idea is that you have the ordering swapped so the job_that_triggers_automatically_when_mr_approved is registered first in the pipeline but as a manual job.

Then the job that create the merge request waits until the number of approvers is 3, and then plays the job_that_triggers_automatically_when_mr_approved.

Body:
In order to achieve this we will use the Gitlab API and the jq package.
Firstly, let's define the jobs.

job_that_creates_mr is the job that creates the merge request and has to wait for 3 approvers before triggering the job_that_triggers_automatically_when_mr_approved

In job_that_creates_mr, I assume that you use the gitlab API for it and specifically https://docs.gitlab.com/ee/api/merge_requests.html#create-mr

POST /projects/:id/merge_requests

In order to proceed we will need the merge request id, so adjust the way you create the mr, an example would be:

MERGE_REQUEST_IID=$(curl -XPOST -s --header "PRIVATE-TOKEN: <access_token>" "https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/merge_requests" --form "source_branch=<source_branch>" --form "target_branch=<target_branch>" --form "title=<mr_title>"  | jq '.iid')

By piping the result to jq we get the merge request id

Next we need to the number of current approvers for the mr with iid that we found previously, to get this we will use https://docs.gitlab.com/ee/api/merge_request_approvals.html#merge-request-level-mr-approvals

GET /projects/:id/merge_requests/:merge_request_iid/approvals

An example command would be:

NUMBER_OF_APPROVERS=$(curl -s --header "PRIVATE-TOKEN: <access_token>" https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/merge_requests/$MERGE_REQUEST_IID/approvals  | jq '.approved_by | length')

Now a template gitlab-ci.yml would be:

stages:
  - run_after_approval
  - create_mr

job_that_triggers_automatically_when_mr_approved:
  stage: run_after_approval
  script:
    - echo 'I run automatically, even though it says manual'
  when: manual

job_that_creates_mr:
  stage: create_mr
  script:
    - apk add curl jq
    - |
      MERGE_REQUEST_IID=$(curl -XPOST -s --header "PRIVATE-TOKEN: <access_token>" "https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/merge_requests" --form "source_branch=<source_branch>" --form "target_branch=<target_branch>" --form "title=<mr_title>"  | jq '.iid')
      NUMBER_OF_APPROVERS=0
      while [[ $NUMBER_OF_APPROVERS -lt 3 ]]
      do
        NUMBER_OF_APPROVERS=$(curl -s --header "PRIVATE-TOKEN: <access_token" https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/merge_requests/$MERGE_REQUEST_IID/approvals  | jq '.approved_by | length')
        sleep 60
      done
      JOB_ID=$(curl -s --header "PRIVATE-TOKEN: <access_token>" "https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/pipelines/$CI_PIPELINE_ID/jobs" | jq '.[] | select(.name=="job_that_triggers_automatically_when_mr_approved") | .id')
      curl -XPOST --header "PRIVATE-TOKEN: <access_token" "https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/jobs/$JOB_ID/play"

Note: In this example change job_that_triggers_automatically_when_mr_approved, with your job name

The idea is that you have the ordering swapped so the job_that_triggers_automatically_when_mr_approved is registered first in the pipeline but as a manual job.

Then the job that create the merge request waits until the number of approvers is 3, and then plays the job_that_triggers_automatically_when_mr_approved.


问:
JInternalFrame acts weird when windows theme changed?
This is my sample code. I am trying to embed a JInternalFrame without titlebar display into a JFrame.

```<code>import javax.swing.*;
import javax.swing.plaf.basic.BasicInternalFrameUI;

class A{

public void doThis(){
    JFrame fr = new JFrame();
    fr.setSize(300,300);
    JInternalFrame f = new JInternalFrame();
    f.setSize(200,200);
    BasicInternalFrameUI ui = (BasicInternalFrameUI) f.getUI();
    ui.setNorthPane(null);
    f.setVisible(true);
    fr.add(f);
    fr.setVisible(true);
    }
}

class MainA{

 public static void main(String a[]){
    A obj = new A();
    obj.doThis();
 }
}
</code>```

The code works fine and displays a JInternalFrame within a JFrame without titlebar as per the requirement as shown below.

I still have this UI running and at the same time when I try to change my XP theme (via Properties>>Appearance>>Theme), the UI automatically repaints itself to show the JInternalFrame with a titlebar again as shown below.

I just can't understand this bizarre behavior. I have no clue if this is an issue with Java Swing or if it is something related to the OS. Please help me with this!

Why is the UI repainting upon theme change with an enabled titlebar when I explicitly code for the titleBar to be set as null?

PS: OS used is Windows XP and I am not sure if the same behavior is observed in Linux or other versions of Windows

答:
'do' is a keyword in Java, so that code does not compile for me.  This code does.

```<code>import javax.swing.*;
import javax.swing.plaf.basic.BasicInternalFrameUI;

class A{

    public void doIt(){
        JFrame fr = new JFrame();
        fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fr.setSize(300,300);
        JInternalFrame f = new JInternalFrame();
        f.setSize(200,200);
        fr.add(f);
        BasicInternalFrameUI ui = (BasicInternalFrameUI) f.getUI();
        ui.setNorthPane(null);
        f.setVisible(true);
        fr.setVisible(true);
    }

 public static void main(String a[]){
    A obj = new A();
    obj.doIt();
 }
}
</code>```

Some notes/questions:

Swing GUIs should be constructed & altered on the EDT.

Why does the code add a JInternalFrame directly to anything other than a JDesktopPane?

There are slight issues with sizing of the JInternalFrame when changing themes.  I suspect it has to do with the lack of validate()/pack() in the code.  Since that was not the question, I could not be bothered investigating it further.

Results

I got a 'null result' here using Windows 7.  The title bar of the JInternalFrame did not re-appear at any time when changing through (in order):

Forbidden Planet (a custom, simple theme)

Windows 7 (Aero)

Architecture (Aero)

Windows 7 Basic (Basic & High Contrast)

Windows Classic (Basic & High Contrast)

Forbidden Planet

Body:
This is my sample code. I am trying to embed a JInternalFrame without titlebar display into a JFrame.

import javax.swing.*;
import javax.swing.plaf.basic.BasicInternalFrameUI;

class A{

public void doThis(){
    JFrame fr = new JFrame();
    fr.setSize(300,300);
    JInternalFrame f = new JInternalFrame();
    f.setSize(200,200);
    BasicInternalFrameUI ui = (BasicInternalFrameUI) f.getUI();
    ui.setNorthPane(null);
    f.setVisible(true);
    fr.add(f);
    fr.setVisible(true);
    }
}

class MainA{

 public static void main(String a[]){
    A obj = new A();
    obj.doThis();
 }
}

The code works fine and displays a JInternalFrame within a JFrame without titlebar as per the requirement as shown below.

I still have this UI running and at the same time when I try to change my XP theme (via Properties>>Appearance>>Theme), the UI automatically repaints itself to show the JInternalFrame with a titlebar again as shown below.

I just can't understand this bizarre behavior. I have no clue if this is an issue with Java Swing or if it is something related to the OS. Please help me with this!

Why is the UI repainting upon theme change with an enabled titlebar when I explicitly code for the titleBar to be set as null?

PS: OS used is Windows XP and I am not sure if the same behavior is observed in Linux or other versions of Windows

Body:
'do' is a keyword in Java, so that code does not compile for me.  This code does.

import javax.swing.*;
import javax.swing.plaf.basic.BasicInternalFrameUI;

class A{

    public void doIt(){
        JFrame fr = new JFrame();
        fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fr.setSize(300,300);
        JInternalFrame f = new JInternalFrame();
        f.setSize(200,200);
        fr.add(f);
        BasicInternalFrameUI ui = (BasicInternalFrameUI) f.getUI();
        ui.setNorthPane(null);
        f.setVisible(true);
        fr.setVisible(true);
    }

 public static void main(String a[]){
    A obj = new A();
    obj.doIt();
 }
}

Some notes/questions:

Swing GUIs should be constructed & altered on the EDT.

Why does the code add a JInternalFrame directly to anything other than a JDesktopPane?

There are slight issues with sizing of the JInternalFrame when changing themes.  I suspect it has to do with the lack of validate()/pack() in the code.  Since that was not the question, I could not be bothered investigating it further.

Results

I got a 'null result' here using Windows 7.  The title bar of the JInternalFrame did not re-appear at any time when changing through (in order):

Forbidden Planet (a custom, simple theme)

Windows 7 (Aero)

Architecture (Aero)

Windows 7 Basic (Basic & High Contrast)

Windows Classic (Basic & High Contrast)

Forbidden Planet