问:
Python ta-lib with pandas.io.data: candlestick not plotting but other charts are ok
iPython 2.3.1, OS-X Yosemite 10.10.2

Python print (sys.version):

2.7.6 (default, Sep  9 2014, 15:04:36)

[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)]

The following code works for data pulled for US stock data e.g. make the security id "INTC" for Intel. However when I access data for European stocks, the candlestick function fails even though all the OHLC data is there in the dataframe. Have put the full code in here to show that the other tech analysis charts plot just fine for the European stock data.

```<code>import pandas.io.data as web
import pandas as pd
import numpy as np
import talib as ta
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.dates import date2num
from matplotlib.finance import candlestick
import datetime

ticker = 'DNO.L'

# Download sample data
sec_id = web.get_data_yahoo(ticker, '2014-06-01')

# Data for matplotlib finance plot
sec_id_ochl = np.array(pd.DataFrame({'0':date2num(sec_id.index),
                                  '1':sec_id.Open,
                                  '2':sec_id.Close,
                                  '3':sec_id.High,
                                  '4':sec_id.Low}))

# Technical Analysis
SMA_FAST = 50
SMA_SLOW = 200
RSI_PERIOD = 14
RSI_AVG_PERIOD = 15
MACD_FAST = 12
MACD_SLOW = 26
MACD_SIGNAL = 9
STOCH_K = 14
STOCH_D = 3
SIGNAL_TOL = 3
Y_AXIS_SIZE = 12

analysis = pd.DataFrame(index = sec_id.index)

analysis['sma_f'] = pd.rolling_mean(sec_id.Close, SMA_FAST)
analysis['sma_s'] = pd.rolling_mean(sec_id.Close, SMA_SLOW)
analysis['rsi'] = ta.RSI(sec_id.Close.as_matrix(), RSI_PERIOD)
analysis['sma_r'] = pd.rolling_mean(analysis.rsi, RSI_AVG_PERIOD) # check shift
analysis['macd'], analysis['macdSignal'], analysis['macdHist'] = \
    ta.MACD(sec_id.Close.as_matrix(), fastperiod=MACD_FAST, slowperiod=MACD_SLOW, signalperiod=MACD_SIGNAL)
analysis['stoch_k'], analysis['stoch_d'] = \
    ta.STOCH(sec_id.High.as_matrix(), sec_id.Low.as_matrix(), sec_id.Close.as_matrix(), slowk_period=STOCH_K, slowd_period=STOCH_D)

analysis['sma'] = np.where(analysis.sma_f > analysis.sma_s, 1, 0)
analysis['macd_test'] = np.where((analysis.macd > analysis.macdSignal), 1, 0)
analysis['stoch_k_test'] = np.where((analysis.stoch_k < 50) & (analysis.stoch_k > analysis.stoch_k.shift(1)), 1, 0)
analysis['rsi_test'] = np.where((analysis.rsi < 50) & (analysis.rsi > analysis.rsi.shift(1)), 1, 0)

# Prepare plot
fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, sharex=True)
ax1.set_ylabel(ticker, size=20)

#size plot
fig.set_size_inches(15,30)

# Plot candles
candlestick(ax1, sec_id_ochl, width=0.5, colorup='g', colordown='r', alpha=1)

# Draw Moving Averages
analysis.sma_f.plot(ax=ax1, c='r')
analysis.sma_s.plot(ax=ax1, c='g')

#RSI
ax2.set_ylabel('RSI', size=Y_AXIS_SIZE)
analysis.rsi.plot(ax = ax2, c='g', label = 'Period: ' + str(RSI_PERIOD))
analysis.sma_r.plot(ax = ax2, c='r', label = 'MA: ' + str(RSI_AVG_PERIOD))
ax2.axhline(y=30, c='b')
ax2.axhline(y=50, c='black')
ax2.axhline(y=70, c='b')
ax2.set_ylim([0,100])
handles, labels = ax2.get_legend_handles_labels()
ax2.legend(handles, labels)

# Draw MACD computed with Talib
ax3.set_ylabel('MACD: '+ str(MACD_FAST) + ', ' + str(MACD_SLOW) + ', ' + str(MACD_SIGNAL), size=Y_AXIS_SIZE)
analysis.macd.plot(ax=ax3, color='b', label='Macd')
analysis.macdSignal.plot(ax=ax3, color='g', label='Signal')
analysis.macdHist.plot(ax=ax3, color='r', label='Hist')
ax3.axhline(0, lw=2, color='0')
handles, labels = ax3.get_legend_handles_labels()
ax3.legend(handles, labels)

# Stochastic plot
ax4.set_ylabel('Stoch (k,d)', size=Y_AXIS_SIZE)
analysis.stoch_k.plot(ax=ax4, label='stoch_k:'+ str(STOCH_K), color='r')
analysis.stoch_d.plot(ax=ax4, label='stoch_d:'+ str(STOCH_D), color='g')
handles, labels = ax4.get_legend_handles_labels()
ax4.legend(handles, labels)
ax4.axhline(y=20, c='b')
ax4.axhline(y=50, c='black')
ax4.axhline(y=80, c='b')

plt.show()
</code>```

答:
I copied your code and ran into the same error you did. I fixed it, but it required a few steps. I've copied the fixed code here, and also the other steps I did to get the code to run without error.

Fix an issue with pandas_datareader, due to changes in the Yahoo API. I got this bit of the solution from another StackOverflow post.

```<code>git clone https://github.com/pydata/pandas-datareader
cd pandas-datareader/
git remote add rgkimball http://github.com/rgkimball/pandas-datareader
git fetch rgkimball fix-yahoo
git checkout fix-yahoo
pip2 uninstall pandas_datareader
python setup.py install
</code>```

I also fixed line 18 in the code using the answer submitted above by @ndrw.

I made a few other changes, which I've included in this Github repo. I've copied the code below for your convenience. I hope it helps!

```<code>from pandas_datareader import data
import pandas as pd
import numpy as np
import talib as ta
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.gridspec as gridspec
from matplotlib.dates import date2num
from matplotlib.finance import candlestick_ohlc as candlestick
import datetime

ticker = 'OPK'

# Download sample data
sec_id = data.get_data_google(ticker, '2014-06-01')

# Data for matplotlib finance plot
sec_id_ochl = np.array(pd.DataFrame({'0':date2num(sec_id.index.to_pydatetime()),
        '1':sec_id.Open,
        '2':sec_id.Close,
        '3':sec_id.High,
        '4':sec_id.Low}))

# Technical Analysis
SMA_FAST = 50
SMA_SLOW = 200
RSI_PERIOD = 14
RSI_AVG_PERIOD = 15
MACD_FAST = 12
MACD_SLOW = 26
MACD_SIGNAL = 9
STOCH_K = 14
STOCH_D = 3
SIGNAL_TOL = 3
Y_AXIS_SIZE = 12

analysis = pd.DataFrame(index = sec_id.index)

analysis['sma_f'] = pd.rolling_mean(sec_id.Close, SMA_FAST)
analysis['sma_s'] = pd.rolling_mean(sec_id.Close, SMA_SLOW)
analysis['rsi'] = ta.RSI(sec_id.Close.as_matrix(), RSI_PERIOD)
analysis['sma_r'] = pd.rolling_mean(analysis.rsi, RSI_AVG_PERIOD) # check shift
analysis['macd'], analysis['macdSignal'], analysis['macdHist'] = ta.MACD(sec_id.Close.as_matrix(), fastperiod=MACD_FAST, slowperiod=MACD_SLOW, signalperiod=MACD_SIGNAL)
analysis['stoch_k'], analysis['stoch_d'] = ta.STOCH(sec_id.High.as_matrix(), sec_id.Low.as_matrix(), sec_id.Close.as_matrix(), slowk_period=STOCH_K, slowd_period=STOCH_D)

analysis['sma'] = np.where(analysis.sma_f > analysis.sma_s, 1, 0)
analysis['macd_test'] = np.where((analysis.macd > analysis.macdSignal), 1, 0)
analysis['stoch_k_test'] = np.where((analysis.stoch_k < 50) & (analysis.stoch_k > analysis.stoch_k.shift(1)), 1, 0)
analysis['rsi_test'] = np.where((analysis.rsi < 50) & (analysis.rsi > analysis.rsi.shift(1)), 1, 0)

# Prepare plot
fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, sharex=True)
ax1.set_ylabel(ticker, size=20)

#size plot
fig.set_size_inches(15,30)

# Plot candles
candlestick(ax1, sec_id_ochl, width=0.5, colorup='g', colordown='r', alpha=1)

# Draw Moving Averages
analysis.sma_f.plot(ax=ax1, c='r')
analysis.sma_s.plot(ax=ax1, c='g')

#RSI
ax2.set_ylabel('RSI', size=Y_AXIS_SIZE)
analysis.rsi.plot(ax = ax2, c='g', label = 'Period: ' + str(RSI_PERIOD))
analysis.sma_r.plot(ax = ax2, c='r', label = 'MA: ' + str(RSI_AVG_PERIOD))
ax2.axhline(y=30, c='b')
ax2.axhline(y=50, c='black')
ax2.axhline(y=70, c='b')
ax2.set_ylim([0,100])
handles, labels = ax2.get_legend_handles_labels()
ax2.legend(handles, labels)

# Draw MACD computed with Talib
ax3.set_ylabel('MACD: '+ str(MACD_FAST) + ', ' + str(MACD_SLOW) + ', ' + str(MACD_SIGNAL), size=Y_AXIS_SIZE)
analysis.macd.plot(ax=ax3, color='b', label='Macd')
analysis.macdSignal.plot(ax=ax3, color='g', label='Signal')
analysis.macdHist.plot(ax=ax3, color='r', label='Hist')
ax3.axhline(0, lw=2, color='0')
handles, labels = ax3.get_legend_handles_labels()
ax3.legend(handles, labels)

# Stochastic plot
ax4.set_ylabel('Stoch (k,d)', size=Y_AXIS_SIZE)
analysis.stoch_k.plot(ax=ax4, label='stoch_k:'+ str(STOCH_K), color='r')
analysis.stoch_d.plot(ax=ax4, label='stoch_d:'+ str(STOCH_D), color='g')
handles, labels = ax4.get_legend_handles_labels()
ax4.legend(handles, labels)
ax4.axhline(y=20, c='b')
ax4.axhline(y=50, c='black')
ax4.axhline(y=80, c='b')

plt.show()
</code>```

Here's the output I get:

Body:
iPython 2.3.1, OS-X Yosemite 10.10.2

Python print (sys.version):

2.7.6 (default, Sep  9 2014, 15:04:36)

[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)]

The following code works for data pulled for US stock data e.g. make the security id "INTC" for Intel. However when I access data for European stocks, the candlestick function fails even though all the OHLC data is there in the dataframe. Have put the full code in here to show that the other tech analysis charts plot just fine for the European stock data.

import pandas.io.data as web
import pandas as pd
import numpy as np
import talib as ta
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.dates import date2num
from matplotlib.finance import candlestick
import datetime

ticker = 'DNO.L'

# Download sample data
sec_id = web.get_data_yahoo(ticker, '2014-06-01')

# Data for matplotlib finance plot
sec_id_ochl = np.array(pd.DataFrame({'0':date2num(sec_id.index),
                                  '1':sec_id.Open,
                                  '2':sec_id.Close,
                                  '3':sec_id.High,
                                  '4':sec_id.Low}))

# Technical Analysis
SMA_FAST = 50
SMA_SLOW = 200
RSI_PERIOD = 14
RSI_AVG_PERIOD = 15
MACD_FAST = 12
MACD_SLOW = 26
MACD_SIGNAL = 9
STOCH_K = 14
STOCH_D = 3
SIGNAL_TOL = 3
Y_AXIS_SIZE = 12

