问:
How to access symbols in __init__.py from __main__.py?
I have a module - let's call it foo - and I want to make it usable via a python -m foo call. My program look like this:

```<code>my_project
├──  foo
│   └── __init__.py
└── my_program.py
</code>```

In __init__.py I have some code which I run when calling python -m foo:

```<code>def bar(name):
    print(name)

# -- code used to 'run' the module
def main(name):
    bar("fritz")

if __name__ == "__main__":
    main()
</code>```

Since I have a fair amount of execution code in __init__.py now (argparse stuff and some logic) I want to separate it into a __main__.py:

```<code>my_project
├──  foo
│   ├── __init__.py
│   └── __main__.py
└── my_program.py
</code>```

Despite that looks very simple to me I didn't manage to import stuff located in __init__.py from __main__.py yet.

I know - if foo is located in site-packages or accessible via PYTHONPATH I can just import foo..

But in case I want to execute __main__.py directly (e.g. from some IDE) with foo located anywhere (i.e. not a folder where Python looks for packages) - is there a way to import foo (__init__.py from the same directory)?

I tried import . and import foo - but both approaches fail (because they just mean something else of course)

What I can do - at least to explain my goal - is something like this:

```<code>sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
import foo
</code>```

Works, but is ugly and a bit dangerous since I don't even know if I really import foo from the same directory..

答:
You can manually set the module import state as if __main__.py were executed with -m:

```<code># foo/__main__.py
import os
import sys
if __package__ is None and __name__ == "__main__":  # executed without -m
   # set special attributes as if part of the package
   __file__ = os.path.abspath(__file__)
   __package__ = os.path.basename(os.path.dirname(__file__))
   # replace import path for __main__ with path for package
   main_path = os.path.dirname(__file__)
   try:
       index = sys.path.index(dir_path)
       if index != 0 or index != 1:
           raise ValueError('expected script directory after current directory or matching it')
   except ValueError:
       raise RuntimeError('sys.path does not include script directory as expected')
   else:
       sys.path[index] = main_path
# import regularly
from . import bar
</code>```

This exploits that python3 path/to/foo/__main__.py executes __main__ as a standalone script: __package__ is None and the __name__ does not include the package either. The search path in this case is <current directory>, <__main__ directory>, ..., though it gets collapsed if the two are the same: the index is either 0 or 1.

As with all trickery on internals, there is some transient state where invariants are violated. Do not perform any imports before the module is patched!

Body:
I have a module - let's call it foo - and I want to make it usable via a python -m foo call. My program look like this:

my_project
├──  foo
│   └── __init__.py
└── my_program.py

In __init__.py I have some code which I run when calling python -m foo:

def bar(name):
    print(name)

# -- code used to 'run' the module
def main(name):
    bar("fritz")

if __name__ == "__main__":
    main()

Since I have a fair amount of execution code in __init__.py now (argparse stuff and some logic) I want to separate it into a __main__.py:

my_project
├──  foo
│   ├── __init__.py
│   └── __main__.py
└── my_program.py

Despite that looks very simple to me I didn't manage to import stuff located in __init__.py from __main__.py yet.

I know - if foo is located in site-packages or accessible via PYTHONPATH I can just import foo..

But in case I want to execute __main__.py directly (e.g. from some IDE) with foo located anywhere (i.e. not a folder where Python looks for packages) - is there a way to import foo (__init__.py from the same directory)?

I tried import . and import foo - but both approaches fail (because they just mean something else of course)

What I can do - at least to explain my goal - is something like this:

sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
import foo

Works, but is ugly and a bit dangerous since I don't even know if I really import foo from the same directory..

Body:
You can manually set the module import state as if __main__.py were executed with -m:

# foo/__main__.py
import os
import sys
if __package__ is None and __name__ == "__main__":  # executed without -m
   # set special attributes as if part of the package
   __file__ = os.path.abspath(__file__)
   __package__ = os.path.basename(os.path.dirname(__file__))
   # replace import path for __main__ with path for package
   main_path = os.path.dirname(__file__)
   try:
       index = sys.path.index(dir_path)
       if index != 0 or index != 1:
           raise ValueError('expected script directory after current directory or matching it')
   except ValueError:
       raise RuntimeError('sys.path does not include script directory as expected')
   else:
       sys.path[index] = main_path
# import regularly
from . import bar

This exploits that python3 path/to/foo/__main__.py executes __main__ as a standalone script: __package__ is None and the __name__ does not include the package either. The search path in this case is <current directory>, <__main__ directory>, ..., though it gets collapsed if the two are the same: the index is either 0 or 1.

As with all trickery on internals, there is some transient state where invariants are violated. Do not perform any imports before the module is patched!


来源: stackexchange

问:
Convert date to specific format in javascript?
Hi i want to convert the current date to a format as follows in javascript:
Apr 12, 2011 06:42:03.

Any suggestions?????

答: This small library duplicates the strftime() functionality available in other languages in JavaScript.

ContentLicense: CC BY-SA 3.0


问:
How to lazy load html div tags using intersection-observer?
Is it possible to lazy-load the entire div-tag using Intersection Observer API?

I have lazy loaded images using the intersection observer api approach. Not sure how to do it for html elements.

答:
Yes, you can lazy load content into divs. The example below simply uses html() to populate the div with a random string on intersect. If the content you want is a separate html page, you could use load() instead.

function lazyDivs() {
  let lis = [].slice.call(document.querySelectorAll("div.lazy")),
    items = ["Aruba", "Jamaica", "Bermuda", "Bahama", "Key Largo", "Montego"];

  if (!lis.length) {
    //do nothing
  } else if ("IntersectionObserver" in window) {
    let o = new IntersectionObserver(function(es, obs) {
      es.forEach(function(e) {
        if (e.isIntersecting) {
          let li = $(e.target);
          li.html(items[Math.floor(Math.random() * items.length)]);
          //li.load('/path/to/html/fragment'); //option to load content from a separate page
          li.removeClass("lazy");
          o.unobserve(e.target);
        }
      });
    });
    lis.forEach(function(li) {
      o.observe(li);
    });
  } else {
    lis.forEach(function(li) {
      let l = $(li);
      l.html(items[Math.floor(Math.random() * items.length)]);
      //l.load('/path/to/html/fragment'); //option to load content from a separate page
      l.removeClass("lazy");
    });
  }
}