analysis = pd.DataFrame(index = sec_id.index)

analysis['sma_f'] = pd.rolling_mean(sec_id.Close, SMA_FAST)
analysis['sma_s'] = pd.rolling_mean(sec_id.Close, SMA_SLOW)
analysis['rsi'] = ta.RSI(sec_id.Close.as_matrix(), RSI_PERIOD)
analysis['sma_r'] = pd.rolling_mean(analysis.rsi, RSI_AVG_PERIOD) # check shift
analysis['macd'], analysis['macdSignal'], analysis['macdHist'] = \
    ta.MACD(sec_id.Close.as_matrix(), fastperiod=MACD_FAST, slowperiod=MACD_SLOW, signalperiod=MACD_SIGNAL)
analysis['stoch_k'], analysis['stoch_d'] = \
    ta.STOCH(sec_id.High.as_matrix(), sec_id.Low.as_matrix(), sec_id.Close.as_matrix(), slowk_period=STOCH_K, slowd_period=STOCH_D)

analysis['sma'] = np.where(analysis.sma_f > analysis.sma_s, 1, 0)
analysis['macd_test'] = np.where((analysis.macd > analysis.macdSignal), 1, 0)
analysis['stoch_k_test'] = np.where((analysis.stoch_k < 50) & (analysis.stoch_k > analysis.stoch_k.shift(1)), 1, 0)
analysis['rsi_test'] = np.where((analysis.rsi < 50) & (analysis.rsi > analysis.rsi.shift(1)), 1, 0)

# Prepare plot
fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, sharex=True)
ax1.set_ylabel(ticker, size=20)

#size plot
fig.set_size_inches(15,30)

# Plot candles
candlestick(ax1, sec_id_ochl, width=0.5, colorup='g', colordown='r', alpha=1)

# Draw Moving Averages
analysis.sma_f.plot(ax=ax1, c='r')
analysis.sma_s.plot(ax=ax1, c='g')

#RSI
ax2.set_ylabel('RSI', size=Y_AXIS_SIZE)
analysis.rsi.plot(ax = ax2, c='g', label = 'Period: ' + str(RSI_PERIOD))
analysis.sma_r.plot(ax = ax2, c='r', label = 'MA: ' + str(RSI_AVG_PERIOD))
ax2.axhline(y=30, c='b')
ax2.axhline(y=50, c='black')
ax2.axhline(y=70, c='b')
ax2.set_ylim([0,100])
handles, labels = ax2.get_legend_handles_labels()
ax2.legend(handles, labels)

# Draw MACD computed with Talib
ax3.set_ylabel('MACD: '+ str(MACD_FAST) + ', ' + str(MACD_SLOW) + ', ' + str(MACD_SIGNAL), size=Y_AXIS_SIZE)
analysis.macd.plot(ax=ax3, color='b', label='Macd')
analysis.macdSignal.plot(ax=ax3, color='g', label='Signal')
analysis.macdHist.plot(ax=ax3, color='r', label='Hist')
ax3.axhline(0, lw=2, color='0')
handles, labels = ax3.get_legend_handles_labels()
ax3.legend(handles, labels)

# Stochastic plot
ax4.set_ylabel('Stoch (k,d)', size=Y_AXIS_SIZE)
analysis.stoch_k.plot(ax=ax4, label='stoch_k:'+ str(STOCH_K), color='r')
analysis.stoch_d.plot(ax=ax4, label='stoch_d:'+ str(STOCH_D), color='g')
handles, labels = ax4.get_legend_handles_labels()
ax4.legend(handles, labels)
ax4.axhline(y=20, c='b')
ax4.axhline(y=50, c='black')
ax4.axhline(y=80, c='b')

plt.show()

Body:
I copied your code and ran into the same error you did. I fixed it, but it required a few steps. I've copied the fixed code here, and also the other steps I did to get the code to run without error.

Fix an issue with pandas_datareader, due to changes in the Yahoo API. I got this bit of the solution from another StackOverflow post.

git clone https://github.com/pydata/pandas-datareader
cd pandas-datareader/
git remote add rgkimball http://github.com/rgkimball/pandas-datareader
git fetch rgkimball fix-yahoo
git checkout fix-yahoo
pip2 uninstall pandas_datareader
python setup.py install

I also fixed line 18 in the code using the answer submitted above by @ndrw.

I made a few other changes, which I've included in this Github repo. I've copied the code below for your convenience. I hope it helps!

from pandas_datareader import data
import pandas as pd
import numpy as np
import talib as ta
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.gridspec as gridspec
from matplotlib.dates import date2num
from matplotlib.finance import candlestick_ohlc as candlestick
import datetime

ticker = 'OPK'

# Download sample data
sec_id = data.get_data_google(ticker, '2014-06-01')

# Data for matplotlib finance plot
sec_id_ochl = np.array(pd.DataFrame({'0':date2num(sec_id.index.to_pydatetime()),
        '1':sec_id.Open,
        '2':sec_id.Close,
        '3':sec_id.High,
        '4':sec_id.Low}))

# Technical Analysis
SMA_FAST = 50
SMA_SLOW = 200
RSI_PERIOD = 14
RSI_AVG_PERIOD = 15
MACD_FAST = 12
MACD_SLOW = 26
MACD_SIGNAL = 9
STOCH_K = 14
STOCH_D = 3
SIGNAL_TOL = 3
Y_AXIS_SIZE = 12

analysis = pd.DataFrame(index = sec_id.index)

analysis['sma_f'] = pd.rolling_mean(sec_id.Close, SMA_FAST)
analysis['sma_s'] = pd.rolling_mean(sec_id.Close, SMA_SLOW)
analysis['rsi'] = ta.RSI(sec_id.Close.as_matrix(), RSI_PERIOD)
analysis['sma_r'] = pd.rolling_mean(analysis.rsi, RSI_AVG_PERIOD) # check shift
analysis['macd'], analysis['macdSignal'], analysis['macdHist'] = ta.MACD(sec_id.Close.as_matrix(), fastperiod=MACD_FAST, slowperiod=MACD_SLOW, signalperiod=MACD_SIGNAL)
analysis['stoch_k'], analysis['stoch_d'] = ta.STOCH(sec_id.High.as_matrix(), sec_id.Low.as_matrix(), sec_id.Close.as_matrix(), slowk_period=STOCH_K, slowd_period=STOCH_D)

analysis['sma'] = np.where(analysis.sma_f > analysis.sma_s, 1, 0)
analysis['macd_test'] = np.where((analysis.macd > analysis.macdSignal), 1, 0)
analysis['stoch_k_test'] = np.where((analysis.stoch_k < 50) & (analysis.stoch_k > analysis.stoch_k.shift(1)), 1, 0)
analysis['rsi_test'] = np.where((analysis.rsi < 50) & (analysis.rsi > analysis.rsi.shift(1)), 1, 0)

# Prepare plot
fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, sharex=True)
ax1.set_ylabel(ticker, size=20)

#size plot
fig.set_size_inches(15,30)

# Plot candles
candlestick(ax1, sec_id_ochl, width=0.5, colorup='g', colordown='r', alpha=1)

# Draw Moving Averages
analysis.sma_f.plot(ax=ax1, c='r')
analysis.sma_s.plot(ax=ax1, c='g')

#RSI
ax2.set_ylabel('RSI', size=Y_AXIS_SIZE)
analysis.rsi.plot(ax = ax2, c='g', label = 'Period: ' + str(RSI_PERIOD))
analysis.sma_r.plot(ax = ax2, c='r', label = 'MA: ' + str(RSI_AVG_PERIOD))
ax2.axhline(y=30, c='b')
ax2.axhline(y=50, c='black')
ax2.axhline(y=70, c='b')
ax2.set_ylim([0,100])
handles, labels = ax2.get_legend_handles_labels()
ax2.legend(handles, labels)

# Draw MACD computed with Talib
ax3.set_ylabel('MACD: '+ str(MACD_FAST) + ', ' + str(MACD_SLOW) + ', ' + str(MACD_SIGNAL), size=Y_AXIS_SIZE)
analysis.macd.plot(ax=ax3, color='b', label='Macd')
analysis.macdSignal.plot(ax=ax3, color='g', label='Signal')
analysis.macdHist.plot(ax=ax3, color='r', label='Hist')
ax3.axhline(0, lw=2, color='0')
handles, labels = ax3.get_legend_handles_labels()
ax3.legend(handles, labels)

# Stochastic plot
ax4.set_ylabel('Stoch (k,d)', size=Y_AXIS_SIZE)
analysis.stoch_k.plot(ax=ax4, label='stoch_k:'+ str(STOCH_K), color='r')
analysis.stoch_d.plot(ax=ax4, label='stoch_d:'+ str(STOCH_D), color='g')
handles, labels = ax4.get_legend_handles_labels()
ax4.legend(handles, labels)
ax4.axhline(y=20, c='b')
ax4.axhline(y=50, c='black')
ax4.axhline(y=80, c='b')

plt.show()

Here's the output I get:


来源: stackexchange

问:
How to know when a View has scrolled into view
We are currently developing an app that displays large data sets in "registers" and in rows. We are using a TableLayout as the base view and then adding table rows for every item (with a LinearLayout in each row).

I have noticed that once the amount of records get beyond a certain point (1000+ records), the device slows down tremendously. I am sure that this is a simple memory issue(maybe rendering too?) and have devised a plan that could increase the speed.

We have implemented continuous paging on a lot of silverlight projects, and I figure that this is the best approach to take in Android?

The only problem I have now is to recognize when a specific view (say row 100) has been scrolled into view, so that I can start to render the next couple of lines.

Does anyone know how to do this, or of a better way to implement/handle large data sets?

Regards

答:
I think this video should be very beneficial to you
http://www.google.com/events/io/2010/sessions/world-of-listview-android.html

This talks about the exact problem you are having and how to fix it!

ContentLicense: CC BY-SA 2.5


问:
How does topic count affect channels performance in the Phoenix framework?
I am currently creating an application with the Phoenix framework that uses channels for two way communication between a large number of mobile devices and a back-end service (obviously Phoenix based).

I am intending to create a single topic for each device given that devices are defined by ID, for example device:2149, device:1234 etc.

I have the following socket:

```<code>defmodule Webservice.DeviceSocket do
  use Phoenix.Socket
  channel "device:*", Webservice.DeviceChannel
  transport :websocket, Phoenix.Transports.WebSocket

  def connect(_params, socket) do
    {:ok, socket}
  end

  def id(_socket), do: nil
end
</code>```

and the following channel:

```<code>defmodule Webservice.DeviceChannel do
  use Phoenix.Channel

  def join("device:" <> device_id, _params, _socket) do
    # do some stuff
    {:ok, socket}
  end

  def handle_in("some_message", %{"data" => data }, socket) do
    # Do stuff
    {:noreply, socket}
  end
end
</code>```

Now given that I expect a large number of devices to use this service say around 90000, this means that 90000 topics need to be managed.

Will a large number of topics result in some overhead that will hurt the application's performance?

答: According to this blog post, Phoenix can handle at least 2 million websocket connections, but of course that assumes your machine is beefy enough. 90,000 should be a breeze.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am currently creating an application with the Phoenix framework that uses channels for two way communication between a large number of mobile devices and a back-end service (obviously Phoenix based).

I am intending to create a single topic for each device given that devices are defined by ID, for example device:2149, device:1234 etc.

I have the following socket:

defmodule Webservice.DeviceSocket do
  use Phoenix.Socket
  channel "device:*", Webservice.DeviceChannel
  transport :websocket, Phoenix.Transports.WebSocket

  def connect(_params, socket) do
    {:ok, socket}
  end

  def id(_socket), do: nil
end

and the following channel:

defmodule Webservice.DeviceChannel do
  use Phoenix.Channel

  def join("device:" <> device_id, _params, _socket) do
    # do some stuff
    {:ok, socket}
  end

  def handle_in("some_message", %{"data" => data }, socket) do
    # Do stuff
    {:noreply, socket}
  end
end

Now given that I expect a large number of devices to use this service say around 90000, this means that 90000 topics need to be managed.

Will a large number of topics result in some overhead that will hurt the application's performance?


问:
2 second interval before the auto save button in form
Can I Make a 2 second interval before the auto-save perform? this code shows my webpage with a single textbox in it, and it auto show my DTRSearch.php result. This code is working perfectly.

```<code><div id="search">
<input type="text" placeholder="Scan" id="t1" name="t1" onkeyup="aa();"
autofocus/></div>

<script type="text/javascript">
function aa(){
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","DTRSearch.php?
nmnm="+document.getElementById("t1").value,false);
xmlhttp.send(null);
document.getElementById("searchdiv").innerHTML=xmlhttp.responseText;
document.getElementById("searchdiv").style.visibility='visible';
}
</script>
<div id="searchdiv" style="visibility:hidden; position:absolute">
</div>
</code>```

DTRSearch.php it query a single row, this a simple form with a submit button, i want this form to perform an auto-save but before that it should show the form for 2 second

```<code><form action="GetDTRSearch.php" method="get">
        <input type="text" value="<?php echo  $id_number;>" name="ID_Number" /><br />
        <input type="text" value="<?php echo  $fullname; ?>"name="Fullname" /><br />
        <p class="Ok"><input type="submit" value="Click Confirm" /></p>
</code>```

答:
This is the sample html code you need to change.

<form name="myForm" id="myForm" action="GetDTRSearch.php" method="get">
        <input type="text" value="<?php echo  $id_number;>" name="ID_Number" />

        <input type="text" value="<?php echo  $fullname; ?>"name="Fullname" />

<input type="submit" value="Click Confirm" />

</form>```
</div>
</div>
</p>

<p>Below code the form will be automatically post back to server after 2 seconds to the action method.
make sure this code will be executed after the data will fetch from DTRSearch.php else it will send blank value to the server. You can use this on submit click or you can directly make function and call this after data is fetched.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>setTimeout(function() {
        document.forms["myForm"].submit();
    }, 2000);</code>```

Body:
Can I Make a 2 second interval before the auto-save perform? this code shows my webpage with a single textbox in it, and it auto show my DTRSearch.php result. This code is working perfectly.

<input type="text" placeholder="Scan" id="t1" name="t1" onkeyup="aa();"
autofocus/>

DTRSearch.php it query a single row, this a simple form with a submit button, i want this form to perform an auto-save but before that it should show the form for 2 second

<form action="GetDTRSearch.php" method="get">
        <input type="text" value="<?php echo  $id_number;>" name="ID_Number" />

        <input type="text" value="<?php echo  $fullname; ?>"name="Fullname" />

<input type="submit" value="Click Confirm" />

Body:
This is the sample html code you need to change.

<form name="myForm" id="myForm" action="GetDTRSearch.php" method="get">
        <input type="text" value="<?php echo  $id_number;>" name="ID_Number" /><br />
        <input type="text" value="<?php echo  $fullname; ?>"name="Fullname" /><br />
        <p class="Ok"><input type="submit" value="Click Confirm" /></p>
</form>

Below code the form will be automatically post back to server after 2 seconds to the action method.
make sure this code will be executed after the data will fetch from DTRSearch.php else it will send blank value to the server. You can use this on submit click or you can directly make function and call this after data is fetched.

setTimeout(function() {
        document.forms["myForm"].submit();
    }, 2000);


问:
Use Javascript libraries in Kotlin
The last time I used Kotlin was Dec 2015 when I used it to solve a couple of Project Euler problems.

This time I want to try its interoperability with Javascript. Now my question is, how do we import/use existing Javascript libraries in Kotlin?
I've seen some people using the native keyword, and I just want a brief explanation of it.

答:
I added a simple barebone project as an example of how to do Kotlin2Js.

https://bitbucket.org/mantis78/gradle4kotlin2js/src

Here is the gradle file that is the main recipe.

```<code>group 'org.boonhighendtech'
version '1.0-SNAPSHOT'

buildscript {
    ext.kotlin_version = '1.1.2-5'
    repositories {
        maven { url 'http://dl.bintray.com/kotlin/kotlin-dev/' }
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

apply plugin: 'kotlin2js'

repositories {
    maven { url 'http://dl.bintray.com/kotlin/kotlin-dev/' }
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version"
}

build {
    outputs.dir("web/")
}

build.doLast {
    copy {
        from 'src/main/webapp'
        into 'web/'
        include '**/*.html'
        include '**/*.js'
        include '**/*.jpg'
        include '**/*.png'
    }

    configurations.compile.each { File file ->
        copy {
            includeEmptyDirs = false

            from zipTree(file.absolutePath)
            into "${projectDir}/web"
            include { fileTreeElement ->
                def path = fileTreeElement.path
                path.endsWith(".js") && (path.startsWith("META-INF/resources/") || !path.startsWith("META-INF/"))
            }
        }
    }
}

clean.doLast {
    file(new File(projectDir, "/web")).deleteDir()
}

compileKotlin2Js {
    kotlinOptions.outputFile = "${projectDir}/web/output.js"
    kotlinOptions.moduleKind = "amd"
    kotlinOptions.sourceMap = true
}
</code>```

Firstly, you can assign a dynamic variable then essentially code it like you code JavaScript, dynamically.

e.g.

```<code>val jQuery: dynamic = passedInJQueryRef
jQuery.whateverFunc()
</code>```

But if your intention is to have it typed, then you need to introduce types to the external library. One way is to make use of the relatively extensive libraries of typedefs by https://github.com/DefinitelyTyped/DefinitelyTyped