$(document).ready(function() {
  lazyDivs();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  border: 1px solid blue;
  width: 100px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 10px auto;
}</code>```

```

ContentLicense: CC BY-SA 4.0

Body:
Yes, you can lazy load content into divs. The example below simply uses html() to populate the div with a random string on intersect. If the content you want is a separate html page, you could use load() instead.

function lazyDivs() {
  let lis = [].slice.call(document.querySelectorAll("div.lazy")),
    items = ["Aruba", "Jamaica", "Bermuda", "Bahama", "Key Largo", "Montego"];

  if (!lis.length) {
    //do nothing
  } else if ("IntersectionObserver" in window) {
    let o = new IntersectionObserver(function(es, obs) {
      es.forEach(function(e) {
        if (e.isIntersecting) {
          let li = $(e.target);
          li.html(items[Math.floor(Math.random() * items.length)]);
          //li.load('/path/to/html/fragment'); //option to load content from a separate page
          li.removeClass("lazy");
          o.unobserve(e.target);
        }
      });
    });
    lis.forEach(function(li) {
      o.observe(li);
    });
  } else {
    lis.forEach(function(li) {
      let l = $(li);
      l.html(items[Math.floor(Math.random() * items.length)]);
      //l.load('/path/to/html/fragment'); //option to load content from a separate page
      l.removeClass("lazy");
    });
  }
}

$(document).ready(function() {
  lazyDivs();
});

div {
  border: 1px solid blue;
  width: 100px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 10px auto;
}

<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
  <div class="lazy"></div>
  <div class="lazy"></div>
  <div class="lazy"></div>
  <div class="lazy"></div>
  <div class="lazy"></div>
  <div class="lazy"></div>
  <div class="lazy"></div>
  <div class="lazy"></div>
  <div class="lazy"></div>
</body>

</html>


问:
Some strange phenomena in my use of np.array() to creat a N*M array
I use the for Statement and some api supported by pandas to load some files, I created a list of temporary data and finally created an array with the list data, This array can be created as I typed a few files at a time, but when I import multiple files, I create a strange array. Ensure that all files are the same number of columns and rows. What should I do?

Py3.6, the latest pandas

when i load few files a times

import numpy as np
dirList=os.listdir(r'C:\Users\Administrator\Desktop\New folder\SecData\renzaorou\sec20190527')
priceList=[]
for i in dirList[:3]:  # few files
for i in dirList: # all files
    print(i)
    df=pd.read_excel('C:\\Users\\Administrator\\Desktop\\New folder\\SecData\\renzaorou\\sec20190527\\'+i)
#     row_price = df['price'].tolist()
#     print(df)
#     break
    priceList.append(df['price'].tolist())

np_price=np.array(priceList)
```

<p>the expected output when i load few files</p>

```array([[ 0.  ,  0.  ,  0.  , ...,  6.32,  6.32,  6.32],
       [ 0.  ,  0.  ,  0.  , ...,  3.45,  3.45,  3.45],
       [ 0.  ,  0.  ,  0.  , ..., 11.51, 11.51, 11.51]])
```

<p>then when i load all files</p>

```array([list([0.0, 0.0, 0.0, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.1.........
```

i expect the Normal output when i load all files

答:
Seems like you just need to append numpy arrays to your list. Try that:

```<code>import numpy as np
dirList=os.listdir(r'C:\Users\Administrator\Desktop\New folder\SecData\renzaorou\sec20190527')
priceList=[]
for i in dirList: # all files
    print(i)
    df=pd.read_excel('C:\\Users\\Administrator\\Desktop\\New folder\\SecData\\renzaorou\\sec20190527\\'+i)
    priceList.append(df['price'].values)

np_price=np.array(priceList)

</code>```

In case the price column is not numeric, just replace

```<code>priceList.append(df['price'].values)
</code>```

with

```<code>priceList.append(pd.to_numeric(df['price']).values)
</code>```

Body:
I use the for Statement and some api supported by pandas to load some files, I created a list of temporary data and finally created an array with the list data, This array can be created as I typed a few files at a time, but when I import multiple files, I create a strange array. Ensure that all files are the same number of columns and rows. What should I do?

Py3.6, the latest pandas

when i load few files a times

import numpy as np
dirList=os.listdir(r'C:\Users\Administrator\Desktop\New folder\SecData\renzaorou\sec20190527')
priceList=[]
for i in dirList[:3]:  # few files
for i in dirList: # all files
    print(i)
    df=pd.read_excel('C:\\Users\\Administrator\\Desktop\\New folder\\SecData\\renzaorou\\sec20190527\\'+i)
#     row_price = df['price'].tolist()
#     print(df)
#     break
    priceList.append(df['price'].tolist())

np_price=np.array(priceList)

the expected output when i load few files

array([[ 0.  ,  0.  ,  0.  , ...,  6.32,  6.32,  6.32],
       [ 0.  ,  0.  ,  0.  , ...,  3.45,  3.45,  3.45],
       [ 0.  ,  0.  ,  0.  , ..., 11.51, 11.51, 11.51]])

then when i load all files

array([list([0.0, 0.0, 0.0, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.19, 6.1.........

i expect the Normal output when i load all files

Body:
Seems like you just need to append numpy arrays to your list. Try that:

import numpy as np
dirList=os.listdir(r'C:\Users\Administrator\Desktop\New folder\SecData\renzaorou\sec20190527')
priceList=[]
for i in dirList: # all files
    print(i)
    df=pd.read_excel('C:\\Users\\Administrator\\Desktop\\New folder\\SecData\\renzaorou\\sec20190527\\'+i)
    priceList.append(df['price'].values)

np_price=np.array(priceList)

In case the price column is not numeric, just replace

priceList.append(df['price'].values)

with

priceList.append(pd.to_numeric(df['price']).values)


Title: How to fix SVG path masking problem when too many parts of path are cut off when a mask is applied

Body:
I have a "Source," a "Target," and a "Spotlight" pointing from the Source to the Target.  The Spotlight is a triangular mask over top of a very, very fat line pointing from Source to Target.

In my real project, I have many sources, targets, and spotlights, but I have simplified the problem to one movable source pointing at one static target, to make it easier to ask for help.

function svg(whichone, x, y) {
    let svgid = '#svg' + whichone,
         // Sorry, no getting around pasting this massive thing...
         blobd = "M489.6108513752572,207.11284015473436L489.4560294659143,206.9252152620039C489.30120755657146,206.73759036927336,488.99156373788566,206.36234058381243,488.60876325021906,205.58436508858713C488.2259627625524,204.8063895933618,487.77000560590477,203.6256883883722,487.53814428083814,202.43576304448177C487.30628295577145,201.24583770059135,487.2985174622857,200.0466882178002,487.4753050845048,198.83780557999933C487.6520927067238,197.62892294219844,488.01343344464766,196.4103071493879,488.4001166790572,195.42843725138627C488.7867999134667,194.4465673533846,489.19882564436193,193.70144335019185,489.5453871410477,193.08186110615307C489.8919486377334,192.46227886211432,490.1730459002095,191.96823837722957,490.7544062595619,191.09078512981716C491.3357666189143,190.21333188240473,492.2173900751429,188.95246587246461,492.8629693907238,188.02079535449502C493.5085487063048,187.08912483652543,493.91808388123815,186.4866498105263,494.3375744423906,185.84475101145395C494.7570650035429,185.20285221238169,495.1865109509143,184.52152964023617,495.6640036014667,183.5268463021932C496.14149625201907,182.5321629641502,496.66703560575235,181.22411886020973,496.99924042579045,179.9032473462372C497.33144524582855,178.5823758322647,497.47031553217147,177.24867690826008,497.40718583283814,175.90139490796335C497.3440561335048,174.55411290766668,497.0789264484952,173.19324783107797,496.63195568902864,171.81798706991256C496.18498492956195,170.4427263087472,495.5561730956381,169.05306986300525,495.141810144419,168.19565798406748C494.7274471932,167.33824610512968,494.52753312468576,167.01307879299608,494.0608920729048,166.30297918050618C493.5942510211239,165.5928795680163,492.8608829860762,164.49784765517012,492.07475503925724,163.27798753005956C491.28862709243816,162.05812740494903,490.44973923384765,160.7134390675741,489.9960870379429,159.9871222682472C489.5424348420381,159.26080546892032,489.47401830881904,159.1528602076415,489.14064121819996,158.3553297160253C488.80726412758094,157.55779922440908,488.20892647956185,156.07068350245552,487.85584660613335,154.56521566185057C487.50276673270474,153.05974782124562,487.3949446338667,151.53592786198928,487.56689027001903,149.99254700962464C487.73883590617146,148.44916615726,488.19054927731423,146.88622441178703,488.5778374173524,145.8545335814745C488.9651255573904,144.82284275116197,489.28798846632384,144.3224028360099,489.91628471140956,143.52005249962178C490.5445809564953,142.71770216323367,491.4783105377333,141.6134414056095,492.26443848455233,140.80502784793575C493.0505664313714,139.996614290262,493.6890927437715,139.48404793253863,494.79448384679046,138.8539183938318C495.8998749498096,138.22378885512498,497.4721308434476,137.4760961354347,499.04438673280947,136.95355273301087C500.6166426221714,136.43100933058705,502.1888985072571,136.13361524542967,503.761154396619,135.9767626493178C505.33341028598096,135.81991005320592,506.905666179619,135.80359894613957,508.4779220732571,135.82025242706987C510.0501779668952,135.83690590800018,511.62243386053325,135.88652397692712,512.9165219815047,135.8488339118953C514.2106101024762,135.81114384686342,515.226530450781,135.68614564787276,516.0126583976,135.57603974211614C516.7987863444191,135.46593383635948,517.3551218897524,135.37072022383688,518.4194176092382,134.74471589739423C519.4837133287239,134.1187115709516,521.0559692223619,132.96191653058892,521.9951495139334,132.1609467199919C522.9343298055047,131.35997690939482,523.2404344950095,130.9148323285634,523.8950921373142,129.81803720655554C524.549749779619,128.7212420845477,525.5529603747237,126.9727964213635,526.1860359767905,125.89881105856631C526.8191115788571,124.82482569576912,527.0820521878858,124.42530063335899,527.6871636765428,123.5235081058853C528.2922751652001,122.62171557841161,529.2395575334857,121.21765558587434,530.0256854760286,120.19699114320576C530.8118134185714,119.17632670053716,531.4367869353714,118.53905780773722,532.5354016405905,117.66893805573754C533.6340163458095,116.79881830373785,535.2062722394476,115.6958476925384,536.150326785219,115.08298823169652C537.0943813309905,114.47012877085467,537.4102345288953,114.34738046037042,538.1963624757144,114.0768080262402C538.9824904225334,113.80623559211001,540.2388931182667,113.38783903433387,541.6532224129523,113.09537076587522C543.067551707638,112.80290249741658,544.6398076012762,112.63636251827545,546.2120634949143,112.61224951964807C547.7843193885524,112.58813652102073,549.3565752821904,112.70645050290717,550.9288311758286,112.92661413998724C552.5010870694667,113.14677777706727,554.0733429631047,113.46879106934091,555.1508909731809,113.70210234685634C556.2284389832571,113.93541362437175,556.8112791097715,114.08002288712896,557.5974070523142,114.27653244415835C558.3835349948571,114.47304200118772,559.3729507534285,114.72145185248932,560.6537865795333,114.98809431542468C561.934622405638,115.25473677836,563.5068782992761,115.5396118529291,565.0791341929142,115.72350011679096C566.6513900865524,115.90738838065282,568.2236459801903,115.99028983380744,569.7959018738285,115.99576066255129C571.3681577674666,116.00123149129514,572.9404136611047,115.92927169562824,574.5126695547428,115.84491552500155C576.084925448381,115.76055935437489,577.657181342019,115.66380680878844,579.2294372356572,115.61963727531504C580.8016931292954,115.57546774184162,582.3739490229335,115.58388122048122,583.9462049122953,115.69739747962039C585.5184608016573,115.81091373875957,587.090716686743,116.02953277839832,588.6629725761048,116.40346913433363C590.2352284654668,116.7774054902689,591.8074843591047,117.30665916250075,593.1580542768571,117.90089979171744C594.5086241946095,118.4951404209341,595.6375081364762,119.15436800713559,596.4236360832953,119.63517765343336C597.2097640301143,120.11598729973115,597.6531359818856,120.41837900612519,598.6599038457714,121.32017153359891C599.6666717096572,122.22196406107258,601.2368354856571,123.72315740962593,602.0229634324761,124.47510780086206C602.8090913792952,125.22705819209818,602.8111834969333,125.22976562601711,603.4235604299143,126.10398845760922C604.0359373628953,126.97821128920134,605.258599111219,128.72394951846664,606.0447270580381,129.98760092062153C606.8308550048572,131.25125232277642,607.1804491501715,132.03281689782088,607.5714651789906,132.88139351467927C607.9624812078096,133.7299701315376,608.3949191201333,134.64555879020986,608.8345405064857,135.92802531939654C609.2741618928382,137.2104918485832,609.7209667532192,138.8598362482843,610.0338799418859,140.48685878452295C610.3467931305524,142.1138813207616,610.5258146475048,143.7185819935378,610.6277130765144,145.30240320266242C610.7296115055238,146.88622441178703,610.7543868465906,148.44916615726,610.7476428452096,149.99254700962464C610.7408988438287,151.53592786198928,610.7026355000002,153.05974782124562,610.6528540489714,154.56521566185054C610.6030725979429,156.07068350245552,610.5417730397143,157.55779922440908,610.4552189163047,159.02767388471275C610.3686647928952,160.49754854501643,610.2568561043047,161.9501821436702,610.0782833649904,163.38659855548696C609.8997106256761,164.82301496730372,609.6543738356381,166.24321419228352,609.2882841102381,167.64814202764438C608.9221943848381,169.05306986300525,608.4353517240762,170.4427263087472,608.1221860990572,171.26108246219437C607.8090204740382,172.0794386156415,607.669531884762,172.32649447679375,607.3266711144953,173.0069270150881C606.9838103442286,173.6873595533825,606.4375773929714,174.80116876881894,605.6916086433048,176.0249228385395C604.945639893638,177.24867690826008,603.999935345562,178.5823758322647,603.4869238743714,179.2972881947285C602.9739124031811,180.01220055719236,602.8935940088762,180.1083263581154,602.3918298893333,180.7623484100856C601.8900657697906,181.41637046205582,600.9668559250096,182.62828876507322,600.1807279781905,183.6334068946769C599.3946000313714,184.6385250242806,598.7455539825143,185.43684298047052,598.2307167447619,186.07874177954284C597.7158795070095,186.72064057861516,597.3352510803619,187.2061202205699,596.6658822694952,188.07929304651725C595.9965134586286,188.95246587246461,595.0384042635429,190.21333188240473,594.4425905300477,191.00520592713477C593.8467767965525,191.79707997186483,593.6132585246477,192.11996205138485,593.1173658113333,192.7395442954236C592.621473098019,193.35912653946238,591.8632059432952,194.27540894801987,591.0770779964761,195.17598699268603C590.2909500496572,196.0765650373522,589.4769613107429,196.96143871812706,588.8348638233906,197.57074661453234C588.1927663360383,198.1800545109376,587.7225601002477,198.51379662297327,586.9364321577049,199.0147322866279C586.150304215162,199.51566795028248,585.0482545658668,200.183797165556,583.7111017944002,200.72498480630097C582.3739490229335,201.26617244704593,580.8016931292954,201.68041851326242,579.404376970581,201.94592864702125C578.0070608118667,202.2114387807801,576.7846843880761,202.32821298208134,575.9985564412572,202.40362872259922C575.2124284944381,202.4790444631171,574.8625490245904,202.51310174285163,573.9014813428475,202.59136637554604C572.9404136611047,202.66963100824046,571.3681577674666,202.79210299389476,569.7959018738285,202.9662909502825C568.2236459801903,203.1404789066703,566.6513900865524,203.36638283379156,565.0791341929142,203.64736636341243C563.5068782992761,203.92834989303333,561.934622405638,204.26441302515386,560.3623665162761,204.58867110090966C558.7901106269142,204.91292917666541,557.2178547418285,205.22538219605644,555.6455988524666,205.4318486861571C554.0733429631047,205.63831517625775,552.5010870694667,205.73879513706802,550.9288311758286,205.6732352194946C549.3565752821904,205.60767530192118,547.7843193885524,205.37607550596408,546.2120634949142,204.99567017250527C544.6398076012762,204.61526483904643,543.067551707638,204.08605396808593,541.8027075467809,203.63613921364853C540.5378633859237,203.1862244592111,539.5804309578476,202.81560582129683,538.7943030110285,202.53429690910642C538.0081750642096,202.25298799691606,537.3933515986477,202.06098881044954,536.2998119190476,201.8190199103766C535.2062722394476,201.57705101030365,533.6340163458095,201.2851123966242,532.0617604564476,201.16803717811686C530.4895045670856,201.05096195960957,528.9172486819999,201.10875013627424,527.394423377962,201.35071903634721C525.8715980739238,201.59268793642016,524.3982033509334,202.01883755990136,523.6120754041143,202.24899684074543C522.8259474572952,202.47915612158945,522.7270862866477,202.51332505979641,521.8915277545049,202.98509925704502C521.0559692223619,203.45687345429363,519.4837133287239,204.36625291058394,518.5233307910477,204.9395190439753C517.5629482533715,205.51278517736668,517.2144390716571,205.74993798785906,516.4283111248382,206.25924476774995C515.6421831780191,206.76855154764084,514.4184364660952,207.5500122969302,513.4396472076286,208.1316183333211C512.4608579491619,208.71322436971204,511.7270261441524,209.09497569320445,510.94089819733335,209.4731574987721C510.1547702505143,209.85133930433975,509.31634616188575,210.22595159198264,508.1110061707523,210.60077868520963C506.905666179619,210.9756057784366,505.33341028598096,211.3506476772477,503.7611543966191,211.54178213301086C502.1888985072571,211.73291658877397,500.6166426221714,211.7401436014891,499.04438673280947,211.54061670247242C497.4721308434476,211.34108980345573,495.8998749498096,210.93480899270722,494.79314112725723,210.55636839312265C493.6864073047048,210.1779277935381,493.0451955532382,209.82732740511747,492.2590676064192,209.25804606724674C491.47293965960006,208.68876472937606,490.54189551742866,207.9008024420552,490.07637344634287,207.50682129839478L489.6108513752572,207.11284015473436",
         lightd = 'L499.0443867370857,211.74737061420427L546.2120634949142,112.46982253913428L';

    let svg = d3.select('body')
    .append('svg')
    .attr('id', 'svg' + whichone)
    .attr("width", 700)
    .attr("height", 365);

    let border = svg.append('rect')
    .attr('x', 0)
    .attr('y', 0)
    .attr('width', d3.select(svgid).attr('width'))
    .attr('height', d3.select(svgid).attr('height'))
    .attr('stroke', 'red')
    .attr('fill', 'none');

    let clippy = d3.select(svgid)
    .append('mask')
    .attr('id', 'clippyBoi' + whichone);

    clippy.append('path')
        .attr('class', 'mask-Spotlight-pt1')
        .attr('d', 'M' + x + ',' + y + lightd + x + ',' + y)
        .attr('stroke', 'white')
        .attr('fill', 'white');

    clippy.append('path')
        .attr('class', 'mask-Spotlight-pt2')
        .attr('d', blobd)
        .attr('stroke', 'white')
        .attr('fill', 'white');

    svg.append('path')
        .attr('class', 'Target')
        .attr('d', blobd)
        .attr('stroke', 'blue')
        .attr('fill', 'blue');

    svg.append('path')
        .attr('d', 'M' + x + ',' + y + 'L847.2378366701346,48.24435029368803')
        .attr('stroke-width', 580)
        .attr('stroke-opacity', 0.5)
        .attr('stroke', 'black')
        .attr('mask', 'url(#clippyBoi' + whichone + ')');

    svg.append('circle')
        .attr('class', 'Source')
        .attr('cx', x)
        .attr('cy', y)
        .attr('r', 10)
        .attr('fill', 'blue');

    svg.append('circle')
        .attr('class', 'Spotlight-Endpoint')
        .attr('cx', 499.0443867370857)
        .attr('cy', 211.74737061420427)
        .attr('r', 3)
        .attr('fill', 'red')

    svg.append('circle')
        .attr('class', 'Spotlight-Endpoint')
        .attr('cx', 546.2120634949142)
        .attr('cy', 112.46982253913428)
        .attr('r', 3)
        .attr('fill', 'red')

}

// Now let's make a couple of examples with the Source at different heights.
svg('1', 245.1862903196939, 176.69529478458054);
svg('2', 216.59826693715638, 264.39370748299325);

Here it also in action on CodePen

When the Source starts within the same y-axis range as the Target, as in the first SVG, the mask goes into overdrive and too much of the path is cut off.

But, when the Source starts outside the y-axis range as the Target, as in the second SVG, the mask works just fine.

Does anyone out there know a) what's causing this overdrive problem and b) how to fix it? Please?

Body:
It seems that there is an issue masking strokes.  Changing from a stroke to masking a <rect> seems to work okay though....

svg.append('rect')
    .attr('width', '100%')
    .attr('height', '100%')
    .attr('fill-opacity', 0.5)
    .attr('fill', 'black')
    .attr('mask', 'url(#clippyBoi' + whichone + ')');

function svg(whichone, x, y) {
 let svgid = '#svg' + whichone,
   // Sorry, no getting around pasting this massive thing...
   blobd = "M489.6108513752572,207.11284015473436L489.4560294659143,206.9252152620039C489.30120755657146,206.73759036927336,488.99156373788566,206.36234058381243,488.60876325021906,205.58436508858713C488.2259627625524,204.8063895933618,487.77000560590477,203.6256883883722,487.53814428083814,202.43576304448177C487.30628295577145,201.24583770059135,487.2985174622857,200.0466882178002,487.4753050845048,198.83780557999933C487.6520927067238,197.62892294219844,488.01343344464766,196.4103071493879,488.4001166790572,195.42843725138627C488.7867999134667,194.4465673533846,489.19882564436193,193.70144335019185,489.5453871410477,193.08186110615307C489.8919486377334,192.46227886211432,490.1730459002095,191.96823837722957,490.7544062595619,191.09078512981716C491.3357666189143,190.21333188240473,492.2173900751429,188.95246587246461,492.8629693907238,188.02079535449502C493.5085487063048,187.08912483652543,493.91808388123815,186.4866498105263,494.3375744423906,185.84475101145395C494.7570650035429,185.20285221238169,495.1865109509143,184.52152964023617,495.6640036014667,183.5268463021932C496.14149625201907,182.5321629641502,496.66703560575235,181.22411886020973,496.99924042579045,179.9032473462372C497.33144524582855,178.5823758322647,497.47031553217147,177.24867690826008,497.40718583283814,175.90139490796335C497.3440561335048,174.55411290766668,497.0789264484952,173.19324783107797,496.63195568902864,171.81798706991256C496.18498492956195,170.4427263087472,495.5561730956381,169.05306986300525,495.141810144419,168.19565798406748C494.7274471932,167.33824610512968,494.52753312468576,167.01307879299608,494.0608920729048,166.30297918050618C493.5942510211239,165.5928795680163,492.8608829860762,164.49784765517012,492.07475503925724,163.27798753005956C491.28862709243816,162.05812740494903,490.44973923384765,160.7134390675741,489.9960870379429,159.9871222682472C489.5424348420381,159.26080546892032,489.47401830881904,159.1528602076415,489.14064121819996,158.3553297160253C488.80726412758094,157.55779922440908,488.20892647956185,156.07068350245552,487.85584660613335,154.56521566185057C487.50276673270474,153.05974782124562,487.3949446338667,151.53592786198928,487.56689027001903,149.99254700962464C487.73883590617146,148.44916615726,488.19054927731423,146.88622441178703,488.5778374173524,145.8545335814745C488.9651255573904,144.82284275116197,489.28798846632384,144.3224028360099,489.91628471140956,143.52005249962178C490.5445809564953,142.71770216323367,491.4783105377333,141.6134414056095,492.26443848455233,140.80502784793575C493.0505664313714,139.996614290262,493.6890927437715,139.48404793253863,494.79448384679046,138.8539183938318C495.8998749498096,138.22378885512498,497.4721308434476,137.4760961354347,499.04438673280947,136.95355273301087C500.6166426221714,136.43100933058705,502.1888985072571,136.13361524542967,503.761154396619,135.9767626493178C505.33341028598096,135.81991005320592,506.905666179619,135.80359894613957,508.4779220732571,135.82025242706987C510.0501779668952,135.83690590800018,511.62243386053325,135.88652397692712,512.9165219815047,135.8488339118953C514.2106101024762,135.81114384686342,515.226530450781,135.68614564787276,516.0126583976,135.57603974211614C516.7987863444191,135.46593383635948,517.3551218897524,135.37072022383688,518.4194176092382,134.74471589739423C519.4837133287239,134.1187115709516,521.0559692223619,132.96191653058892,521.9951495139334,132.1609467199919C522.9343298055047,131.35997690939482,523.2404344950095,130.9148323285634,523.8950921373142,129.81803720655554C524.549749779619,128.7212420845477,525.5529603747237,126.9727964213635,526.1860359767905,125.89881105856631C526.8191115788571," +
                         "124.82482569576912,527.0820521878858,124.42530063335899,527.6871636765428,123.5235081058853C528.2922751652001,122.62171557841161,529.2395575334857,121.21765558587434,530.0256854760286,120.19699114320576C530.8118134185714,119.17632670053716,531.4367869353714,118.53905780773722,532.5354016405905,117.66893805573754C533.6340163458095,116.79881830373785,535.2062722394476,115.6958476925384,536.150326785219,115.08298823169652C537.0943813309905,114.47012877085467,537.4102345288953,114.34738046037042,538.1963624757144,114.0768080262402C538.9824904225334,113.80623559211001,540.2388931182667,113.38783903433387,541.6532224129523,113.09537076587522C543.067551707638,112.80290249741658,544.6398076012762,112.63636251827545,546.2120634949143,112.61224951964807C547.7843193885524,112.58813652102073,549.3565752821904,112.70645050290717,550.9288311758286,112.92661413998724C552.5010870694667,113.14677777706727,554.0733429631047,113.46879106934091,555.1508909731809,113.70210234685634C556.2284389832571,113.93541362437175,556.8112791097715,114.08002288712896,557.5974070523142,114.27653244415835C558.3835349948571,114.47304200118772,559.3729507534285,114.72145185248932,560.6537865795333,114.98809431542468C561.934622405638,115.25473677836,563.5068782992761,115.5396118529291,565.0791341929142,115.72350011679096C566.6513900865524,115.90738838065282,568.2236459801903,115.99028983380744,569.7959018738285,115.99576066255129C571.3681577674666,116.00123149129514,572.9404136611047,115.92927169562824,574.5126695547428,115.84491552500155C576.084925448381,115.76055935437489,577.657181342019,115.66380680878844,579.2294372356572,115.61963727531504C580.8016931292954,115.57546774184162,582.3739490229335,115.58388122048122,583.9462049122953,115.69739747962039C585.5184608016573,115.81091373875957,587.090716686743,116.02953277839832,588.6629725761048,116.40346913433363C590.2352284654668,116.7774054902689,591.8074843591047,117.30665916250075,593.1580542768571,117.90089979171744C594.5086241946095,118.4951404209341,595.6375081364762,119.15436800713559,596.4236360832953,119.63517765343336C597.2097640301143,120.11598729973115,597.6531359818856,120.41837900612519,598.6599038457714,121.32017153359891C599.6666717096572,122.22196406107258,601.2368354856571,123.72315740962593,602.0229634324761,124.47510780086206C602.8090913792952,125.22705819209818,602.8111834969333,125.22976562601711,603.4235604299143,126.10398845760922C604.0359373628953,126.97821128920134,605.258599111219,128.72394951846664,606.0447270580381,129.98760092062153C606.8308550048572,131.25125232277642,607.1804491501715,132.03281689782088,607.5714651789906,132.88139351467927C607.9624812078096,133.7299701315376,608.3949191201333,134.64555879020986,608.8345405064857,135.92802531939654C609.2741618928382,137.2104918485832,609.7209667532192,138.8598362482843,610.0338799418859,140.48685878452295C610.3467931305524,142.1138813207616,610.5258146475048,143.7185819935378,610.6277130765144,145.30240320266242C610.7296115055238,146.88622441178703,610.7543868465906,148.44916615726,610.7476428452096,149.99254700962464C610.7408988438287,151.53592786198928,610.7026355000002,153.05974782124562,610.6528540489714,154.56521566185054C610.6030725979429,156.07068350245552,610.5417730397143,157.55779922440908,610.4552189163047,159.02767388471275C610.3686647928952,160.49754854501643,610.2568561043047,161.9501821436702,610.0782833649904," +
                         "163.38659855548696C609.8997106256761,164.82301496730372,609.6543738356381,166.24321419228352,609.2882841102381,167.64814202764438C608.9221943848381,169.05306986300525,608.4353517240762,170.4427263087472,608.1221860990572,171.26108246219437C607.8090204740382,172.0794386156415,607.669531884762,172.32649447679375,607.3266711144953,173.0069270150881C606.9838103442286,173.6873595533825,606.4375773929714,174.80116876881894,605.6916086433048,176.0249228385395C604.945639893638,177.24867690826008,603.999935345562,178.5823758322647,603.4869238743714,179.2972881947285C602.9739124031811,180.01220055719236,602.8935940088762,180.1083263581154,602.3918298893333,180.7623484100856C601.8900657697906,181.41637046205582,600.9668559250096,182.62828876507322,600.1807279781905,183.6334068946769C599.3946000313714,184.6385250242806,598.7455539825143,185.43684298047052,598.2307167447619,186.07874177954284C597.7158795070095,186.72064057861516,597.3352510803619,187.2061202205699,596.6658822694952,188.07929304651725C595.9965134586286,188.95246587246461,595.0384042635429,190.21333188240473,594.4425905300477,191.00520592713477C593.8467767965525,191.79707997186483,593.6132585246477,192.11996205138485,593.1173658113333,192.7395442954236C592.621473098019,193.35912653946238,591.8632059432952,194.27540894801987,591.0770779964761,195.17598699268603C590.2909500496572,196.0765650373522,589.4769613107429,196.96143871812706,588.8348638233906,197.57074661453234C588.1927663360383,198.1800545109376,587.7225601002477,198.51379662297327,586.9364321577049,199.0147322866279C586.150304215162,199.51566795028248,585.0482545658668,200.183797165556,583.7111017944002,200.72498480630097C582.3739490229335,201.26617244704593,580.8016931292954,201.68041851326242,579.404376970581,201.94592864702125C578.0070608118667,202.2114387807801,576.7846843880761,202.32821298208134,575.9985564412572,202.40362872259922C575.2124284944381,202.4790444631171,574.8625490245904,202.51310174285163,573.9014813428475,202.59136637554604C572.9404136611047,202.66963100824046,571.3681577674666,202.79210299389476,569.7959018738285,202.9662909502825C568.2236459801903,203.1404789066703,566.6513900865524,203.36638283379156,565.0791341929142," +
                         "203.64736636341243C563.5068782992761,203.92834989303333,561.934622405638,204.26441302515386,560.3623665162761,204.58867110090966C558.7901106269142,204.91292917666541,557.2178547418285,205.22538219605644,555.6455988524666,205.4318486861571C554.0733429631047,205.63831517625775,552.5010870694667,205.73879513706802,550.9288311758286,205.6732352194946C549.3565752821904,205.60767530192118,547.7843193885524,205.37607550596408,546.2120634949142,204.99567017250527C544.6398076012762,204.61526483904643,543.067551707638,204.08605396808593,541.8027075467809,203.63613921364853C540.5378633859237,203.1862244592111,539.5804309578476,202.81560582129683,538.7943030110285,202.53429690910642C538.0081750642096,202.25298799691606,537.3933515986477,202.06098881044954,536.2998119190476,201.8190199103766C535.2062722394476,201.57705101030365,533.6340163458095,201.2851123966242,532.0617604564476,201.16803717811686C530.4895045670856,201.05096195960957,528.9172486819999,201.10875013627424,527.394423377962,201.35071903634721C525.8715980739238,201.59268793642016,524.3982033509334,202.01883755990136,523.6120754041143,202.24899684074543C522.8259474572952,202.47915612158945,522.7270862866477,202.51332505979641,521.8915277545049,202.98509925704502C521.0559692223619,203.45687345429363,519.4837133287239,204.36625291058394,518.5233307910477,204.9395190439753C517.5629482533715,205.51278517736668,517.2144390716571,205.74993798785906,516.4283111248382,206.25924476774995C515.6421831780191,206.76855154764084,514.4184364660952,207.5500122969302,513.4396472076286,208.1316183333211C512.4608579491619,208.71322436971204,511.7270261441524,209.09497569320445,510.94089819733335,209.4731574987721C510.1547702505143,209.85133930433975,509.31634616188575,210.22595159198264,508.1110061707523,210.60077868520963C506.905666179619,210.9756057784366,505.33341028598096,211.3506476772477,503.7611543966191,211.54178213301086C502.1888985072571,211.73291658877397,500.6166426221714,211.7401436014891,499.04438673280947,211.54061670247242C497.4721308434476,211.34108980345573,495.8998749498096,210.93480899270722,494.79314112725723,210.55636839312265C493.6864073047048,210.1779277935381,493.0451955532382,209.82732740511747,492.2590676064192,209.25804606724674C491.47293965960006,208.68876472937606,490.54189551742866,207.9008024420552,490.07637344634287,207.50682129839478L489.6108513752572,207.11284015473436",
   lightd = 'L499.0443867370857,211.74737061420427L546.2120634949142,112.46982253913428L';

 let svg = d3.select('body')
 .append('svg')
 .attr('id', 'svg' + whichone)
 .attr("width", 700)
 .attr("height", 365);

 let border = svg.append('rect')
 .attr('x', 0)
 .attr('y', 0)
 .attr('width', d3.select(svgid).attr('width'))
 .attr('height', d3.select(svgid).attr('height'))
 .attr('stroke', 'red')
 .attr('fill', 'none');

 let clippy = d3.select(svgid)
 .append('mask')
 .attr('id', 'clippyBoi' + whichone);

 clippy.append('path')
  .attr('class', 'mask-Spotlight-pt1')
  .attr('d', 'M' + x + ',' + y + lightd + x + ',' + y)
  .attr('stroke', 'white')
  .attr('fill', 'white');

 clippy.append('path')
  .attr('class', 'mask-Spotlight-pt2')
  .attr('d', blobd)
  .attr('stroke', 'white')
  .attr('fill', 'white');

 svg.append('path')
  .attr('class', 'Target')
  .attr('d', blobd)
  .attr('stroke', 'blue')
  .attr('fill', 'blue');

 svg.append('rect')
  .attr('width', '100%')
  .attr('height', '100%')
  .attr('fill-opacity', 0.5)
  .attr('fill', 'black')
  .attr('mask', 'url(#clippyBoi' + whichone + ')');

 svg.append('circle')
  .attr('class', 'Source')
  .attr('cx', x)
  .attr('cy', y)
  .attr('r', 10)
  .attr('fill', 'blue');

 svg.append('circle')
  .attr('class', 'Spotlight-Endpoint')
  .attr('cx', 499.0443867370857)
  .attr('cy', 211.74737061420427)
  .attr('r', 3)
  .attr('fill', 'red')

 svg.append('circle')
  .attr('class', 'Spotlight-Endpoint')
  .attr('cx', 546.2120634949142)
  .attr('cy', 112.46982253913428)
  .attr('r', 3)
  .attr('fill', 'red')

}

// Now let's make a couple of examples with the Source at different heights.
svg('1', 245, 156);
svg('2', 245, 264);

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>


问:
How to create user in mongodb with docker-compose
I'm trying to create some kind of script that will create a docker with mongodb and automatically create a user.

I can usually manage my docker images with docker-compose but this time, I don't know how to do it.

Basically, here is what I have to do:

clean/destroy container (docker-compose down)

create a docker container with mongodb and start it (without --auth parameter)

execute a java script containing db.createUser()

stop the container

restart the same container with --auth parameter to allow login with the user created in the javascript

I can't find how to do that properly with docker-compose because when it starts, I have to give it the command --auth. If I do that, I cannot execute my javascript to add my user. MongoDB allows users creation without being logged in if there is no user and if --auth parameter is not provided.

I want to do that automatically, I do not want to manually do some commands. The goal is to have a script that can be executed before each integration tests to start from a clean database.

Here is my project:

integration-test/src/test/resources/scripts/docker-compose.yml

```<code>mongodb:
    container_name: mongo
    image: mongo
  ports:
    - "27017:27017"
  volumes:
    - .:/setup
  command: --auth
</code>```

integration-test/src/test/resources/scripts/docker-init.sh

```<code>docker-compose down
docker-compose up -d
sleep 1
docker exec mongo bash -c "mongo myDatabase /setup/mongodb-setup.js"
</code>```

integration-test/src/test/resources/scripts/mongodb-setup.js

```<code>db.createUser(
{
    user: "myUser",
    pwd: "myPassword",
    roles: [
      { role: "readWrite", db: "myDatabase" }
    ]
})
</code>```

Finding a way to start again a container with a new parameter (in this case --auth) would help but I can't find how to do that (docker start does not take parameters).

Any idea how I should do what I would like ?

If not, I can still delete everything from my database with some Java code or something else but I would like a complete mongodb docker setup created with a script.

答:
Mongo image provides the /docker-entrypoint-initdb.d/ path to deploy custom .js or .sh setup scripts.

Check this post to get more details :
How to create a DB for MongoDB container on start up?

Body:
I'm trying to create some kind of script that will create a docker with mongodb and automatically create a user.

I can usually manage my docker images with docker-compose but this time, I don't know how to do it.

Basically, here is what I have to do:

clean/destroy container (docker-compose down)

create a docker container with mongodb and start it (without --auth parameter)

execute a java script containing db.createUser()

stop the container

restart the same container with --auth parameter to allow login with the user created in the javascript

I can't find how to do that properly with docker-compose because when it starts, I have to give it the command --auth. If I do that, I cannot execute my javascript to add my user. MongoDB allows users creation without being logged in if there is no user and if --auth parameter is not provided.

I want to do that automatically, I do not want to manually do some commands. The goal is to have a script that can be executed before each integration tests to start from a clean database.

Here is my project:

integration-test/src/test/resources/scripts/docker-compose.yml

mongodb:
    container_name: mongo
    image: mongo
  ports:
    - "27017:27017"
  volumes:
    - .:/setup
  command: --auth

integration-test/src/test/resources/scripts/docker-init.sh

docker-compose down
docker-compose up -d
sleep 1
docker exec mongo bash -c "mongo myDatabase /setup/mongodb-setup.js"

integration-test/src/test/resources/scripts/mongodb-setup.js

db.createUser(
{
    user: "myUser",
    pwd: "myPassword",
    roles: [
      { role: "readWrite", db: "myDatabase" }
    ]
})

Finding a way to start again a container with a new parameter (in this case --auth) would help but I can't find how to do that (docker start does not take parameters).

Any idea how I should do what I would like ?

If not, I can still delete everything from my database with some Java code or something else but I would like a complete mongodb docker setup created with a script.


问:
Remove custom postype base slug and prefix permalink with custom taxonomy + post title or just post title
What I want to achieve seems pretty trivial still the solution is yet to be found:

I want to be able to avoid having the slug of the custom postype, (ie.  article) and have in the permalink the custom taxonomy's (ie. site_topic) and its term (ie. blog) or if not set avoid having it and have just the normal title.

What's been tried so far to change the permalink structure:
(it does work in the dashboard swapping links as needed but the pages when visited result in a 404, and yes permalinks have been flushed at each edit).

```<code>function ms_post_types_permalink_edit( $permalink, $post, $leavename ) {

  if ( in_array( $post->post_type, [ 'article', 'template' ] ) || 'publish' == $post->post_status ) {
    $terms = wp_get_object_terms( $post->ID, 'site_topic' );
    if( $terms ){
        return str_replace( '/' . $post->post_type . '/', '/' . $terms[0]->slug . '/', $permalink );
  }
    return str_replace( '/' . $post->post_type . '/', '/', $permalink );
}
 return str_replace( '/' . $post->post_type . '/', '/', $permalink );
}

add_filter( 'post_type_link', 'ms_post_types_permalink_edit', 10, 3 );
</code>```

What we would like to achieve is a working permalink structure that works in both cases for these custom postypes while retaining the normal permalink structure for the rest of the postypes:

domain.com/custom-taxonomy-term/custom-post-title

domain.com/post-title

As a bonus the custom postype has the following in its registration:

```<code>....
'rewrite' => [
  'with_front' => false,
  'slug' => false,
]
....
</code>```

What I also tried in combination with the above is both the following or a combination of them at once:

```<code>function ms_post_types_rewrite_rule() {
    add_rewrite_rule('article/([^/]*)/?$', 'index.php?article=$matches[1]', 'top');
    add_rewrite_rule('article/([^/]*)/([^/]*)?$', 'index.php?site_topic=$matches[1]&article="$matches[2]', 'top');
}

add_action('init', 'ms_post_types_rewrite_rule');
</code>```

and

```<code>function ms_pre_get_posts( $query ) {

  if ( ! $query->is_main_query() ) {
    return;
  }

  if ( 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
    return;
  }
  if ( ! empty( $query->query['name'] ) ) {
    $query->set( 'post_type', [ 'article' ] );
  }
}

add_action( 'pre_get_posts', 'ms_pre_get_posts' );
</code>```

答:
Use below code in your active themes function.php file

```<code>function remove_ra_slug( $post_link, $post, $leavename ) {

        $terms = get_the_terms( $post->ID, 'site_topic' );
        if ( !empty( $terms ) ){
        // get the first term
        $term = array_shift( $terms );

        if ( 'article' != $post->post_type || 'publish' != $post->post_status ) {
            return $post_link;
        }

        $post_link = str_replace( '/' . $post->post_type . '/', '/' . $terms->slug . '/', $post_link );
    }
        return $post_link;
    }
    add_filter( 'post_type_link', 'remove_ra_slug', 10, 3 );
</code>```

Just removing the slug isn't enough. Right now, you'll get a 404 page because WordPress only expects posts and pages to behave this way. You'll also need to add the following:

```<code>function parse_ra_request( $query ) {

    if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
        return;
    }

    if ( ! empty( $query->query['name'] ) ) {
        $query->set( 'post_type', array( 'article' ) );
    }
}
add_action( 'pre_get_posts', 'parse_ra_request' );
</code>```

Tested and works well

Body:
What I want to achieve seems pretty trivial still the solution is yet to be found:

I want to be able to avoid having the slug of the custom postype, (ie.  article) and have in the permalink the custom taxonomy's (ie. site_topic) and its term (ie. blog) or if not set avoid having it and have just the normal title.

What's been tried so far to change the permalink structure:
(it does work in the dashboard swapping links as needed but the pages when visited result in a 404, and yes permalinks have been flushed at each edit).

function ms_post_types_permalink_edit( $permalink, $post, $leavename ) {

  if ( in_array( $post->post_type, [ 'article', 'template' ] ) || 'publish' == $post->post_status ) {
    $terms = wp_get_object_terms( $post->ID, 'site_topic' );
    if( $terms ){
        return str_replace( '/' . $post->post_type . '/', '/' . $terms[0]->slug . '/', $permalink );
  }
    return str_replace( '/' . $post->post_type . '/', '/', $permalink );
}
 return str_replace( '/' . $post->post_type . '/', '/', $permalink );
}

add_filter( 'post_type_link', 'ms_post_types_permalink_edit', 10, 3 );

What we would like to achieve is a working permalink structure that works in both cases for these custom postypes while retaining the normal permalink structure for the rest of the postypes:

domain.com/custom-taxonomy-term/custom-post-title

domain.com/post-title

As a bonus the custom postype has the following in its registration:

....
'rewrite' => [
  'with_front' => false,
  'slug' => false,
]
....

What I also tried in combination with the above is both the following or a combination of them at once:

function ms_post_types_rewrite_rule() {
    add_rewrite_rule('article/([^/]*)/?$', 'index.php?article=$matches[1]', 'top');
    add_rewrite_rule('article/([^/]*)/([^/]*)?$', 'index.php?site_topic=$matches[1]&article="$matches[2]', 'top');
}

add_action('init', 'ms_post_types_rewrite_rule');

and

function ms_pre_get_posts( $query ) {

  if ( ! $query->is_main_query() ) {
    return;
  }

  if ( 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
    return;
  }
  if ( ! empty( $query->query['name'] ) ) {
    $query->set( 'post_type', [ 'article' ] );
  }
}

add_action( 'pre_get_posts', 'ms_pre_get_posts' );

Body:
Use below code in your active themes function.php file

function remove_ra_slug( $post_link, $post, $leavename ) {

        $terms = get_the_terms( $post->ID, 'site_topic' );
        if ( !empty( $terms ) ){
        // get the first term
        $term = array_shift( $terms );

        if ( 'article' != $post->post_type || 'publish' != $post->post_status ) {
            return $post_link;
        }

        $post_link = str_replace( '/' . $post->post_type . '/', '/' . $terms->slug . '/', $post_link );
    }
        return $post_link;
    }
    add_filter( 'post_type_link', 'remove_ra_slug', 10, 3 );

Just removing the slug isn't enough. Right now, you'll get a 404 page because WordPress only expects posts and pages to behave this way. You'll also need to add the following:

function parse_ra_request( $query ) {

    if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
        return;
    }

    if ( ! empty( $query->query['name'] ) ) {
        $query->set( 'post_type', array( 'article' ) );
    }
}
add_action( 'pre_get_posts', 'parse_ra_request' );

Tested and works well


问:
Google Analytics - only track traffic to a folder of the site
I want to track traffic for mysite.com/current-campaign/ and careless about traffic on mysite.com in general.

Is it ok to place the GA tracking code in the files inside the /current-campaign/ folder or does it HAVE TO be in the root of the server for tracking to work?

答:
GA will only track on the pages you actually put the tracking code on, regardless of where the page is located (unless you start messing with things like domain settings or filters etc..).

So IOW yes, it is okay to do that. If you don't have tracking code on mysite.com/somePage.html then it's not gonna track that page (though it might show up as the URL in some reports like referring URL or exit link or whatever, same as any other page you don't track)


问:
Toast in OnPostExecute() once the fragment changes
I have two fragments in my Activity : Fragment_A and Fragment_B.

In Fragment A, I created an AsyncTask (when the user "swipeRefreshes" the screen). In the onPostExecute() of this task, I want to display a Toast :

```<code>private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
    private Exception mLastError = null;

    MakeRequestTask() {
        //Some stuff
    }

    @Override
    protected List<String> doInBackground(Void... params) {
        //Some stuff
    }

    @Override
    protected void onPreExecute() {
        //Some stuff
    }

    @Override
    protected void onPostExecute(List<String> output) {
        swipeRefreshLayout.setRefreshing(false);
        Toast.makeText(getActivity(), "TO_DISPLAY", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onCancelled() {
        swipeRefreshLayout.setRefreshing(false);
        //Some stuff
    }
}
</code>```

If the user changes from Fragment_A to Fragment_B before the AsyncTask finishes, I get a crash:

java.lang.IllegalStateException: Fragment Fragment_A not attached to a context.

I know how to avoid the crash (by adding the condition isAdded()), but I want my Toast to be displayed no matter which Fragment is displayed/alive on top of my Activity.

答:
Or you can just use and interface or an EventBus in the onPostExecute method, and show the Toast inside the activity.

```<code>@Override
    protected void onPostExecute(List<String> output) {
        swipeRefreshLayout.setRefreshing(false);
        activityContractInterface.showToast()
        }
    }
</code>```

And in your Activity:

```<code>@Override
public void showToast(){
     Toast.makeText(getActivity(), "TO_DISPLAY", Toast.LENGTH_SHORT).show();
}
</code>```

Or the EventBus approach:

```<code>@Override
        protected void onPostExecute(List<String> output) {
            swipeRefreshLayout.setRefreshing(false);
            EventBus.getDefault().post(new ShowToastEvent())
//just create an empty class, hope you know what EventBus is
            }
</code>```

And in your activity:

```<code>@Subscribe(threadMode = ThreadMode.Main){
 Toast.makeText(getActivity(), "TO_DISPLAY", Toast.LENGTH_SHORT).show();
}
</code>```

EventBusLibrary

Body:
I have two fragments in my Activity : Fragment_A and Fragment_B.

In Fragment A, I created an AsyncTask (when the user "swipeRefreshes" the screen). In the onPostExecute() of this task, I want to display a Toast :

private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
    private Exception mLastError = null;

    MakeRequestTask() {
        //Some stuff
    }

    @Override
    protected List<String> doInBackground(Void... params) {
        //Some stuff
    }

    @Override
    protected void onPreExecute() {
        //Some stuff
    }

    @Override
    protected void onPostExecute(List<String> output) {
        swipeRefreshLayout.setRefreshing(false);
        Toast.makeText(getActivity(), "TO_DISPLAY", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onCancelled() {
        swipeRefreshLayout.setRefreshing(false);
        //Some stuff
    }
}

If the user changes from Fragment_A to Fragment_B before the AsyncTask finishes, I get a crash:

java.lang.IllegalStateException: Fragment Fragment_A not attached to a context.

I know how to avoid the crash (by adding the condition isAdded()), but I want my Toast to be displayed no matter which Fragment is displayed/alive on top of my Activity.

Body:
Or you can just use and interface or an EventBus in the onPostExecute method, and show the Toast inside the activity.

@Override
    protected void onPostExecute(List<String> output) {
        swipeRefreshLayout.setRefreshing(false);
        activityContractInterface.showToast()
        }
    }

And in your Activity:

@Override
public void showToast(){
     Toast.makeText(getActivity(), "TO_DISPLAY", Toast.LENGTH_SHORT).show();
}

Or the EventBus approach:

@Override
        protected void onPostExecute(List<String> output) {
            swipeRefreshLayout.setRefreshing(false);
            EventBus.getDefault().post(new ShowToastEvent())
//just create an empty class, hope you know what EventBus is
            }

And in your activity:

@Subscribe(threadMode = ThreadMode.Main){
 Toast.makeText(getActivity(), "TO_DISPLAY", Toast.LENGTH_SHORT).show();
}

EventBusLibrary


问:
How to replace www from the url in ruby?
I want to replace www from this url "https://www.cmnetwork.co/courses/3684/redirect"
with newlife.

I know using split we can do this. Is there any standard way of doing this?

Newly generated url should be:
"https://newlife.cmnetwork.co/courses/3684/redirect"

答:
I would argue that if you want to manipulate an URL then you should use a proper URI class and not use methods on the URL string.

```<code>uri = URI('https://www.cmnetwork.co/courses/3684/redirect')
uri.host = 'newlife.cmnetwork.co'

uri.to_s
#=> "https://newlife.cmnetwork.co/courses/3684/redirect"
</code>```

It might feel like an overkill for this very simple example but it is IMO the better practice.

Body:
I would argue that if you want to manipulate an URL then you should use a proper URI class and not use methods on the URL string.

uri = URI('https://www.cmnetwork.co/courses/3684/redirect')
uri.host = 'newlife.cmnetwork.co'

uri.to_s
#=> "https://newlife.cmnetwork.co/courses/3684/redirect"

It might feel like an overkill for this very simple example but it is IMO the better practice.


问:
Why is this regex expression returning 'true'?
I am using this exact regex in a RegularExpressionValidator and it works fine. However this code in c# is returning true. Can you please let me know what I am doing wrong?

I am checking for numbers only regex

```<code>var x = Regex.IsMatch("1234asdf", @"[0-9]+").ToString();
</code>```

答:
Because is finding what you're looking for inside the provided string.
You have tyo use ^ and $ to force the whole string to mathc the regex:

^[0-9]+$

^ matches the beginning, $, the end of the string

Please, look ath the Anchors section of this doc: Regular Expression Language - Quick Reference

BTW, instead of [0-9] you should use \d

Body:
I am using this exact regex in a RegularExpressionValidator and it works fine. However this code in c# is returning true. Can you please let me know what I am doing wrong?

I am checking for numbers only regex

var x = Regex.IsMatch("1234asdf", @"[0-9]+").ToString();


问:
Iphone voice to text & back to voice API
I want in my iphone app , Voice to Text and then back to Voice.

I tried searching on forum and Google and found some APIs like  OpenEars, Vocal Kit and tts , but these are all for English Languages and not for other languages like German , French and Spanish, Chinese, etc.

Is there any Free API for this and I am missing it on Google or there isn't any API for this? Please Help

The existing apps in App Store like Jibbigo and MLD are using such functionality , so what are they using??

ANSWER by Paul Dixon

The Nuance API is free for development but asks to purchase before going live in the APP Store, so it should be accepted that there is no free API ,,, please help guys

答:
what about OpenEars?

Free and allows commercial use.

ContentLicense: CC BY-SA 2.5


问:
how to get multiple column distinct value and either diffrent field has same data in reverse
I have a table with 3 column named msg, sender and receiver. Now i need to get the distinct sender and receiver. but in here if i have sender a and receiver b Or sender b and receiver a, it is showing me both. but i want only last one.

```<code>msg | sender | receiver
hi  | 1      | 5
he  | 2      | 6
jh  | 5      |1

SELECT DSTINCT `sender`, `receiver` from `table`
</code>```

it is giving me this result

```<code>1-5
2-6
5-1
</code>```

but i need

```<code>5-1
2-6
</code>```

is there any sql query that can solve this?

答:
Sure, let's use the fact that thy're integers and always put the smaller one on the first column and the bigger one in the right column

```<code>SELECT DISTINCT
  CASE WHEN sender < receiver THEN sender ELSE receiver END as PartyA,
  CASE WHEN sender < receiver THEN receiver ELSE sender END as PartyB
from `table`
</code>```

It doesnt exactly produce 5-1 (it produces 1-5) but I'm thinking you don't really care, you just want the unique list of people who had a conversation, and 5-1 == 1-5

Body:
I have a table with 3 column named msg, sender and receiver. Now i need to get the distinct sender and receiver. but in here if i have sender a and receiver b Or sender b and receiver a, it is showing me both. but i want only last one.

msg | sender | receiver
hi  | 1      | 5
he  | 2      | 6
jh  | 5      |1

SELECT DSTINCT `sender`, `receiver` from `table`

it is giving me this result

1-5
2-6
5-1

but i need

5-1
2-6

is there any sql query that can solve this?

Body:
Sure, let's use the fact that thy're integers and always put the smaller one on the first column and the bigger one in the right column

SELECT DISTINCT
  CASE WHEN sender < receiver THEN sender ELSE receiver END as PartyA,
  CASE WHEN sender < receiver THEN receiver ELSE sender END as PartyB
from `table`

It doesnt exactly produce 5-1 (it produces 1-5) but I'm thinking you don't really care, you just want the unique list of people who had a conversation, and 5-1 == 1-5


问:
How to add a frontend asset from a git repo/npm project to a rails project
I want to contribute to an open source project written in rails with some frontend web stuff, that depends on an asset, which I have on an external git repository. So I would like to add the asset dependency from the git link and just add my code to the frontend.

I do not know much about rails, especially asset managements, but that the css and js files are all in the manifest files, and come seemingly from some ruby gems, which include the css and js assets then.

So is there a good way to add an asset to my rails manifest file/assets without having it as a ruby gem, just from a git repo?

Thank you so much for help and pardon my rails illiteracy :S

答:
I managed to add just a .gemspec to my npm repo, move my js and css to the vendor/assets folder, all in a dedicated "gemfile branch"

```<code>Gem::Specification.new do |s|
  s.name        = 'asset-name'
  s.version     = '0.0.0'
  s.date        = '2020-05-30'
  s.summary     = "What my package does."
  s.description = ""
  s.files       = [
        "vendor/assets/javascripts/app.min.js",
        "vendor/assets/stylesheets/app.css"
  ]
  s.license       = 'MIT'
end
</code>```

and then added the repo with its branch to the rail projectsGemfile` like this:

gem "asset-name", :git => "git://github.com/user/repo.git", :branch => "ruby-gem"

Body:
I managed to add just a .gemspec to my npm repo, move my js and css to the vendor/assets folder, all in a dedicated "gemfile branch"

Gem::Specification.new do |s|
  s.name        = 'asset-name'
  s.version     = '0.0.0'
  s.date        = '2020-05-30'
  s.summary     = "What my package does."
  s.description = ""
  s.files       = [
        "vendor/assets/javascripts/app.min.js",
        "vendor/assets/stylesheets/app.css"
  ]
  s.license       = 'MIT'
end

and then added the repo with its branch to the rail projectsGemfile` like this:

gem "asset-name", :git => "git://github.com/user/repo.git", :branch => "ruby-gem"


问:
Update MKPF text during save in MB1A tcode
I am working on a requirement to update MKPF-BKTXT during save in MB1A tcode. I found MB_DOCUMENT_BADI, but the methods of the BADI only allows importing parameters and does not allow changing MKPF.

Has anyone in the community worked on similar? How to do this?

答:
You can use BTE event 00001120 to do that and substitute BKTXT. Here is the detailed guide:

https://wiki.scn.sap.com/wiki/display/ERPFI/Example+for+BTE+00001120

Just create Product, register your custom FM as process module and code your substitution.


问:
'SuppressMessage' for a whole namespace
I use underscores for my test methods for a better readability and I want to suppress FxCop errors/warnings for the whole test namespace.

How can I achieve this? I played with GlobalSuppressions.cs but nothing worked:

```<code>[module: System.Diagnostics.CodeAnalysis.SuppressMessage(
    "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores",
    Scope = "namespace", Target = "Company.Product.Tests")]

[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(
    "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores",
    Scope = "namespace", Target = "Company.Product.Tests")]
</code>```

答:
Suppression of a code analysis warning for a namespace and all its descendant symbols is possible since Visual Studio 2019:

```<code>[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(
    "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores",
    Justification = "Test methods require underscores for readability."
    Scope = "namespaceanddescendants", Target = "Company.Product.Tests")]
</code>```

Scope - The target on which the warning is being suppressed. If the target is not specified, it is set to the target of the attribute. Supported scopes include the following:

...

namespaceanddescendants - (New for Visual Studio 2019) This scope suppresses warnings in a namespace and all its descendant symbols. The namespaceanddescendants value is only valid for Roslyn analyzers, and is ignored by binary, FxCop-based static analysis.

Suppress code analysis warnings#SuppressMessage attribute @ MS Docs

Title: 'SuppressMessage' for a whole namespace

Body:
I use underscores for my test methods for a better readability and I want to suppress FxCop errors/warnings for the whole test namespace.

How can I achieve this? I played with GlobalSuppressions.cs but nothing worked:

[module: System.Diagnostics.CodeAnalysis.SuppressMessage(
    "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores",
    Scope = "namespace", Target = "Company.Product.Tests")]

[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(
    "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores",
    Scope = "namespace", Target = "Company.Product.Tests")]

Body:
Suppression of a code analysis warning for a namespace and all its descendant symbols is possible since Visual Studio 2019:

[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(
    "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores",
    Justification = "Test methods require underscores for readability."
    Scope = "namespaceanddescendants", Target = "Company.Product.Tests")]

Scope - The target on which the warning is being suppressed. If the target is not specified, it is set to the target of the attribute. Supported scopes include the following:

...

namespaceanddescendants - (New for Visual Studio 2019) This scope suppresses warnings in a namespace and all its descendant symbols. The namespaceanddescendants value is only valid for Roslyn analyzers, and is ignored by binary, FxCop-based static analysis.

Suppress code analysis warnings#SuppressMessage attribute @ MS Docs


问:
Print vertical data in horizontal way
I have a data which is in vertical form => want to print in horizontal way.

How do I write it to the text file => FILE 2?

DATA I have in FILE 1

```<code>RAM
RAJ
RAHUL
VIRAJ
</code>```

Data should be Written to the FILE 2 in this format

NAME1|NAME2|NAME3|NAME 4

```<code>RAM | RAJ | RAHUL | VIRAJ
</code>```

My code

```<code>awk 'BEGIN{FS=""}{for(i=1;i<=NF;i++)print i,$i}'
</code>```

答:
You can use the tr shell command to replace end of line characters ("\n") with any sequence, such as "|" in your example:

```<code>cat file | tr '\n' '|'
</code>```

Title: Print vertical data in horizontal way

Body:
I have a data which is in vertical form => want to print in horizontal way.

How do I write it to the text file => FILE 2?

DATA I have in FILE 1

RAM
RAJ
RAHUL
VIRAJ

Data should be Written to the FILE 2 in this format

NAME1|NAME2|NAME3|NAME 4

RAM | RAJ | RAHUL | VIRAJ

My code

awk 'BEGIN{FS=""}{for(i=1;i<=NF;i++)print i,$i}'

Body:
You can use the tr shell command to replace end of line characters ("\n") with any sequence, such as "|" in your example:

cat file | tr '\n' '|'


问:
Freeling Python API working on sample, get Import error on other code
I'm trying out Freeling's API for python. The installation and test were ok, they provide a sample.py file that works perfectly (I've played around a little bit with it and it works).

So I was trying to use it on some other python code I have, in a different folder (I'm kind of guessing this is a path issue), but whenever I import freeling (like it shows on the sample.py):

```<code>import freeling

FREELINGDIR = "/usr/local";
DATA = FREELINGDIR+"/share/freeling/";
LANG="es";
freeling.util_init_locale("default");
</code>```

I get this error:

```<code>ModuleNotFoundError: No module named 'freeling'.
</code>```

The sample.py is located on the ~/Freeling-4.0/APIs/Python/ folder, while my other file is located in ~/project/, I dont know if that can be an issue.
Thank you!

答: You need to set PYTHONPATH so python can find the modules if they are not in the same folder.</p>

Body:
I'm trying out Freeling's API for python. The installation and test were ok, they provide a sample.py file that works perfectly (I've played around a little bit with it and it works).

So I was trying to use it on some other python code I have, in a different folder (I'm kind of guessing this is a path issue), but whenever I import freeling (like it shows on the sample.py):

import freeling

FREELINGDIR = "/usr/local";
DATA = FREELINGDIR+"/share/freeling/";
LANG="es";
freeling.util_init_locale("default");

I get this error:

ModuleNotFoundError: No module named 'freeling'.

The sample.py is located on the ~/Freeling-4.0/APIs/Python/ folder, while my other file is located in ~/project/, I dont know if that can be an issue.
Thank you!


问:
Memory error while creating large one hot encoding for lstm
I am trying to build a character level lstm model using keras and for that I need to create one hot encoding for characters to feed in the model. And I have around 1000 characters in each line with around 160,000 lines.

I tried to create a numpy array of zeros and make the corresponding entries 1, but I am geting memory error due to large size of the matrix is there any other way to do this.

答:
Perhaps an easier and more intuitive solution is to add a custom one-hot encoding layer in your Keras model architecture.

```<code>def build_model(self, batch_size, print_summary=False):
    X = Input(shape=(self.sequence_length,), batch_size=batch_size)
    embedding = OneHotEncoding(num_classes=self.vocab_size+1,
                               sequence_length=self.sequence_length)(X)
    encoder = Bidirectional(CuDNNLSTM(units=self.recurrent_units,
                                      return_sequences=True))(embedding)
    ...
</code>```

where we can define the OneHotEncoding layer as follows:

```<code>from tensorflow.keras.layers import Lambda
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Layer # for creating custom layers

class OneHotEncoding(Layer):
     def __init__(self, num_classes=None, sequence_length=None):
         if num_classes is None or sequence_length is None:
             raise ValueError("Can't leave params @num_classes or @sequence_length empty")
         super(OneHotEncoding, self).__init__()
         self.num_classes = num_classes
         self.sequence_length = sequence_length
     def encode(self, inputs):
         return K.one_hot(indices=inputs,
                          num_classes=self.num_classes)
     def call(self, inputs):
         return Lambda(function=self.encode,
                       input_shape=(self.sequence_length,))(inputs)
</code>```

Here we are utilizing the fact that the Keras model is fed the training samples in appropriate batch sizes (with the standard fit function), which in turn doesn't yield a MemoryError.

Body:
Perhaps an easier and more intuitive solution is to add a custom one-hot encoding layer in your Keras model architecture.

def build_model(self, batch_size, print_summary=False):
    X = Input(shape=(self.sequence_length,), batch_size=batch_size)
    embedding = OneHotEncoding(num_classes=self.vocab_size+1,
                               sequence_length=self.sequence_length)(X)
    encoder = Bidirectional(CuDNNLSTM(units=self.recurrent_units,
                                      return_sequences=True))(embedding)
    ...

where we can define the OneHotEncoding layer as follows:

from tensorflow.keras.layers import Lambda
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Layer # for creating custom layers

class OneHotEncoding(Layer):
     def __init__(self, num_classes=None, sequence_length=None):
         if num_classes is None or sequence_length is None:
             raise ValueError("Can't leave params @num_classes or @sequence_length empty")
         super(OneHotEncoding, self).__init__()
         self.num_classes = num_classes
         self.sequence_length = sequence_length
     def encode(self, inputs):
         return K.one_hot(indices=inputs,
                          num_classes=self.num_classes)
     def call(self, inputs):
         return Lambda(function=self.encode,
                       input_shape=(self.sequence_length,))(inputs)

Here we are utilizing the fact that the Keras model is fed the training samples in appropriate batch sizes (with the standard fit function), which in turn doesn't yield a MemoryError.


问:
Kubernetes equivalent of 'docker run -it'
I have one docker image and I am using following command to run it.

```<code>docker run -it -p 1976:1976 --name demo demo.docker.cloud.com/demo/runtime:latest
</code>```

I want to run the same in Kubernetes. This is my current yaml file.

apiVersion: v1
kind: Deployment
metadata:
  name: demo-deployment
  labels:
    app: demo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: demo
  template:
    metadata:
      labels:
        app: demo
    spec:
      containers:
      - name: demo
        image: demo.docker.cloud.com/demo/runtime:latest
        ports:
        - containerPort: 1976
        imagePullPolicy: Never```

This yaml file covers everything except flag "-it". I am not able to find its Kubernetes equivalent. Please help me out with this. Thanks

答:
Looking at the Container definition in the API reference, the equivalent options are stdin: true and tty: true.

(None of the applications I work on have ever needed this; the documentation for stdin: talks about "reads from stdin in the container" and the typical sort of server-type processes you'd run in a Deployment don't read from stdin at all.)

Body:
I have one docker image and I am using following command to run it.

docker run -it -p 1976:1976 --name demo demo.docker.cloud.com/demo/runtime:latest

I want to run the same in Kubernetes. This is my current yaml file.

apiVersion: v1
kind: Deployment
metadata:
  name: demo-deployment
  labels:
    app: demo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: demo
  template:
    metadata:
      labels:
        app: demo
    spec:
      containers:
      - name: demo
        image: demo.docker.cloud.com/demo/runtime:latest
        ports:
        - containerPort: 1976
        imagePullPolicy: Never

This yaml file covers everything except flag "-it". I am not able to find its Kubernetes equivalent. Please help me out with this. Thanks


问:
What are good examples of problems that graphs can solve better than the alternative?
After reading Stevey Yegge's Get That Job At Google article, I found this little quote interesting:

Whenever someone gives you a problem, think graphs. They are the most fundamental and flexible way of representing any kind of a relationship, so it's about a 50–50 shot that any interesting design problem has a graph involved in it. Make absolutely sure you can't think of a way to solve it using graphs before moving on to other solution types. This tip is important!

What are some examples of problems that are best represented and/or solved by graph data structures/algorithms?

One example I can think of: navigation units (ala Garmin, TomTom), that supply road directions from your current location to another, utilize graphs and advanced pathing algorithms.

What are some others?

答:
Basically nearlly all common data structures like trees, lists, queues, etc, can be thought as type of graph, some with different type of constraint.

To my experiences, I have used graph intensively in network flow problems, which is used in lots of areas like telecommunication network routing and  optimisation, workload assignment, matching, supply chain optimisation and public transport planning.

Another interesting area is social network modelling as previous answer mentioned.

There are far more, like integrated circuit optimisation, etc.

OwnerDisplayName: KingNestor


答:
Using sub method of ruby we can replace sub-string.

```<code>url = "https://www.cmnetwork.co/courses/3684/redirect"
url = url.sub('www.','newlife.')
</code>```

Title: How to replace www from the url in ruby?

Body:
I want to replace www from this url "https://www.cmnetwork.co/courses/3684/redirect"
with newlife.

I know using split we can do this. Is there any standard way of doing this?

Newly generated url should be:
"https://newlife.cmnetwork.co/courses/3684/redirect"

Body:
Using sub method of ruby we can replace sub-string.

url = "https://www.cmnetwork.co/courses/3684/redirect"
url = url.sub('www.','newlife.')


问:
Child ControlValueAccessor Component with formgroup - expression has changed after it was checked
on loading of my parent component, i am updating the form of that (parent) component by using patchValue.

on of that form components i my child ControlValueAccessor component that also has a formgroup. therefore, on my writeValue function i am updating the child component regarding the value that passed from the parent component patchValue.

my writeValue function looks like that:

```<code>    writeValue(value: CountryAndCity): void {
    if (value != null && value.country && value.city) {
      this.isDefaultValueDefined = true;
      this.form.patchValue({country: value.country});
      this.form.patchValue({city: value.city});
      **this.cdRef.detectChanges();**
    }
  }
</code>```

As you can see, i had to use detectChanges() as the last line of the above function because without it i am getting the error:

ParentComponent.html:1 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ng-pristine: true'. Current value: 'ng-pristine: false'.

i think i understand why is that. Angular start the check of the parent component, then, start to check the child component but then, on the child component the child component, on the writeValue function changing the parent component form state.

i feel uncomfortable with the use of detectChanges(). is there a way to do something else? is it a must when using parent and child components that each of them has formGroup and the child component is one of the parent formgroup formControl?

答:
Your approach is good and @Tobi's answer is good too!

That said, if you do not want to struggle too much in building nested forms (using sub components)/creating custom control value accessors you should definitely checkout this library: https://github.com/cloudnc/ngx-sub-form

The error you encountered should never happen if you use the library as we handle that case pretty much like Tobi did.

From your point of view it'll just require you to extend a class and not much more! Will also give you type safety, access to nested errors, etc.

I've also replied to a question on how to build complex/nested/sub forms, this might be of interest for you https://stackoverflow.com/a/56375605/2398593

Edit:

If you want to go further, I've just published a blog post to explain a lot of things about forms and ngx-sub-form here https://dev.to/maxime1992/building-scalable-robust-and-type-safe-forms-with-angular-3nf9

Body:
on loading of my parent component, i am updating the form of that (parent) component by using patchValue.

on of that form components i my child ControlValueAccessor component that also has a formgroup. therefore, on my writeValue function i am updating the child component regarding the value that passed from the parent component patchValue.

my writeValue function looks like that:

    writeValue(value: CountryAndCity): void {
    if (value != null && value.country && value.city) {
      this.isDefaultValueDefined = true;
      this.form.patchValue({country: value.country});
      this.form.patchValue({city: value.city});
      **this.cdRef.detectChanges();**
    }
  }

As you can see, i had to use detectChanges() as the last line of the above function because without it i am getting the error:

ParentComponent.html:1 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ng-pristine: true'. Current value: 'ng-pristine: false'.

i think i understand why is that. Angular start the check of the parent component, then, start to check the child component but then, on the child component the child component, on the writeValue function changing the parent component form state.

i feel uncomfortable with the use of detectChanges(). is there a way to do something else? is it a must when using parent and child components that each of them has formGroup and the child component is one of the parent formgroup formControl?


问:
How to re-enable introductory onboarding wizard after reinstalling WooCommerce
I uninstalled my WooCommerce plugin and chose to delete all data. When installed it back I cannot see the Introductory Onboarding Wizard. I need it to create my shop and all the pages again. I suspect this is because some traces were left from the first installation. How can I re-enable it again?

答:
/wp-admin/?page=wc-setup worked perfectly for me too.

Just login into wordpress and edit this in URL bar. Voila, it works!

Regrads


问:
Auto generate Class/Model based on pre existing table
How can I generate a class/model based on a preexisting table without creating the class/model by hand. In my case this is only used on flat tables without any relations.
Assuming I have the following table in my postgres database:

```<code>id  |  brand_name  |  cloth_type
1      nike           t-shirt
2      adidas         t-shirt
3      nike           skirt
</code>```

How can I get an object/instance of the first row (id 1) without to write a model by myself?
Is there a way to create an abstract class that is generated on the fly or where the attributes are added based on the table?

I found this, but could not really grasp how to implement it.
https://docs.sqlalchemy.org/en/13/orm/extensions/automap.html

What I would like to achieve could look something like this (rough code)

```<code>engine = db_connect(db_config_section)  # creates engine based on config
file
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
abstract_class = ...  # somehow generate abstract class
obj = session.query(abstract_class).get(1)
</code>```

Thanks for possible replies.

Edit:
In the linked solution there is still a class defined with a fixed class name and table name. That is not what I am searching for.
The code I want should be indipendent from one table. For example the code that works for the cloth tabel (as in my example) should also work for the follwing table (car):

```<code>   id  |  brand_name  |  car_type | doors
    1      bmw           suv        4
    2      ford          pickup     2
    3      fiat          cuv        2
</code>```

答:
Ok I solved it. As IljaEverilä sad, the solution is mostly given by the stackoverflow post he linked. I simpy had to adjust it a bit. I was a bit slow in understanding it, sorry for that.
Here is my solution:</p>

```<code>def create_class_by_table(table_name, engine):
      table = Table(table_name, Base.metadata, autoload=True, autoload_with=engine)
      class_name = table_name.capitalize()
      attributes = {'__table__': table}
      new_class = type(class_name, (Base,), attributes)
      return new_class

new_class = create_class_by_table(table_name, engine)  # table_name could be e.g. 'car'
obj = session.query(new_class).get(obj_id)
</code>```

Body:
How can I generate a class/model based on a preexisting table without creating the class/model by hand. In my case this is only used on flat tables without any relations.
Assuming I have the following table in my postgres database:

id  |  brand_name  |  cloth_type
1      nike           t-shirt
2      adidas         t-shirt
3      nike           skirt

How can I get an object/instance of the first row (id 1) without to write a model by myself?
Is there a way to create an abstract class that is generated on the fly or where the attributes are added based on the table?

I found this, but could not really grasp how to implement it.
https://docs.sqlalchemy.org/en/13/orm/extensions/automap.html

What I would like to achieve could look something like this (rough code)

engine = db_connect(db_config_section)  # creates engine based on config
file
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
abstract_class = ...  # somehow generate abstract class
obj = session.query(abstract_class).get(1)

Thanks for possible replies.

Edit:
In the linked solution there is still a class defined with a fixed class name and table name. That is not what I am searching for.
The code I want should be indipendent from one table. For example the code that works for the cloth tabel (as in my example) should also work for the follwing table (car):

   id  |  brand_name  |  car_type | doors
    1      bmw           suv        4
    2      ford          pickup     2
    3      fiat          cuv        2

Body:
Ok I solved it. As IljaEverilä sad, the solution is mostly given by the stackoverflow post he linked. I simpy had to adjust it a bit. I was a bit slow in understanding it, sorry for that.
Here is my solution:

def create_class_by_table(table_name, engine):
      table = Table(table_name, Base.metadata, autoload=True, autoload_with=engine)
      class_name = table_name.capitalize()
      attributes = {'__table__': table}
      new_class = type(class_name, (Base,), attributes)
      return new_class

new_class = create_class_by_table(table_name, engine)  # table_name could be e.g. 'car'
obj = session.query(new_class).get(obj_id)


问:
How to silence 'The last statement should return a value' warning?
Sun Studio 12.1 prints the warning

```<code>Warning: The last statement should return a value.
</code>```

frequently for functions like that:

```<code>int f()
{
  /* some code that may return */

  // if we end up here, something is broken
  throw std::runtime_error("Error ...");
}
</code>```

It is perfectly clear that we do not need a return value at the end of the function. I hesitate to insert something like

```<code>// Silence a compiler warning
return 42;
</code>```

at the end of such a function, since it is dead code anyway. For more complicated return types, it might actually be difficult to construct a 'sensible' bogus value.

What is the recommended way to silence such a warning?

答: Since you know the exception will be systematically called, why don't you simply return a 0?</p>

Body:
Sun Studio 12.1 prints the warning

Warning: The last statement should return a value.

frequently for functions like that:

int f()
{
  /* some code that may return */

  // if we end up here, something is broken
  throw std::runtime_error("Error ...");
}

It is perfectly clear that we do not need a return value at the end of the function. I hesitate to insert something like

// Silence a compiler warning
return 42;

at the end of such a function, since it is dead code anyway. For more complicated return types, it might actually be difficult to construct a 'sensible' bogus value.

What is the recommended way to silence such a warning?


问:
container_linux.go:247: invalid header field value - permission > denied - Problem with Quarkus native image on OpenShift
I'm trying to run a Quarkus native image application on Openshift 3.x.

I've generated the native image in a Fedora machine following Quarkus' instructions:

./mvnw package -Pnative

I've verified that the generated binary runs ok in the Fedora machine:

```<code>2019-05-30 08:45:06,957 INFO  [io.quarkus] (main) Quarkus 0.15.0 started in 0.052s. Listening on: http://0.0.0.0:8080
2019-05-30 08:45:06,963 INFO  [io.quarkus] (main) Installed features: [cdi, resteasy, resteasy-jsonb]
^C2019-05-30 08:45:12,836 INFO  [io.quarkus] (main) Quarkus stopped in 0.011s
</code>```

Then I insert that image into a Docker container:

```<code>FROM registry.fedoraproject.org/fedora-minimal
WORKDIR /work/

RUN curl -v -H 'Cache-Control: no-cache' -fSL "http://xxx/quarkus-ms-users-1.0-SNAPSHOT-runner" -o /work/application

RUN ls -la /work
EXPOSE 8080
CMD ["./application", "-Dquarkus.http.host=0.0.0.0"]
</code>```

I build the image in Openshift and when the container is deployed it fails with:

Error: failed to start container "quarkus-native-ms-users": Error
  response from daemon: {"message":"invalid header field value \"oci
  runtime error: container_linux.go:247: starting container process
  caused \\"exec: \\\\"./application\\\\": permission
  denied\\"\n\""}

What's wrong with this image?

答:
The problem was I was missing the execution permision for the binary RUN chmod +x /work/application.

Complete Dockerfile:

```<code>FROM registry.fedoraproject.org/fedora-minimal
WORKDIR /work/

RUN curl -v -H 'Cache-Control: no-cache' -fSL "http://xxx/quarkus-ms-users-1.0-SNAPSHOT-runner" -o /work/application
RUN chmod +x /work/application
RUN ls -la /work
EXPOSE 8080
CMD ["./application", "-Dquarkus.http.host=0.0.0.0"]
</code>```

Body:
I'm trying to run a Quarkus native image application on Openshift 3.x.

I've generated the native image in a Fedora machine following Quarkus' instructions:

./mvnw package -Pnative

I've verified that the generated binary runs ok in the Fedora machine:

2019-05-30 08:45:06,957 INFO  [io.quarkus] (main) Quarkus 0.15.0 started in 0.052s. Listening on: http://0.0.0.0:8080
2019-05-30 08:45:06,963 INFO  [io.quarkus] (main) Installed features: [cdi, resteasy, resteasy-jsonb]
^C2019-05-30 08:45:12,836 INFO  [io.quarkus] (main) Quarkus stopped in 0.011s

Then I insert that image into a Docker container:

FROM registry.fedoraproject.org/fedora-minimal
WORKDIR /work/

RUN curl -v -H 'Cache-Control: no-cache' -fSL "http://xxx/quarkus-ms-users-1.0-SNAPSHOT-runner" -o /work/application

RUN ls -la /work
EXPOSE 8080
CMD ["./application", "-Dquarkus.http.host=0.0.0.0"]

I build the image in Openshift and when the container is deployed it fails with:

Error: failed to start container "quarkus-native-ms-users": Error
  response from daemon: {"message":"invalid header field value \"oci
  runtime error: container_linux.go:247: starting container process
  caused \\"exec: \\\\"./application\\\\": permission
  denied\\"\n\""}

What's wrong with this image?

Body:
The problem was I was missing the execution permision for the binary RUN chmod +x /work/application.

Complete Dockerfile:

FROM registry.fedoraproject.org/fedora-minimal
WORKDIR /work/

RUN curl -v -H 'Cache-Control: no-cache' -fSL "http://xxx/quarkus-ms-users-1.0-SNAPSHOT-runner" -o /work/application
RUN chmod +x /work/application
RUN ls -la /work
EXPOSE 8080
CMD ["./application", "-Dquarkus.http.host=0.0.0.0"]