Find the ts.d there, then run ts2kt (https://github.com/Kotlin/ts2kt) to get your Kotlin files. That typically gets you there. Occasionally, certain conversions are not well done. You will have to hand fix the conversion. E.g. snapsvg's snapsvg.attr() call takes in "{}" but it got converted to some strange interface.

It was

```<code>fun attr(params: `ts$2`): Snap.Element
</code>```

And I replaced it with

```<code> fun attr(params: Json): Snap.Element
</code>```

and it works like a charm.

Title: Use Javascript libraries in Kotlin

Body:
I added a simple barebone project as an example of how to do Kotlin2Js.

https://bitbucket.org/mantis78/gradle4kotlin2js/src

Here is the gradle file that is the main recipe.

group 'org.boonhighendtech'
version '1.0-SNAPSHOT'

buildscript {
    ext.kotlin_version = '1.1.2-5'
    repositories {
        maven { url 'http://dl.bintray.com/kotlin/kotlin-dev/' }
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

apply plugin: 'kotlin2js'

repositories {
    maven { url 'http://dl.bintray.com/kotlin/kotlin-dev/' }
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version"
}

build {
    outputs.dir("web/")
}

build.doLast {
    copy {
        from 'src/main/webapp'
        into 'web/'
        include '**/*.html'
        include '**/*.js'
        include '**/*.jpg'
        include '**/*.png'
    }

    configurations.compile.each { File file ->
        copy {
            includeEmptyDirs = false

            from zipTree(file.absolutePath)
            into "${projectDir}/web"
            include { fileTreeElement ->
                def path = fileTreeElement.path
                path.endsWith(".js") && (path.startsWith("META-INF/resources/") || !path.startsWith("META-INF/"))
            }
        }
    }
}

clean.doLast {
    file(new File(projectDir, "/web")).deleteDir()
}

compileKotlin2Js {
    kotlinOptions.outputFile = "${projectDir}/web/output.js"
    kotlinOptions.moduleKind = "amd"
    kotlinOptions.sourceMap = true
}

Firstly, you can assign a dynamic variable then essentially code it like you code JavaScript, dynamically.

e.g.

val jQuery: dynamic = passedInJQueryRef
jQuery.whateverFunc()

But if your intention is to have it typed, then you need to introduce types to the external library. One way is to make use of the relatively extensive libraries of typedefs by https://github.com/DefinitelyTyped/DefinitelyTyped

Find the ts.d there, then run ts2kt (https://github.com/Kotlin/ts2kt) to get your Kotlin files. That typically gets you there. Occasionally, certain conversions are not well done. You will have to hand fix the conversion. E.g. snapsvg's snapsvg.attr() call takes in "{}" but it got converted to some strange interface.

It was

fun attr(params: `ts$2`): Snap.Element

And I replaced it with

 fun attr(params: Json): Snap.Element

and it works like a charm.


问:
How to remove all characters not inside parentheses using regex
I have a string that contains commas both inside and outside of a parentheses block:
    foo(bat,foo),bat

How can I use regex to replace the comma not inside parentheses?
                                                                  foo(bat,foo)bat

答:
Do you really want to use re, or is anyway to achieve your goal is ok?

In the latter case, here is a way to do it:

```<code>mystring = 'foo(bat,foo),bat'
''.join(si + ',' if '(' in si else si for si in mystring.split(','))

#'foo(bat,foo)bat'
</code>```

Body:
Do you really want to use re, or is anyway to achieve your goal is ok?

In the latter case, here is a way to do it:

mystring = 'foo(bat,foo),bat'
''.join(si + ',' if '(' in si else si for si in mystring.split(','))

#'foo(bat,foo)bat'


问:
Override an environmental variable on Azure App Service without using the app settings
I need to override one of the default Azure environmental variables. The most obvious way is to add an app setting with the same name, which will override the environmental variable, however, I'd like to approach it in a different way, as this variable is essentially not an app settings.

My perfect approach would be to set it during an ARM deployment, but after checking Azure Resource Explorer, it looks like the environmental variables are not exposed anywhere. Are those stored in some files on the machine that could be transformed during a deployment by any chance? That could be another solution.

答:
My perfect approach would be to set it during an ARM deployment, but after checking Azure Resource Explorer, it looks like the environmental variables are not exposed anywhere.

In ARM template, we could define the Application Settings to apply to the Web App. As David Ebbo said, please try to explicitly set WEBSITE_DYNAMIC_CACHE to 0 from the appsettings.

```<code>{
    "name": "appsettings",
    "type": "config",
    "apiVersion": "2015-08-01",
    "dependsOn": [
        "[concat('Microsoft.Web/sites/', variables('webSiteName'))]"
    ],
  "tags": {
    "displayName": "WebAppSettings"
  },
  "properties": {
    "WEBSITE_DYNAMIC_CACHE": "0"
  }
}
</code>```

Update:

I do not find a resource/section in ARM template could be used to directly inject an environment variable. XDT Transform provide a way to inject environment variables, if possible, you could try to use it.

```<code><?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.webServer>
    <runtime xdt:Transform="InsertIfMissing">
      <environmentVariables xdt:Transform="InsertIfMissing">
         <add name="WEBSITE_DYNAMIC_CACHE" value="0" xdt:Locator="Match(name)" xdt:Transform="InsertIfMissing" />
      </environmentVariables>
    </runtime>
  </system.webServer>
</configuration>
</code>```

Body:
My perfect approach would be to set it during an ARM deployment, but after checking Azure Resource Explorer, it looks like the environmental variables are not exposed anywhere.

In ARM template, we could define the Application Settings to apply to the Web App. As David Ebbo said, please try to explicitly set WEBSITE_DYNAMIC_CACHE to 0 from the appsettings.

{
    "name": "appsettings",
    "type": "config",
    "apiVersion": "2015-08-01",
    "dependsOn": [
        "[concat('Microsoft.Web/sites/', variables('webSiteName'))]"
    ],
  "tags": {
    "displayName": "WebAppSettings"
  },
  "properties": {
    "WEBSITE_DYNAMIC_CACHE": "0"
  }
}

Update:

I do not find a resource/section in ARM template could be used to directly inject an environment variable. XDT Transform provide a way to inject environment variables, if possible, you could try to use it.

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.webServer>
    <runtime xdt:Transform="InsertIfMissing">
      <environmentVariables xdt:Transform="InsertIfMissing">
         <add name="WEBSITE_DYNAMIC_CACHE" value="0" xdt:Locator="Match(name)" xdt:Transform="InsertIfMissing" />
      </environmentVariables>
    </runtime>
  </system.webServer>
</configuration>


问:
Difference between public and private variables
```<code>namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         private int numberTwo = 12;

         static void yo()
         {
         }
    }
}
</code>```

Can someone tell me the difference between the variables numberOne and numberTwo in this code excerpt?

答:
Other objects can access NumberOne, but they can't access numberTwo.

So I can do Your_Object.numberOne = 14; but I can't do Your_Object.numberTwo= 14;

Now I might be able to access the numberTwo through reflection depending on the permissions set up in the application, but I can't directly.

Variables in C#

Reflection in C#

Accessors in C#

Body:
namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         private int numberTwo = 12;

         static void yo()
         {
         }
    }
}

Can someone tell me the difference between the variables numberOne and numberTwo in this code excerpt?


问:
Reusing Tensorflow Variables
I want to have basically two different graphs based on whether I am training my network or actually running it. Basically, one piece uses some unsupervised techniques to learn the values of a given matrix and then I want to use the exact same matrix in a different graph.

I know how to get the value of the matrix using matrix_value = sess.run(my_matrix, {input=input_data}) but then is there a way to initialize a tf.Variable with a set value?

答:
You can try something like this:

```<code>import numpy as np
import tensorflow as tf

value = [0, 1, 2, 3, 4, 5, 6, 7]
init = tf.constant_initializer(value)

with tf.Session():
    x = tf.get_variable('x', shape=[2, 4], initializer=init)
    x.initializer.run()
    print(x.eval())
</code>```

I hope this helps !

Title: Reusing Tensorflow Variables

Body:
You can try something like this:

import numpy as np
import tensorflow as tf

value = [0, 1, 2, 3, 4, 5, 6, 7]
init = tf.constant_initializer(value)

with tf.Session():
    x = tf.get_variable('x', shape=[2, 4], initializer=init)
    x.initializer.run()
    print(x.eval())

I hope this helps !


问:
How to splice user correctly from scope in AngularJS?
I am trying to remove user from the list. For some reason, splicing is not removing the user from the list. Can any one help me solve this. I am getting the users from a backend API call, and I am using a PUT method to update it when it removes that particular user.

app.js

```<code>app.controller('MyCtrl', function($scope, $window) {

    $scope.inactive = true;

    $scope.confirmedAction = user => {
        const index = $scope.userInfo.users.indexOf(user);
        $scope.userInfo.users.splice(user, 1);
        $window.location.href = '#/user';
    };

});
</code>```

答:
From comments I noticed:

user is an object, and the function's parameter user is not the same instance!

Also assuming you have id property in user object.

Using Array.findIndex.

```<code>app.controller('MyCtrl', function($scope, $window) {
        $scope.inactive = true;
        $scope.confirmedAction = function (user) {
           var index = $scope.userInfo.users.findIndex(u=> u.id == user.id);
          if(index>=0) {
              $scope.userInfo.users.splice(user, 1);
              $window.location.href = '#/user';
          }
        }
    });
</code>```

Body:
I am trying to remove user from the list. For some reason, splicing is not removing the user from the list. Can any one help me solve this. I am getting the users from a backend API call, and I am using a PUT method to update it when it removes that particular user.

app.js

app.controller('MyCtrl', function($scope, $window) {

    $scope.inactive = true;

    $scope.confirmedAction = user => {
        const index = $scope.userInfo.users.indexOf(user);
        $scope.userInfo.users.splice(user, 1);
        $window.location.href = '#/user';
    };

});

Body:
From comments I noticed:

user is an object, and the function's parameter user is not the same instance!

Also assuming you have id property in user object.

Using Array.findIndex.

app.controller('MyCtrl', function($scope, $window) {
        $scope.inactive = true;
        $scope.confirmedAction = function (user) {
           var index = $scope.userInfo.users.findIndex(u=> u.id == user.id);
          if(index>=0) {
              $scope.userInfo.users.splice(user, 1);
              $window.location.href = '#/user';
          }
        }
    });


问:
java.sql.SQLException: Unable to find a suitable driver for jdbc weka.experiment.DatabaseUtils.connectToDatabase(DatabaseUtils.java:563)
I'm trying to connect Weka to MS SQL DB via a weka experiment retrieve instance query and getting the below error

One thing to note here is I do not have any default port assigned for the MS SQL DB instance and below is my Databaseutil.props file contents

```<code># database URL
jdbcURL=jdbc:sqlserver://MSSQL\SQLEXPRESS;databaseName=MovieDatabase
# specific data types
string, getString() = 0;
boolean, getBoolean() = 1;
double, getDouble() = 2;
byte, getByte() = 3;
short, getByte()= 4;
int, getInteger() = 5;
long, getLong() = 6;
float, getFloat() = 7;
date, getDate() = 8;
text, getString() = 9;
time, getTime() = 10;
timestamp, getTime() = 11;

# map SQL Server data type to WEKA data type
# default mappings
varchar=0
float=2
tinyint=3
int=5
# values added manually
string=0
bigint=6
nvarchar=9
decimal=2
bit=1
</code>```

Error:

sql.SQLException: Unable to find a suitable driver for jdbc:sqlserver://MSSQL\sqlexpress:1433;authentication=NotSpecified;authenticationScheme=nativeAuthentication;xopenStates=false;sendTimeAsDatetime=true;trustServerCertificate=false;TransparentNetworkIPResolution=true;serverNameAsACE=false;sendStringParametersAsUnicode=true;selectMethod=direct;responseBuffering=adaptive;packetSize=8000;multiSubnetFailover=false;loginTimeout=15;lockTimeout=-1;lastUpdateCount=true;encrypt=false;disableStatementPooling=true;databaseName=MovieDatabase;columnEncryptionSetting=Disabled;applicationName=Microsoft JDBC Driver for SQL Server;applicationIntent=readwrite;

     weka.experiment.DatabaseUtils.connectToDatabase(DatabaseUtils.java:563)

     weka.experiment.InstanceQuery.retrieveInstances(InstanceQuery.java:658)

答:
Try adding the jdbcDriver property to your DatabaseUtils.props file:</p>

```<code>jdbcDriver=com.microsoft.sqlserver.jdbc.SQLServerDriver
</code>```

Body:
I'm trying to connect Weka to MS SQL DB via a weka experiment retrieve instance query and getting the below error

One thing to note here is I do not have any default port assigned for the MS SQL DB instance and below is my Databaseutil.props file contents

# database URL
jdbcURL=jdbc:sqlserver://MSSQL\SQLEXPRESS;databaseName=MovieDatabase
# specific data types
string, getString() = 0;
boolean, getBoolean() = 1;
double, getDouble() = 2;
byte, getByte() = 3;
short, getByte()= 4;
int, getInteger() = 5;
long, getLong() = 6;
float, getFloat() = 7;
date, getDate() = 8;
text, getString() = 9;
time, getTime() = 10;
timestamp, getTime() = 11;

# map SQL Server data type to WEKA data type
# default mappings
varchar=0
float=2
tinyint=3
int=5
# values added manually
string=0
bigint=6
nvarchar=9
decimal=2
bit=1

Error:

sql.SQLException: Unable to find a suitable driver for jdbc:sqlserver://MSSQL\sqlexpress:1433;authentication=NotSpecified;authenticationScheme=nativeAuthentication;xopenStates=false;sendTimeAsDatetime=true;trustServerCertificate=false;TransparentNetworkIPResolution=true;serverNameAsACE=false;sendStringParametersAsUnicode=true;selectMethod=direct;responseBuffering=adaptive;packetSize=8000;multiSubnetFailover=false;loginTimeout=15;lockTimeout=-1;lastUpdateCount=true;encrypt=false;disableStatementPooling=true;databaseName=MovieDatabase;columnEncryptionSetting=Disabled;applicationName=Microsoft JDBC Driver for SQL Server;applicationIntent=readwrite;

     weka.experiment.DatabaseUtils.connectToDatabase(DatabaseUtils.java:563)

     weka.experiment.InstanceQuery.retrieveInstances(InstanceQuery.java:658)

Body:
Try adding the jdbcDriver property to your DatabaseUtils.props file:

jdbcDriver=com.microsoft.sqlserver.jdbc.SQLServerDriver


问:
Block cross-domain iframe console logging
I'm making a page that has multiple iFrames that show reports. The reports generate a ton of console output which contributes to the page taking up more memory.

I tried to do the workaround with

```<code>console.log = function() {}
</code>```

As well as a couple others I found, but none of them work. Majority of the errors are "Failed to load resource" and failed GET requests. I'm wondering if there's a way to maybe filter just those out.

Again the issue is that all the iFrames are cross domain and I have 0 access to the source.

答: Failed requests and other browser errors are logged by the browser internally, not through console.log. There is no way for your page to filter them out. If you don't want to see them, don't look at the console.

Body:
I'm making a page that has multiple iFrames that show reports. The reports generate a ton of console output which contributes to the page taking up more memory.

I tried to do the workaround with

console.log = function() {}

As well as a couple others I found, but none of them work. Majority of the errors are "Failed to load resource" and failed GET requests. I'm wondering if there's a way to maybe filter just those out.

Again the issue is that all the iFrames are cross domain and I have 0 access to the source.


问:
Use MSAL Auth token to consume Web API 2
I have an ASP.Net Web API 2 on which I implemented the following security:
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-devquickstarts-webapi-dotnet

It worked, I can't access the controllers except if I remove the [Authorize] attribute.

Now, I have a logged in user in a Xamarin app. The user is logged in via MSAL authentication which works fine too.
Very basic implementation :

```<code>var authenticationResult = await App.IdentityClientApp.AcquireTokenSilentAsync(App.ClientScope);
var token = authenticationResult.Token;
</code>```

Now, I want to access the web API by giving the MSAL authentication token in the DefaultRequestHeaders with something like this :

```<code>this.httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
</code>```

Is there anyway this is possible ? How can I use this token to make my user consume my web API ?

Thank you !

答:
The tutorial Help protect a web API by using bearer tokens from Azure AD you mentioned targets on AD v1.0 and you need to register your apps on Azure Portal. While MSAL targets on AD v2.0 and you need to register your app at apps.dev.microsoft.com, and you need to use the middleware in your Web API 2 as follows:

var tvps = new TokenValidationParameters
{
    ValidAudience = clientId,
    ValidateIssuer = false,
};

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
    AccessTokenFormat = new Microsoft.Owin.Security.Jwt.JwtFormat(tvps, new OpenIdConnectCachingSecurityTokenProvider("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration"))
});
```

For more details, you could refer to active-directory-v2-devquickstarts-dotnet-api.

Additionally, you could refer to AppModelv2-WebAPI-DotNet for code samples about the web api backend and the mobile client via MSAL accessing the web api backend.

Update:

I downloaded the code sample AppModelv2-WebAPI-DotNet

Follow How to register an app with the v2.0 endpoint for registering my app for v2.0 as follows:

Copy the Application Id from the above screenshot and update it to TodoListClient and TodoListService project as follows:

Launch TodoListService first, then you could debug TodoListService as follows:

Also, you could copy the Token and leverage postman to simulate the request as follows:

Body:
I have an ASP.Net Web API 2 on which I implemented the following security:
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-devquickstarts-webapi-dotnet

It worked, I can't access the controllers except if I remove the [Authorize] attribute.

Now, I have a logged in user in a Xamarin app. The user is logged in via MSAL authentication which works fine too.
Very basic implementation :

var authenticationResult = await App.IdentityClientApp.AcquireTokenSilentAsync(App.ClientScope);
var token = authenticationResult.Token;

Now, I want to access the web API by giving the MSAL authentication token in the DefaultRequestHeaders with something like this :

this.httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

Is there anyway this is possible ? How can I use this token to make my user consume my web API ?

Thank you !

Body:
The tutorial Help protect a web API by using bearer tokens from Azure AD you mentioned targets on AD v1.0 and you need to register your apps on Azure Portal. While MSAL targets on AD v2.0 and you need to register your app at apps.dev.microsoft.com, and you need to use the middleware in your Web API 2 as follows:

var tvps = new TokenValidationParameters
{
    ValidAudience = clientId,
    ValidateIssuer = false,
};

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
    AccessTokenFormat = new Microsoft.Owin.Security.Jwt.JwtFormat(tvps, new OpenIdConnectCachingSecurityTokenProvider("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration"))
});

For more details, you could refer to active-directory-v2-devquickstarts-dotnet-api.

Additionally, you could refer to AppModelv2-WebAPI-DotNet for code samples about the web api backend and the mobile client via MSAL accessing the web api backend.

Update:

I downloaded the code sample AppModelv2-WebAPI-DotNet

Follow How to register an app with the v2.0 endpoint for registering my app for v2.0 as follows:

Copy the Application Id from the above screenshot and update it to TodoListClient and TodoListService project as follows:

Launch TodoListService first, then you could debug TodoListService as follows:

Also, you could copy the Token and leverage postman to simulate the request as follows:


问:
In MySql, how to create a sequential set of values based on a record id where a specific related_id is available
What I am attempting to do is populate a value of 1, 2, 3, 4 based on the sequence of the primary key id, from low to high, where a repetitive value is present. Also, only doing this update based on a class value of 'jt'.

Example:

```<code>ID   abstract_id   class   jump_no
101   123           st        null
102   123           st        null
103   123           jt        1
104   123           jt        2
105   205           jt        1
106   205           jt        2
107   205           jt        3
108   391           st        null
</code>```

Currently my table has all null value for the jump_no column. I am trying to populate that sequence, per abstract_id grouping but only with a class value of 'jt'.
So the 1, 2, 3, 4 "counter" restarts for every new abstract_id.

答:
There are a couple ways to do this.  One uses correlated subqueries.  Another that I use more often uses user-defined variables:

```<code>update yourtable y
join (
    select id, abstract_id,
       case abstract_id
                when @prev_abstract_id
                then @jump_no := @jump_no + 1
                else @jump_no := 1 AND @prev_abstract_id := abstract_id end jump_no
    from yourtable join (select @jump_no:=0, @prev_abstract_id:=0) t
    order by id, abstract_id) t on y.id = t.id
set y.jump_no = t.jump_no;
</code>```

Online SQL Example

Body:
What I am attempting to do is populate a value of 1, 2, 3, 4 based on the sequence of the primary key id, from low to high, where a repetitive value is present. Also, only doing this update based on a class value of 'jt'.

Example:

ID   abstract_id   class   jump_no
101   123           st        null
102   123           st        null
103   123           jt        1
104   123           jt        2
105   205           jt        1
106   205           jt        2
107   205           jt        3
108   391           st        null

Currently my table has all null value for the jump_no column. I am trying to populate that sequence, per abstract_id grouping but only with a class value of 'jt'.
So the 1, 2, 3, 4 "counter" restarts for every new abstract_id.

Body:
There are a couple ways to do this.  One uses correlated subqueries.  Another that I use more often uses user-defined variables:

update yourtable y
join (
    select id, abstract_id,
       case abstract_id
                when @prev_abstract_id
                then @jump_no := @jump_no + 1
                else @jump_no := 1 AND @prev_abstract_id := abstract_id end jump_no
    from yourtable join (select @jump_no:=0, @prev_abstract_id:=0) t
    order by id, abstract_id) t on y.id = t.id
set y.jump_no = t.jump_no;

Online SQL Example


问:
php/sql- How do I use LIKE operator on variable to pull results from database?
As question said, I want to use the LIKE Operator so whenever user inputs something, like "M", it returns all database entries starting with "m" rather then anything named just "M". This is my code

```<code>$strSymbolName = @$_REQUEST["searchSymbol"];
//searchSymbol is the variable with user Input inside

if(!empty($strSymbolName))
{ // process the form
 // Establish dbserver connection and default database

$db = $objDBUtil->Open();
 // Run a Query to get company name

$query = "SELECT symSymbol, symName FROM symbols " .
 "WHERE symSymbol =" . $objDBUtil->DBQuotes($strSymbolName);
//Retrieves company symbol and name from database. Stores this in result

$result = $db->query($query);`
</code>```

What I thought of doing was using the LIKE operator on the WHERE statement, so something like-

```<code>WHERE symSymbol LIKE = " . $objDBUtil->DBQuotes($strSymbolName);
</code>```

But this didn't work...How would I apply the LIKE operator here?

答:
You need to append the % on the end of your variable like:

```<code>WHERE symSymbol LIKE " . $objDBUtil->DBQuotes($strSymbolName) . "%";
</code>```

This will return anything starting with your variable.

Body:
As question said, I want to use the LIKE Operator so whenever user inputs something, like "M", it returns all database entries starting with "m" rather then anything named just "M". This is my code

$strSymbolName = @$_REQUEST["searchSymbol"];
//searchSymbol is the variable with user Input inside

if(!empty($strSymbolName))
{ // process the form
 // Establish dbserver connection and default database

$db = $objDBUtil->Open();
 // Run a Query to get company name

$query = "SELECT symSymbol, symName FROM symbols " .
 "WHERE symSymbol =" . $objDBUtil->DBQuotes($strSymbolName);
//Retrieves company symbol and name from database. Stores this in result

$result = $db->query($query);`

What I thought of doing was using the LIKE operator on the WHERE statement, so something like-

WHERE symSymbol LIKE = " . $objDBUtil->DBQuotes($strSymbolName);

But this didn't work...How would I apply the LIKE operator here?

Body:
You need to append the % on the end of your variable like:

WHERE symSymbol LIKE " . $objDBUtil->DBQuotes($strSymbolName) . "%";

This will return anything starting with your variable.


问:
A set of mouse/keyboard actions Java program
I want to build a program that does the following:

User clicks on a button (like on a GUI) to record his/hers movements.
Then, the user does a set of actions on the computer - this could be clicking on file explorer and deleting/creating/renaming a file, opening Chrome or another program etc... basically a few keyboard/mouse movements.

Then the user can specify a time at which the program should replicate this recording of movements. (The program hasn't been stopped and it uses the current time of the computer's clock to know when to do it)

Can I do something like this in Java? Searched quite a bit and couldn't see something relevant. The only thing that came to my mind since I am still a beginner is MouseEvents etc but I don't think these can be done outside the frames of GUI.

Thanks in advance I am keen to build this project!

答:
JNativeHook is worth looking into for this and similar purposes. I found it helpful.

https://github.com/kwhat/jnativehook


问:
Visual Studio 2017 open tab in new Window
How does one open a current tab as a new window while using a shortcut in Visual Studio(2017)?

I know an open tab can be dragged out of the IDE and be kept as it's own window, but a shortcut for this action could be quite handy.

答: You can assign a keyboard shortcut to the Window.Float command to open a current tab as a new window.


问:
Accessing a class' member variable from another class
Consider this example:

```<code>public class FirstClass {
    public static int x;

   public static void main(String[] args){
     x = 5;
     SecondClass sc = new SecondClass();
   }

   public int getX(){
     return x;
   }

}
//assume class SecondClass is in another File
public class SecondClass{}
</code>```

I want to access variable x from class SecondClass and as far as I know there are two ways I can do this.

In SecondClass class I can simply do FirstClass.x ---> do stuff. IntelliJ allows me to do this since x has public visibility.

I make the constructor of SecondClass take a FirstClass fc as a parameter and then do this.fc = fc;  while having declared it as a member variable after class declaration. Then, in the main I change the instance of SecondClass to  SecondClass sc = new SecondClass(this);  And now I can have access in SecondClass through fc.getX();

What is the difference between the two as I have never seen an explanation in this scenario ?

Apologies if my example is not abstract enough but I tried to make it as much as possible.

Thanks in advance.

答:
You can access variable x from Second Class by FirstClass.x because I think you have declared x as static. Otherwise, you cannot access like that. Then you have to create an object of First Class then you have to access that variable x.

Don't pass the class in the constructor of Second Class. Just pass the variable x. This will be better. If we pass the class then we can do so many things from Second Class. For that reason, we will provide those data which are needed in Second Class.

SecondClass sc = new SecondClass(x);

Body:
Consider this example:

public class FirstClass {
    public static int x;

   public static void main(String[] args){
     x = 5;
     SecondClass sc = new SecondClass();
   }

   public int getX(){
     return x;
   }

}
//assume class SecondClass is in another File
public class SecondClass{}

I want to access variable x from class SecondClass and as far as I know there are two ways I can do this.

In SecondClass class I can simply do FirstClass.x ---> do stuff. IntelliJ allows me to do this since x has public visibility.

I make the constructor of SecondClass take a FirstClass fc as a parameter and then do this.fc = fc;  while having declared it as a member variable after class declaration. Then, in the main I change the instance of SecondClass to  SecondClass sc = new SecondClass(this);  And now I can have access in SecondClass through fc.getX();

What is the difference between the two as I have never seen an explanation in this scenario ?

Apologies if my example is not abstract enough but I tried to make it as much as possible.

Thanks in advance.


问:
Is Swift 3.2 production ready?
Apple recently released Xcode 9, which ships with a Swift 3.2/4 compiler. Swift 3.2 includes numerous features (such as support for where constraints on associated types), while still being a member of the Swift 3 family. So, my question is:

Is Swift 3.2 production ready? Can I write and deploy apps to the App Store using Xcode 9 beta?

答: You currently cannot deploy to the App Store, it will take some time and upcoming Xcode betas until that's possible. In the last years we didn't need the GM to upload to the App Store, but the first Xcode Betas didn't let you do that.</p>

Title: Is Swift 3.2 production ready?


问:
How do I get a Bootstrap 4 nav to appear on the same line as a header?
Here you can see what it looks like right now.

What it looks like now

How do I get the nav to appear on the right side of the screen while making it be on the same line as the copyright? I cannot seem to get anything to work that I have seen on here so far.

Here is my current code:

```<code><div class="container-fluid footer">
    <div class="spacer"></div>
    <div class="container">
        <h5 style="display: inline">Copyright © 2017 Custom Prop Shop</h5>
        <ul class="nav flex-column flex-sm-row justify-content-end pull-right">
            <li class="nav-item">
                <a class="nav-link" href="request-estimate.html">Request an Estimate</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="our-work.html">Our Work</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="our-clients.html">Our Clients</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="our-story.html">Our Story</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="contact.html">Contact</a>
            </li>
        </ul>
    </div>
    <div class="spacer"></div>
</div>
</code>```

CSS is only controlling color of the text/background and the font-size for this part.

答:
I think the easiest way would be to make the container d-flex, and then use my-auto to vertically center the h5...

```<code><div class="container d-flex justify-content-between">
        <h5 class="my-auto">Copyright © 2017 Custom Prop Shop</h5>
        <ul class="nav flex-column flex-sm-row">..</ul>
</div>
</code>```

https://www.codeply.com/go/1WWhy3uP9C

Body:
Here you can see what it looks like right now.

What it looks like now

How do I get the nav to appear on the right side of the screen while making it be on the same line as the copyright? I cannot seem to get anything to work that I have seen on here so far.

Here is my current code:

Copyright © 2017 Custom Prop Shop

                Request an Estimate

                Our Work

                Our Clients

                Our Story

                Contact

CSS is only controlling color of the text/background and the font-size for this part.

Body:
I think the easiest way would be to make the container d-flex, and then use my-auto to vertically center the h5...

<div class="container d-flex justify-content-between">
        <h5 class="my-auto">Copyright © 2017 Custom Prop Shop</h5>
        <ul class="nav flex-column flex-sm-row">..</ul>
</div>

https://www.codeply.com/go/1WWhy3uP9C


问:
How do I return a unsure type?
I have a parent Class named 'Shape' and write a method in it
I want any class extends from it can call the bigger method for other use.
simple logic like this:

```<code>public abstract Class Shape{
    public int size;
    public Shape() {}
    public Class<? extends Shape> bigger() {
        this.size += 1;
        return this; // ← Here,How can I return it with unsure type?
    }
}
</code>```

but how can I return a unsure type in here ?
thanks for any ideas!

====

and if I have a class Square extends Shape;

and I want use it like this:

```<code>Square S = new Square().bigger();
</code>```

And it will return a Shape Class, not a Square Class.

but I don't wanna use: (Square) new Square.bigger();

I hope it can automatic recognize what Class a using this method

And return the correct type.

答:
You can override bigger() method which returns Square (not Shape).
It is regal.

```<code>public abstract class Shape {
    public int size;
    public Shape() {}
    public Shape bigger() {
        this.size += 1;
        return this; // ← Here,How can I return it with unsure type?
    }
}

public class Square extends Shape {
    @Override
    public Square bigger() { // returns Square, not Shape
        return this;
    }
}
</code>```

Title: How do I return a unsure type?

Body:
I have a parent Class named 'Shape' and write a method in it
I want any class extends from it can call the bigger method for other use.
simple logic like this:

public abstract Class Shape{
    public int size;
    public Shape() {}
    public Class<? extends Shape> bigger() {
        this.size += 1;
        return this; // ← Here,How can I return it with unsure type?
    }
}

but how can I return a unsure type in here ?
thanks for any ideas!

====

and if I have a class Square extends Shape;

and I want use it like this:

Square S = new Square().bigger();

And it will return a Shape Class, not a Square Class.

but I don't wanna use: (Square) new Square.bigger();

I hope it can automatic recognize what Class a using this method

And return the correct type.

Body:
You can override bigger() method which returns Square (not Shape).
It is regal.

public abstract class Shape {
    public int size;
    public Shape() {}
    public Shape bigger() {
        this.size += 1;
        return this; // ← Here,How can I return it with unsure type?
    }
}

public class Square extends Shape {
    @Override
    public Square bigger() { // returns Square, not Shape
        return this;
    }
}


问:
Coffeescript compilation error in ruby on rails
I am using coffeescript+ruby-on-rails. The compilation of coffeescript into pure JS leads to an error if there is a syntax problem in the coffee code. On the browser when I run the app, I get this error: ExecJS::RuntimeError

Is there any way to find out what caused the compilation error, when it was trying to compile coffee code to JS?
Attached is a screenshot of the error

Following is the entry in the server log, which no way indicates the file which actually caused the syntax error:

```<code>ActionView::Template::Error (SyntaxError: [stdin]:25:10: unexpected :):
    4:     <meta name="viewport" content="width=device-width, initial-scale=1.0">
    5:     <title><%= content_for?(:title) ? yield(:title) : "Inmonarch Website" %></title>
    6:     <meta name="description" content="<%= content_for?(:description) ? yield(:description) : "Inmonarch Website" %>">
    7:     <%= stylesheet_link_tag 'application', media: 'all' %>
    8:     <%= javascript_include_tag 'application' %>
    9:     <%= csrf_meta_tags %>
   10:   </head>
  app/views/layouts/dashboard.html.erb:7:in `_app_views_layouts_dashboard_html_erb__3120053487817944018_56303120'

  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_source.erb (7.4ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (3.0ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.6ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb within rescues/layout (25.5ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/web-console-2.3.0/lib/web_console/templates/_markup.html.erb (0.3ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/web-console-2.3.0/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.3ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/web-console-2.3.0/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.3ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/web-console-2.3.0/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.3ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/web-console-2.3.0/lib/web_console/templates/console.js.erb within layouts/javascript (296.8ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/web-console-2.3.0/lib/web_console/templates/main.js.erb within layouts/javascript (0.2ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/web-console-2.3.0/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.3ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/web-console-2.3.0/lib/web_console/templates/index.html.erb (313.8ms)
</code>```

PS:- I know what the syntax error is, I made the syntax error deliberately to find out if I am able to trace the error with the help of logs, which I couldn't.

答: You can use an online linter like http://www.coffeelint.org/ if you know its coffeescript causing the error</p>

Body:
I am using coffeescript+ruby-on-rails. The compilation of coffeescript into pure JS leads to an error if there is a syntax problem in the coffee code. On the browser when I run the app, I get this error: ExecJS::RuntimeError

Is there any way to find out what caused the compilation error, when it was trying to compile coffee code to JS?
Attached is a screenshot of the error

Following is the entry in the server log, which no way indicates the file which actually caused the syntax error:

ActionView::Template::Error (SyntaxError: [stdin]:25:10: unexpected :):
    4:     <meta name="viewport" content="width=device-width, initial-scale=1.0">
    5:     <title><%= content_for?(:title) ? yield(:title) : "Inmonarch Website" %></title>
    6:     <meta name="description" content="<%= content_for?(:description) ? yield(:description) : "Inmonarch Website" %>">
    7:     <%= stylesheet_link_tag 'application', media: 'all' %>
    8:     <%= javascript_include_tag 'application' %>
    9:     <%= csrf_meta_tags %>
   10:
  app/views/layouts/dashboard.html.erb:7:in `_app_views_layouts_dashboard_html_erb__3120053487817944018_56303120'

  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_source.erb (7.4ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (3.0ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.6ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb within rescues/layout (25.5ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/web-console-2.3.0/lib/web_console/templates/_markup.html.erb (0.3ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/web-console-2.3.0/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.3ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/web-console-2.3.0/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.3ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/web-console-2.3.0/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.3ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/web-console-2.3.0/lib/web_console/templates/console.js.erb within layouts/javascript (296.8ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/web-console-2.3.0/lib/web_console/templates/main.js.erb within layouts/javascript (0.2ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/web-console-2.3.0/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.3ms)
  Rendered /home/vipin8169/.rvm/gems/ruby-2.2.3@rails426/gems/web-console-2.3.0/lib/web_console/templates/index.html.erb (313.8ms)

PS:- I know what the syntax error is, I made the syntax error deliberately to find out if I am able to trace the error with the help of logs, which I couldn't.


问:
jQuery File Type Input Plugin needed
I am looking to customize the input type  file to a custom browse button. does anyone know of any good plugins i could use of ?</p>

答:
That is not possible due to browser security. You have to use the input element with the type file. I think you can put and image on top of the browser button to customize it as long you make sure that the click event is past to the file input.

Because of browser security you can not access the clients file system with anything other as the file input element. You never get the file structure with a script language such as javascript. Not even when you check the value attribute with for example javascript. The value attribute will only return the filename not the path.

You could try to use Uploadify jquery plugin to customize the button. But that will work with a flash file if I remember correct.

Edit: Yes checked it. It is possible with Uploadify. There is an option buttonImg you can use.

```<code>$(document).ready(function() {
  $('#file_upload').uploadify({
    'uploader'  : '/uploadify/uploadify.swf',
    'script'    : '/uploadify/uploadify.php',
    'cancelImg' : '/uploadify/cancel.png',
    'folder'    : '/uploads',
    'buttonImg' : '/img/inputbutton.png',
    'auto'      : true
  });
});
</code>```

Title: jQuery File Type Input Plugin needed

Body:
That is not possible due to browser security. You have to use the input element with the type file. I think you can put and image on top of the browser button to customize it as long you make sure that the click event is past to the file input.

Because of browser security you can not access the clients file system with anything other as the file input element. You never get the file structure with a script language such as javascript. Not even when you check the value attribute with for example javascript. The value attribute will only return the filename not the path.

You could try to use Uploadify jquery plugin to customize the button. But that will work with a flash file if I remember correct.

Edit: Yes checked it. It is possible with Uploadify. There is an option buttonImg you can use.

$(document).ready(function() {
  $('#file_upload').uploadify({
    'uploader'  : '/uploadify/uploadify.swf',
    'script'    : '/uploadify/uploadify.php',
    'cancelImg' : '/uploadify/cancel.png',
    'folder'    : '/uploads',
    'buttonImg' : '/img/inputbutton.png',
    'auto'      : true
  });
});


问:
"expected'; ',' or 'or') 'before' * 'token" error when using structure
all

I have a few problems with using structures.

The source is shown below.

main.c

#include <stdio.h>
#include "info.h"

_Rbuffer Rb;

void write(_Rbuffer Rb *rb)
{
    printf("write function\n");
}

void main(void)
{

    printf("Hello World\n");

}
```

<h2>info.h</h2>

<pre class="lang-c prettyprint-override"><code>#include <stdint.h>

typedef struct
{
    uint8_t Button1;
} _Rbuffer;

extern _Rbuffer Rb;
</code>```

When compiling, the following error occurs.

```<code>root@test-VirtualBox:~/sample# gcc main.c
main.c:6:24: error: expected ‘;’, ‘,’ or ‘)’ before ‘*’ token
 void write(_Rbuffer Rb *rb)
                        ^
root@test-VirtualBox:~/sample#
</code>```

I am currently unable to change info.h.

I declare a structure and I do not know why an error occurs.

How do I fix this?

答:
1 You should use int main instead of void main .

2 You should use void write(_Rbuffer *rb) instead of void write(_Rbuffer Rb *rb) .

Body:
all

I have a few problems with using structures.

The source is shown below.

main.c

#include <stdio.h>
#include "info.h"

_Rbuffer Rb;

void write(_Rbuffer Rb *rb)
{
    printf("write function\n");
}

void main(void)
{

    printf("Hello World\n");

}

info.h

#include <stdint.h>

typedef struct
{
    uint8_t Button1;
} _Rbuffer;

extern _Rbuffer Rb;

When compiling, the following error occurs.

root@test-VirtualBox:~/sample# gcc main.c
main.c:6:24: error: expected ‘;’, ‘,’ or ‘)’ before ‘*’ token
 void write(_Rbuffer Rb *rb)
                        ^
root@test-VirtualBox:~/sample#

I am currently unable to change info.h.

I declare a structure and I do not know why an error occurs.

How do I fix this?


问:
VBA vlookup for value in a string and inverse
These are columns A, B and C in an excel sheet.

If the middle account number in column A is >=40000 and <60000 Then the Actual Amount is value should multiply by -1. What VB code does this?

```<code>Account Number    Account Description      Actual Amount

10-40100-400    Contributions - Support    ($12,843.63)
10-53450-400    Rental Income              ($9,584.60)
10-53500-400    Housing Income             ($67,933.38)
10-54900-400    Miscellanous Revenue       ($2,615.56)
10-72100-400    Salary and Wages            $43,378.11
10-72100-420    Salary and Wages            $607.91
10-72400-400    Health Insurance            $14,843.94
10-72440-400    Life Insurance              $286.62
10-72500-400    FICA Expense                $3,283.73
10-72500-420    FICA Expense                $46.50
10-75400-400    Professional Services       $9,392.28
10-81100-400    Office Supplies             $3,754.16
10-81300-400    Telephone                   $540.00
10-82110-400    Furnishings and Equipment   $6,186.20
10-82140-400    Maintenance & Repair-Equi   $4,658.21
10-82160-400    Maintenance & Repair-Buil   $13,576.61
10-82200-400    Utilities                   $35,467.33
10-82600-400    Vehicle Expenses            $196.18
10-83100-400    Meals and Entertainment     $10.83
10-83140-400    Travel                      $34.84
10-85240-400    Prop/Casualty Insurance     $22,535.60
10-85260-400    Auto Insurance              $691.47
10-85300-400    Dues and Subscriptions      $145.00
10-85980-400    Miscellaneous Expense      ($45.00)
10-86500-400    Permits and Licenses        $1,010.00
10-99150-400    Ministry Grant Transfers    $32,249.97
10-99200-400    Ministry Transfers         ($8,992.44)
20-72100-400    Salary and Wages            $0.00
Totals for 71500:                           $0.00

Grand Totals:                               $0.00
</code>```

I have tried copying column A into column D and then trimming it to the number.

Then use an if statement to do the inverse.

```<code>lastrow = Cells(Rows.Count, 2).End(xlUp).Row
Range("A15:A" & lastrow).Copy Range("D15")
Dim rng As Range
Dim rngsear As Range
Set rng = Range("D15:D" & lastrow)
For Each rng In Selection
rng = Mid(rng, 4, 5)
Next rng
With ActiveSheet
     lastrow = .Range("D" & .Rows.Count).End(xlUp).Row
     Set rng = .Range("D15:D" & lastrow)
     Set rngsear = .Range("C15:C" & lastrow)
     rngsear.Value = .Evaluate("IF((" & rng.Address & " >= 40000)*(" & rng.Address & " < 60000)," & rngsear.Address & " * -1," & rngsear.Address & ")")
End With
</code>```

But it conflicts with the previous code I used to get the 3 columns.

```<code>Dim sSheetName As String
Dim sDataRange As String
sSheetName = ActiveSheet.Name
sDataRange = Selection.Address
Range("C9:F9").Select
Selection.Cut Destination:=Range("D9:G9")
Range("C:C,D:D,F:F,G:G").Select
Range("G1").Activate
Selection.Delete Shift:=xlToLeft
    Dim lastrow As Long
lastrow = Cells(Rows.Count, 2).End(xlUp).Row
Range("A15:C" & lastrow).Sort key1:=Range("A15:A" & lastrow), _
order1:=xlAscending, Header:=xlNo
</code>```

Whats the best method to do this?

答:
Use Mid to get the 5 digit account number from the value in column A and use Val to convert it to a number. Then you can do the >=40000 And <=60000 check and multiply the balance by -1 if required. Once you know the balance you can simply set the value of column D.

```<code>Option Explicit

Sub ConvertBalance()
    Dim ws As Worksheet
    Dim lngLastRow As Long
    Dim lngRow As Long
    Dim lngAccountNumber As Long
    Dim lngBalance As Long

    Set ws = ThisWorkbook.Worksheets("Sheet1") '<-- change to your worksheet
    lngLastRow = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row

    For lngRow = 2 To lngLastRow '<-- change start row if you need to
        lngAccountNumber = Val(Mid(ws.Cells(lngRow, 1).Value, 4, 5))
        lngBalance = ws.Cells(lngRow, 3).Value
        If lngAccountNumber >= 40000 And lngAccountNumber <= 60000 Then
            lngBalance = lngBalance * -1
        End If
        ws.Cells(lngRow, 4) = lngBalance
    Next lngRow

End Sub
</code>```

If you just want to use a formula in column D inserted with VBA you can use this formula:

```<code>=C2*IF(AND(VALUE(MID(A2,4,5))>=40000,VALUE(MID(A2,4,5))<=60000),-1,1)
</code>```

And in the code it is:

Option Explicit

```<code>Sub ConvertBalance2()
    Dim ws As Worksheet
    Dim lngLastRow As Long

    Set ws = ThisWorkbook.Worksheets("Sheet1") '<-- change to your worksheet
    lngLastRow = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row

    With ws.Range("D2:D" & lngLastRow)
        .Formula = "=C2*IF(AND(VALUE(MID(A2,4,5))>=40000,VALUE(MID(A2,4,5))<=60000),-1,1)"
    End With

End Sub
</code>```

Body:
These are columns A, B and C in an excel sheet.

If the middle account number in column A is >=40000 and <60000 Then the Actual Amount is value should multiply by -1. What VB code does this?

Account Number    Account Description      Actual Amount

10-40100-400    Contributions - Support    ($12,843.63)
10-53450-400    Rental Income              ($9,584.60)
10-53500-400    Housing Income             ($67,933.38)
10-54900-400    Miscellanous Revenue       ($2,615.56)
10-72100-400    Salary and Wages            $43,378.11
10-72100-420    Salary and Wages            $607.91
10-72400-400    Health Insurance            $14,843.94
10-72440-400    Life Insurance              $286.62
10-72500-400    FICA Expense                $3,283.73
10-72500-420    FICA Expense                $46.50
10-75400-400    Professional Services       $9,392.28
10-81100-400    Office Supplies             $3,754.16
10-81300-400    Telephone                   $540.00
10-82110-400    Furnishings and Equipment   $6,186.20
10-82140-400    Maintenance & Repair-Equi   $4,658.21
10-82160-400    Maintenance & Repair-Buil   $13,576.61
10-82200-400    Utilities                   $35,467.33
10-82600-400    Vehicle Expenses            $196.18
10-83100-400    Meals and Entertainment     $10.83
10-83140-400    Travel                      $34.84
10-85240-400    Prop/Casualty Insurance     $22,535.60
10-85260-400    Auto Insurance              $691.47
10-85300-400    Dues and Subscriptions      $145.00
10-85980-400    Miscellaneous Expense      ($45.00)
10-86500-400    Permits and Licenses        $1,010.00
10-99150-400    Ministry Grant Transfers    $32,249.97
10-99200-400    Ministry Transfers         ($8,992.44)
20-72100-400    Salary and Wages            $0.00
Totals for 71500:                           $0.00

Grand Totals:                               $0.00

I have tried copying column A into column D and then trimming it to the number.

Then use an if statement to do the inverse.

lastrow = Cells(Rows.Count, 2).End(xlUp).Row
Range("A15:A" & lastrow).Copy Range("D15")
Dim rng As Range
Dim rngsear As Range
Set rng = Range("D15:D" & lastrow)
For Each rng In Selection
rng = Mid(rng, 4, 5)
Next rng
With ActiveSheet
     lastrow = .Range("D" & .Rows.Count).End(xlUp).Row
     Set rng = .Range("D15:D" & lastrow)
     Set rngsear = .Range("C15:C" & lastrow)
     rngsear.Value = .Evaluate("IF((" & rng.Address & " >= 40000)*(" & rng.Address & " < 60000)," & rngsear.Address & " * -1," & rngsear.Address & ")")
End With

But it conflicts with the previous code I used to get the 3 columns.

Dim sSheetName As String
Dim sDataRange As String
sSheetName = ActiveSheet.Name
sDataRange = Selection.Address
Range("C9:F9").Select
Selection.Cut Destination:=Range("D9:G9")
Range("C:C,D:D,F:F,G:G").Select
Range("G1").Activate
Selection.Delete Shift:=xlToLeft
    Dim lastrow As Long
lastrow = Cells(Rows.Count, 2).End(xlUp).Row
Range("A15:C" & lastrow).Sort key1:=Range("A15:A" & lastrow), _
order1:=xlAscending, Header:=xlNo

Whats the best method to do this?

Body:
Use Mid to get the 5 digit account number from the value in column A and use Val to convert it to a number. Then you can do the >=40000 And <=60000 check and multiply the balance by -1 if required. Once you know the balance you can simply set the value of column D.

Option Explicit

Sub ConvertBalance()
    Dim ws As Worksheet
    Dim lngLastRow As Long
    Dim lngRow As Long
    Dim lngAccountNumber As Long
    Dim lngBalance As Long

    Set ws = ThisWorkbook.Worksheets("Sheet1") '<-- change to your worksheet
    lngLastRow = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row

    For lngRow = 2 To lngLastRow '<-- change start row if you need to
        lngAccountNumber = Val(Mid(ws.Cells(lngRow, 1).Value, 4, 5))
        lngBalance = ws.Cells(lngRow, 3).Value
        If lngAccountNumber >= 40000 And lngAccountNumber <= 60000 Then
            lngBalance = lngBalance * -1
        End If
        ws.Cells(lngRow, 4) = lngBalance
    Next lngRow

End Sub

If you just want to use a formula in column D inserted with VBA you can use this formula:

=C2*IF(AND(VALUE(MID(A2,4,5))>=40000,VALUE(MID(A2,4,5))<=60000),-1,1)

And in the code it is:

Option Explicit

Sub ConvertBalance2()
    Dim ws As Worksheet
    Dim lngLastRow As Long

    Set ws = ThisWorkbook.Worksheets("Sheet1") '<-- change to your worksheet
    lngLastRow = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row

    With ws.Range("D2:D" & lngLastRow)
        .Formula = "=C2*IF(AND(VALUE(MID(A2,4,5))>=40000,VALUE(MID(A2,4,5))<=60000),-1,1)"
    End With

End Sub


问:
Wrapper over Graphics APIs
I'm a huge fan of having a game engine that has the abilty to adapt, not just in what it can do, but also in how it can handle new code. Recently, for my graphics subsystem, I wrote a class to be overriden that works like this:

```<code>class LowLevelGraphicsInterface {
    virtual bool setRenderTarget(const RenderTarget* renderTarget) = 0;
    virtual bool setStreamSource(const VertexBuffer* vertexBuffer) = 0;
    virtual bool setShader(const Shader* shader) = 0;
    virtual bool draw(void) = 0;

    //etc.
};
</code>```

My idea was to create a list of functions that are universal among most graphics APIs. Then for DirectX11 I would just create a new child class:

```<code>class LGI_DX11 : public LowLevelGraphicsInterface {
    virtual bool setRenderTarget(const RenderTarget* renderTarget);
    virtual bool setStreamSource(const VertexBuffer* vertexBuffer);
    virtual bool setShader(const Shader* shader);
    virtual bool draw(void);

    //etc.
};
</code>```

Each of these functions would then interface with DX11 directly. I do realize that there is a layer of indirection here. Are people turned off by this fact?

Is this a widely used method? Is there something else I could/should be doing? There is the option of using the preprocessor but that seems messy to me. Someone also mentioned templates to me. What do you guys think?

答:
So, I realize that this is an old question, but I can't resist chiming in. Wanting to write code like this is just a side effect of trying to cope with object-oriented indoctrination.

The first question is whether or not you really need to swap out rendering back-ends, or just think it's cool. If an appropriate back-end can be determined at build time for a given platform, then problem solved: use a plain, non-virtual interface with an implementation selected at build time.

If you find that you really do need to swap it out, still use a non-virtual interface, just load the implementations as shared libraries. With this kind of swapping, you will likely want both engine rendering code and some performance intensive game-specific rendering code factored out and swappable. That way, you can use the common, high-level engine rendering interface for things done mostly by the engine, while still having access to back-end specific code to avoid the conversion costs mentioned by PMF.

Now, it should be said that while swapping with shared libraries introduces indirection, 1. You can easily get the indirection to be < to ~= that of virtual calls and 2. This high-level indirection is never a performance concern in any substantial game/engine. The main benefit is keeping dead code unloaded (and out of the way) and simplifying APIs and overall project design, increasing readability and comprehension.

Beginners aren't typically aware of this, because there is so much blind OO pushing these days, but this style of "OO first, ask questions never" is not without cost. This kind of design has a taxing code comprehension cost and leads to code (much lower-level than this example) that is inherently slow. Object orientation has its place, certainly, but (in games and other performance intensive applications) the best way to design that I have found is to write applications as minimally OO as possible, only conceding when a problem forces your hand. You will develop an intuition for where to draw the line as you gain more experience.

Title: Wrapper over Graphics APIs

Body:
I'm a huge fan of having a game engine that has the abilty to adapt, not just in what it can do, but also in how it can handle new code. Recently, for my graphics subsystem, I wrote a class to be overriden that works like this:

class LowLevelGraphicsInterface {
    virtual bool setRenderTarget(const RenderTarget* renderTarget) = 0;
    virtual bool setStreamSource(const VertexBuffer* vertexBuffer) = 0;
    virtual bool setShader(const Shader* shader) = 0;
    virtual bool draw(void) = 0;

    //etc.
};

My idea was to create a list of functions that are universal among most graphics APIs. Then for DirectX11 I would just create a new child class:

class LGI_DX11 : public LowLevelGraphicsInterface {
    virtual bool setRenderTarget(const RenderTarget* renderTarget);
    virtual bool setStreamSource(const VertexBuffer* vertexBuffer);
    virtual bool setShader(const Shader* shader);
    virtual bool draw(void);

    //etc.
};

Each of these functions would then interface with DX11 directly. I do realize that there is a layer of indirection here. Are people turned off by this fact?

Is this a widely used method? Is there something else I could/should be doing? There is the option of using the preprocessor but that seems messy to me. Someone also mentioned templates to me. What do you guys think?


答:
If you want to search something that starts with "M", add a % after the value, and remove the = as it is not needed when using LIKE

```<code>$query = "SELECT symSymbol, symName FROM symbols WHERE symSymbol LIKE ".$objDBUtil->DBQuotes($strSymbolName)."%";
</code>```

For more information about LIKE, check here.

WHERE CustomerName LIKE 'a%'        || Finds any values that starts with "a"

WHERE CustomerName LIKE '%a'        || Finds any values that ends with "a"

WHERE CustomerName LIKE '%or%'    || Finds any values that have "or" in any position

WHERE CustomerName LIKE '_r%'       || Finds any values that have "r" in the second position

WHERE CustomerName LIKE 'a_%_%' || Finds any values that starts with "a" and are at least 3 characters in length

WHERE ContactName LIKE 'a%o'          || Finds any values that starts with "a" and ends with "o"

Title: php/sql- How do I use LIKE operator on variable to pull results from database?

Body:
If you want to search something that starts with "M", add a % after the value, and remove the = as it is not needed when using LIKE

$query = "SELECT symSymbol, symName FROM symbols WHERE symSymbol LIKE ".$objDBUtil->DBQuotes($strSymbolName)."%";

For more information about LIKE, check here.

WHERE CustomerName LIKE 'a%'        || Finds any values that starts with "a"

WHERE CustomerName LIKE '%a'        || Finds any values that ends with "a"

WHERE CustomerName LIKE '%or%'    || Finds any values that have "or" in any position

WHERE CustomerName LIKE '_r%'       || Finds any values that have "r" in the second position

WHERE CustomerName LIKE 'a_%_%' || Finds any values that starts with "a" and are at least 3 characters in length

WHERE ContactName LIKE 'a%o'          || Finds any values that starts with "a" and ends with "o"


问:
Can you replicate a specific database or table using Amazon's RDS
We are using Amazon RDS and we have a MASTER replicating to a SLAVE.

We want to create a new slave that will only replicate specific databases or tables from the master.

By default RDS simply just replicates the entire master's databases over to the slave's.  But we only want to do specific tables.  I know this is possible in MySQL in general, but I'm not sure about RDS and I can't find an answer anywhere.

These settings exists in MySQL, I do not see them on the custom parameter settings for RDS unless I'm missing something.

```<code>--replicate-ignore-db=db_name
--replicate-ignore-table=db_name.tbl_name
</code>```

答:
My answer is now stale. I recommend reading the other answers that confirm it as possible.

As Kat said, no, they don't provide that feature.

I don't expect it either, since we could use it to break their as-a-service encapsulation, which requires certain tables to replicate for primary features to work.

A work-around that I'm considering, is to create an EC2 based MySQL instance in between the master and the slave in the replication chain (using the external replication feature), with those filters applied, and the black-hole engine pre-set for all tables, just to keep things easy.

One bonus advantage, is that the RDS slave has less binary log data to parse, since it's pre-filtered.

Body:
We are using Amazon RDS and we have a MASTER replicating to a SLAVE.

We want to create a new slave that will only replicate specific databases or tables from the master.

By default RDS simply just replicates the entire master's databases over to the slave's.  But we only want to do specific tables.  I know this is possible in MySQL in general, but I'm not sure about RDS and I can't find an answer anywhere.

These settings exists in MySQL, I do not see them on the custom parameter settings for RDS unless I'm missing something.

--replicate-ignore-db=db_name
--replicate-ignore-table=db_name.tbl_name

ContentLicense: CC BY-SA 4.0


问:
How can I rotate log files monthly using Perl?
In Unix, I need to be able to archive log files into monthly folders, labelled accordingly. How do I do this in Perl?</p>

答:
Does it have to be Perl? Have you tried logrotate?

As far as a Perl solution: mkdir will create the directories, and if you use POSIX 'strftime';, then you'll be able to generate nice directory names based on the current time (ie, my $dirname = strftime('%Y-%m-%d',localtime()) will generate a YYYY-MM-DD string), and you can move the files using rename. That's just core Perl, there are a ton of CPAN modules that do some or all of this (such as File::Copy, instead of rename).

OwnerDisplayName: Alex Wong

LastEditorDisplayName: brian d foy

OwnerDisplayName: Andrew Barnett


问:
How to execute pure aql query?
I'm using Official Aerospike Package for golang.

Is there any way to get list of all existing indexes this like?

aql> show indexes

Also I haven't found any way to execute pure aql query.

How can I do this?

Update:
I'm looking for something similar to this but for aerospike (example from Rails)

custom_query = "select * from users"
result = ActiveRecord::Base.connection.execute(custom_query)

答:
aql>show indexes
is a valid aql command and should show you all the secondary indexes you currently have on the server.

aql runs the C api underneath. You can do pretty much everything with aql at a rudimnetary level.
Type: aql>help   it will throw all the aql commands at you, cut and paste!
aql also stores command history in a text file - so persists over sessions.
aql>run 'filepath/filename' is a handy way to store all aql commands in a text file and run them.

Re: aql query -- look at: select * from ns. where ... you can do equality and range queries provided you have pre-built the secondary indexes.

Aerospike ver 3.12+ introduced predicate filtering - ie ~complex queries - I don't think aql has been updated to run those yet.

HTH.

Title: How to execute pure aql query?


答:
```<code>$db = $objDBUtil->Open();

$param = $objDBUtil->DBQuotes($strSymbolName);

$query = "SELECT symSymbol, symName FROM symbols WHERE symSymbol LIKE '%$param%'";

$result = $db->query($query);
</code>```


问:
Syntax Error issues around Case When
I am trying to write the following query for Microsoft Access and am encountering issues around the last three characters here, Can someone tell me what's wrong with my syntax for Access purposes:

SELECT DISTINCT Searches.Search ,IIF(Chemical_Names.Category  IS NOT NULL, Chemical_Names.Category, IIF(CAS_Numbers.Category IS NOT NULL , CAS_Numbers.Category, IIF(Brand_Name.Category IS NOT NULL, Brand_Name.Category,
IIF(PART.Category IS NOT NULL , PART.Category,CAT.Category))))  AS Category
FROM Searches
     LEFT JOIN
       (SELECT * FROM Cat1 UNION
        SELECT * FROM Cat2 UNION
        SELECT * FROM Cat3 UNION
        SELECT * FROM Cat4) as CAT
    ON
                       Searches.Search = CAT.Search
     LEFT JOIN
       (SELECT * FROM Part1 UNION
        SELECT * FROM Part2 UNION
        SELECT * FROM Part3 UNION

        SELECT * FROM Part4) as PART
    ON
                       Searches.Search = PART.Search
      LEFT JOIN
       Supplier_Name
    ON
                       Searches.Search = Supplier_Name.Search
      LEFT JOIN
       Chemical_Names
    ON
                       Searches.Search = Chemical_Names.Search
     LEFT JOIN
       Chemical_Names
    ON
                       Searches.Search = CAS_Number.Search
     LEFT JOIN
       Brand_Name
    ON
                       Searches.Search = Brand_Name.Search;

答:
I think you can try using the Nz() function to conditionally show the first non null category in your chain of preference:

```<code>SELECT DISTINCT
    Nz(Chemical_Names.Category,
        Nz(CAS_Number.Category,
            Nz(Brand_Name.Category,
                Nz(PART.Category, CAT.Category)))) AS Category
FROM Searches
...
</code>```

The Nz() function is Access' version of what would be COALESCE() in most other databases.

You could also handle this use IIF(), which is Access' version of the CASE expression:

```<code>SELECT DISTINCT
    IIF(Chemical_Names.Category IS NOT NULL, Chemical_Names.Category,
        IIF(CAS_Number.Category IS NOT NULL, CAS_Number.Category,
            IIF(Brand_Name.Category IS NOT NULL, Brand_Name.Category,
                IIF(PART.Category IS NOT NULL, PART.Category, CAT.Category)))) AS Category
FROM Searches
...
</code>```

Title: Syntax Error issues around Case When

Body:
I think you can try using the Nz() function to conditionally show the first non null category in your chain of preference:

SELECT DISTINCT
    Nz(Chemical_Names.Category,
        Nz(CAS_Number.Category,
            Nz(Brand_Name.Category,
                Nz(PART.Category, CAT.Category)))) AS Category
FROM Searches
...

The Nz() function is Access' version of what would be COALESCE() in most other databases.

You could also handle this use IIF(), which is Access' version of the CASE expression:

SELECT DISTINCT
    IIF(Chemical_Names.Category IS NOT NULL, Chemical_Names.Category,
        IIF(CAS_Number.Category IS NOT NULL, CAS_Number.Category,
            IIF(Brand_Name.Category IS NOT NULL, Brand_Name.Category,
                IIF(PART.Category IS NOT NULL, PART.Category, CAT.Category)))) AS Category
FROM Searches
...


问:
Difference between public and private variables
```<code>namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         private int numberTwo = 12;

         static void yo()
         {
         }
    }
}
</code>```

Can someone tell me the difference between the variables numberOne and numberTwo in this code excerpt?

答: in general, PUBLIC means any other code outside the class can change its value.  PRIVATE are only able to be used/changed IN the class itself.   Additionally, if you build classes that are derived from another, and you want the child-level class to be able to use/change values of its parent, but not other generic code outside the class, use PROTECTED.</p>

Body:
namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         private int numberTwo = 12;

         static void yo()
         {
         }
    }
}

Can someone tell me the difference between the variables numberOne and numberTwo in this code excerpt?