text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Best way to search in top n rows in sqlite I have a BIG transactions table. I want to to find a specific field(card number) in transactions inserted in last one minute, Therefore it is not reasonable to search the entire table. So i want to search just in top 20 rows.
Here is the my code:
public boolean isCardTapedInLastMinute(String date, String time,String UID) {
String oneMinuteBefore = getOneMinuteBefore(time);
String tables = TRX.TABLE_NAME;
String[] columns = {TRX._ID};
String selection = TRX.COLUMN_NAME_TRX_DATE + " = ? AND " +
TRX.COLUMN_NAME_TRX_TIME + " >= ? AND " +
TRX.COLUMN_NAME_CARD_ID + " = ?";
String[] selectionArgs = {date, oneMinuteBefore, UID};
String sortOrder = TRX.COLUMN_NAME_TRX_DATE
+ BusDBContract.SORT_ORDER_DESC
+ ", "
+ TRX.COLUMN_NAME_TRX_TIME
+ BusDBContract.SORT_ORDER_DESC;
String limit = "1";
Cursor cursor = query(selection, selectionArgs, columns, tables, sortOrder, limit);
if (null == cursor) {
return false;
}
if (!cursor.moveToFirst()) {
cursor.close();
return false;
}
return true;
}
and the query method:
private Cursor queryWith(String selection, String[] selectionArgs, String[] columns, String tables, String sortOrder, String limit) {
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(tables);
Cursor cursor;
try {
cursor = builder
.query(
mBusOH.getReadableDatabase(),
columns,
selection,
selectionArgs,
null,
null,
sortOrder,
limit);
} catch (SQLException e) {
Log.e(TAG, "[query]sql_exception: " + e.getMessage());
return null;
}
return cursor;
}
It is working correctly and it searches the entire table.
It takes about 50-100 ms to be performed for 15000 rows but it may be bigger and i want to optimize it by searching in top 20 rows.
What is the best way to do so?
EDIT: db scheme:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31261815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: webpack eval-source-map makes chrome breakpoint not working I 'm trying to use eval-source-map instead of source-map because doc says it should be faster to build bundles.
But if I use eval-source-map, breakpoints in chrome doesn't get hit.
I've googled and it doesn't seem eval-source-map breaks breakpoint functionality.
A: I have the same issue with eval-source-map, so I finally switch back to source-map.
However, I do find two approaches to make eval-source-map work, quite dirty though.
*
*Insert a debugger in the JS file you are working on. Open DevTools before you visit the page, then the debugger will bring you to the right place, add your break points and they should work now.
*Or insert console.log('here is it') instead of debugger. Then open DevTools -> Console, on the right end of the line, a link will bring you to the place where console.log fires. Add your break points and they should also work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39908032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Express not serving static images Attempting to use express to serve static assets (css, images, js) for the index.html view.
In app.js
app.use(express.static(path.join(__dirname, 'public')));
In index.html
<link rel="stylesheet" type="text/css" href="/css/style.css">
<script type="text/javascript" src="/js/app.js"></script>
<img src="/images/logo.jpg" alt="logo"/>
Folder structure
public
css
style.css
images
logo.jpg
js
app.js
All three required files seem to be served just fine, as they all have a 200 response status however the logo.jpg is not being rendered.
EDIT: The app.js in the public folder is not the script used to start the server.
FULL app.js
require('dotenv').config();
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const logger = require('morgan');
const index = require('./routes/index');
const install = require('./routes/install');
const webhook = require('./routes/webhooks');
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(logger('dev'));
app.use('/webhook', bodyParser.raw({ type: 'application/json' }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/install', install);
app.use('/webhook', webhook);
const server = http.createServer(app);
server.listen(3000, () => console.log('App running'));
Full Folder structure
public
css
style.css
images
logo.jpg
js
app.js
routes
index
index.js
install
index.js
webhooks
index.js
views
app
index.html
error.html
app.js
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56029411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SSRS - Is there a better way to do this expression? I have a line chart and one of the series expressions look like this:
=IIF((DateDiff("dd", Fields!EstimatedImpDt.Value, Fields!ActualImpDt.Value) = 0)
,100
,(100 - (((DateDiff("dd", Fields!EstimatedImpDt.Value, Fields!ActualImpDt.Value))
/ (DateDiff("dd", Fields!CreateDt.Value, Fields!EstimatedImpDt.Value)))
* 100
)
)
)
I've checked to make sure there is data in each field, and I've checked to make sure the Parenthesis are all in the correct spot. Some of them may not be 100% necessary but I believe they are. It doesn't look like a calculated series would work. Is there anything visibly wrong with the expression? Is there a more effective way of doing this?
EDIT:
So I think Timeline Score, which gets its value from this expression is returning as a date, which is why it isn't showing up in the report when I run the page that contains the report. I tries using =CInt(Format()) around the whole expression but that didn't work.
here is a screenshot of what is going on:
I only have one row in the database but there should still be a point on the chart for this value.
EDIT 2: So I figured it out. For some reason using "dd" wasn't working. So I switched it to DateInterval.Day and it works perfect now!
A: The expressions looks OK. You do have some extra sets of parenthesis.
I think your IIF should check the DENOMINATOR
DateDiff("dd", Fields!CreateDt.Value, Fields!EstimatedImpDt.Value)
of the expression rather than the NUMERATOR
DateDiff("dd", Fields!EstimatedImpDt.Value, Fields!ActualImpDt.Value)
to avoid DIV0 errors.
=IIF(DateDiff("dd", Fields!CreateDt.Value, Fields!EstimatedImpDt.Value) = 0, 100, 100 - (DateDiff("dd", Fields!EstimatedImpDt.Value, Fields!ActualImpDt.Value) / DateDiff("dd", Fields!CreateDt.Value, Fields!EstimatedImpDt.Value)) * 100)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39649704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create Table in subplot I have a python plot and then would like to have a set of statistics in a table in a subplot adjacent to it. I have used kind of an adhoc approach in which I create a subplot with white axis colors and then make a table in the subplot. You can see that the table has white lines running through it if you look closely. My code is below.
import pandas as pd
import numpy as np
import datetime as dt
import matplotlib.pyplot
from patsy import dmatrices
import statsmodels.api as sm
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(1, 2,width_ratios=[6,1])
ax1 = plt.subplot(gs[0])
plt.plot_date(sp_df.index,np.log(sp_df['PX_LAST']),'k')
sells = sp_df[(sp_df['hurst'] > 0.5) & (sp_df['sharpe'] < 0.5) & (sp_df['20dma'] < sp_df['65dma'])].index
buys = sp_df[(sp_df['hurst'] > 0.5) & (sp_df['sharpe'] > 0.5) & (sp_df['20dma'] > sp_df['65dma']) & (sp_df['50dma'] > sp_df['200dma'])].index
plt.plot_date(buys,np.log(sp_df.ix[buys]['PX_LAST']),'g^')
plt.plot_date(sells,np.log(sp_df.ix[sells]['PX_LAST']),'rv')
plt.xlim(sp_df.index[0] - dt.timedelta(days=90),sp_df.index[-1] + dt.timedelta(days=90))
ax2 = plt.subplot(gs[1])
total_return = 2.50
annualized_return = 1.257
sharpe_ratio = .85
max_dd = .12
dd_duration = 300
stats = {"Total Return" : "%0.2f%%" % ((total_return - 1.0) * 100.0),
"Annualized Return" : "%0.2f%%" %((annualized_return - 1.0) * 100.0),
"Sharpe Ratio" : "%0.2f" % sharpe_ratio,
"Max Drawdown" : "%0.2f%%" % (max_dd * 100.0),
"Drawdown Duration" : str(dd_duration) + " days"}
bbox=[0.0,0.0,.5, .5]
stats = pd.DataFrame(stats,index=range(1)).T
plt.table(cellText = stats.get_values(),colWidths=[0.6]*2,rowLabels=stats.index,colLabels=['Metrics'],loc='right')
plt.tick_params(axis='both',top='off',left='off',labelleft='off',right='off',bottom='off',labelbottom='off')
ax = plt.gca()
ax.spines['bottom'].set_color('white')
ax.spines['top'].set_color('white')
ax.spines['left'].set_color('white')
ax.spines['right'].set_color('white')
fig = plt.gcf()
fig.set_size_inches(11.5,8.5)
Along with a picture
A: Based on this answer you can also use Latex to create a table.
For ease of usability, you can create a function that turns your data into the corresponding text-string:
import numpy as np
import matplotlib.pyplot as plt
from math import pi
from matplotlib import rc
rc('text', usetex=True)
# function that creates latex-table
def latex_table(celldata,rowlabel,collabel):
table = r'\begin{table} \begin{tabular}{|1|'
for c in range(0,len(collabel)):
# add additional columns
table += r'1|'
table += r'} \hline'
# provide the column headers
for c in range(0,len(collabel)-1):
table += collabel[c]
table += r'&'
table += collabel[-1]
table += r'\\ \hline'
# populate the table:
# this assumes the format to be celldata[index of rows][index of columns]
for r in range(0,len(rowlabel)):
table += rowlabel[r]
table += r'&'
for c in range(0,len(collabel)-2):
if not isinstance(celldata[r][c], basestring):
table += str(celldata[r][c])
else:
table += celldata[r][c]
table += r'&'
if not isinstance(celldata[r][-1], basestring):
table += str(celldata[r][-1])
else:
table += celldata[r][-1]
table += r'\\ \hline'
table += r'\end{tabular} \end{table}'
return table
# set up your data:
celldata = [[32, r'$\alpha$', 123],[200, 321, 50]]
rowlabel = [r'1st row', r'2nd row']
collabel = [r' ', r'$\alpha$', r'$\beta$', r'$\gamma$']
table = latex_table(celldata,rowlabel,collabel)
# set up the figure and subplots
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
ax1.plot(np.arange(100))
ax2.text(.1,.5,table, size=50)
ax2.axis('off')
plt.show()
The underlying idea of this function is to create one long string, called table which can be interpreted as a Latex-command. It is important to import rc and set rc('text', uestec=True) to ensure that the string can be understood as Latex.
The string is appended using +=; the input is as raw string, hence the r. The example data highlights the data format.
Finally, with this example, your figure looks like this:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28681782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Issue on Adding Arrow Content After Button Can you please take a look at this demo and let me know why I am not able to add arrow content after the button
@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css');
.btn-warning:after{
content: '';
position: absolute;
left: 100%;
top: 50%;
margin-top: -13px;
border-left: 0;
border-bottom: 13px solid transparent;
border-top: 13px solid transparent;
border-left: 10px solid #5A55A3;
}
<div class="container">
<button class="btn btn-warning">Button With Arraow out<br /> This is Test</button>
</div>
A: The arrow is just off the page to the right (note the horizontal scroll bar). It's absolutely positioned relative to the document and left:100% places it just past the right edge of the page. It seems that you want the arrow to be absolutely positioned relative to the button element itself.
Absolute positioning places an element "at a specified position relative to its closest positioned ancestor or to the containing block." (See absolute position @ MDN.) So the button itself needs to be "positioned".
In my example, below, I've added position:relative to the button element so that it becomes a "positioned ancestor".
@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css');
.btn-warning {
position: relative;
}
.btn-warning:after {
content: '';
position: absolute;
left: 100%;
top: 50%;
margin-top: -13px;
border-left: 0;
border-bottom: 13px solid transparent;
border-top: 13px solid transparent;
border-left: 10px solid #5A55A3;
}
<div class="container">
<button class="btn btn-warning">Button With Arraow out<br />This is Test</button>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33744116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Change the returned WP Rest API JSON response Format Is there a way to change the returned wp rest api json format? Instead of an array i'd like the response to be in an object format.
Desired format:
{
"articles": [
{
"id": 160,
"title": "This is a new post ",
"slug": "this-is-a-new-post-faf0no",
"author": 3,
}
]
}
I didn't find any hooks related to this. Any help is appreciated. Thank you.
A: You can try to make it an object with
$myObject = json_decode($responseJSON);
and you can take value with
echo $myObject['articles'][0]->title;
with foreach:
foreach($myObject['articles'] as $key => $value) {
echo $value->title . ", " . $value->slug . "<br>";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56709515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: "Java not found" in using tabula-py everyone, I am using tabula-py in python to extract table from pdfs. I used following codes.
import tabula
table_temp = tabula.read_pdf('./example_pdf/sample1.pdf',pages=11)
However, I got the error message as pasted below, in which I was told "no such file or directory: 'java'". I have installed Java in the following folder
"/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home".
Could anyone help me on solving the problem?
Thanks.
FileNotFoundError Traceback (most recent call last)
<ipython-input-4-41c9ba6fd519> in <module>()
----> 1 table_temp = tabula.read_pdf('./example_pdf/sample1.pdf',pages=11)
/Users/Myworld/anaconda/lib/python3.5/site-packages/tabula/wrapper.py in read_pdf(input_path, **kwargs)
64
65 try:
---> 66 output = subprocess.check_output(args)
67 finally:
68 if is_url:
/Users/Myworld/anaconda/lib/python3.5/subprocess.py in check_output(timeout, *popenargs, **kwargs)
314
315 return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 316 **kwargs).stdout
317
318
/Users/Myworld/anaconda/lib/python3.5/subprocess.py in run(input, timeout, check, *popenargs, **kwargs)
381 kwargs['stdin'] = PIPE
382
--> 383 with Popen(*popenargs, **kwargs) as process:
384 try:
385 stdout, stderr = process.communicate(input, timeout=timeout)
/Users/Myworld/anaconda/lib/python3.5/subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds)
674 c2pread, c2pwrite,
675 errread, errwrite,
--> 676 restore_signals, start_new_session)
677 except:
678 # Cleanup if the child failed starting.
/Users/Myworld/anaconda/lib/python3.5/subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)
1280 else:
1281 err_msg += ': ' + repr(orig_executable)
-> 1282 raise child_exception_type(errno_num, err_msg)
1283 raise child_exception_type(err_msg)
1284
FileNotFoundError: [Errno 2] No such file or directory: 'java'
A: I had run into the same error. The line actually causing the error for me was subprocess.call('java').
Installing Java on my machine fixed the error for me.
If installing Java still doesn't solve the problem for you, try running which java, and add the output directory to your PATH environment variable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44490203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Transform y axis in bar plot using scale_y_log10() Using the data.frame below, I want to have a bar plot with y axis log transformed.
I got this plot
using this code
ggplot(df, aes(x=id, y=ymean , fill=var, group=var)) +
geom_bar(position="dodge", stat="identity",
width = 0.7,
size=.9)+
geom_errorbar(aes(ymin=ymin,ymax=ymax),
size=.25,
width=.07,
position=position_dodge(.7))+
theme_bw()
to log transform y axis to show the "low" level in B and D which is close to zero, I used
+scale_y_log10()
which resulted in
Any suggestions how to transform y axis of the first plot?
By the way, some values in my data is close to zero but none of it is zero.
UPDATE
Trying this suggested answer by @computermacgyver
ggplot(df, aes(x=id, y=ymean , fill=var, group=var)) +
geom_bar(position="dodge", stat="identity",
width = 0.7,
size=.9)+
scale_y_log10("y",
breaks = trans_breaks("log10", function(x) 10^x),
labels = trans_format("log10", math_format(10^.x)))+
geom_errorbar(aes(ymin=ymin,ymax=ymax),
size=.25,
width=.07,
position=position_dodge(.7))+
theme_bw()
I got
DATA
dput(df)
structure(list(id = structure(c(7L, 7L, 7L, 1L, 1L, 1L, 2L, 2L,
2L, 6L, 6L, 6L, 5L, 5L, 5L, 3L, 3L, 3L, 4L, 4L, 4L), .Label = c("A",
"B", "C", "D", "E", "F", "G"), class = "factor"), var = structure(c(1L,
2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L,
3L, 1L, 2L, 3L), .Label = c("high", "medium", "low"), class = "factor"),
ymin = c(0.189863418, 0.19131948, 0.117720496, 0.255852069,
0.139624146, 0.048182771, 0.056593774, 0.037262727, 0.001156667,
0.024461299, 0.026203592, 0.031913077, 0.040168571, 0.035235902,
0.019156667, 0.04172913, 0.03591233, 0.026405094, 0.019256055,
0.011310755, 0.000412414), ymax = c(0.268973856, 0.219709677,
0.158936508, 0.343307692, 0.205225352, 0.068857143, 0.06059596,
0.047296296, 0.002559633, 0.032446541, 0.029476821, 0.0394,
0.048959184, 0.046833333, 0.047666667, 0.044269231, 0.051,
0.029181818, 0.03052381, 0.026892857, 0.001511628), ymean = c(0.231733739333333,
0.204891473333333, 0.140787890333333, 0.295301559666667,
0.173604191666667, 0.057967681, 0.058076578, 0.043017856,
0.00141152033333333, 0.0274970166666667, 0.0273799226666667,
0.0357511486666667, 0.0442377366666667, 0.0409452846666667,
0.0298284603333333, 0.042549019, 0.0407020586666667, 0.0272998796666667,
0.023900407, 0.016336106, 0.000488014)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -21L), .Names = c("id",
"var", "ymin", "ymax", "ymean"))
A: As @Miff has written bars are generally not useful on a log scale. With barplots, we compare the height of the bars to one another. To do this, we need a fixed point from which to compare, usually 0, but log(0) is negative infinity.
So, I would strongly suggest that you consider using geom_point() instead of geom_bar(). I.e.,
ggplot(df, aes(x=id, y=ymean , color=var)) +
geom_point(position=position_dodge(.7))+
scale_y_log10("y",
breaks = trans_breaks("log10", function(x) 10^x),
labels = trans_format("log10", math_format(10^.x)))+
geom_errorbar(aes(ymin=ymin,ymax=ymax),
size=.25,
width=.07,
position=position_dodge(.7))+
theme_bw()
If you really, really want bars, then you should use geom_rect instead of geom_bar and set your own baseline. That is, the baseline for geom_bar is zero but you will have to invent a new baseline in a log scale. Your Plot 1 seems to use 10^-7.
This can be accomplished with the following, but again, I consider this a really bad idea.
ggplot(df, aes(xmin=as.numeric(id)-.4,xmax=as.numeric(id)+.4, x=id, ymin=10E-7, ymax=ymean, fill=var)) +
geom_rect(position=position_dodge(.8))+
scale_y_log10("y",
breaks = trans_breaks("log10", function(x) 10^x),
labels = trans_format("log10", math_format(10^.x)))+
geom_errorbar(aes(ymin=ymin,ymax=ymax),
size=.25,
width=.07,
position=position_dodge(.8))+
theme_bw()
A: If you need bars flipped, maybe calculate your own log10(y), see example:
library(ggplot2)
library(dplyr)
# make your own log10
dfPlot <- df %>%
mutate(ymin = -log10(ymin),
ymax = -log10(ymax),
ymean = -log10(ymean))
# then plot
ggplot(dfPlot, aes(x = id, y = ymean, fill = var, group = var)) +
geom_bar(position = "dodge", stat = "identity",
width = 0.7,
size = 0.9)+
geom_errorbar(aes(ymin = ymin, ymax = ymax),
size = 0.25,
width = 0.07,
position = position_dodge(0.7)) +
scale_y_continuous(name = expression(-log[10](italic(ymean)))) +
theme_bw()
A: Firstly, don't do it! The help file from ?geom_bar says:
A bar chart uses height to represent a value, and so the base of the
bar must always be shown to produce a valid visual comparison. Naomi
Robbins has a nice article on this topic. This is why it doesn't make
sense to use a log-scaled y axis with a bar chart.
To give a concrete example, the following is a way of producing the graph you want, but a larger k will also be correct but produce a different plot visually.
k<- 10000
ggplot(df, aes(x=id, y=ymean*k , fill=var, group=var)) +
geom_bar(position="dodge", stat="identity",
width = 0.7,
size=.9)+
geom_errorbar(aes(ymin=ymin*k,ymax=ymax*k),
size=.25,
width=.07,
position=position_dodge(.7))+
theme_bw() + scale_y_log10(labels=function(x)x/k)
k=1e4
k=1e6
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46639120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can using line-height < 1 cause problems? I'm using a specific font (font-size: 16px). When I use line-height:1, the character's baseline is not positioned at the bottom. There is a 2px gap:
If I reduce the line-height to 0.75 I get better results. I can align the text in a more precise way to other elements. I can implement the spacings defined in graphic mockups without doing extra calculations. Using padding-bottom I can control the line spacing.
Does setting a line-height < 1 have side-effects that I should be aware of? Is it supported by today's browsers in a concise way?
A: I would not call it "bad practice" even though it can cause ugly results when your text wraps over multiple lines. Just using it for "alignment-hacks" like you said should be no problem at all.
Edit:
Maybe my Answer promised too much. Be careful with the line-height property beacause as I mentioned it may cause ugly results on multi-line text. If you want to keep your website responsive margins on your paragraphs (positive or negative) are clearly the better solution.
A: Good practise in this area is the well readable text. Nothing else matters. The text should be easy to read.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38569915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Override Spring Boot Security Spring Boot Security,
My Application is already running using Spring Security. Now I want to authenticate the users through OAuth. Is there any way to build a custom servlet to achieve this?
A: You can add a new Filter to intercept and authenticate OAuth requests in which it should call the authenticationManager.authenticate method and save the result of the authentication token in the SecurityContextHolder. This way the user is fully authenticated.
Note, that this way you don't "override" or "bypass" the Spring Security. You just use it to perform a different authentication.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59320141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Setting up keith-wood CountDown on Static HTML Page I'm using HTML Static Page for my website index, and I want to setup Keith-wood countdown.
It has some defaults and I cant find(?) them, here is the code in index.html :
<div id="container-counter">
<div id="defaultCountdown"></div>
</div>
Where can I change the target date in default var?
-
Edit: Since the defaults cant be found, it means that the setup code is not visible and was likely not included as it should be:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/jquery.countdown.css">
<script type="text/javascript" src="js/jquery.plugin.js"></script>
<script type="text/javascript" src="js/jquery.countdown.js"></script>
The default JS example for this plugin from http://keith-wood.name/countdown.html reads:
var newYear = new Date();
newYear = new Date(newYear.getFullYear() + 1, 1 - 1, 1);
$('#defaultCountdown').countdown({until: newYear});
With all of this is in place, the question can now be answered:
Where can I change the target date in default var?
A: After a quick look, Keith-wood countdown works as follows (example code they provide that works with your code):
newYear = new Date();
var newYear = new Date(newYear.getFullYear() + 1, 1 - 1, 1);
$('#defaultCountdown').countdown({until: newYear});
If I understand your question right, then you simply need to change the code at line 2:
newYear = new Date(newYear.getFullYear() + 1, 1 - 1, 1);
Since this sets the newYear variable to the date you want to count down to. So to set the date as per your question you simply need to properly set the JS constructor for the new Date on that line:
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Hence if you are counting down to a launch at 10AM on the 15th December 2014 then you will just set it to:
new Date(2014, 12, 15, 10, 0, 0, 0)
If you want to know more about the basic set-up, not just changing the dates you can find that here on keith-wood's website.
Hope that helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22618592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: File format not recognized with GNU gdb 6.4 on Solaris 10 Below details are from a session in a Sun machine running Solaris 10.
$ file devli
devli: ELF 32-bit MSB executable SPARC Version 1, dynamically linked, stripped
$ file a
a: ELF 32-bit MSB executable SPARC Version 1, dynamically linked, not stripped
$ gdb
GNU gdb 6.4
Copyright 2005 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "sparc-sun-solaris2.10".
(gdb) file a
Reading symbols from /tmp/tnmy/a...(no debugging symbols found)...done.
(gdb) file devli
"/tmp/tnmy/devli": not in executable format: File format not recognized
(gdb) q
$ ls -l a devlisrvr
-rwxr-xr-x 1 test2 dba 1480 Dec 23 18:23 a
-rwxr-xr-x 1 test2 dba 633088 Dec 23 18:26 devli
$ uname -a ;
SunOS myhost 5.10 Generic_127111-11 sun4v sparc SUNW,SPARC-Enterprise-T5220
$ cat a.c
int main() {return 0;}
$ /opt/SUNONE8/SUNWspro/bin/CC -V
CC: Sun C++ 5.5 2003/03/12
$ file `which gdb`
/usr/local/bin/gdb: ELF 32-bit MSB executable SPARC Version 1, dynamically linked, not stripped
$
Any details on why would not gdb recognize the file format for devli? I searched over the Internet but could not find anything related to this particular issue. Any pointers would be helpful.
a.c goes into a, built using gcc; devli using Sun ONE Studio 8.
A: Note that GDB 6.4 is 4 years old. You might get better luck with (current) GDB 7.0.
It is also possible that the devli executable is corrupt (file just looks at the first few bytes of the executable, but GDB requires much more of the file contents to be self-consistent). Does readelf --all > /dev/null report any warnings?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1952882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sort columns in sql I have a table with number of columns. Most of the columns except primary key columns can have nulls. I need a query which will query this table and fetch the results in such a way that, the records which have nulls for all columns except the primary columns should be shown first. In the below example, EmpId and name are primary keys and as shown in the expected result, the records with no data for non-primary columns should be on top of the results. I have tried sorting based on all the non-primary columns but didn't get expected result.
A: Use nulls first and order by all retrieved columns.
Select empid,
name,
address,
phone,
zip,
gender
from TABLE
Order by empid nulls first,
name nulls first,
address nulls first,
phone nulls first,
zip nulls first,
gender nulls first;
And you really should supply the query(ies) you've tried.
A: If all of address, phone, zip, gender is NULL, then put row first. Else sort by pk etc.
Select empid,
name,
address,
phone,
zip,
gender
from TABLE
Order by case when coalesce(address, phone, zip, gender) is null then 0 else 1 end,
empid, name, address, phone, zip, gender;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33925396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ld: cannot open output file conftest.exe: Permission denied Using MSYS2 (version x86_64-20160205) on Windows 7 64bits, I'm trying to compile corkscrew.
Here is the output:
$ ./configure
loading cache ./config.cache
checking for a BSD compatible install... (cached) /usr/bin/install -c
checking whether build environment is sane... yes
checking whether make sets ${MAKE}... (cached) no
checking for working aclocal... found
checking for working autoconf... missing
checking for working automake... found
checking for working autoheader... missing
checking for working makeinfo... missing
checking for gcc... (cached) gcc
checking whether the C compiler (gcc ) works... yes
checking whether the C compiler (gcc ) is a cross-compiler... no
checking whether we are using GNU C... (cached) yes
checking whether gcc accepts -g... (cached) yes
checking for gcc option to accept ANSI C... (cached) none needed
checking how to run the C preprocessor... (cached) gcc -E
checking for function prototypes... yes
checking for gcc... (cached) gcc
checking whether the C compiler (gcc -g -O2 ) works... no
configure: error: installation or configuration problem: C compiler cannot create executables.
And the content of config.log:
This file contains any messages produced by compilers while
running configure, to aid debugging if configure makes a mistake.
configure:556: checking for a BSD compatible install
configure:609: checking whether build environment is sane
configure:666: checking whether make sets ${MAKE}
configure:712: checking for working aclocal
configure:725: checking for working autoconf
configure:738: checking for working automake
configure:751: checking for working autoheader
configure:764: checking for working makeinfo
configure:783: checking for gcc
configure:896: checking whether the C compiler (gcc ) works
configure:912: gcc -o conftest conftest.c 1>&5
configure:909:1: warning: return type defaults to 'int' [-Wimplicit-int]
main(){return(0);}
^
configure:938: checking whether the C compiler (gcc ) is a cross-compiler
configure:943: checking whether we are using GNU C
configure:971: checking whether gcc accepts -g
configure:1006: checking for gcc option to accept ANSI C
configure:1083: checking how to run the C preprocessor
configure:1165: checking for function prototypes
configure:1327: checking for gcc
configure:1440: checking whether the C compiler (gcc -g -O2 ) works
configure:1456: gcc -o conftest -g -O2 conftest.c 1>&5
configure:1453:1: warning: return type defaults to 'int' [-Wimplicit-int]
main(){return(0);}
^
/usr/lib/gcc/x86_64-pc-msys/5.3.0/../../../../x86_64-pc-msys/bin/ld: cannot open output file conftest.exe: Permission denied
collect2: error: ld returned 1 exit status
configure: failed program was:
#line 1451 "configure"
#include "confdefs.h"
main(){return(0);}
I've tested this answer without any success. Or to be more precise, it goes to the next step (which is failing at detecting my system, which is more a corkscrew's config issue I think) randomly...
This is not a rights problem as I have all the rights on that folder and I use my user to execute ./configure.
Any idea?
A: It looks like ld is having trouble creating an executable file due to permission problems. Try building the program in a folder that you are sure that you own (like C:\Users\yourusername) or try adjusting the permissions for the folder you are building in.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37731125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Remove div from page with JavaScript I am trying to remove a div from my page once i receive an XMPHttpRequest response. I have also tried setting the display of the div to none using: document.getElementById('password').style.display = 'none'; but that didnt work either.
HTML:
<div class="login-container">
<div class="title">Login Form</div>
<div class="form-fields" id="form-fields">
<form name="login_form" method="post" id="login-form" onsubmit="return submitForm()">
<input type="text" name="username" id="username" placeholder="Username" required></input>
<input type="password" name="password" id="password" placeholder="Password" required></input>
<input type="submit" value="Log in" id="submit-button"></input>
<input id="sessionID" class="hidden"></input>
</form>
</div>
<div id="success-message" class="hidden">Congratulations! You have been logged in.</div>
<button id="logout" class="hidden"></button>
</div>
Javascript Function:
function sendLoginInfo() {
var loginRequest = new XMLHttpRequest();
loginRequest.open("POST", "server/login.php", false);
loginRequest.setRequestHeader('Content-type', "application/json");
loginRequest.onreadystatechange = function () {
if(loginRequest.readyState == 4 && loginRequest.status == 200) {
sessionID = keyRequest.responseText;
var el = document.getElementById( 'password' );
el.parentNode.removeChild( el );
}
}
loginRequest.send(JSON.stringify(JSONFormData));
}
Update
This problem was solved by changing:
<form name="login_form" method="post" id="login-form" onsubmit="return submitForm()">
To:
<form name="login_form" method="post" id="login-form" onsubmit="submitForm(); return false;">
A: instead of
document.getElementById('password').style.display = 0;
try
document.getElementById('password').style.display = 'none';
A: You can't really remove divs as far as I know but you can set the visibility of a div to "none" (not "0" as you tried it).
style="display:none"
This makes the div invisible and there won't be any white space.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26664441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: By implementing the interface it inherit unwanted methods I have interface A which defined 3 methods that should implement and class B must is implementing all three methods. No problem.
But in class C also i'm implementing the interface A so I have to write the implementation for all three methods. But my class C doesn't want the doSomthing3().
I'm just giving here an example but my real application is a large one with many methods.
Assume I have 100 sub classes that implement interface A and now I want 50 classes to have another new method which I can put in interface A. But then do I have to implement it in all 100 sub classes?
How come I avoid to inherit unwanted method.
public interface A {
public void doSomething1();
public void doSomething2();
public void doSomething3();
}
public class B implements A{
public void doSomething1(){
System.out.println("doSomething 1");
}
public void doSomething2(){
System.out.println("doSomething 2");
}
public void doSomething3(){
System.out.println("doSomething 3");
}
}
public class C implements A{
public void doSomething1(){
System.out.println("doSomething 1");
}
public void doSomething2(){
System.out.println("doSomething 2");
}
public void doSomething3(){ /*Do nothing in this class */ }
}
A: You could create two interfaces. One will contains the methods that you will implement in both classes and the other one the extra method that you want for the other class. Then just implement the right interface to the right class.
public interface A {
public void doSomething1();
public void doSomething2();
}
public interface B extends A {
public void doSomething3();
}
Then
public class ClassB implements B{
public void doSomething1(){
System.out.println("doSomething 1");
}
public void doSomething2(){
System.out.println("doSomething 2");
}
public void doSomething3(){
System.out.println("doSomething 3");
}
}
public class ClassA implements A{
public void doSomething1(){
System.out.println("doSomething 1");
}
public void doSomething2(){
System.out.println("doSomething 2");
}
}
A: This issue is solved by introducing such called Adapter: this is an abstract class, which implements all methods from inherited interface. In your desired class you could override only that methods, which you want:
public abstract class AAdapter implements A(){
public void doSomething1(){
}
public void doSomething2(){
}
public void doSomething3(){
}
}
and in your class:
public class C extends AAdapter(){
@Override
public void doSomething1(){
system.out.println("doSomething 1");
}
@Override
public void doSomething2(){
system.out.println("doSomething 2");
}
}
A: You can create a simple implementation of your interface that always trigger NoSuchMethodError or any other runtime exception.
And then simply extends that class and override only the useful methods.
Or as stated in another answer, you might consider redesigning your interfaces.
A: You can consider creating stub implementation:
public class SimpleA implements A {
@Override
public void doSomething1() {
throw new UnsupportedOperationException();
}
// rest omitted
}
Now your classes can extend SimpleA and override only needed methods.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16958708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Angular bazel ts_devserver add polyfills ts_devserver(
name = "devserver",
additional_root_paths = ["project/src/_"],
entry_module = "project/src/main.dev",
port = 4200,
scripts = [
"@npm//:node_modules/tslib/tslib.js",
"@npm//:node_modules/@angular/localize/bundles/localize-init.umd.js",
"@npm//:node_modules/@angular/common/locales/es-MX.js",
"@npm//date-fns:date-fns.umd.js",
"@npm//immutable:immutable.umd.js",
":date_fns_locale_umd",
],
serving_path = "/bundle.min.js",
static_files = [
"@npm//:node_modules/zone.js/dist/zone.min.js",
":global_stylesheet",
":asset_injected_index_html",
"favicon.ico",
"manifest.json"
],
deps = [
":polyfills",
":bazel_umd_modules",
":src"
],
)
I'm getting the following error
Uncaught Error: It looks like your application or one of its dependencies is using i18n.
Angular 9 introduced a global `$localize()` function that needs to be loaded.
Please run `ng add @angular/localize` from the Angular CLI.
(For non-CLI projects, add `import '@angular/localize/init';` to your `polyfills.ts` file.
For server-side rendering applications add the import to your `main.server.ts` file.)
at _global.$localize (core.umd.js:32815)
at Object.eval (ng-bootstrap.umd.js:63)
at Object.execCb (es-MX.ts:78)
at Module.check (es-MX.ts:78)
at Module.enable (es-MX.ts:78)
at Object.enable (es-MX.ts:78)
at Module.<anonymous> (es-MX.ts:78)
at es-MX.ts:78
at each (es-MX.ts:53)
at Module.enable (es-MX.ts:78)
polyfills.ts is a ts_library()
import '@angular/localize/init';
I don't now why how to init before app starts... In tests I do it by adding //src:polyfills to runtime_deps and localize init in the srcs.
Any ideas?
A: I solved this adding this script to ts_devserver bootstrap
ts_devserver(
name = "devserver",
additional_root_paths = ["project/src/_"],
bootstrap = [
"@npm//:node_modules/@angular/localize/bundles/localize-init.umd.js",
]
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61930303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Run script while having browser focused I am currently working on a home project with a Raspberry Pi and the 7" display. Almost everything works, only the last bit I am a bit confused with. A chromium window in kiosk mode is open which refreshes on mouse movement. Also on mouse movement I want to change the backlight for a few seconds to full light.
The script below works so far stand-alone:
#!/bin/bash
while true; do
pos1=$(xdotool getmouselocation)
sleep 0.5
pos2=$(xdotool getmouselocation)
if [[ $pos1 != $pos2 ]]; then
sudo /usr/local/bin/rpi-backlight -b 100
sleep 10
sudo /usr/local/bin/rpi-backlight -b 0 -d 2
fi
done
I already tried to make it happen by
*
*putting it in one script together with the chromium call,
*opening both in autostart,
*creating a systemd service for the script above. It does not seem to work in the background.
Can anyone tell me, where I am mistaken?
A: I made it happen by putting both in autostart. My syntax seemed to be wrong.
@/path/script.sh &
@chromium-browser --kiosk http://website.xyz
works like a charme, where ampersand "&" is for making it a background process.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66659199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Mongodb BI Connector & Tableau: Error while trying to run mongosqld I'm trying to connect Tableau to MongoDB using MongoDB BI Connector and this instruction (version 2.1 (current)):
https://docs.mongodb.com/bi-connector/v2.1/installation/
but I get an error in step 5:
mongosqld --schema=schema.drdl --mongo-uri=mongodb://localhost:27017
2017-07-04T15:19:44.032+0200 I CONTROL [initandlisten] mongosqld version: v2.1.0
2017-07-04T15:19:44.032+0200 I CONTROL [initandlisten] git version: 518180ba2c547d2cc6071f955d98ec6de730c0c9
2017-07-04T15:19:44.032+0200 I CONTROL [initandlisten] arguments: --mongo-uri mongodb://localhost:27017 --schema schema.drdl
2017-07-04T15:19:44.032+0200 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for mongosqld.
2017-07-04T15:19:44.032+0200 I CONTROL [initandlisten]
2017-07-04T15:19:44.038+0200 I NETWORK [initandlisten] connecting to mongodb at mongodb://localhost:27017
error starting server: listen unix /tmp/mysql.sock: bind: address already in use
mongosqld is installed properly:
mongosqld --version
mongosqld version v2.1.0
git version: 518180ba2c547d2cc6071f955d98ec6de730c0c9
also, my mongod is running and working with the default port (27017) by running this command:
sudo mongod --dbpath /mnt/PROJET-CIRMAR-1T/
Do you have any idea that what's the problem with running mongosqld?
A: I don't know why but the problem was with the mysql.sock file. So, you can remove it or move it somewhere else and try executing the command again. At least in my case, the problem is solved and mongosqld is running! Maybe it helps someone in the future and maybe someone let us know what's the exact reason!
A: Thanks Aboozar.
Mongosqld will - by default - attempt to bind to unix domain sockets on OSes where that exists. The error you saw above is an indication that some other process was already bound to mysql.sock - this could have been another instance of mongosqld or a mysqld server.
To reliably avoid situations like this in the future, you can start mongosqld with the additional flag --noUnixSocket.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44907923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What namespace does global variables belong to, if we don't declare a namespace name explicitly for it? Recently I am trying to be familiar with C++. And I am a little confused with the "Namespace" stuff. Here's a example code:
#include <iostream>
using namespace std;
namespace foo
{
int value() { return 5; }
}
namespace bar
{
const double pi = 3.1416;
double value() { return 2*pi; }
}
int a; //what's the namespace it belongs to?
int main () {
cout << foo::value() << '\n';
cout << bar::value() << '\n';
cout << bar::pi << '\n';
return 0;
}
Above code shows two explicit namespaces: foo and bar. And both of them have some global variables in their scope. My question is for variable a, becuase we don't specify the namespace name for it, what namespace(or anonymous namespace) does it belong to? Or it has no namespace to attach to? If I want to use this variable a from other files, how do we specify its namespace?
A: a is in the global namespace scope. If it isn't shadowed, and assuming you have included the right header files, you can simply refer to it as a in your other file. However, if it is shadowed, or if you just want to play it safe and refer to it explicity, you can refer to it as ::a.
For example,
#include <header_for_a.h>
namespace B
{
int a;//This now shadows the "a" from the global namespace.
void foo()
{
a = 1;//This is referring to B::a;
::a = 2; // This is referring to "a" from the global namespace.
}
}
A: int a
belongs to global namespace. That means another variable with same name in global namespace could buy you a linker error.
If I want to use this variable a from other files, how do we specify its namespace?
You can just enclose it in namespace. Generally a namespace should have all related entities in it. So, if you think it can be put inside already existing namespace then get set go.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27664779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Tuple unpacking in R Python has the *(...) syntactic sugar. Can you do this in R?
t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])
From here: https://stackoverflow.com/a/2238361/1007926
This allows each element of the tuple to be assigned to an argument of, in this case, the datetime function.
An analogous trick in R might look like this, if the syntax were the same as Python:
lims <- c(10,20)
my.seq <- seq(*lims)
I don't believe this exactly the same as "unpacking" used in this question:
>>> a, b, c = (1, 2, 3)
Is there a way to do it in R, as below?
a, b, c = c(1, 2, 3)
Python-like unpacking of numeric value in R
A: The closest thing I can think of is do.call:
> lims <- c(10,20)
> do.call(seq, as.list(lims))
[1] 10 11 12 13 14 15 16 17 18 19 20
But do note that there are some subtle differences in evaluation that may cause some function calls to be different than if you had called them directly rather than via do.call.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27199521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Most idiomatic way to write batchesOf size seq in F# I'm trying to learn F# by rewriting some C# algorithms I have into idiomatic F#.
One of the first functions I'm trying to rewrite is a batchesOf where:
[1..17] |> batchesOf 5
Which would split the sequence into batches with a max of five in each, i.e:
[[1; 2; 3; 4; 5]; [6; 7; 8; 9; 10]; [11; 12; 13; 14; 15]; [16; 17]]
My first attempt at doing this is kind of ugly where I've resorted to using a mutable ref object after running into errors trying to use mutable type inside the closure. Using ref is particularly unpleasant since to dereference it you have to use the ! operator which when inside a condition expression can be counter intuitive to some devs who will read it as logical not. Another problem I ran into is where Seq.skip and Seq.take are not like their Linq aliases in that they will throw an error if size exceeds the size of the sequence.
let batchesOf size (sequence: _ seq) : _ list seq =
seq {
let s = ref sequence
while not (!s |> Seq.isEmpty) do
yield !s |> Seq.truncate size |> List.ofSeq
s := System.Linq.Enumerable.Skip(!s, size)
}
Anyway what would be the most elegant/idiomatic way to rewrite this in F#? Keeping the original behaviour but preferably without the ref mutable variable.
A: This can be done without recursion if you want
[0..20]
|> Seq.mapi (fun i elem -> (i/size),elem)
|> Seq.groupBy (fun (a,_) -> a)
|> Seq.map (fun (_,se) -> se |> Seq.map (snd));;
val it : seq<seq<int>> =
seq
[seq [0; 1; 2; 3; ...]; seq [5; 6; 7; 8; ...]; seq [10; 11; 12; 13; ...];
seq [15; 16; 17; 18; ...]; ...]
Depending on how you think this may be easier to understand. Tomas' solution is probably more idiomatic F# though
A: Hurray, we can use List.chunkBySize, Seq.chunkBySize and Array.chunkBySize in F# 4, as mentioned by Brad Collins and Scott Wlaschin.
A: Implementing this function using the seq<_> type idiomatically is difficult - the type is inherently mutable, so there is no simple nice functional way. Your version is quite inefficient, because it uses Skip repeatedly on the sequence. A better imperative option would be to use GetEnumerator and just iterate over elements using IEnumerator. You can find various imperative options in this snippet: http://fssnip.net/1o
If you're learning F#, then it is better to try writing the function using F# list type. This way, you can use idiomatic functional style. Then you can write batchesOf using pattern matching with recursion and accumulator argument like this:
let batchesOf size input =
// Inner function that does the actual work.
// 'input' is the remaining part of the list, 'num' is the number of elements
// in a current batch, which is stored in 'batch'. Finally, 'acc' is a list of
// batches (in a reverse order)
let rec loop input num batch acc =
match input with
| [] ->
// We've reached the end - add current batch to the list of all
// batches if it is not empty and return batch (in the right order)
if batch <> [] then (List.rev batch)::acc else acc
|> List.rev
| x::xs when num = size - 1 ->
// We've reached the end of the batch - add the last element
// and add batch to the list of batches.
loop xs 0 [] ((List.rev (x::batch))::acc)
| x::xs ->
// Take one element from the input and add it to the current batch
loop xs (num + 1) (x::batch) acc
loop input 0 [] []
As a footnote, the imperative version can be made a bit nicer using computation expression for working with IEnumerator, but that's not standard and it is quite advanced trick (for example, see http://fssnip.net/37).
A: A friend asked me this a while back. Here's a recycled answer. This works and is pure:
let batchesOf n =
Seq.mapi (fun i v -> i / n, v) >>
Seq.groupBy fst >>
Seq.map snd >>
Seq.map (Seq.map snd)
Or an impure version:
let batchesOf n =
let i = ref -1
Seq.groupBy (fun _ -> i := !i + 1; !i / n) >> Seq.map snd
These produce a seq<seq<'a>>. If you really must have an 'a list list as in your sample then just add ... |> Seq.map (List.ofSeq) |> List.ofSeq as in:
> [1..17] |> batchesOf 5 |> Seq.map (List.ofSeq) |> List.ofSeq;;
val it : int list list = [[1; 2; 3; 4; 5]; [6; 7; 8; 9; 10]; [11; 12; 13; 14; 15]; [16; 17]]
Hope that helps!
A: This isn't perhaps idiomatic but it works:
let batchesOf n l =
let _, _, temp', res' = List.fold (fun (i, n, temp, res) hd ->
if i < n then
(i + 1, n, hd :: temp, res)
else
(1, i, [hd], (List.rev temp) :: res))
(0, n, [], []) l
(List.rev temp') :: res' |> List.rev
A: Here's a simple implementation for sequences:
let chunks size (items:seq<_>) =
use e = items.GetEnumerator()
let rec loop i acc =
seq {
if i = size then
yield (List.rev acc)
yield! loop 0 []
elif e.MoveNext() then
yield! loop (i+1) (e.Current::acc)
else
yield (List.rev acc)
}
if size = 0 then invalidArg "size" "must be greater than zero"
if Seq.isEmpty items then Seq.empty else loop 0 []
let s = Seq.init 10 id
chunks 3 s
//output: seq [[0; 1; 2]; [3; 4; 5]; [6; 7; 8]; [9]]
A: My method involves converting the list to an array and recursively chunking the array:
let batchesOf (sz:int) lt =
let arr = List.toArray lt
let rec bite curr =
if (curr + sz - 1 ) >= arr.Length then
[Array.toList arr.[ curr .. (arr.Length - 1)]]
else
let curr1 = curr + sz
(Array.toList (arr.[curr .. (curr + sz - 1)])) :: (bite curr1)
bite 0
batchesOf 5 [1 .. 17]
[[1; 2; 3; 4; 5]; [6; 7; 8; 9; 10]; [11; 12; 13; 14; 15]; [16; 17]]
A: I found this to be a quite terse solution:
let partition n (stream:seq<_>) = seq {
let enum = stream.GetEnumerator()
let rec collect n partition =
if n = 1 || not (enum.MoveNext()) then
partition
else
collect (n-1) (partition @ [enum.Current])
while enum.MoveNext() do
yield collect n [enum.Current]
}
It works on a sequence and produces a sequence. The output sequence consists of lists of n elements from the input sequence.
A: You can solve your task with analog of Clojure partition library function below:
let partition n step coll =
let rec split ss =
seq {
yield(ss |> Seq.truncate n)
if Seq.length(ss |> Seq.truncate (step+1)) > step then
yield! split <| (ss |> Seq.skip step)
}
split coll
Being used as partition 5 5 it will provide you with sought batchesOf 5 functionality:
[1..17] |> partition 5 5;;
val it : seq<seq<int>> =
seq
[seq [1; 2; 3; 4; ...]; seq [6; 7; 8; 9; ...]; seq [11; 12; 13; 14; ...];
seq [16; 17]]
As a premium by playing with n and step you can use it for slicing overlapping batches aka sliding windows, and even apply to infinite sequences, like below:
Seq.initInfinite(fun x -> x) |> partition 4 1;;
val it : seq<seq<int>> =
seq
[seq [0; 1; 2; 3]; seq [1; 2; 3; 4]; seq [2; 3; 4; 5]; seq [3; 4; 5; 6];
...]
Consider it as a prototype only as it does many redundant evaluations on the source sequence and not likely fit for production purposes.
A: This version passes all my tests I could think of including ones for lazy evaluation and single sequence evaluation:
let batchIn batchLength sequence =
let padding = seq { for i in 1 .. batchLength -> None }
let wrapped = sequence |> Seq.map Some
Seq.concat [wrapped; padding]
|> Seq.windowed batchLength
|> Seq.mapi (fun i el -> (i, el))
|> Seq.filter (fun t -> fst t % batchLength = 0)
|> Seq.map snd
|> Seq.map (Seq.choose id)
|> Seq.filter (fun el -> not (Seq.isEmpty el))
I am still quite new to F# so if I'm missing anything - please do correct me, it will be greatly appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How can I add expansions to a bash argument I have this simple script to find a file on a folder, with "find" command in the shell works, but in the script doesn't.
#!/bin/bash
echo ""
read -p "-Write file you need- " FILE
read -p "-Write the folder to search- " FOLDER
FILE="'*$FILE*'"
find $FOLDER -name $FILE
If "FILE" is "test" I want to be '*test *' so find can find not only the same name of file, also test.txt and more.
EDIT:
I'm using #!/bin/bash -ex that tell me what's happen in every line of code, if I add
echo $FILE
Its tell me this:
echo $FILE
'* test *'
find "$FOLDER" -name "$FILE"
find /home -name ' ' \ ' ' *test * '\ ' ' '
I don't know why It's adding so many quoting marks and not using the same content of variable like echo
A: Use quotes where they are needed, like this
#!/bin/bash
echo ""
read -p "-Write file you need- " FILE
read -p "-Write the folder to search- " FOLDER
FILE="*$FILE*"
set -x
find "$FOLDER" -name "$FILE"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72850656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Equivalent for 'event of VHDL on Verilog - Synthetizable I need an equivalent for 'event of VHDL using Verilog.
This is an example to convert from VHDL to Verilog(Note: I need both posedge and negedge in the same porcess):
process (CLK, I) begin
if (I'event and I = 1) then //posedge
x <= x + 1;
elsif (I'event and I = 0) //negedge
x <= c + 2;
end if;
if (CLK'event and CLK = 1) // posedge
a <= b + 1;
end if;
end process;
A: I'll just take a stab at rewriting the code.
It appears that you have 2 separate things going on here. You have the assignment of a and the assignment of x. Assignment of a is based off the clock and assignment of x is based off of I.
always @(clk) begin
if (posedge clk)
a <= b + 1;
end
always @(in_i) begin
if (posedge in_i)
x <= x + 1;
else if (negedge in_i)
x <= c + 2;
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26598922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dictionary inside a list. Return the dictionary name I'm making my first project a tic tac toe game. I have the following:
the_board = {'1 3': ' ' , '2 3': ' ' , '3 3': ' ' ,
'1 2': ' ' , '2 2': ' ' , '3 2': ' ' ,
'1 1': ' ' , '2 1': ' ' , '3 1': ' ' }
wins = [[the_board['1 3'],the_board['2 3'],the_board['3 3']],
[the_board['1 2'],the_board['2 2'],the_board['3 2']],
[the_board['1 1'],the_board['2 1'],the_board['3 1']],
[the_board['1 3'],the_board['1 2'],the_board['1 1']],
[the_board['2 3'],the_board['2 2'],the_board['2 1']],
[the_board['3 3'],the_board['3 2'],the_board['3 1']],
[the_board['1 3'],the_board['2 2'],the_board['3 1']],
[the_board['1 1'],the_board['2 2'],the_board['3 3']]]
Is there any way that when I type wins[0][0], it prints "the_board['1 3']"? Can I then assign an "X" to the_board['1 3']?
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62745235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get metadata from Azure Data Lake store gen1 We would like to get the metadata out of the file system. Is there anything like fsImage which stores such a medata information? We used following command:
curl -i -X GET -H 'Authorization: Bearer <REDACTED>' 'https://<yourstorename>.azuredatalakestore.net/webhdfs/v1/?op=LISTSTATUS'
But this gives only lists only one level metadata. As per HDFS Api documentation, tried using following command:
curl -i -X GET -H 'Authorization: Bearer <REDACTED>' 'https://<yourstorename>.azuredatalakestore.net/webhdfs/v1/?op=LISTSTATUS_BATCH&startAfter=<CHILD> #added code style
But it gives error that it is not implemented.
A: I checked with Azur support and they mentioned that not all the methods provided by Hadoop are implemented. So in my case LISTSTATUS_BATCH is not implmented.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54226146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: .NET WCF RIA + Services; Can I have it all? What I'd like to have is "regular" WCF service calls responding on my root URL as well as the regular RIA stuff. Seems simple, but is turning out to be a bit of a pain. The RIA stuff works including ODATA JSON and SOAP, but the traditional web services doesn't want to run off the root URL.
See the following code:
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.DomainServices.Hosting;
using System.ServiceModel.DomainServices.Server;
using System.ServiceModel.Web;
using Microsoft.ServiceModel.DomainServices.Hosting;
namespace ConsoleApplication1
{
public partial class Program
{
[EnableClientAccess, ServiceContract]
public class TestDomainService : DomainService
{
[Query(IsDefault = true)]
public IQueryable<Foo> GetAllFoos()
{
return new Foo[] { new Foo { Id = 1, Name = "Jonathan" } }.AsQueryable();
}
[WebInvoke(Method="GET"), OperationContract]
public Message Test()
{
return WebOperationContext.Current.CreateTextResponse("Test");
}
}
public class Foo
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
static void Main(string[] args)
{
var baseUri = new Uri("http://localhost:999");
var svc = new DomainServiceHost(typeof(TestDomainService), new Uri[] { baseUri });
svc.Description.Behaviors.RemoveAll<AspNetCompatibilityRequirementsAttribute>();
svc.Description.Behaviors.OfType<ServiceMetadataBehavior>().First().HttpGetEnabled = true;
var svcDescription = DomainServiceDescription.GetDescription(typeof(TestDomainService));
var odataEndpoints = new ODataEndpointFactory().CreateEndpoints(svcDescription, svc);
var soapEndpoints = new SoapXmlEndpointFactory().CreateEndpoints(svcDescription, svc);
var jsonEndpoints = new JsonEndpointFactory().CreateEndpoints(svcDescription, svc);
var odata = odataEndpoints.First();
odata.Contract.Namespace = new Uri(baseUri, "ODATA").ToString();
odata.Address = new System.ServiceModel.EndpointAddress(new Uri(baseUri, "ODATA"));
var soap = soapEndpoints.First();
soap.Contract.Namespace = new Uri(baseUri, "SOAP").ToString();
soap.Address = new System.ServiceModel.EndpointAddress(new Uri(baseUri, "SOAP"));
var json = jsonEndpoints.First();
json.Contract.Namespace = new Uri(baseUri, "JSON").ToString();
json.Address = new System.ServiceModel.EndpointAddress(new Uri(baseUri, "JSON"));
var ep = new ServiceEndpoint(svc.Description.Endpoints[0].Contract, new WebHttpBinding(), new EndpointAddress(baseUri));
ep.Behaviors.Add(new WebHttpBehavior());
var cd = ContractDescription.GetContract(typeof(TestDomainService));
foreach (var op in cd.Operations)
{
if (ep.Contract.Operations.Any(o => o.Name == op.Name) == false)
{
ep.Contract.Operations.Add(op);
}
}
svc.Description.Endpoints.Add(ep);
svc.Description.Endpoints.Add(odata);
svc.Description.Endpoints.Add(soap);
svc.Description.Endpoints.Add(json);
svc.Open();
foreach (var endpoint in svc.Description.Endpoints)
{
Console.WriteLine("Domain service started on: {0}", endpoint.Address.Uri);
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
Accessing http://localhost:999/Test should result in just Test being displayed, but instead I get:
<Fault xmlns="http://schemas.microsoft.com/ws/2005/05/envelope/none">
<Code>
<Value>Sender</Value>
<Subcode>
<Value xmlns:a="http://schemas.microsoft.com/ws/2005/05/addressing/none">a:ActionNotSupported</Value>
</Subcode>
</Code>
<Reason>
<Text xml:lang="en-US">The message with Action '' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).</Text>
</Reason>
</Fault>
Can anyone see what I'm missing?
Thanks in advance!
A: For me, I just needed to return raw strings on that endpoint so I implemented my own HttpBehavior and DispatchFormatter as such:
public class WebHttpBehaviorEx : WebHttpBehavior
{
protected override IDispatchMessageFormatter GetReplyDispatchFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
{
return new DynamicFormatter();
}
}
public class DynamicFormatter : IDispatchMessageFormatter
{
public void DeserializeRequest(Message message, object[] parameters)
{
throw new NotImplementedException();
}
public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
{
return WebOperationContext.Current.CreateTextResponse((result ?? string.Empty).ToString());
}
}
and changed
ep.Behaviors.Add(new WebHttpBehavior());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8067999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: select data header join detail last doc_num header is promotion? I have two tables, named t_header and t_detail.
this data header
ID | doc_num | promotion
1 0001 0
2 0002 1
this data detail
ID | doc_num | item | price
1 0001 2 100
2 0001 3 170
3 0001 4 102
4 0001 5 105
5 0002 3 120
6 0002 4 99
7 0002 7 165
if promo = 1, then the price in detail would take detailed data promo price, for the table above if the item = 3 then will take the price = 120 because the item with doc_num 002 promo = 1, if no promo it will take prices docnum 001, 001 num doc standard prices, and group by item
output
ID | doc_num | item | price | promotion
1 0001 2 100 0
5 0002 3 120 1
6 0002 4 99 1
4 0001 5 105 0
7 0002 7 165 0
A: I guess you need to select promo price if it's available otherwise you need normal price. So you should select columns using IF statement after LEFT JOIN.
this query may help :
SELECT
if(td_prom.ID, td_prom.ID, td_norm.ID) as ID,
th.doc_num,
if(td_prom.price, td_prom.price, td_norm.price) as price,
if(td_prom.item, td_prom.item, td_norm.item) as item,
th.promo
FROM
t_header th
LEFT JOIN t_detail as td_norm ON th.doc_num = td_norm.doc_num AND th.promo = 0
LEFT JOIN t_detail as td_prom ON th.doc_num = td_prom.doc_num AND th.promo = 1
GROUP BY item
A: As I can see in you desired result, you don't want items to be shown twice. Next to this I assume you have an items table in your database. Then I came up with this query.
First part is to extract items in promo.
Second part add only those items which are not in promo, but exclude items that have a promo on them.
SELECT d.id, d.doc_num, d.item, d.price, h.promo
FROM items AS i
INNER JOIN detail AS d ON i.id = d.id
INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 1
UNION ALL
SELECT nopromo.*
FROM (SELECT d.id, d.doc_num, d.item, d.price, h.promo
FROM items AS i
INNER JOIN detail AS d ON i.id = d.id
INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 0) AS nopromo
LEFT OUTER JOIN
(SELECT d.id, d.doc_num, d.item, d.price, h.promo
FROM item AS i
INNER JOIN detail AS d ON i.id = d.id
INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 1) AS ipromo
ON nopromo.item = ipromo.item
WHERE ipromo.id IS NULL
ORDER BY item
Result
+---+--------+-----+------+------+
|id |doc_num |item |price |promo |
+---+--------+-----+------+------+
|1 |0001 |2 |100 |0 |
|5 |0002 |3 |120 |1 |
|6 |0002 |4 |99 |1 |
|4 |0001 |5 |105 |0 |
|7 |0002 |7 |165 |1 |
+---+--------+-----+------+------+
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43087408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get Gps location(long,lat) and time in this Android application I need help form my android app. in this app,NOW, i take some data from a form end then i put it on a db. but i need to show and i need to put in to a db the current GPS Location and the Current Time Too.I already tried to use tutorial and see other posts on the forum with NO results. I need help because I don't understand how to work the location Listener and whereI have to change the project.
Thanks.
This is my Code
FORM.java
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AutoCompleteTextView;
public class Form extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onAddClick(View botton) {
AutoCompleteTextView spedID = (AutoCompleteTextView) findViewById(R.id.SpedID);
AutoCompleteTextView spedCliente = (AutoCompleteTextView) findViewById(R.id.SpedCliente);
AutoCompleteTextView spedCorriere = (AutoCompleteTextView) findViewById(R.id.SpedCorriere);
Intent intent = new Intent();
intent.setClass(this, Result.class);
intent.putExtra("SpedID", spedID.getText().toString());
intent.putExtra("SpedCliente", spedCliente.getText().toString());
intent.putExtra("SpedCorriere", spedCorriere.getText().toString());
startActivity(intent);
}
public void onCancelClick(View botton) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(this, Result.class));
intent.putExtra("Cancel", "Cancel");
startActivity(intent);
}
}
RESULT.java
import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.TextView;
public class Result extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
TextView resultText = (TextView) findViewById(R.id.resultText);
Bundle bundle = getIntent().getExtras();
if (bundle.getString("Cancel") != null) {
resultText.setText(getString(R.string.cancelOp));
} else {
String spedID = bundle.getString("SpedID");
String spedCliente = bundle.getString("SpedCliente");
String spedCorriere = bundle.getString("SpedCorriere");
insertSpedizione(spedID, spedCliente, spedCorriere); // metodo per
// inserire
// dati in
// db
resultText.setText(getString(R.string.resultOk) + "\n" + spedID
+ "\n" + spedCliente + "\n" + spedCorriere);
}
}
private void insertSpedizione(String idsped, String cliente,
String idcorriere) {
// metodo insertspedizione riceve in ingresso i parametri sped,cliente
// etc etc
DatabaseHelper databaseHelper = new DatabaseHelper(this);
SQLiteDatabase db = databaseHelper.getWritableDatabase(); // creo un
// database
// Srivibile
ContentValues cv = new ContentValues(); // Hashmap
cv.put(DatabaseHelper.IDSPED, idsped); // nome colonna, valore
cv.put(DatabaseHelper.CLIENTE, cliente);// nome colonna, valore
cv.put(DatabaseHelper.IDCORRIERE, idcorriere);// nome colonna, valore
db.insert("spedizioni", DatabaseHelper.IDSPED, cv); // faccio un insert
// nella TABLE
// spedizioni con
// parametri IDSPED
// not null e il
// ContentValues
db.close(); // quando abbiamo finito chiudiamo
}
}
DATABASEHELPER.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "datasped.db"; // nome database
// che viene
// creato da
// SQLiteOpenHelper
public static final String IDSPED = "idsped";
public static final String CLIENTE = "cliente";
public static final String IDCORRIERE = "idcorriere";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1); // 1 è la versione iniziale del
// database che viene aggiornata
// con onUpgrade
}
@Override
public void onCreate(SQLiteDatabase db) { // onCreate crea la
// tabella(formattazione,
// indici, etc) con tutti i dati
// ce voglio nel .db
db.execSQL("CREATE TABLE spedizioni (_id INTEGER PRIMARY KEY AUTOINCREMENT,idsped TEXT, cliente TEXT,idcorriere TEXT);");
}// in questo caso mi basta creare una Table semplice con id incrementale
// per ogni dato inserito
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // cambia
// la
// versione
// del
// database
android.util.Log.w("spedizioni",
"Ugrading database, which will destroy all old data");
db.execSQL("DROP TABLE IF EXIST spedizioni");
onCreate(db); // ricreo il Database
}
}
MANIFEST.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="matteo.android.SpedyGo" android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="9" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Form" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Result" android:label="@string/result">
</activity>
</application>
</manifest>
STRINGS.xml
<resources>
<string name="hello">Hello World, Form!</string>
<string name="app_name">SpedyGo</string>
<string name="InserisciSpedizione">Inserisci Spedizione</string>
<string name="textsped">Id Spedizione</string>
<string name="textcliente">Cliente</string>
<string name="textCorriere">Id Corriere</string>
<string name="cancel">Cancella</string>
<string name="confirm">Conferma</string>
<string name="result">Risultato</string>
<string name="resultOk">Operazione Avvenuta con Successo</string>
<string name="cancelOp">Operazione Cancellata</string>
</resources>
MAIN.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/InserisciSpedizione"
android:textSize="30sp" android:textStyle="bold" android:gravity="center" />
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="@+id/linearLayout1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/textsped"
android:textStyle="bold" android:padding="5sp" android:width="120sp"
android:textSize="16sp"></TextView>
<AutoCompleteTextView android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:width="500sp" android:id="@+id/SpedID"></AutoCompleteTextView>
</LinearLayout>
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="@+id/linearLayout1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textStyle="bold"
android:padding="5sp" android:text="@string/textcliente"
android:textSize="16sp" android:width="120sp"></TextView>
<AutoCompleteTextView android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:width="500sp" android:id="@+id/SpedCliente"></AutoCompleteTextView>
</LinearLayout>
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="@+id/linearLayout1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textStyle="bold"
android:padding="5sp" android:text="@string/textCorriere"
android:textSize="16sp" android:width="120sp"></TextView>
<AutoCompleteTextView android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:width="500sp" android:id="@+id/SpedCorriere"></AutoCompleteTextView>
</LinearLayout>
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="@+id/linearLayout2">
<Button android:layout_height="wrap_content" android:text="@string/cancel"
android:layout_width="130sp" android:onClick="onCancelClick"></Button>
<Button android:layout_height="wrap_content" android:text="@string/confirm"
android:layout_width="130sp" android:onClick="onAddClick"></Button>
</LinearLayout>
</LinearLayout>
RESULT.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:textStyle="bold"
android:focusableInTouchMode="false" android:textSize="25sp"
android:padding="10sp" android:gravity="center" android:text="@string/result" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:textStyle="bold"
android:focusableInTouchMode="false" android:textSize="20sp"
android:padding="10sp" android:gravity="center" android:text=""
android:id="@+id/resultText" />
</LinearLayout>
A: Declare private LocationManager locationManager;
then
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new GeoUpdateHandler());
next create a class GeoUpdateHandler which implements LocationListener and has the function
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lon = (int) (location.getLongitude() * 1E6);
String tim = String.format("%d", location.getTime());}
A: Here is a simple example of retrieving the location of a user, using the Network Provider
// Acquire a reference to the system Location Manager
myLocManager = (LocationManager)getSystemService( Context.LOCATION_SERVICE );
// Define a listener that responds to location updates
locationListener = new LocationListener()
{
@Override
public void onLocationChanged(Location location)
{
// Return a string representation of the latitude & longitude. Pass it to the textview and update the text
String tempLat = ""+location.getLatitude();
String tempLon = ""+location.getLongitude();
tempLat = refineStrg( tempLat );
tempLon = refineStrg( tempLon );
// Store/set lat and long values
storeLat_storeLong( tempLat, tempLon );
}
@Override
public void onProviderDisabled(String arg0)
{
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider)
{
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
// TODO Auto-generated method stub
}
};
// The two lines below request location updates from the network location provider
myLocManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0,locationListener );
Remember to include the proper permissions in the manifest file for accessing user location (consult the website I posted in my comment)
Finally to retrieve the current time you could use the Calendar or Date class, like so:
Calendar cal = Calendar.getInstance();
cal.getTime();
Look here for info on how to use the Date class over the Calendar.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10114793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using dlls written in C# in Java Project I'm working on a Java project and I'm not very familiar with using Java
I usually use C# with aforge for my computer vision projects
now I have to use Java and I want to use the aforge DLLs which are written in C#
is there a way to do this ?
Thank you
A: It is possible, but you'll need to do some work to get them calling properly. I've never done it myself, but until someone better equipped to answer the question comes along here's a few places to start.
Take a look at the JNI (Java Native Interface, google or wikipedia can tell you more), which lets you call out from Java to other languages. There seems to be a project called jni4net ( http://jni4net.sourceforge.net ) which is intended to do exactly what you want, but it's in alpha at the moment and might not be stable enough. Still it could be worth having a look.
You can also do it yourself, calling through the JNI as a C call which will then get through to the CLR eventually, but it looks like a lot of effort. I know this isn't a quick and easy solution, but it might give you a couple of places to get started. also http://www.codeproject.com/KB/cross-platform/javacsharp.aspx seemed to be a fairly good look at how to go about it.
As all of the other answers so far have said though, it's fiddly and a pain. If you can do something else instead, it will probably be worth it.
A: Have a look at Jni4Net and this stack overflow question: is there an effective tool to convert c# to java?
A: You would have to use native calls which would a) be really irritating to keep up to date and B) defeat the huge advantage of java being cross-platform.
Your best bet might be to try to find something that can convert C# to java--or better yet recode your C# code into java.
In the long run it will save you a lot of stress.
A: No sure about this possibility but your idea is not so good.
You still can use COM or hook or try ngen but this ways all are weird.
Java is very similar C# . Try to code in Java or something like stab , I think that is much easer to code in some JVM-based langue for jvm.
A: Diferent compilers dud, it's not possible. Unless You use java sharp language in visual studio, then the compilers mach.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5618599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How to zoom in and zoom out terminal console in linux I am able to zoom in the Ubuntu Terminal by Pressing Ctrl - Shift and ++ . But I donot know how to zoom out the Ubuntu Terminal.
Is there any short-cuts available for doing so?
A: Try this following method:
*
*Zoom In : Ctrl+Shift++
*Zoom Out: Ctrl+-
*Zoom 100%: Ctrl+0
Hope this helps!
A: To zoom in do
ctrl Shift +
To zoom out do
ctrl -
A: Try the following keystrokes
Ctrl + -
A: Ctrl + - doesn't work for me. But a workaround is to change the shortcut for the Zoom Out action.
Right click on the terminal and select Preferences. Then Shortcuts. Then change the Shortcut Key for Zoom Out to whatever you want. I chose Ctrl + Backspace.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54302941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Binding a callbacks to an expiring shared_ptr? I am familiar with std::shared_ptr and std::weak_ptr and know how they work. However, I would like the std::shared_ptr to emit a callback, like a boost signal. This would allow std::weak_ptr, who still refer to the deleted object, to be cleaned up right in time.
Is there maybe already some smart pointer implementation, which will report the destruction?
Explanation
I think there might be a small design flaw in std::weak_ptrs, that can lead to false memory leaks. By "false memory leak" I mean an object, that is still accessible by the program, but whose reason of existence is not valid anymore. The difference to a true memory leak is, that the true memory leak is completely unknown by the program, while the false leak is just a part that wasn't cleaned up properly.
Another description can be found at codingwisdom.com
Use Watchers
*
*One of the problems with freeing an object is that you may have done so while other things are still pointing at it. This introduces dangling pointers and crashes! To combat the evil of dangling pointers, I like to use a basic "watcher" system. This is not unlike the weak reference discussed above. The implementation is like this:
*Create a base class "Watchable" that you derive from on objects that should broadcast when they're being deleted. The Watchable object keeps track of other objects pointing at it.
Create a "Watcher" smart pointer that, when assigned to, adds itself to the list of objects to be informed when its target goes away.
This basic technique will go a long way toward solving dangling pointer issues without sacrificing explicit control over when an object is to be destroyed.
Example
Let's say we implement the observer pattern using boost Boost Signals2. We have a class Observable, that contains one or more signals and another class Observer, that connects to Observable's signals.
What would happen to Observable's slots, when a observing Observer is deleted? When we do nothing, then the connection would point to nowhere and we would probably receive a segmentation fault, when emitting the signal.
To deal with this issue, boost's slots also offer a method track(const weak_ptr<void>& tracked_object). That means, if I call track and pass a weak_ptr to Observer, then the slot won't be called when the weak_ptr expired. Instead, it will be deleted from the signal.
Where is the problem? Let's we delete an Observer and never call a certain signal of Observable ever again. In this case, the tracked connection will also never be deleted. Next time we emit the signal it will be cleaned up. But we don't emit it. So the connection just stays there and wastes resources.
A solution would be: when owning shared_ptr should emit a signal when it is destroying it's object. This would allow other other objects to clean up right in time. Everything that has a weak_ptr to the deleted object might register a callback and false memory leaks could be avoided.
A: //
// create a C function that does some cleanup or reuse of the object
//
void RecycleFunction
(
MyClass * pObj
)
{
// do some cleanup with pObj
}
//
// when you create your object and assign it to a shared pointer register a cleanup function
//
std::shared_ptr<MyClass> myObj = std::shared_ptr<MyClass>( new MyClass,
RecycleFunction);
Once the last reference expires "RecyleFunction" is called with your object as parameter. I use this pattern to recycle objects and insert them back into a pool.
A:
This would allow std::weak_ptr, who still refer to the deleted object,
to be cleaned up right in time.
Actually, they only hold weak references, which do not prevent the object from being destroyed. Holding weak_ptrs to an object does not prevent it's destruction or deletion in any fashion.
The quote you've given sounds to me like that guy just doesn't know which objects own which other objects, instead of having a proper ownership hierarchy where it's clearly defined how long everything lives.
As for boost::signals2, that's what a scoped_connection is for- i.e., you're doing it wrong.
The long and short is that there's nothing wrong with the tools in the Standard (except auto_ptr which is broken and bad and we have unique_ptr now). The problem is that you're not using them properly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30012967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to solve an authentication error on Belboon webservice in .NET? This is what i've tried in VB.NET, but i always get an authentication error ("Unauthorized (user= transaction=1)"):
Dim s As com.belboon.api.BelboonHandler = New com.belboon.api.BelboonHandler
s.Credentials = New System.Net.NetworkCredential(username, password)
's.RequestEncoding = Text.ASCIIEncoding.UTF8
s.UseDefaultCredentials = False
's.PreAuthenticate = True
's.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)"
's.InitializeLifetimeService()
's.UnsafeAuthenticatedConnectionSharing = False
s.getAccountInfo()
There is only an example in PHP delivered by Belboon. I've tried this too, and it works fine:
define('WSDL_SERVER', 'http://api.belboon.com/?wsdl');
// SOAP options (http://de.php.net/manual/de/soapclient.soapclient.php)
$config = array(
'login' => 'YOUR_LOGIN_NAME',
'password' => 'YOUR_WEBSERVICE_PASSWORD',
'trace' => true
);
try {
$client = new SoapClient(WSDL_SERVER, $config);
$result = $client->getAccountInfo();
echo '<pre>';
print_r($result);
} catch( Exception $e ) {
But what might the auth error in VB.NET be caused by? The credentials are definitely the same in both examples...
A: Sorry, got it myself. Like explained here:
https://intellitect.com/calling-web-services-using-basic-authentication/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53950788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JSP convert string to object As the title said, I want to execute following code
<%
String res = "response.sendError ( HttpServletResponse.SC_UNAUTHORIZED,\"You don't have enough privileges\" );";
%>
<%=res%>
so when I execute this code I need to get http 401 Unauthorized error.
Since it is in string format I get following string in browser instead of get http 401 Unauthorized error
response.sendError ( HttpServletResponse.SC_UNAUTHORIZED,"You don't have enough privileges" );
So how can I convert this string into object so that I can get http 401 Unauthorized error.
A: Just use:
<% response.sendError(...); %>
The <% ... %> delimiters already execute code directly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19227111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android UriMatcher doesn't match wildcards I have a ContentProvider and I need to match some URIs containing UUIDs as wildcards.
UriMatcher from ContentProvider:
public static final Uri CONTENT_URI_NOTIFICATIONS = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH_NOTIFICATIONS);
public static final Uri CONTENT_URI_USERS = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH_USERS);
private static final int NOTIFICATIONS = 40;
private static final int USER_ID = 70;
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static
{
sURIMatcher.addURI(AUTHORITY, BASE_PATH_NOTIFICATIONS, NOTIFICATIONS);
sURIMatcher.addURI(AUTHORITY, BASE_PATH_USERS + "/*", USER_ID);
}
Query Code for NOTIFICATIONS:
Uri uri = Uri.parse(String.valueOf(MyContentProvider.CONTENT_URI_NOTIFICATIONS));
return new CursorLoader(getActivity(), uri, projection, null, null, null);
Query Code for USER_ID:
String userId = "73279386-5459-4316-9ff9-7c6b7b84029a";
Uri uri = Uri.parse(MyContentProvider.CONTENT_URI_USERS + "/" + userId);
return new CursorLoader(getActivity(), uri, projection, null, null, null);
From the above UriMatcher, the NOTIFICATIONS URI matches, but the USER_ID does not. Any idea what could be wrong here ? Worth noting is that when I used to have integers instead of UUIDs for representing users and used to have # instead of * in the UriMatcher, everything worked as intended. After switching to the wildcard, the matcher stopped matching the URIs containing UUIDs.
A: Apparently the order in which you add the URIs counts. If you have set like below, USER_DETAILS won't be recognized anymore. You have to switch the order and add USER_DETAILS first.
sURIMatcher.addURI(AUTHORITY, BASE_PATH_USERS + "/*", USER_ID);
sURIMatcher.addURI(AUTHORITY, BASE_PATH_USERS + "/details", USER_DETAILS);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30446481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can't access file in Alias-directory via download-script i'm working on a download-script atm. The php-files are located in the xampp htdocs-directory, while the folder containing the files is located on an external HDD.
I've already set up an Alias for the external drive:
<Directory "h:/Filme">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Require all granted
Order allow,deny
Allow from all
</Directory>
Alias /filme "H:/Filme"
This is the download-script:
<?php
$download_dir = "filme/";
$files = array(
"1" => "300.avi",
"2" => "asdf.txt",
"3" => "doc.pdf",
"4" => "bild3.jpg",
);
$file = $download_dir.$files[$_GET['id']];
header("Content-Type: x-type/subtype");
header("Content-Length: ".filesize($file));
header("Content-Disposition: attachment; filename=".$files[$_GET['id']]);
readfile($file);
?>
Download is started via:
<a href="download.php?id=2">asdf.txt</a><BR>
Now, the problem is the following:
i can acces files, like for example asdf.txt, by typing localhost/filme/asdf.txt in my browser's address-bar.
However, the file i can download using the download-script says:
<br />
<b>Warning</b>: filesize(): stat failed for filme/asdf.txt in <b>C:\Program Files\xampp\htdocs\download.php</b> on line <b>26</b><br />
<br />
<b>Warning</b>: readfile(filme/asdf.txt): failed to open stream: No such file or directory in <b>C:\Program Files\xampp\htdocs\download.php</b> on line <b>32</b><br />
And i honestly have NO idea how to fix this O.o
TY for answers etc <3
A: There is a difference between the path structure in HTTP and in the file system. PHP knows nothing about the defined alias for HTTP access.
You have to define the path to the files in a way that the file system understands. Which probably means to use
$download_dir = "H:/Filme/";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17903220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Export a string or an array to CSV I have a very simple array that I'd like to export to CSV:
var uniqueCounties = ["555","123","345"];
I have tried using methods found online but I have been getting various errors, and all the methods online deal with nested arrays.
My function at the moment is converting to a string. I was hoping it would simplify the process but I'm still now sure how to progress:
function download_csv() {
var csv = uniqueCounties.toString();
console.log(csv);
}
I was originally trying this method:
uniqueCounties.forEach(function(infoArray, index){
dataString = infoArray.join(",");
csvContent += index < data.length ? dataString+ "\n" : dataString;
});
But kept getting the error infoArray.join is not a function.
A: If you have a 2d array of strings (or anything that you are ok with toString-ing) for example:
const input = [
["555","123","345"],
[1, 2, 3],
[true, false, "foo"]
]
Then you can do something like this:
function toCsv(input) {
return input.map(row => row.join(',')).join('\n')
}
const csvString = toCsv(input)
Resulting in this string:
555,123,345
1,2,3
true,false,foo
If you just want to convert a single 1d array to csv, like in the example then:
const uniqueCounties = ["555","123","345"]
// If you want each value as a column
const csvAsSingleRow = uniqueCounties.join(',')
// If you want each value as a row
const csvAsSingleColumn = uniqueCounties.join('\n')
This gets more and more complicated if you want to include escaping, etc... In that case I'd recommend looking for a library that does this well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43123685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Trying to multithread program. C++/CLI Hey i'm trying to multithread my program in c++/cli but i'm having problems with creating the threads the code im using is:
private: Void startThread() {
MoveProj.Velocity = Variables.Velocity;
MoveProj.ProjectilePos = Projectile1.ProjectilePos;
Thread^ MotionThread1 = gcnew Thread(gcnew ParameterizedThreadStart(MoveProj, MotionThread::MoveProjectile));
Thread^ MainThread = gcnew Thread(gcnew ThreadStart());
}
but i'm getting the errors
Error 44 error C3350: 'System::Threading::ParameterizedThreadStart' : a delegate constructor expects 2 argument(s) c:\users\gaz\documents\visual studio 2012\projects\projectilemotion\projectilemotion\Simulation.h 344
Error 89 error C3350: 'System::Threading::ParameterizedThreadStart' : a delegate constructor expects 2 argument(s) c:\users\gaz\documents\visual studio 2012\projects\projectilemotion\projectilemotion\Simulation.h 344
Error 45 error C3350: 'System::Threading::ThreadStart' : a delegate constructor expects 2 argument(s) c:\users\gaz\documents\visual studio 2012\projects\projectilemotion\projectilemotion\Simulation.h 345
Error 90 error C3350: 'System::Threading::ThreadStart' : a delegate constructor expects 2 argument(s) c:\users\gaz\documents\visual studio 2012\projects\projectilemotion\projectilemotion\Simulation.h 345
Error 43 error C3867: 'MotionThread::MoveProjectile': function call missing argument list; use '&MotionThread::MoveProjectile' to create a pointer to member c:\users\gaz\documents\visual studio 2012\projects\projectilemotion\projectilemotion\Simulation.h 344
Error 88 error C3867: 'MotionThread::MoveProjectile': function call missing argument list; use '&MotionThread::MoveProjectile' to create a pointer to member c:\users\gaz\documents\visual studio 2012\projects\projectilemotion\projectilemotion\Simulation.h 344
any help with this would be a great help as its for my college(British so senior year for americnas i think) computing project and my tutor wants it in relatively soon.
A: The error message is telling you what to do:
function call missing argument list;
use '&MotionThread::MoveProjectile' to create a pointer to member
^
Therefore, here's the correct syntax:
Thread^ MotionThread1 = gcnew Thread(
gcnew ParameterizedThreadStart(MoveProj, &MotionThread::MoveProjectile));
^
For the other one, you're currently trying to create a delegate, without telling it what method the delegate should point to. Try something like this:
Thread^ MainThread = gcnew Thread(gcnew ThreadStart(this, &MyClass::MainMethod));
^^^^^^^^^^^^^^^^^^^^^^^^^^
Edit
I didn't read through your full code. If you expect people to take their time to help you, you need to take some time & spend the effort to distill it down to just what's needed.
I will, however, comment on the errors you're getting.
error C2440: 'initializing' :
cannot convert from 'MotionThread' to 'MotionThread ^'
You've got a variable somewhere that's a reference type, but you're using it without the ^. This is valid C++/CLI, but none of the managed APIs will work with that easily. Switch the member to a ^ and use gcnew.
error C3352: 'float Allformvariables::CalcCurrentVelocity(System::Object ^)' :
the specified function does not match the delegate type 'void (void)'
As the error message says: You're trying to construct a delegate that doesn't take any parameters and returns void, and the method you're passing doesn't match that. Either fix the method or switch to a different delegate type.
error C3754: delegate constructor: member function 'MotionThread::MoveProjectile'
cannot be called on an instance of type 'MotionThread'
I have a feeling this one will go away when you add the missing ^ that I mentioned above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15949738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Issue with cron job scheduling I am trying to schedule a job every 10 minute during PST hours. What I am trying is:
0,10 8-15 * * * /path-to-script
But this thing is not working, any help is much appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32615084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Microsoft Azure - same login for windows app and web app I created two separate apps
*
*browser app (web app)
For authentication I am using adal.js, and its working fine.
*non browser app (console app)
for authentication adal.net and its working fine.
Problem:
For both browser app and for non browser, I have to login. so twice login on same machine.
Question.
What to do to merge these web and console app to one application, where user can authenticate once (single sign in ) and use both console app and web app.
A: As your applications are separate, essentially in the background meaning a different application ID and set of keys then merging the logins will not be possible. The authentication is based on OAuth so each application is treated as a separate resource meaning you'll need a valid token to authenticate requests against it.
Think of it another way, if you login to say Facebook or Twitter who both use OAuth then you login to the website, you have to login to the application on the mobile device again, that token cannot be used for another application.
A: It depends on the browser you were using.
If you were using the same browser for the web app and console app, the Azure AD will issue the cookies when you first time. And then the second sign-in request should be sign-in without users enter the credential again based on the cookies.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40420181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Overriding default SWIG name for static class functions I have several classes that I am using swig to wrap for an embedded Lua script. We have already defined what we want the function calls to look like.
display.writeLine("Hello")
The problem is that SWIG doesn't seem to have an option to define how it generates the library name. The c++ class looks like this.
class Display
{
public:
static void writeLine(char *);
}
I can easily get SWIG to wrap this function, it's just that always shows up like this
Display_writeLine()
So instead of just using my custom namespace, I would have to do
display.Display_writeLine()
which is not what I want. I have tried experimenting with the rename rules but nothing seems to work. Right now I have an extern C function that then calls my static function but it's an extra call I don't need. Seems like it should be something simple...
A: You can easily make a shortcut for your function that does same of function code and load the file on start:
display = {}
function display.writeline(str)
display.Display_writeLine(str)
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18300339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Visual Studio 2012 I am Having some issues with Visual Studio 2012, When build my solution and run the debug it says MSVCP100D.dll is missing
Screen dump:
When i try to run my program using Release it compiles fine and runs but then it randomly runs into run time error:
it then will not build any more underlining these CV_8U & CV_8UC3
I am using OpenCV library, also my code worked perfectly fine on Visual Studio 2010; but i decided to upgrade to 2012.
I would ideally Build my solution using DEBUG..........
Any solutions or suggestions...?
Regards
A: It looks like you are linking against the opencv libs for Visual Studio 2010. You will have to compile the opencv library for Visual Studio 2012 yourself as the pre-built ones are for Visual Studio 2010.
The information on how to do that can be found under Installation by Making Your Own Libraries from the Source Files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14944283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: copy multiple files and give prefix and keep originals how do i copy files in unix. i want to keep the originals and add a prefix to the originals.
i have the following:
file1.csv
file2.csv
file3.csv
file4.csv
...
fileX.csv
what I will end up with after giving the command(with "H_" being the prefix in this example):
file1.csv
file2.csv
file3.csv
file4.csv
...
fileX.csv
H_file1.csv
H_file2.csv
H_file3.csv
H_file4.csv
...
H_fileX.csv
I was looking at the cp or mv command, but have no luck yet
A: for file in *.csv; do
cp "$file" "H_$file"
done
A: for f in *.csv; do cp -v -- "$f" "H_$f"; done
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22213485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: I can't get magnific-popup animations to work I've been through the excellent documentation for this and it's great.
http://dimsemenov.com/plugins/magnific-popup/documentation.html
I have the basic pop up working fine.
My problem is with the animations. I just can't get them to work. Apologies if I've missed something very basic but I've spent too long on this now and hope someone can point out my mistake. It currently just appears no fade nothing.
I've played with it on codepen and can recreate the issue by removing the CSS so perhaps this is not getting through correctly, although I know it is linking as it is styling the pop up just not the animations.
Here is my html:
<div id="Column1"><div id="aboutus" >
<div id="pop" >
<a href="/stalkseed/assets/Uploads/stalk-seed-about-us.jpg" data-effect="mfp-newspaper" title="" alt="" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('about-us','','/stalkseed/assets/Uploads/aboutus-ovr.jpg',1)"><img src="/stalkseed/assets/Uploads/aboutus.jpg" name="about-us" border="0" id="about-us"/></a>
</div>
My JavaScript from the same page:
<script type="text/javascript">//<![CDATA[
$(document).ready(function() {
$('#pop').magnificPopup({
delegate: 'a',
type: 'image',
removalDelay: 500, //delay removal by X to allow out-animation
callbacks: {
beforeOpen: function() {
// just a hack that adds mfp-anim class to markup
this.st.image.markup = this.st.image.markup.replace('mfp-figure', 'mfp-figure mfp-with-anim');
this.st.mainClass = this.st.el.attr('data-effect');
}
},
closeOnContentClick: true,
midClick: true // allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source.
});});
//]]>
</script>
My CSS
@charset "UTF-8";
/* CSS Document */
/* Magnific Popup CSS */
.mfp-bg {
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 502;
overflow: hidden;
position: fixed;
background: #0b0b0b;
opacity: 0.8;
filter: alpha(opacity=80); }
.mfp-wrap {
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 503;
position: fixed;
outline: none !important;
-webkit-backface-visibility: hidden; }
.mfp-container {
height: 100%;
text-align: center;
position: absolute;
width: 100%;
height: 100%;
left: 0;
top: 0;
padding: 0 8px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box; }
.mfp-container:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle; }
.mfp-align-top .mfp-container:before {
display: none; }
.mfp-content {
position: relative;
display: inline-block;
vertical-align: middle;
margin: 0 auto;
text-align: left;
z-index: 505; }
.mfp-inline-holder .mfp-content,
.mfp-ajax-holder .mfp-content {
width: 100%;
cursor: auto; }
.mfp-ajax-cur {
cursor: progress; }
.mfp-zoom-out-cur,
.mfp-zoom-out-cur .mfp-image-holder .mfp-close {
cursor: -moz-zoom-out;
cursor: -webkit-zoom-out;
cursor: zoom-out; }
.mfp-zoom {
cursor: pointer;
cursor: -webkit-zoom-in;
cursor: -moz-zoom-in;
cursor: zoom-in; }
.mfp-auto-cursor .mfp-content {
cursor: auto; }
.mfp-close,
.mfp-arrow,
.mfp-preloader,
.mfp-counter {
-webkit-user-select: none;
-moz-user-select: none;
user-select: none; }
.mfp-loading.mfp-figure {
display: none; }
.mfp-hide {
display: none !important; }
.mfp-preloader {
color: #cccccc;
position: absolute;
top: 50%;
width: auto;
text-align: center;
margin-top: -0.8em;
left: 8px;
right: 8px;
z-index: 504; }
.mfp-preloader a {
color: #cccccc; }
.mfp-preloader a:hover {
color: white; }
.mfp-s-ready .mfp-preloader {
display: none; }
.mfp-s-error .mfp-content {
display: none; }
button.mfp-close,
button.mfp-arrow {
overflow: visible;
cursor: pointer;
background: transparent;
border: 0;
-webkit-appearance: none;
display: block;
padding: 0;
z-index: 506; }
button::-moz-focus-inner {
padding: 0;
border: 0; }
.mfp-close {
width: 44px;
height: 44px;
line-height: 44px;
position: absolute;
right: 0;
top: 0;
text-decoration: none;
text-align: center;
opacity: 0.65;
padding: 0 0 18px 10px;
color: white;
font-style: normal;
font-size: 28px;
font-family: Arial, Baskerville, monospace; }
.mfp-close:hover, .mfp-close:focus {
opacity: 1; }
.mfp-close:active {
top: 1px; }
.mfp-close-btn-in .mfp-close {
color: #333333; }
.mfp-image-holder .mfp-close,
.mfp-iframe-holder .mfp-close {
color: white;
right: -6px;
text-align: right;
padding-right: 6px;
width: 100%; }
.mfp-counter {
position: absolute;
top: 0;
right: 0;
color: #cccccc;
font-size: 12px;
line-height: 18px; }
.mfp-arrow {
position: absolute;
top: 0;
opacity: 0.65;
margin: 0;
top: 50%;
margin-top: -55px;
padding: 0;
width: 90px;
height: 110px;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0); }
.mfp-arrow:active {
margin-top: -54px; }
.mfp-arrow:hover,
.mfp-arrow:focus {
opacity: 1; }
.mfp-arrow:before, .mfp-arrow:after,
.mfp-arrow .mfp-b,
.mfp-arrow .mfp-a {
content: '';
display: block;
width: 0;
height: 0;
position: absolute;
left: 0;
top: 0;
margin-top: 35px;
margin-left: 35px;
border: solid transparent; }
.mfp-arrow:after,
.mfp-arrow .mfp-a {
opacity: 0.8;
border-top-width: 12px;
border-bottom-width: 12px;
top: 8px; }
.mfp-arrow:before,
.mfp-arrow .mfp-b {
border-top-width: 20px;
border-bottom-width: 20px; }
.mfp-arrow-left {
left: 0; }
.mfp-arrow-left:after,
.mfp-arrow-left .mfp-a {
border-right: 12px solid black;
left: 5px; }
.mfp-arrow-left:before,
.mfp-arrow-left .mfp-b {
border-right: 20px solid white; }
.mfp-arrow-right {
right: 0; }
.mfp-arrow-right:after,
.mfp-arrow-right .mfp-a {
border-left: 12px solid black;
left: 3px; }
.mfp-arrow-right:before,
.mfp-arrow-right .mfp-b {
border-left: 20px solid white; }
.mfp-iframe-holder {
padding-top: 40px;
padding-bottom: 40px; }
.mfp-iframe-holder .mfp-content {
line-height: 0;
width: 100%;
max-width: 900px; }
.mfp-iframe-scaler {
width: 100%;
height: 0;
overflow: hidden;
padding-top: 56.25%; }
.mfp-iframe-scaler iframe {
position: absolute;
display: block;
top: 0;
left: 0;
width: 100%;
height: 100%;
box-shadow: 0 0 8px rgba(0, 0, 0, 0.6);
background: black; }
.mfp-iframe-holder .mfp-close {
top: -40px; }
/* Main image in popup */
img.mfp-img {
width: auto;
max-width: 100%;
height: auto;
display: block;
line-height: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 40px 0 40px;
margin: 0 auto; }
/* The shadow behind the image */
.mfp-figure:after {
content: '';
position: absolute;
left: 0;
top: 40px;
bottom: 40px;
display: block;
right: 0;
width: auto;
height: auto;
z-index: -1;
box-shadow: 0 0 8px rgba(0, 0, 0, 0.6); }
.mfp-figure {
line-height: 0; }
.mfp-bottom-bar {
margin-top: -36px;
position: absolute;
top: 100%;
left: 0;
width: 100%;
cursor: auto; }
.mfp-title {
text-align: left;
line-height: 18px;
color: #f3f3f3;
word-break: break-word;
padding-right: 36px; }
.mfp-figure small {
color: #bdbdbd;
display: block;
font-size: 12px;
line-height: 14px; }
.mfp-image-holder .mfp-content {
max-width: 100%; }
.mfp-gallery .mfp-image-holder .mfp-figure {
cursor: pointer; }
@media screen and (max-width: 800px) and (orientation: landscape), screen and (max-height: 300px) {
/**
* Remove all paddings around the image on small screen
*/
.mfp-img-mobile .mfp-image-holder {
padding-left: 0;
padding-right: 0; }
.mfp-img-mobile img.mfp-img {
padding: 0; }
/* The shadow behind the image */
.mfp-img-mobile .mfp-figure:after {
top: 0;
bottom: 0; }
.mfp-img-mobile .mfp-bottom-bar {
background: rgba(0, 0, 0, 0.6);
bottom: 0;
margin: 0;
top: auto;
padding: 3px 5px;
position: fixed;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box; }
.mfp-img-mobile .mfp-bottom-bar:empty {
padding: 0; }
.mfp-img-mobile .mfp-counter {
right: 5px;
top: 3px; }
.mfp-img-mobile .mfp-close {
top: 0;
right: 0;
width: 35px;
height: 35px;
line-height: 35px;
background: rgba(0, 0, 0, 0.6);
position: fixed;
text-align: center;
padding: 0; }
.mfp-img-mobile .mfp-figure small {
display: inline;
margin-left: 5px; } }
@media all and (max-width: 800px) {
.mfp-arrow {
-webkit-transform: scale(0.75);
transform: scale(0.75); }
.mfp-arrow-left {
-webkit-transform-origin: 0;
transform-origin: 0; }
.mfp-arrow-right {
-webkit-transform-origin: 100%;
transform-origin: 100%; }
.mfp-container {
padding-left: 6px;
padding-right: 6px; } }
.mfp-ie7 .mfp-img {
padding: 0; }
.mfp-ie7 .mfp-bottom-bar {
width: 600px;
left: 50%;
margin-left: -300px;
margin-top: 5px;
padding-bottom: 5px; }
.mfp-ie7 .mfp-container {
padding: 0; }
.mfp-ie7 .mfp-content {
padding-top: 44px; }
.mfp-ie7 .mfp-close {
top: 0;
right: 0;
padding-top: 0; }
/*html,body {margin:0; padding:10px; -webkit-backface-visibility:hidden;
background-color: #eee3da;
}*/
/* text-based popup styling */
.white-popup {
position: relative;
background: #FFF;
padding: 25px;
width:auto;
max-width: 400px;
margin: 0 auto;
}
/*
====== Zoom effect ======
*/
.mfp-zoom-in {
/* start state */
.mfp-with-anim {
opacity: 0;
transition: all 0.2s ease-in-out;
transform: scale(0.8);
}
&.mfp-bg {
opacity: 0;
transition: all 0.3s ease-out;
}
/* animate in */
&.mfp-ready {
.mfp-with-anim {
opacity: 1;
transform: scale(1);
}
&.mfp-bg {
opacity: 0.8;
}
}
/* animate out */
&.mfp-removing {
.mfp-with-anim {
transform: scale(0.8);
opacity: 0;
}
&.mfp-bg {
opacity: 0;
}
}
}
/*
====== Newspaper effect ======
*/
.mfp-newspaper {
/* start state */
.mfp-with-anim {
opacity: 0;
-webkit-transition: all 0.2s ease-in-out;
transition: all 0.5s;
transform: scale(0) rotate(500deg);
}
&.mfp-bg {
opacity: 0;
transition: all 0.5s;
}
/* animate in */
&.mfp-ready {
.mfp-with-anim {
opacity: 1;
transform: scale(1) rotate(0deg);
}
&.mfp-bg {
opacity: 0.8;
}
}
/* animate out */
&.mfp-removing {
.mfp-with-anim {
transform: scale(0) rotate(500deg);
opacity: 0;
}
&.mfp-bg {
opacity: 0;
}
}
}
/*
====== Move-horizontal effect ======
*/
.mfp-move-horizontal {
/* start state */
.mfp-with-anim {
opacity: 0;
transition: all 0.3s;
transform: translateX(-50px);
}
&.mfp-bg {
opacity: 0;
transition: all 0.3s;
}
/* animate in */
&.mfp-ready {
.mfp-with-anim {
opacity: 1;
transform: translateX(0);
}
&.mfp-bg {
opacity: 0.8;
}
}
/* animate out */
&.mfp-removing {
.mfp-with-anim {
transform: translateX(50px);
opacity: 0;
}
&.mfp-bg {
opacity: 0;
}
}
}
/*
====== Move-from-top effect ======
*/
.mfp-move-from-top {
.mfp-content {
vertical-align:top;
}
/* start state */
.mfp-with-anim {
opacity: 0;
transition: all 0.2s;
transform: translateY(-100px);
}
&.mfp-bg {
opacity: 0;
transition: all 0.2s;
}
/* animate in */
&.mfp-ready {
.mfp-with-anim {
opacity: 1;
transform: translateY(0);
}
&.mfp-bg {
opacity: 0.8;
}
}
/* animate out */
&.mfp-removing {
.mfp-with-anim {
transform: translateY(-50px);
opacity: 0;
}
&.mfp-bg {
opacity: 0;
}
}
}
/*
====== 3d unfold ======
*/
.mfp-3d-unfold {
.mfp-content {
perspective: 2000px;
}
/* start state */
.mfp-with-anim {
opacity: 0;
transition: all 0.3s ease-in-out;
transform-style: preserve-3d;
transform: rotateY(-60deg);
}
&.mfp-bg {
opacity: 0;
transition: all 0.5s;
}
/* animate in */
&.mfp-ready {
.mfp-with-anim {
opacity: 1;
transform: rotateY(0deg);
}
&.mfp-bg {
opacity: 0.8;
}
}
/* animate out */
&.mfp-removing {
.mfp-with-anim {
transform: rotateY(60deg);
opacity: 0;
}
&.mfp-bg {
opacity: 0;
}
}
}
/*
====== Zoom-out effect ======
*/
.mfp-zoom-out {
/* start state */
.mfp-with-anim {
opacity: 0;
transition: all 0.3s ease-in-out;
transform: scale(1.3);
}
&.mfp-bg {
opacity: 0;
transition: all 0.3s ease-out;
}
/* animate in */
&.mfp-ready {
.mfp-with-anim {
opacity: 1;
transform: scale(1);
}
&.mfp-bg {
opacity: 0.8;
}
}
/* animate out */
&.mfp-removing {
.mfp-with-anim {
transform: scale(1.3);
opacity: 0;
}
&.mfp-bg {
opacity: 0;
}
}
}
/*
====== "Hinge" close effect ======
*/
@keyframes hinge {
0% { transform: rotate(0); transform-origin: top left; animation-timing-function: ease-in-out; }
20%, 60% { transform: rotate(80deg); transform-origin: top left; animation-timing-function: ease-in-out; }
40% { transform: rotate(60deg); transform-origin: top left; animation-timing-function: ease-in-out; }
80% { transform: rotate(60deg) translateY(0); opacity: 1; transform-origin: top left; animation-timing-function: ease-in-out; }
100% { transform: translateY(700px); opacity: 0; }
}
.hinge {
animation-duration: 1s;
animation-name: hinge;
}
.mfp-with-fade {
// before-open state
.mfp-content,
&.mfp-bg {
opacity: 0;
transition: opacity .5s ease-out;
}
// open state
&.mfp-ready {
.mfp-content {
opacity: 1;
}
&.mfp-bg {
opacity: 0.8; // background opacity
}
}
// closed state
&.mfp-removing {
&.mfp-bg {
opacity: 0;
}
}
}
A: I ran into this same problem and after banging my head against all the hard surfaces in my office I discovered that I need to rename the css classes to match the fade example he provided here.
So for example the mfp-zoom-out animation:
.mfp-zoom-out .mfp-with-anim should be .mfp-zoom-out.mfp-bg
.mfp-zoom-out.mfp-bg stays the same
.mfp-zoom-out.mfp-ready .mfp-with-anim should be .mfp-zoom-out.mfp-ready .mfp-content
.mfp-zoom-out.mfp-ready.mfp-bg should be .mfp-zoom-out.mfp-bg.mfp-ready
.mfp-zoom-out.mfp-removing .mfp-with-anim should be .mfp-zoom-out.mfp-removing .mfp-content
.mfp-zoom-out.mfp-removing.mfp-bg should be .mfp-zoom-out.mfp-bg.mfp-removing
A: You can also make great use of animate.css (http://daneden.github.io/animate.css/). Once you initialize the popup make sure you add animate class along with the desired animation class from the library. For example animate fadeIn.
A: Check i have code for Fade-zoom animation for first dialog and Fade-move animation for second dialog.
You can get magnific-popup.css and magnific-popup.min.js files in the dist folder...Files can be downloaded from https://github.com/dimsemenov/Magnific-Popup
<html lang="en">
<head>
<title><!-- Insert your title here --></title>
<link rel="stylesheet" href="magnific-popup.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="jquery.magnific-popup.min.js"></script>
</head>
<body>
<div class="example gc3">
<h3>Dialog with CSS animation</h3>
<div class="html-code">
<a class="popup-with-zoom-anim" href="#small-dialog" >Open with fade-zoom animation</a><br/>
<a class="popup-with-move-anim" href="#small-dialog" >Open with fade-slide animation</a>
<!-- dialog itself, mfp-hide class is required to make dialog hidden -->
<div id="small-dialog" class="zoom-anim-dialog mfp-hide">
<h1>Dialog example</h1>
<p>This is dummy copy. It is not meant to be read. It has been placed here solely to demonstrate the look and feel of finished, typeset text. Only for show. He who searches for meaning here will be sorely disappointed.</p>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('.popup-with-zoom-anim').magnificPopup({
type: 'inline',
fixedContentPos: false,
fixedBgPos: true,
overflowY: 'auto',
closeBtnInside: true,
preloader: false,
midClick: true,
removalDelay: 300,
mainClass: 'my-mfp-zoom-in'
});
$('.popup-with-move-anim').magnificPopup({
type: 'inline',
fixedContentPos: false,
fixedBgPos: true,
overflowY: 'auto',
closeBtnInside: true,
preloader: false,
midClick: true,
removalDelay: 300,
mainClass: 'my-mfp-slide-bottom'
});
});
</script>
<style type="text/css">
/* Styles for dialog window */
#small-dialog {
background: white;
padding: 20px 30px;
text-align: left;
max-width: 400px;
margin: 40px auto;
position: relative;
}
/**
* Fade-zoom animation for first dialog
*/
/* start state */
.my-mfp-zoom-in .zoom-anim-dialog {
opacity: 0;
-webkit-transition: all 0.2s ease-in-out;
-moz-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
-webkit-transform: scale(0.8);
-moz-transform: scale(0.8);
-ms-transform: scale(0.8);
-o-transform: scale(0.8);
transform: scale(0.8);
}
/* animate in */
.my-mfp-zoom-in.mfp-ready .zoom-anim-dialog {
opacity: 1;
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
}
/* animate out */
.my-mfp-zoom-in.mfp-removing .zoom-anim-dialog {
-webkit-transform: scale(0.8);
-moz-transform: scale(0.8);
-ms-transform: scale(0.8);
-o-transform: scale(0.8);
transform: scale(0.8);
opacity: 0;
}
/* Dark overlay, start state */
.my-mfp-zoom-in.mfp-bg {
opacity: 0.001; /* Chrome opacity transition bug */
-webkit-transition: opacity 0.3s ease-out;
-moz-transition: opacity 0.3s ease-out;
-o-transition: opacity 0.3s ease-out;
transition: opacity 0.3s ease-out;
}
/* animate in */
.my-mfp-zoom-in.mfp-ready.mfp-bg {
opacity: 0.8;
}
/* animate out */
.my-mfp-zoom-in.mfp-removing.mfp-bg {
opacity: 0;
}
/**
* Fade-move animation for second dialog
*/
/* at start */
.my-mfp-slide-bottom .zoom-anim-dialog {
opacity: 0;
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
-o-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
-webkit-transform: translateY(-20px) perspective( 600px ) rotateX( 10deg );
-moz-transform: translateY(-20px) perspective( 600px ) rotateX( 10deg );
-ms-transform: translateY(-20px) perspective( 600px ) rotateX( 10deg );
-o-transform: translateY(-20px) perspective( 600px ) rotateX( 10deg );
transform: translateY(-20px) perspective( 600px ) rotateX( 10deg );
}
/* animate in */
.my-mfp-slide-bottom.mfp-ready .zoom-anim-dialog {
opacity: 1;
-webkit-transform: translateY(0) perspective( 600px ) rotateX( 0 );
-moz-transform: translateY(0) perspective( 600px ) rotateX( 0 );
-ms-transform: translateY(0) perspective( 600px ) rotateX( 0 );
-o-transform: translateY(0) perspective( 600px ) rotateX( 0 );
transform: translateY(0) perspective( 600px ) rotateX( 0 );
}
/* animate out */
.my-mfp-slide-bottom.mfp-removing .zoom-anim-dialog {
opacity: 0;
-webkit-transform: translateY(-10px) perspective( 600px ) rotateX( 10deg );
-moz-transform: translateY(-10px) perspective( 600px ) rotateX( 10deg );
-ms-transform: translateY(-10px) perspective( 600px ) rotateX( 10deg );
-o-transform: translateY(-10px) perspective( 600px ) rotateX( 10deg );
transform: translateY(-10px) perspective( 600px ) rotateX( 10deg );
}
/* Dark overlay, start state */
.my-mfp-slide-bottom.mfp-bg {
opacity: 0.01;
-webkit-transition: opacity 0.3s ease-out;
-moz-transition: opacity 0.3s ease-out;
-o-transition: opacity 0.3s ease-out;
transition: opacity 0.3s ease-out;
}
/* animate in */
.my-mfp-slide-bottom.mfp-ready.mfp-bg {
opacity: 0.8;
}
/* animate out */
.my-mfp-slide-bottom.mfp-removing.mfp-bg {
opacity: 0;
}
</style>
</div>
</body>
</html>
A: In case anyone interested in the .mfp-move-from-top animation below is the code:
.mfp-move-from-top .mfp-content{
vertical-align:bottom;
}
.mfp-move-from-top .mfp-with-anim{
opacity: 0;
transition: all 0.2s;
transform: translateY(-100px);
}
.mfp-move-from-top.mfp-bg {
opacity: 0;
transition: all 0.2
}
.mfp-move-from-top.mfp-ready .mfp-with-anim {
opacity: 1;
transform: translateY(0);
}
.mfp-move-from-top.mfp-bg.mfp-ready {
opacity: 0.8;
}
.mfp-move-from-top.mfp-removing .mfp-with-anim {
transform: translateY(-50px);
opacity: 0;
}
.mfp-move-from-top.mfp-removing.mfp-bg {
opacity: 0;
}
A: I had the same problem. found the solution here:
just change
beforeOpen: function() {
this.st.mainClass = this.st.el.attr('data-effect');
}
to this (adds a space and then the class, in case option is being used):
into
beforeOpen: function() {
this.st.mainClass += ' ' + this.st.el.attr('data-effect');
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17371848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: How to fix an error with implementation socket.io in Chrome Extension? I want to use socket.io in its extension, but when I import the library, it throws the error "Uncaught ReferenceError: document is not defined". I realized that this socket.io does document and window checks, however, in the background.js I can't use either the document API or the window object. I use manifest v3. What should I do to use sockets?
error image
background.js image
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69492090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: comparing Gregorian calendar date values I am trying to set up part of a program that allows a person to view transactions of an account based on the date of the transaction. The user enters the month day and year to view transactions and that is compared to the date that is connected to a given transaction. I am having difficult writing the lines of code that determine if the date is equal
if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH).compareTo(month)==0){
if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.DAY_OF_MONTH).compareTo(day)==0){
if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR).compareTo(year)==0){
The error that I am receiving is "cannot invoke compareTo(int) on the primitive type int"
see full code below:
System.out.println("Enter the account number of the account that you want to view transactions for");
number=keyboard.nextLong();
System.out.println("Enter the month day and year of the date that the transactions were completed");
int month=keyboard.nextInt()-1;
int day=keyboard.nextInt();
int year=keyboard.nextInt();
found=false;
try{
for(int i=0;i<aBank.getAccounts().size();i++){
if (aBank.getAccounts().get(i).getAccountNumber().compareTo(number)==0){
found=true;
System.out.println("Below is a list of transactions completed on "+month+ "/" +day+ "/" +year);
for (int j=0;j<aBank.getAccounts().get(i).getTransaction().size();j++){
if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH).compareTo(month)==0){
if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.DAY_OF_MONTH).compareTo(day)==0){
if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR).compareTo(year)==0){
aBank.getAccounts().get(i).getTransaction().get(j).toString();
break;
}
}
}
}
A: For primitive values you can just use ==
aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR)==year
A: Just use:
aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH) == month
A: If all of the XYZ.getTransDate() returns Calendar, then
XYZ.getTransDate().get(SOMETHING) returns primitive int. Primitives do not have comapreTo method, just use ==
so instead of XYZ.getTransDate().get(MONTH).compareTo(month) == 0 use
XYZ.getTransDate().get(MONTH) == month
A: This should work:
Calendar transDate = aBank.getAccounts().get(i).getTransaction().get(j).getTransDate();
if (transDate.get(Calendar.YEAR) == year &&
transDate.get(Calendar.MONTH) == month &&
transDate.get(Calendar.DAY_OF_MONTH) == day) {
// do something
}
Even better if you use something like Apache Commons Lang:
if (DateUtils.isSameDay(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate(),
Calendar.getInstance().set(year, month, day)) {
...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6247543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wildfly 10 : log which cipher is used for https Before removing/restricting ciphers enabled on https-listener, I would like to identify which cipher is used by clients.
How could I make a log file of that ?
Thank you
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59984288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Recaptcha Solving With Python In Selenium Chrome Session (2Captcha) I want to resolve ReCaptcha on websites via Python with the Selenium module.
My question is: How can I send a 2Captcha request from within the Selenium Chrome Browser, that resolves the ReCaptcha and validates the successful outcome within the selenium chrome page?
I want the script to click on the submit button after it is resolved so I can continue my Selenium script.
The code below successfully resolve the ReCaptcha but that is outside Selenium.
import requests
from time import sleep
# Add these values
API_KEY = 'FILLINAPIKEYHERE' # Your 2captcha API KEY
site_key = 'FILLINTHEPAGE'SRECAPTCHAKEYHERE' # site-key, read the 2captcha docs on how to get this
url = 'THEWEBPAGETHATNEEDSRESOLVEMENT' # example url
proxy = 'PROXY:PORTINHERE' # example proxy
proxy = {'http': 'http://' + proxy, 'https': 'https://' + proxy}
s = requests.Session()
# here we post site key to 2captcha to get captcha ID (and we parse it here too)
captcha_id = s.post("http://2captcha.com/in.php?key={}&method=userrecaptcha&googlekey={}&pageurl={}".format(API_KEY, site_key, url), proxies=proxy).text.split('|')[1]
# then we parse gresponse from 2captcha response
recaptcha_answer = s.get("http://2captcha.com/res.php?key={}&action=get&id={}".format(API_KEY, captcha_id), proxies=proxy).text
print("solving ref captcha...")
while 'CAPCHA_NOT_READY' in recaptcha_answer:
sleep(5)
recaptcha_answer = s.get("http://2captcha.com/res.php?key={}&action=get&id={}".format(API_KEY, captcha_id), proxies=proxy).text
recaptcha_answer = recaptcha_answer.split('|')[1]
# we make the payload for the post data here, use something like mitmproxy or fiddler to see what is needed
payload = {
'key': 'value',
'gresponse': recaptcha_answer # This is the response from 2captcha, which is needed for the post request to go through.
}
# then send the post request to the url
response = s.post(url, payload, proxies=proxy)
# And that's all there is to it other than scraping data from the website, which is dynamic for every website.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51281805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: html FileReader : convert blob to image file? client side code
<head>
<script>
var reader = new FileReader();
var objVal;
var image = new Image();
reader.onload = function(e) {
document.getElementById('propertyImg').setAttribute('src', e.target.result);
};
function readURL(input){
if(input.files && input.files[0]){
reader.readAsDataURL(input.files[0]);
}
else {
document.images[0].src = input.value || "No file selected";
}
}
function sendPost(){
var url = 'http://myurl.com';
var name = document.getElementById('fileInput').files[0].name;
var data = document.getElementById('propertyImg').getAttribute('src');
var f = document.createElement("form");
var imgName = document.createElement("input");
var imgData = document.createElement("input");
var f_attr = { 'method' : 'post' , 'action' : url};
var imgName_attr = {"type" : "hidden", "name" : "img_name", "value" : name};
var imgData_attr = {"type" : "hidden", "name" : "data", "value" : data};
setAttributes(f, f_attr);
setAttributes(imgName, imgName_attr);
setAttributes(imgData, imgData_attr);
f.appendChild(imgName);
f.appendChild(imgData);
document.body.appendChild(f);
f.submit();
}
function setAttributes(el, attrs) {
for(var key in attrs) {
el.setAttribute(key, attrs[key]);
}
}
</script>
<body>
<img id="propertyImg" src="./img/sprite.png"></img>
<input type='file' id='fileInput'class='width70_prop' onchange="readURL(this);"></input>
<button onclick="sendPost()">sendPost</button>
</body>
serverside code
<html>
<head>
<?
$FileName = $_POST['img_name'];
$data = $_POST['data'];
list($header, $content) = split('[,]', $data);
file_put_contents($FileName, base64_decode($content));
print "Data Written";
?>
<script>
function showImg(){
var imgSrc = "<?=$data?>";
var imgDiv = document.getElementById('imgDiv');
imgDiv.src = imgSrc;
}
</script>
</head>
<body>
<img id='imgDiv'></img>
<button onclick="showImg()">show</button>
</body>
</html>
the blob sent to server had infomation about header and its content.
when I split header then save decoded its content, it worked....
I changed above code which now works. thx guys
A: oops.. someone beat me to it...
When you read files as Dataurl on the clientside: reader.readAsDataUrl(...)
the file is encoded in to a base64 string.. That's why if you save the data directly, it's not in the correct format.
As the previous answer states, you base64_decode your data into the correct format.
A: First, there isn't anything in $_POST["data"] because the index (data) is named by the key in the JSON key : value pair, not the JavaScript var.
Secondly, you should change this:
$Handle = fopen($FileName, 'w');
fwrite($Handle, $data);
print "Data Written";
fclose($Handle);
to this:
file_put_contents($FileName, base64_decode($data));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13023231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Angular *ngIf Condition with OR in component html I am trying to get an *ngIf with an OR but the second option is ignored.
Here is the code:
<div *ngIf="router.url != '/one' || router.url != '/two'">
show something
</div>
How can I get this to work?
A: Using router.url != '/one' || router.url != '/two' means:
If router.url != '/one' returns true
If router.url != '/two' returns true
The second condition is never evaluated if the first condition is met because you are using OR
A: That's correct that you second condition is ignored, as when router.url != '/one' it already satisfies condition and second one is never evaluated, try this way
<div *ngIf="!(router.url == '/one' || router.url == '/two')">
show something
</div>
A: Run this code, maybe it'll explain something:
<p>Current URL: {{ router.url }}</p>
<p>Statement: router.url != '/one' - <strong>{{ router.url != '/one' }}</strong></p>
<p>Statement: router.url != '/two' - <strong>{{ router.url != '/two' }}</strong></p>
<p>Statement: router.url != '/one' || router.url != '/two' - <strong>{{ router.url != '/one' || router.url != '/two' }}</strong></p>
<div *ngIf="router.url != '/one' || router.url != '/two'">
show something
</div>
A: Your condition is always true, because it checks if a value is either different from either one or another. So the condition would only be false if router.url were at the same time equal to both '/one' and '/two', which is logically impossible.
A: Check your values to make sure the problem is not related to your data and replace != by !==.
However, in your case, I think you should be using and &&, because with an ||, your div will show up since if your route is /one or /two the condition will be true.
Try this:
<div *ngIf="router.url !== '/one' && router.url !== '/two'">
show something
</div>
Which is the same as:
<div *ngIf="!(router.url === '/one' || router.url === '/two')">
show something
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54689201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: PostgresQL grouping columns with aggregate I currently have a table with the following columns:
asset, asset_alt, price, price_alt, time
Trying to view the combined values to ideally return something like this:
asset, price, time
Wherein the asset and asset_alt values would be combined into one column (asset) and the price would be derived from either price or price_alt depending on the asset.
I have tried something like this, but it doesn't provide proper averages for the assets and also doesn't follow the ideal return format mentioned above.
SELECT
ab.asset,
ab.asset_alt,
time_bucket('01:00:00'::interval, ab."time") AS bucket,
avg(ab.price) AS price,
avg(ab.price_alt) AS price_alt,
FROM assets ab
GROUP BY ab.asset, ab.asset_alt, (time_bucket('01:00:00'::interval, ab."time"));
A:
Wherein the asset and asset_alt values would be combined into one column (asset)
What is a relation between asset_alt and asset?
If asset_alt is empty then use asset:
select
COALESCE(ab.asset_alt, ab.asset) AS asset, -- join assets columns in one
-- use right price column
CASE
WHEN ab.asset_alt IS NOT NULL THEN ab.price_alt
ELSE ab.price
END AS price
FROM FROM assets ab
GROUP BY
COALESCE(ab.asset_alt, ab.asset),
CASE
WHEN ab.asset_alt IS NOT NULL THEN ab.price_alt
ELSE ab.price
END
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70588689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Laravel and Angular. Issue with query results from Laravel when I search using Postman and Chrome I'm using Angular 4 and Laravel 5.4.
When I'm using Postman and querying the next route: http://ventas.dev./api/ubigeo, it return two records because I have the next code:
$tot = Ubigeo::where('dist', 'like', '%'. $request->input('term') . '%')->count();
return response()->json(["ubigeo" => $tot], 201);
But when I call the same route from Angular it return all records from Ubigeo table.
Why I have this problem?
From Postman:
https://ibb.co/n5PraF
From Chrome (Angular):
https://ibb.co/bW8HFF
A: How many results do you get when you fire the reuquest directly on your database? Which result are you getting?
Is it possible that there is an error with your custom route? Do you have two server running?
A: My error was stupid. I was sending a null value in my term variable:
let obj = 'term='+term;
And it was necessary to do so:
let obj = {term: term};
All my new Angular function service code is:
loadUbigeo(term:string){
let obj = {term: term};
let body = JSON.stringify(obj);
let headers = new Headers({
'Content-Type': 'application/json'
});
return this.http.post(`${this.sett.url}/ubigeo`, body, { headers })
.map(res => {
return res.json();
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45045195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IntelliJ gets stuck on "Copying resources" Had a problem trying to debug a Java application that I had using IntelliJ IDEA 13.
When attempting debugging, it would get stuck in the make process, displaying "Copying resources" indefinitely.
A: For some reason, it got stuck because I had manually created two named pipes in the same folder. Deleting the pipes allowed the make process to terminate successfully.
EDIT: I'm only posting this because Googling did not give me any good results, and I think it would save someone else some time if they could find it easily when it occurs.
A: I was having the same problem. I think its because i had setup angular project for UI inside my webapp folder, because of this it was loading all the dependencies from node_modules folder which takes lot of time.
When i took backup of my that angular project and deleted it from the webapp, it worked.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25872895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Availability of SSO in Outlook addin The Identity API requirement sets lists that the SSO is still in preview for Office addin.
Any tentative dates when SSO will be available for Outlook-addin ?
A: SSO is currently available in the Preview API Requirement Set for Outlook Add-ins.
A: It is available in Outlook add-ins (in preview). Please see SSO in Office Add-ins, Preview status.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53294366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: My Java program compiles without any errors, but will not fully run Here is the error that I am receiving.
thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
Here is the code that I am working with. I am able to enter the "last name" but then I get the error message that is displayed above. Any help would be greatly appreciated.
import java.util.*;
public class lab81
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.print("Enter last name:");
double lastName;
lastName = input.nextDouble();
System.out.print("Enter first name:");
double firstName;
firstName = input.nextDouble();
System.out.print("Enter this years units:");
double thisYearsUnits;
thisYearsUnits = input.nextDouble();
System.out.print("Enter last years units:");
double lastYearsUnits;
lastYearsUnits = input.nextDouble();
double numberOfUnits = thisYearsUnits;
final double UNITS1 = 1000;
final double UNITS2 = 3000;
final double UNITS3 = 6000;
final double BONUS1 = 25;
final double BONUS2 = 50;
final double BONUS3 = 100;
final double BONUS4 = 200;
if(thisYearsUnits < lastYearsUnits)
{
double bonusAmount;
bonusAmount = 0;
System.out.println(lastName + ", " + firstName);
System.out.println("Bonus is $" + bonusAmount);
}
else if(numberOfUnits <= UNITS1)
{
double bonusAmount;
bonusAmount = BONUS1;
System.out.println(lastName + ", " + firstName);
System.out.println("Bonus is $" + bonusAmount);
}
else if(numberOfUnits <= UNITS2)
{
double bonusAmount;
bonusAmount = BONUS2;
System.out.println(lastName + ", " + firstName);
System.out.println("Bonus is $" + bonusAmount);
}
else if(numberOfUnits <= UNITS3)
{
double bonusAmount;
bonusAmount = BONUS3;
System.out.println(lastName + ", " + firstName);
System.out.println("Bonus is $" + bonusAmount);
}
else if(numberOfUnits > UNITS3)
{
double bonusAmount;
bonusAmount = BONUS4;
System.out.println(lastName + ", " + firstName);
System.out.println("Bonus is $" + bonusAmount);
}
}
}
A: You are trying to parse characters into a double and that's why it's throwing an exception.
Declare your first name & last name as strings and get them from input by using
Input.nextLine()
Instead of
Input.nextDouble()
A: Are you storing text into your firstname and lastname variables? That is obvious data type mismatch. Use Strings, they are what stores text.
String firstname;
// Stuff
firstname = input.nextLine();
Doubles are for floating point number of a certain length. Also, use int whenever possible.
final int UNITS1 = 1000;
final int UNITS2 = 3000;
final int UNITS3 = 6000;
final int BONUS1 = 25;
final int BONUS2 = 50;
final int BONUS3 = 100;
final int BONUS4 = 200;
// Stuff
int bonusAmount;
Work on your primitive datatype knowledge. Hope this helps!
A: Cases when these exception are thrown:-
InputMismatchException − if the next token does not match the Float regular expression, or is out of range
lastname=scaner.nextDouble();
At this line you would have been entering string value, however it expecting double.
NoSuchElementException − if the input is exhausted
IllegalStateException − if this scanner is closed
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29452874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Looking for a safe, portable password-storage method I'm working on C++ project that is supposed to run on both Win32 and Linux, the software is to be deployed to small computers, usually working in remote locations - each machine likely to contain it's own users/service-men pool.
Recently, our client has requested that we introduce access control via password protection.
We are to meet the following criteria :
*
*Support remote login
*Support remote password change
*Support remote password reset EDITED
*Support data retrieval on accidental/purposeful deletion
*Support secure storage
I'm capable of meeting the "remote" requirements using an existing library, however what I do need to consider is a method of storing this data, preferably in a way that will work on both platforms and will not let the user see it/read it, encryption is not the issue here - it's the storage method itself.
Can anyone recommend a safe storage method that could help me meet those criteria?
EDIT
We're initially considering using a portable SQLite database, however what we are interested in, is limiting the access to the file with the data to users. How can we achieve that? (file not visible to the user, file cannot be opened manually by user etc.)
EDIT 2
Cheers for the responses flowing in so far, Can we focus on ways to limit the access to the file itself? Encryption is not the issue here. What we're looking for is a way to hide and or backup the file, and only permit the "MyApp.exe" to work with it.
So far we're also investigating Alternate NTFS Streams, however we're not sure if this will work on Linux
A: For logon you want to store an iterated salted hash of the password not the password itself. Two possibilities are:
*
*bcrypt - A modified form of blowfish that increases the work factor
*PBKDF2 - A function from the PKCS#5 spec that uses HMAC with a hash function and random salt to iterate over a password many times.
However, this will not work with your requirements:
*
*Support remote password retrieval
I am hoping you can convince the client that what they really mean is to reset the password, in which case you can still use a password hash.
*
*Support data retrieval on accidental/purposeful deletion
This requirementment is harder to work around and will require you to weaken security by storing encrypted passwords in the database so they can be reversed. To do this you should use a master key, encrypt each password with a random IV using a cipher like AES/CBC or AES/CTR mode. You should regularly rekey the master key and reencrypt all the passwords . You will then need a mechanism for working out when to allow password retrieval (e.g. mother's maiden name etc)
To use the password to encrypt data use the PKDF2 function from PKCS#5 to generate a key from the password.
A: Never store the password itself. Hash the password using a salt and store that.
A: You could use a SQLite database. As it's just a file you can use standard file permissions to restrict access. e.g. chmod 600 foo.dbs will restrict access to the file so that only the owner can read/write to it.
Then as others have suggested you store a hashed password in the database and it'll be reasonably secure.
Rumour has it that there's a commercial version of SQLite available that encrypts the entire database file. However, this shouldn't be a substitute for storing hashed passwords, merely an addition to hashing.
edit: Here's the link to the commercial version of sqlite with support for encryption of the entire DB.
A: I'm not quite sure if I fully understand your question. But anyway.
How about setting up a user "FooUser" (assuming your product is "Foo"). Store the file / database at a location with read/write permitions only for user FooUser. Access file / database via service / daemon impersonating FooUser.
A: First and foremost, neve store the plain-text password, instead store its hash. Using a salt is a good idea too if you expect the number of users to become large enough to have password collisions.
Do you actually need to store password on all of the systems, or can you get away with a centralized, password server, solution? If a server based solution is acceptable then a decent challenge response scheme can authenticate people without revealing their password or its hash. Secure communication witht the server using certificates, to make forgery harder and then just don't allow access to the password storage on the server, through whatever means is appropriate, which can be OS specific since there is only one, or just don't let people onto the server.
A: I think the right way to go is:
*
*in memory, you concatenate user name + password + some cookie (lets say: megan fox").
You then apply a commercial hash algorithm to it. I use SHA (System.Security.Cryptography.SHA1CryptoServiceProvider) from .NET Framework but I am sure it is no problem to make it work in C++ or perhaps get it for C++.
So, even if someone gets to look the stored hash, there is no way he can know the password. Event if he wants to compare identical passwords, he will get nothing because of the user name + cookie concatenation.
Your login code must create the hash and compare it against the stored one
Problem is, you do not get to recover the password. But I think this is something good.
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2599990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Cypress installation on a 32-bit server For some reason, I have to install Cypress (version: 7.2.0) on a 32-bit machine. I notice that only 64-bit is supported on Linux:
https://docs.cypress.io/guides/getting-started/installing-cypress#System-requirements
But, a 32-bit release is available for Windows. So I guess it is possible to somehow build Cypress (version: 7.2.0) for 32-bit Linux. I just need some help to point me in the right direction to build and install Cypress (version: 7.2.0) on a 32-bit Linux server.
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67745076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Running multiple functions at the same time? This must be a question asked a lot, and yet I couldn't quite find what I'm looking for.
Imagine this:
*
*A program starts up "Hello, what's your name?"
*You enter a number and it goes "Your name can't be a number!"
You keep entering a number and keep getting that error, while in the background it just keeps track of how long the program has been running, by doing n++ every second, no matter what goes on in the text/input part. Eventually you could enter something like "time" and then it shows how long you've been there, in seconds...
SO my question is: Just how the hell would you go about doing that? To have them run independently?
Thanks in advance!
Edit: I'm not trying to do this timing thing in particular, it's just the easiest example I could come up with to ask about running functions independently..
A: You don't need to run parallel tasks in order to measure the elapsed time. An example in C++11:
#include <chrono>
#include <string>
#include <iostream>
int main()
{
auto t1 = std::chrono::system_clock::now();
std::string s;
std::cin >> s;
// Or whatever you want to do...
auto t2 = std::chrono::system_clock::now();
auto elapsedMS =
(std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1)).count()
std::cout << elapsedMS;
}
EDIT:
Since it seems you are interested in a way to launch several tasks in parallel, here is a hint (again, using C++11):
#include <ctime>
#include <future>
#include <thread>
#include <iostream>
int long_computation(int x, int y)
{
std::this_thread::sleep_for(std::chrono::seconds(5));
return (x + y);
}
int main()
{
auto f = std::async(std::launch::async, long_computation, 42, 1729);
// Do things in the meanwhile...
std::string s;
std::cin >> s;
// And we could continue...
std::cout << f.get(); // Here we join with the asynchronous operation
}
The example above starts a long computation that will take at least 5 seconds, and in the meanwhile does other stuff. Then, eventually, it calls get() on the future object to join with the asynchronous computation and retrieve its result (waiting until it is finished if it hasn't finished yet).
A: If you really want to use threads, not just counting time you can use boost.
Example:
include <boost/thread.hpp>
void task1() {
// do something
}
void task2() {
// do something
}
void main () {
using namespace boost;
thread thread1 = thread(task1);
thread thread2 = thread(task2);
thread2.join();
thread1.join();
}
A:
I'm not trying to do this timing thing in particular, it's just the easiest example I could come up with to ask about running functions independently..
Then you may want to look into multithreading. In C++11, you can do this:
#include <thread>
#include <iostream>
void func1() {
std::cout << "func1" << std::endl;
}
void func2() {
std::cout << "func2" << std::endl;
}
int main() {
std::thread td1(func1);
std::thread td2(func2);
std::cout << "Started 2 threads. Waiting for them to finish..." << std::endl;
td1.join();
td2.join();
std::cout << "Threads finished." << std::endl;
return 0;
}
If you're not using C++11, you still have options. You can look into:
*
*Boost Threads (Requires Boost of course)
*POSIX threads
A: Firstly you don't need to increment your own time variable. Just record the time when the program starts and the time command will return the difference between time now and start time.
More generally -
*
*It's possible to kick off a long-running task in another thread. You'll need to research this on your own; try googling that phrase.
*Event-driven programming might be more appropriate for this use case. Try "C++ event driven IO" for google, or something.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16508018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Spring: Exception when trying to start server When I run the Application.java file I get this exception
java.lang.SecurityException: class "javax.servlet.MultipartConfigElement"'s signer information does not match signer information of other classes in the same package
I'm using eclipse with gradle
Application.Java:
package com.overip.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@EnableWebMvc
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
}
The whole exception thrown:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.0.2.RELEASE)
2014-10-29 08:41:39.629 INFO 122080 --- [ main] com.overip.server.Application : Starting Application on Dell-PC with PID 122080 (started by Fady & Emad in C:\Users\Fady & Emad\workspace\OverIP)
2014-10-29 08:41:39.688 INFO 122080 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6d463b81: startup date [Wed Oct 29 08:41:39 EET 2014]; root of context hierarchy
2014-10-29 08:41:40.619 INFO 122080 --- [ main] .b.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/C:/Users/Fady%20&%20Emad/workspace/OverIP/bin/, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter-web/1.0.2.RELEASE/fb26276f8400658e15d571350c5b577dfe40567a/spring-boot-starter-web-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/mysql/mysql-connector-java/5.1.33/8af455a9a3267e6664cafc87ace71a4e4ef02837/mysql-connector-java-5.1.33.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter-actuator/1.0.2.RELEASE/699771411accffc41656db59ae51dd6663a653d6/spring-boot-starter-actuator-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter-aop/1.0.2.RELEASE/58b239d692c4fab48dc8c430eabd527a2e153816/spring-boot-starter-aop-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter-test/1.0.2.RELEASE/ccab7d782c8a8bf95c06573edd2f40d7da332e36/spring-boot-starter-test-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/com.google.guava/guava/17.0/9c6ef172e8de35fd8d4d8783e4821e57cdef7445/guava-17.0.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/com.squareup.retrofit/retrofit/1.6.0/39a9e4b49ded46aa1b67d492fe287c4cebcd815c/retrofit-1.6.0.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/commons-io/commons-io/2.4/b1b6ea3b7e4aa4f492509a4952029cd8e48019ad/commons-io-2.4.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/javax.servlet/servlet-api/2.5/5959582d97d8b61f4d154ca9e495aafd16726e34/servlet-api-2.5.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter-jetty/1.0.2.RELEASE/6f8da7ee1e540b2f21f99946ca74eb1726f2fd82/spring-boot-starter-jetty-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/junit/junit/4.11/4e031bb61df09069aeb2bffb4019e7a5034a4ee0/junit-4.11.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/commons-logging/commons-logging/1.1.3/f6f66e966c70a83ffbdb6f17a0919eaf7c8aca7f/commons-logging-1.1.3.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework/spring-core/4.0.3.RELEASE/138d28200d97f4affe9ccaa47fab54718b438319/spring-core-4.0.3.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework/spring-beans/4.0.3.RELEASE/41eabd53fd4ba5ba2b2d8af6c256a3741f65c2f3/spring-beans-4.0.3.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/aopalliance/aopalliance/1.0/235ba8b489512805ac13a8f9ea77a1ca5ebe3e8/aopalliance-1.0.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework/spring-aop/4.0.3.RELEASE/dcedf5329d7092d66cc9d2496687a5f29d883eb6/spring-aop-4.0.3.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework/spring-expression/4.0.3.RELEASE/40b25b3a693cb4cc382ddf2e69ff1b29c75a2e7d/spring-expression-4.0.3.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework/spring-context/4.0.3.RELEASE/782a71a312dc307fa531023aa66247b9b4a109d/spring-context-4.0.3.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot/1.0.2.RELEASE/8d1a06e468b16577075db27123091758b6f880af/spring-boot-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-autoconfigure/1.0.2.RELEASE/3a70e3021aec334ee8b1a454ea791d27997a7191/spring-boot-autoconfigure-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-api/1.7.7/2b8019b6249bb05d81d3a3094e468753e2b21311/slf4j-api-1.7.7.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.slf4j/jcl-over-slf4j/1.7.7/56003dcd0a31deea6391b9e2ef2f2dc90b205a92/jcl-over-slf4j-1.7.7.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.slf4j/jul-to-slf4j/1.7.7/def21bc1a6e648ee40b41a84f1db443132913105/jul-to-slf4j-1.7.7.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.slf4j/log4j-over-slf4j/1.7.7/d521cb26a9c4407caafcec302e7804b048b07cea/log4j-over-slf4j-1.7.7.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/ch.qos.logback/logback-core/1.1.2/2d23694879c2c12f125dac5076bdfd5d771cc4cb/logback-core-1.1.2.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/ch.qos.logback/logback-classic/1.1.2/b316e9737eea25e9ddd6d88eaeee76878045c6b2/logback-classic-1.1.2.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter-logging/1.0.2.RELEASE/47a20c5bad47916ca99d768782de12c54b707a00/spring-boot-starter-logging-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter/1.0.2.RELEASE/a6cbc3adc8d95a0e5405d3c1ca30ad8e6bed1cf1/spring-boot-starter-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.yaml/snakeyaml/1.13/73cbb494a912866c4c831a178c3a2a9169f4eaad/snakeyaml-1.13.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/com.fasterxml.jackson.core/jackson-annotations/2.3.0/f5e853a20b60758922453d56f9ae1e64af5cb3da/jackson-annotations-2.3.0.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/com.fasterxml.jackson.core/jackson-core/2.3.3/7d8c5d79cc99995e21e6f955857312d8409f02a1/jackson-core-2.3.3.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/com.fasterxml.jackson.core/jackson-databind/2.3.3/63b77400b5f1cf83a81823562c48d3120ef5518e/jackson-databind-2.3.3.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework/spring-web/4.0.3.RELEASE/4d5066f31ea4b9c58957bf8c0c213b13ed44c1c5/spring-web-4.0.3.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework/spring-webmvc/4.0.3.RELEASE/d6fd9778619ab87a41ae3aa879a53ee60f160c08/spring-webmvc-4.0.3.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-actuator/1.0.2.RELEASE/ec33fd737d646dc4e092176bee856245e2f02f8c/spring-boot-actuator-1.0.2.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.aspectj/aspectjrt/1.7.4/e49a5c0acee8fd66225dc1d031692d132323417f/aspectjrt-1.7.4.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.aspectj/aspectjweaver/1.7.4/d9d511e417710492f78bb0fb291a629d56bf4216/aspectjweaver-1.7.4.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.hamcrest/hamcrest-core/1.3/42a25dc3219429f0e5d060061f71acb49bf010a0/hamcrest-core-1.3.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.objenesis/objenesis/1.0/9b473564e792c2bdf1449da1f0b1b5bff9805704/objenesis-1.0.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.mockito/mockito-core/1.9.5/c3264abeea62c4d2f367e21484fbb40c7e256393/mockito-core-1.9.5.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.hamcrest/hamcrest-library/1.3/4785a3c21320980282f9f33d0d1264a69040538f/hamcrest-library-1.3.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.springframework/spring-test/4.0.3.RELEASE/76b870a5aa132b4c0dd78cd061feb3e1652cddd1/spring-test-4.0.3.RELEASE.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/com.google.code.gson/gson/2.2.4/a60a5e993c98c864010053cb901b7eab25306568/gson-2.2.4.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-util/8.1.14.v20131031/43063284480a41eca024dc8852452eedf6379c16/jetty-util-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-xml/8.1.14.v20131031/8732c74817fef6d2e3e667636e6c4f27fb4cada9/jetty-xml-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-continuation/8.1.14.v20131031/e3396abd21360191c2277e848eff489b58bba45d/jetty-continuation-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-io/8.1.14.v20131031/12f6f92d7e58349501f2cfc0716b8f1c6a2962eb/jetty-io-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-http/8.1.14.v20131031/8dd4e01b374e16cf0335b7975a7aa0a57396d5da/jetty-http-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-server/8.1.14.v20131031/7f7f9b929b9d9169dd68f36327c819ab9a03a661/jetty-server-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-security/8.1.14.v20131031/d6fd7add8e6015a95558b67b43edf7752a925884/jetty-security-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-servlet/8.1.14.v20131031/2ea127b7001965201d28ce715f5754573205c4ae/jetty-servlet-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-webapp/8.1.14.v20131031/1f29371c74381ac42f961e9b984a7af28cc62093/jetty-webapp-8.1.14.v20131031.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.orbit/javax.servlet/3.0.0.v201112011016/aaaa85845fb5c59da00193f06b8e5278d8bf3f8/javax.servlet-3.0.0.v201112011016.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.orbit/javax.servlet.jsp/2.2.0.v201112011158/80b4ffe7c26ee97313bea2ddda5835fd38812ee4/javax.servlet.jsp-2.2.0.v201112011158.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.orbit/org.apache.jasper.glassfish/2.2.2.v201112011158/3945afe6a042228a92da320aec3fa1bc1308183b/org.apache.jasper.glassfish-2.2.2.v201112011158.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.orbit/javax.servlet.jsp.jstl/1.2.0.v201105211821/db594f1c8fc00d536f6d135bd7f8a9a99a6b8eea/javax.servlet.jsp.jstl-1.2.0.v201105211821.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.orbit/org.apache.taglibs.standard.glassfish/1.2.0.v201112081803/2c4baa72af1d3aae3a1e029d4f8ca07498dabbe0/org.apache.taglibs.standard.glassfish-1.2.0.v201112081803.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.orbit/javax.el/2.2.0.v201108011116/ec8944c11833d84b0283a5afbad0fafb264f86a9/javax.el-2.2.0.v201108011116.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.orbit/com.sun.el/2.2.0.v201108011116/15f7774c3fa514835a371f47c152317704ea411a/com.sun.el-2.2.0.v201108011116.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.orbit/org.eclipse.jdt.core/3.7.1/5b79bfee0852ca685e33cab74496fa3400271b5b/org.eclipse.jdt.core-3.7.1.jar, file:/C:/Users/Fady%20&%20Emad/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-jsp/8.1.14.v20131031/87dc1723a32113d74be2420d940f6825e3b6af42/jetty-jsp-8.1.14.v20131031.jar]
2014-10-29 08:41:40.622 INFO 122080 --- [ main] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6d463b81: startup date [Wed Oct 29 08:41:39 EET 2014]; root of context hierarchy
2014-10-29 08:41:40.629 WARN 122080 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception thrown from ApplicationListener handling ContextClosedEvent
java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6d463b81: startup date [Wed Oct 29 08:41:39 EET 2014]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:346)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:333)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:880)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.doClose(EmbeddedWebApplicationContext.java:152)
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:841)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:329)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:898)
at com.overip.server.Application.main(Application.java:16)
2014-10-29 08:41:40.630 WARN 122080 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception thrown from LifecycleProcessor on context close
java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6d463b81: startup date [Wed Oct 29 08:41:39 EET 2014]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:359)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:888)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.doClose(EmbeddedWebApplicationContext.java:152)
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:841)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:329)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:898)
at com.overip.server.Application.main(Application.java:16)
Exception in thread "main" java.lang.SecurityException: class "javax.servlet.MultipartConfigElement"'s signer information does not match signer information of other classes in the same package
at java.lang.ClassLoader.checkCerts(Unknown Source)
at java.lang.ClassLoader.preDefineClass(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:236)
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getBeanNamesForType(OnBeanCondition.java:144)
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchingBeans(OnBeanCondition.java:113)
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchOutcome(OnBeanCondition.java:75)
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:44)
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:92)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader$TrackedConditionEvaluator.shouldSkip(ConfigurationClassBeanDefinitionReader.java:400)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:127)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:116)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:324)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:120)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:648)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:311)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:898)
at com.overip.server.Application.main(Application.java:16)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26624481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Open documents(pdf,doc,docx,txt) in browser page using php (without using google docs viewer) My question is that i want to open documents(pdf,doc,docx,txt) in browser page using php (without using google docs viewer) can any one help me?
A: Some of these are doable. Some, not so much. Let's tackle the low-hanging fruit first.
Text files
You can just wrap the content in <pre> tags after running it through htmlspecialchars.
PDF
There is no native way for PHP to turn a PDF document into HTML and images. Your best bet is probably ImageMagick, a common image manipulation program. You can basically call convert file.pdf file.png and it will convert the PDF file into a PNG image that you can then serve to the user. ImageMagick is installed on many Linux servers. If it's not available on your host's machine, please ask them to install it, most quality hosts shouldn't have a problem with this.
DOC & DOCX
We're getting a bit more tricky. Again, there's no way to do this in pure PHP. The Docvert extension looks like a possible choice, though it requires OpenOffice be installed as well. I was actually going to recommend plain vanilla OpenOffice/LibreOffice as well, because it can do the job directly from the command line. It's very unlikely that a shared host will want to install this. You'll probably need your own dedicated or virtual private server.
In the end, while these options can be made to work, the output quality is not guaranteeable. Overall, this is kind of a bad idea that you should not seriously consider implementing.
A: I am sure libraries and such exist that can do this. Google could probably help you there more than I can.
For txt files I would suggest breaking lines after a certain number of characters and putting them inside pre tags.
I know people will not be happy about this response, but if you are on a Linux environment and have pdf2html installed you could use shell_exec and call pdf2html.
Note: If you use shell_exec be wary of what you pass to it since it will be executed on the server outside of PHP.
A: I thought I'd just add that pdfs generally view well in a simple embed tag.
Or use an object so you can have fall backs if it cannot be displayed on the client.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5280649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to process an array of task asynchronously with swift combine I have a publisher which takes a network call and returns an array of IDs. I now need to call another network call for each ID to get all my data. And I want the final publisher to have the resulting object.
First network result:
"user": {
"id": 0,
"items": [1, 2, 3, 4, 5]
}
Final object:
struct User {
let id: Int
let items: [Item]
... other fields ...
}
struct Item {
let id: Int
... other fields ...
}
Handling multiple network calls:
userPublisher.flatMap { user in
let itemIDs = user.items
return Future<[Item], Never>() { fulfill in
... OperationQueue of network requests ...
}
}
I would like to perform the network requests in parallel, since they are not dependent on each other. I'm not sure if Future is right here, but I'd imagine I would then have code to do a
DispatchGroup or OperationQueue and fulfill when they're all done. Is there more of a Combine way of doing this?
Doe Combine have a concept of splitting one stream into many parallel streams and joining the streams together?
A: Combine offers extensions around URLSession to handle network requests unless you really need to integrate with OperationQueue based networking, then Future is a fine candidate. You can run multiple Futures and collect them at some point, but I'd really suggest looking at URLSession extensions for Combine.
struct User: Codable {
var username: String
}
let requestURL = URL(string: "https://example.com/")!
let publisher = URLSession.shared.dataTaskPublisher(for: requestURL)
.map { $0.data }
.decode(type: User.self, decoder: JSONDecoder())
Regarding running a batch of requests, it's possible to use Publishers.MergeMany, i.e:
struct User: Codable {
var username: String
}
let userIds = [1, 2, 3]
let subscriber = Just(userIds)
.setFailureType(to: Error.self)
.flatMap { (values) -> Publishers.MergeMany<AnyPublisher<User, Error>> in
let tasks = values.map { (userId) -> AnyPublisher<User, Error> in
let requestURL = URL(string: "https://jsonplaceholder.typicode.com/users/\(userId)")!
return URLSession.shared.dataTaskPublisher(for: requestURL)
.map { $0.data }
.decode(type: User.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
return Publishers.MergeMany(tasks)
}.collect().sink(receiveCompletion: { (completion) in
if case .failure(let error) = completion {
print("Got error: \(error.localizedDescription)")
}
}) { (allUsers) in
print("Got users:")
allUsers.map { print("\($0)") }
}
In the example above I use collect to collect all results, which postpones emitting the value to the Sink until all of the network requests successfully finished, however you can get rid of the collect and receive each User in the example above one by one as network requests complete.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58675046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Use binding file to set the package on a namespace? I'm working on two large 3rd party schemas, one includes the other and generates a large number of type name collisions. If I could set the package on a namespace this problem would go away.
I hoped something like
<jaxb:bindings namespace="http://www.openapplications.org/oagis/9" >
<jaxb:schemaBindings>
<jaxb:package name="org.oagis" />
</jaxb:schemaBindings>
</jaxb:bindings>
would work, or perhaps
<jaxb:bindings node="/xsd:schema[@targetNamespace='http://www.openapplications.org/oagis/9']">
<jaxb:schemaBindings>
<jaxb:package name="org.oagis" />
</jaxb:schemaBindings>
</jaxb:bindings>
But no joy.
Trying to set on the individual xsd files in that namespace left me with the dread
[ERROR] Multiple <schemaBindings> are defined for the target namespace "http://www.openapplications.org/oagis/9"
Pointers/suggestions are appreciated.
A: This is a bit hard to answer without seeing the whole compilation. However I often got this error when compiling third-party schemas in the case when the same schema was included via different URLs.
I.e. I've implemented a project which compiled an extensive set of OGC Schemas. The problem was that these schemas referenced each other via relative and absolute URLs. So when I customized one of the schemas there were other schemas for the same namespace URI. Since JAXB processes imports and includes, it is not quite transparent what exactly gets compiled. Try to check your XJC logs for cues or - if you compile schemas directly via URLs (which is not recommended) - go through a logging proxy and see what actually gets accessed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22671356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Does Kafka broker server take into account updates to it's configuration file? Does Kafka broker server take into account updates to it's configuration file?
Its cumbersome having to restart all the servers in the cluster simply to update a configuration.
A: No, it's currently not possible to do dynamic configuration updates.
There's a Jira ticket for that exact issue here, and the accompanying KIP (Kafka Improvement Proposal).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34649156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: In what circumstances is uri passed to Android's ContentObserver.onChange() callback? The onChange() method of Android's ContentObserver class says, "Includes the changed content Uri when available." In what circumstances is the URI available? In what circumstances is it not available?
The uri parameter was added in API level 16 (Android 4.1) and so I would expect it to be set in Android 4.1 and newer. However I'm seeing a case on Android 4.3 where uri is not set.
Method 1: Works
MyContentObserver.onChange() is called and is passed a valid uri:
contentResolver.registerContentObserver(myUri, true, new MyContentObserver());
Method 2: Doesn't work--why not?
MyContentObserver.onChange() is called but the uri parameter is null:
contentResolver.query();
cursor.registerContentObserver(new MyContentObserver);
Is this expected? Is one of these preferred over the other? I've tested this using "content://com.google.android.gm/[email protected]/labels" and using my own custom ContentProvider.
A: This is an old question, but still unanswered. So I will add my answer in case people is still curious about it.
When your content provider notifies the registered observer using getContext().getContentResolver().notifyChange(URI, "your_uri");, it asks the ContentResponder for it. The return value from that method is the ContentObserver that you registered with the registerContentObserver() method of the content responder, which is what you did in the first case. However, in the second case, you registered the observer in the Cursor using the registerContentObserver() method of the Cursor, so the ContentResponder doesn't know about it.
A: If you are setting ContentObserver upon common tables(e.g people, mediaprovider etc) then unfortunately you might not receive any Uri as an argument, it might be blank as it depends upon underneath content provider implementation. To receive an valid Uri upon change, respective ContentProvider has to be modified to notify change along with URI.
e.g getContext().getContentResolver().notifyChange(Uri, "your_uri"); // this notifies all the registered ContentObserver with Uri of modified concerned dataset.
If you are writing your own ContentProvider then use above mentioned line whenever you perform update, delete or insert operation on your database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18991761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Swift tableView with 3 Prototype Cells and auto-height I have a concept which I want to realize in Xcode. Its a default TableViewController with 3 Prototype cells.
Cell 1 = name (Prototype Pages)
Cell 2 = seperator (Prototype Seperator)
Cell 3 = only ImageView (Prototype Seperator-with-only-image)
Cell 1 and cell 2 is OK. I need to set the height of all "Prototype Seperator-with-only-image" cells to auto. The height should be calculated based on added image dimensions.
Here my mockup
Addional info: The "Prototype Seperator-with-only-image" can occur multiple times and the dimensions of the images can vary.
Any ideas how I can achieve this?
A: You can set the tableview's rowHeight equal to UITableViewAutomaticDimension in your viewDidLoad method:
self.yourTableView.rowHeight = UITableViewAutomaticDimension
self.yourTableView.estimatedRowHeight = 42.0
Here you are telling your tableview to calculate the dimension of the row.
Then you are saying that you estimate that the row will have a height of 42, basically setting a minimum height.
I think this is a great example using a demo app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38075260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Storing Multiple Changes in Entity Framework I'm trying to achieve a form of two phase commit using Entity Framework 1.0.
What I would like to achieve at a high level is:
*
*get all the data from the database and store this in a cache.
*modify individual entities
*Commit all changes into the database
The problem's i've encountered so far is that caching an IQueryable is a bit pointless as it's going to go back to the database regardless. So the other option is to use IEnumberable for storing the results of a query, but that stops me inheriting one query and refining it into another (I can live with that however). The other problem is that as soon as the EntityContext expires (which i've managed to persist in the current httprequest) that's it, no changes can be tracked.
Has anyone tried to do something similar to this in the past or got any pointers?
Many thanks,
Matt
jumpingmattflash.co.uk
A: The IQueryable is just that a queryable object not the actual data.
You need to run the ToList to get the data out.
You can do what you are trying to do if you can keep the Context open and use transactionscope. In most cases however this is not possible. This would also lock the database leading to other probelms.
A better way to do it would be:
*
*Read the data from the database
*Dispose of the context
*Client makes any changes needed
*Open new context
*Read the data again.
*make changes by copying data from changed data to second set
*commit the changes
*dispose of the context
A: Call .ToList() on your IQueryable results from the database. To then start refining into other queries use .AsQueryable(). This should solve your first problem.
As for your second problem, I'm also searching for a solution. As I understand the underlying implementation of the relationship parts of Entity Framework revolves around the ObjectStateManager in the System.Data.Objects namespace of the System.Data.Entity assembly. This in turn uses the MetadataWorkspace class in the System.Data.Metadata.Edm namespace to lookup the relationship mappings. These might be able to be used without an underlying database connection, and if so, would provide some very groovy tools to update complex object graphs.
It would be nice if the context had a Detach and Attach in a similar way to individual Entities. It looks like the next version of the Entity Framework is going to focus on these specific type of issues; more freedom when dealing with Entities and Contexts.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/916144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to unit test HttpClient GetAsync I have the following in my controller:
public async Task<IActionResult> IndexAsync()
{
string baseUrl = "https://apilink.com";
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(baseUrl))
using (HttpContent content = response.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
var recipeList = JsonConvert.DeserializeObject<Recipe[]>(data);
return View();
}
}
return View();
}
I want to unit test this but cannot work out how to test the HttpClient.
I have tried:
[Test]
public void Index_OnPageLoad_AllRecipesLoaded()
{
var testController = new HomeController();
mockHttpClient.Setup(m => m.GetAsync(It.IsAny<string>())).Returns(
() => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
mockHttpContent.Setup(m => m.ReadAsStringAsync()).Returns(() => Task.FromResult(LoadJson()));
var result = testController.IndexAsync();
Assert.IsNotNull(result);
}
// Loads the Json data as I don't actually want to make the API call in the test.
public string LoadJson()
{
using (StreamReader r = new StreamReader("testJsonData.json"))
{
string json = r.ReadToEnd();
return json;
}
}
Is there a way to mock this effectively/simply? Or should I maybe inject my own IHttpClient interface? (I am not sure if that is good practice?)
Thanks
A: There are several ways to unit test HttpClient, but none are straightforward because HttpClient does not implement a straightforward abstraction.
1) Write an abstraction
Here is a straightforward abstraction and you can use this instead of HttpClient. This is my recommended approach. You can inject this into your services and mock the abstraction with Moq as you have done above.
public interface IClient
{
/// <summary>
/// Sends a strongly typed request to the server and waits for a strongly typed response
/// </summary>
/// <typeparam name="TResponseBody">The expected type of the response body</typeparam>
/// <param name="request">The request that will be translated to a http request</param>
/// <returns>The response as the strong type specified by TResponseBody /></returns>
/// <typeparam name="TRequestBody"></typeparam>
Task<Response<TResponseBody>> SendAsync<TResponseBody, TRequestBody>(IRequest<TRequestBody> request);
/// <summary>
/// Default headers to be sent with http requests
/// </summary>
IHeadersCollection DefaultRequestHeaders { get; }
/// <summary>
/// Base Uri for the client. Any resources specified on requests will be relative to this.
/// </summary>
AbsoluteUrl BaseUri { get; }
}
Full code reference here. The Client class implements the abstraction.
2) Create a Fake Http Server and Verify the Calls on the Server-Side
This code sets up a fake server, and your tests can verify the Http calls.
using var server = ServerExtensions
.GetLocalhostAddress()
.GetSingleRequestServer(async (context) =>
{
Assert.AreEqual("seg1/", context?.Request?.Url?.Segments?[1]);
Assert.AreEqual("seg2", context?.Request?.Url?.Segments?[2]);
Assert.AreEqual("?Id=1", context?.Request?.Url?.Query);
Assert.AreEqual(headerValue, context?.Request?.Headers[headerKey]);
if (hasRequestBody)
{
var length = context?.Request?.ContentLength64;
if (!length.HasValue) throw new InvalidOperationException();
var buffer = new byte[length.Value];
_ = (context?.Request?.InputStream.ReadAsync(buffer, 0, (int)length.Value));
Assert.AreEqual(requestJson, Encoding.UTF8.GetString(buffer));
}
if (context == null) throw new InvalidOperationException();
await context.WriteContentAndCloseAsync(responseJson).ConfigureAwait(false);
});
Full code reference here.
3) Mock the HttpHandler
You can inject a Mock HttpHandler into the HttpClient. Here is an example:
private static void GetHttpClientMoq(out Mock<HttpMessageHandler> handlerMock, out HttpClient httpClient, HttpResponseMessage value)
{
handlerMock = new Mock<HttpMessageHandler>();
handlerMock
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(value)
.Verifiable();
httpClient = new HttpClient(handlerMock.Object);
}
Full code reference. You can then verify the calls from the mock itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66828772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't Print the RDLC report when I deploy onto another computer? When i run this on VS it works fine but when i run it on another computer it cant find the RDLC path.
private void button1_Click(object sender, EventArgs e)
{
LocalReport localReport = new LocalReport();
ReportParameterCollection reportParameters = new ReportParameterCollection();
reportParameters.Add(new ReportParameter("Pallet_label", lb_pallet_name.Text));
reportParameters.Add(new ReportParameter("Par_PalNum", LB_Number.Text));
localReport.ReportPath = Application.StartupPath + "\\pallet_label.rdlc";
localReport.SetParameters(reportParameters);
localReport.PrintToPrinter();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71382327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: upload_err_partial error when uploading files of size greater than 3GB I want to upload upto 10GB files using a normal php form. But even after increasing the below values,
upload_max_filesize
post_max_size
php_value upload_max_filesize
php_value post_max_size
request_terminate_timeout
FcgidMaxRequestLen
am able to upload a file upto 3.5gb without any problem. But above that am getting an error as "upload_err_partial". I also reffered a lot of site but the answer I thought releavant was adding "header(connection:close)". I added the line but still I did not get any result. Could anyone guide me in this.
A: This error usually means that the uploading is cancelled by the user , and some times it can be server problem also which can cause this. Try to contact to your hosting provider and see what can he do
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27921389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to calculate averages for a 3D matrix for the same day of data over multiple years in Matlab? I am interested in calculating GPH anomalies in Matlab. I have a 3D matrix of lat, lon, and data. Where the data (3rd dimension) is a daily GPH value spaced in one-day increments for 32 years (from Jan. 1st 1979 to Jan. 1st 2011). The matrix is 95x38x11689. How do I compute a daily average across all years for each day of data, when the matrix is 3D?
In other words, how do I compute the average of Jan. 1st dates for all years to compute the climatological mean of all Jan. 1st's from 1979-2010 (where I don't have time information, but a GPH value for each day)? And so forth for each day after. The data also includes leap years. How do I handle that?
Example: Sort, and average all Jan. 1st GPH values for indices 1, 365, 730, etc. And for each day of all years after that in the same manner.
A: First let's take out all the Feb 29th, because these days are in the middle of the data and not appear in every year, and will bother the averaging:
Feb29=60+365*[1:4:32];
mean_Feb29=mean(GPH(:,:,Feb29),3); % A matrix of 95x38 with the mean of all February 29th
GPH(:,:,Feb29)=[]; % omit Feb 29th from the data
Last_Jan_1=GPH(:,:,end); % for Jan 1st you have additional data set, of year 2011
GPH(:,:,end)=[]; % omit Jan 1st 2011
re_GPH=reshape(GPH,95,38,365,[]);
av_GPH=mean(re_GPH,4);
Now re_GPH is a matrix of 95x38x365, where each slice in 3rd dimension is an average of a day in the year, starting Jan 1st, etc.
If you want the to include the last Jan 1st (Jen 1st 2011), run this line at after the previous code:
av_GPH(:,:,1)=mean(cat(3,av_GPH(:,:,1),Last_Jan_1),3);
For the ease of knowing which slice nubmer corresponds to each date, you can make an array of all the dates in the year:
t1 = datetime(2011,1,1,'format','MMMMd')
t2 = datetime(2011,12,31,'format','MMMMd')
t3=t1:t2;
Now, for example :
t3(156)=
datetime
June5
So av_GPH(:,:,156) is the average of June 5th.
For your comment, if you want to subtract each day from its average:
sub_GPH=GPH-repmat(av_GPH,1,1,32);
And for February 29th, you will need to do that BEFORE you erase them from the data (line 3 up there):
sub_GPH_Feb_29=GPH(:,:,Feb29)-repmat(mean_Feb29,1,1,8);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47076159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: PHP+Ubuntu Send email using gmail form localhost I have searched several posts on this but no luck. Everyone is using postfix. But when I gone through the text on
https://help.ubuntu.com/community/Postfix
What is a Mail Transfer Agent
In other words, it's a mail server not a
mail client like Thunderbird, Evolution, Outlook, Eudora, or a
web-based email service like Yahoo, GMail, Hotmail, Earthlink,
Comcast, SBCGlobal.net, ATT.net etc.... If you worked for a company
named Acme and owned acme.com, you could provide your employees with
email addresses @acme.com. Employees could send and receive email
through your computer, but not without your computer running all the
time. If all your email addresses are at a domain (@gmail.com,
@yahoo.com) you do not own (you don't own Google) or do not host
(acme.com) then you do not need this at all.
As the last line says You cannot us it for gmail or yahoo to make it work from localhost..!
Can anyone tell me how can I configure mail server on localhost using gmail SMTP? I am using Ubuntu 14.
Links I have tried before NONE of them worked for me. No error or warnings during testing of below listed links
https://askubuntu.com/questions/314664/sending-php-mail-from-localhost
https://askubuntu.com/questions/228938/how-can-i-configure-postfix-to-send-all-email-through-my-gmail-account
https://easyengine.io/tutorials/linux/ubuntu-postfix-gmail-smtp/
https://easyengine.io/tutorials/mail/postfix-debugging/
A: Please do following steps to send mail from localhost on Ubuntu/Linux through gmail :-
For that you need to install msmtp on Linux/Ubuntu server.
Gmail uses https:// (it's hyper text secure) so you need install ca-certificates
~$ sudo apt-get install msmtp ca-certificates
It will take few seconds to install msmtp package.
Now you have to create configuration file(msmtprc) using , gedit editor.
~$ sudo gedit /etc/msmtprc
Now you have to copy and paste following code in gedit (file you created with above command)
defaults
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
account default
host smtp.gmail.com
port 587
auth on
user [email protected]
password MY_GMAIL_PASSSWORD
from [email protected]
logfile /var/log/msmtp.log
Don't forget to replace MY_GMAIL_ID with your "gmail id" and MY_GMAIL_PASSSWORD with your "gmail password" in above lines of code.
Now create msmtp.log as
~$ sudo touch /var/log/msmtp.log
You have to make this file readable by anyone with
~$ sudo chmod 0644 /etc/msmtprc
Now Enable sendmail log file as writable with
~$ sudo chmod 0777 /var/log/msmtp.log
Your configuration for gmail's SMTP is now ready. Now send one test email as
~$ echo -e "Subject: Test Mail\r\n\r\nThis is my first test email." |msmtp --debug --from=default -t [email protected]
Please check your Gmail inbox.
Now if you want to send email with php from localhost please follow below instructions:-
Open and edit php.ini file
~$ sudo gedit /etc/php/7.0/apache2/php.ini
You have to set sendmail_path in your php.ini file.
Check your SMTP path with
~$ which msmtp
and you will get /usr/bin/msmtp like that.
Search sendmail_path in php.ini and edit as below
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = /usr/bin/msmtp -t
Please check 3rd line carefully there is no semicolon before sendmail_path.
Now save and exit from gedit. Now it's time to restart your apache
~$ sudo /etc/init.d/apache2 restart
Now create one php file with mail function from http://in2.php.net/manual/en/function.mail.php.
Do test and enjoy !!
A: This article explains exactly how to do what you want:
https://www.howtoforge.com/tutorial/configure-postfix-to-use-gmail-as-a-mail-relay/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33969783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Filters with dynamic fields in elasticsearch I am switching a very old version of ElasticSearch to version 6.5.
...
"text_mined_entities": {
"nlp": {
"abbreviations": [],
"chunks": [],
"recurring_chunks": [],
"tagged_entities_grouped": {
"NEURO|SCICRUNCH": [
{
"category": "NEURO",
"end": 41,
"label": "Infant",
"match": "infant",
"original_value": "Infant",
"reference": "BIRNLEX695",
"reference_db": "SCICRUNCH",
"sentence": 0,
"start": 35
},
...
I am wanting to filter on the text_mined_entities.nlp.tagged_entities_grouped.*.reference fields ( which are stored as 'keyword' ), but haven't had much luck. Something like:
GET _search
{
"query": {
"bool": {
"filter": { "term": {
"text_mined_entities.nlp.tagged_entities_grouped.*.reference": "BIRNLEX695"
}}
}
}
}
Any suggestions? Thanks.
A: Wildcard on fields can't be applied on term query. Instead you can use query_string which supports wildcard on field as well. So following will work:
Assuming text_mined_entities and nlp are of type nested
{
"query": {
"nested": {
"path": "text_mined_entities.nlp",
"query": {
"query_string": {
"query": "BIRNLEX695",
"fields": [
"text_mined_entities.nlp.tagged_entities_grouped.*.reference"
]
}
}
}
}
}
Update (if text_mined_entities & nlp are object type and not nested):
{
"query": {
"query_string": {
"query": "BIRNLEX695",
"fields": [
"text_mined_entities.nlp.tagged_entities_grouped.*.reference"
]
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53462890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Make the animation faster when there are thousands of components I am trying to hide a JSplitPane with animation. By hide, I mean to setDividerLocation(0) so its left component is invisible (technically it is visible, but with zero width):
public class SplitPaneTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));
JPanel rightPanel = new JPanel(new GridLayout(60, 60));
for (int i = 0; i < 60 * 60; i++) {
// rightPanel.add(new JLabel("s"));
}
rightPanel.setBorder(BorderFactory.createLineBorder(Color.red));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
frame.add(splitPane);
JButton button = new JButton("Press me to hide");
button.addActionListener(e -> hideWithAnimation(splitPane));
leftPanel.add(button, BorderLayout.PAGE_START);
frame.setMaximumSize(new Dimension(800, 800));
frame.setSize(800, 800);
frame.setLocationByPlatform(true);
frame.setVisible(true);
});
}
private static void hideWithAnimation(JSplitPane splitPane) {
final Timer timer = new Timer(10, null);
timer.addActionListener(e -> {
splitPane.setDividerLocation(Math.max(0, splitPane.getDividerLocation() - 3));
if (splitPane.getDividerLocation() == 0)
timer.stop();
});
timer.start();
}
}
If you run it, will see that everything seems good, and the animation runs smooth.
However, in the real application the right of the JSplitPane is a JPanel with CardLayout and each card has a lot of components.
If you uncomment this line in order to simulate the number of components:
// rightPanel.add(new JLabel("s"));
and re-run the above example, you will see that the animation no longer runs smoothly. So, the question is, is is possible to make it smooth(-ier)?
I have no idea how to approach a solution - if any exists.
Based on my research, I registered a global ComponentListener:
Toolkit.getDefaultToolkit()
.addAWTEventListener(System.out::println, AWTEvent.COMPONENT_EVENT_MASK);
and saw the tons of events that are being fired. So, I think the source of the problem is the tons of component events that are being fired for each component. Also, it seems that components with custom renderers (like JList - ListCellRenderer and JTable - TableCellRenderer), component events are firing for all of the renderers. For example, if a JList has 30 elements, 30 events (component) will be fired only for it. It also seems (and that's why I mentioned it) that for CardLayout, events are taking place for the "invisible" components as well.
I know that 60*60 might sound crazy to you, but in a real application (mine has ~1500) as it makes sense, the painting is heavier.
A:
I know that 60*60 might sound crazy to you, but in a real application (mine has ~1500) as it makes sense, the painting is heavier.
The layout manager is invoked every time the divider location is changed which would add a lot of overhead.
One solution might be to stop invoking the layout manager as the divider is animating. This can be done by overriding the doLayout() method of the right panel:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SplitPaneTest2 {
public static boolean doLayout = true;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));
JPanel rightPanel = new JPanel(new GridLayout(60, 60))
{
@Override
public void doLayout()
{
if (SplitPaneTest2.doLayout)
super.doLayout();
}
};
for (int i = 0; i < 60 * 60; i++) {
rightPanel.add(new JLabel("s"));
}
rightPanel.setBorder(BorderFactory.createLineBorder(Color.red));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
frame.add(splitPane);
JButton button = new JButton("Press me to hide");
button.addActionListener(e -> hideWithAnimation(splitPane));
leftPanel.add(button, BorderLayout.PAGE_START);
frame.setMaximumSize(new Dimension(800, 800));
frame.setSize(800, 800);
frame.setLocationByPlatform(true);
frame.setVisible(true);
});
}
private static void hideWithAnimation(JSplitPane splitPane) {
SplitPaneTest2.doLayout = false;
final Timer timer = new Timer(10, null);
timer.addActionListener(e -> {
splitPane.setDividerLocation(Math.max(0, splitPane.getDividerLocation() - 3));
if (splitPane.getDividerLocation() == 0)
{
timer.stop();
SplitPaneTest2.doLayout = true;
splitPane.getRightComponent().revalidate();
}
});
timer.start();
}
}
Edit:
I was not going to include my test on swapping out the panel full of components with a panel that uses an image of components since I fell the animation is the same, but since it was suggested by someone else here is my attempt for your evaluation:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.*;
public class SplitPaneTest2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));
JPanel rightPanel = new JPanel(new GridLayout(60, 60));
for (int i = 0; i < 60 * 60; i++) {
rightPanel.add(new JLabel("s"));
}
rightPanel.setBorder(BorderFactory.createLineBorder(Color.red));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
frame.add(splitPane);
JButton button = new JButton("Press me to hide");
button.addActionListener(e -> hideWithAnimation(splitPane));
leftPanel.add(button, BorderLayout.PAGE_START);
frame.setMaximumSize(new Dimension(800, 800));
frame.setSize(800, 800);
frame.setLocationByPlatform(true);
frame.setVisible(true);
});
}
private static void hideWithAnimation(JSplitPane splitPane) {
Component right = splitPane.getRightComponent();
Dimension size = right.getSize();
BufferedImage bi = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
right.paint( g );
g.dispose();
JLabel label = new JLabel( new ImageIcon( bi ) );
label.setHorizontalAlignment(JLabel.LEFT);
splitPane.setRightComponent( label );
splitPane.setDividerLocation( splitPane.getDividerLocation() );
final Timer timer = new Timer(10, null);
timer.addActionListener(e -> {
splitPane.setDividerLocation(Math.max(0, splitPane.getDividerLocation() - 3));
if (splitPane.getDividerLocation() == 0)
{
timer.stop();
splitPane.setRightComponent( right );
}
});
timer.start();
}
}
A: @GeorgeZ. I think the concept presented by @camickr has to do with when you actually do the layout. As an alternative to overriding doLayout, I would suggest subclassing the GridLayout to only lay out the components at the end of the animation (without overriding doLayout). But this is the same concept as camickr's.
Although if the contents of your components in the right panel (ie the text of the labels) remain unchanged during the animation of the divider, you can also create an Image of the right panel when the user clicks the button and display that instead of the actual panel. This solution, I would imagine, involves:
*
*A CardLayout for the right panel. One card has the actual rightPanel contents (ie the JLabels). The second card has only one JLabel which will be loaded with the Image (as an ImageIcon) of the first card.
*As far as I know, by looking at the CardLayout's implementation, the bounds of all the child components of the Container are set during layoutContainer method. That would probably mean that the labels would be layed out inspite being invisible while the second card would be shown. So you should probably combine this with the subclassed GridLayout to lay out only at the end of the animation.
*To draw the Image of the first card, one should first create a BufferedImage, then createGraphics on it, then call rightPanel.paint on the created Graphics2D object and finally dispose the Graphics2D object after that.
*Create the second card such that the JLabel would be centered in it. To do this, you just have to provide the second card with a GridBagLayout and add only one Component in it (the JLabel) which should be the only. GridBagLayout always centers the contents.
Let me know if such a solution could be useful for you. It might not be useful because you could maybe want to actually see the labels change their lay out profile while the animation is in progress, or you may even want the user to be able to interact with the Components of the rightPanel while the animation is in progress. In both cases, taking a picture of the rightPanel and displaying it instead of the real labels while the animation takes place, should not suffice. So it really depends, in this case, on how dynamic will be the content of the rightPanel. Please let me know in the comments.
If the contents are always the same for every program run, then you could probably pre-create that Image and store it. Or even, a multitude of Images and store them and just display them one after another when the animation turns on.
Similarly, if the contents are not always the same for every program run, then you could also subclass GridLayout and precalculate the bounds of each component at startup. Then that would make GridLayout a bit faster in laying out the components (it would be like encoding a video with the location of each object), but as I am testing it, GridLayout is already fast: it just calculates about 10 variables at the start of laying out, and then imediately passes over to setting the bounds of each Component.
Edit 1:
And here is my attempt of my idea (with the Image):
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.IntBinaryOperator;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class SplitPaneTest {
//Just a Timer which plays the animation of the split pane's divider going from side to side...
public static class SplitPaneAnimationTimer extends Timer {
private final JSplitPane splitPane;
private int speed, newDivLoc;
private IntBinaryOperator directionf;
private Consumer<SplitPaneAnimationTimer> onFinish;
public SplitPaneAnimationTimer(final int delay, final JSplitPane splitPane) {
super(delay, null);
this.splitPane = Objects.requireNonNull(splitPane);
super.setRepeats(true);
super.setCoalesce(false);
super.addActionListener(e -> {
splitPane.setDividerLocation(directionf.applyAsInt(newDivLoc, splitPane.getDividerLocation() + speed));
if (newDivLoc == splitPane.getDividerLocation()) {
stop();
if (onFinish != null)
onFinish.accept(this);
}
});
speed = 0;
newDivLoc = 0;
directionf = null;
onFinish = null;
}
public int getSpeed() {
return speed;
}
public JSplitPane getSplitPane() {
return splitPane;
}
public void play(final int newDividerLocation, final int speed, final IntBinaryOperator directionf, final Consumer<SplitPaneAnimationTimer> onFinish) {
if (newDividerLocation != splitPane.getDividerLocation() && Math.signum(speed) != Math.signum(newDividerLocation - splitPane.getDividerLocation()))
throw new IllegalArgumentException("Speed needs to be in the direction towards the newDividerLocation (from the current position).");
this.directionf = Objects.requireNonNull(directionf);
newDivLoc = newDividerLocation;
this.speed = speed;
this.onFinish = onFinish;
restart();
}
}
//Just a GridLayout subclassed to only allow laying out the components only if it is enabled.
public static class ToggleGridLayout extends GridLayout {
private boolean enabled;
public ToggleGridLayout(final int rows, final int cols) {
super(rows, cols);
enabled = true;
}
@Override
public void layoutContainer(final Container parent) {
if (enabled)
super.layoutContainer(parent);
}
public void setEnabled(final boolean enabled) {
this.enabled = enabled;
}
}
//How to create a BufferedImage (instead of using the constructor):
private static BufferedImage createBufferedImage(final int width, final int height, final boolean transparent) {
final GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice gdev = genv.getDefaultScreenDevice();
final GraphicsConfiguration gcnf = gdev.getDefaultConfiguration();
return transparent
? gcnf.createCompatibleImage(width, height, Transparency.TRANSLUCENT)
: gcnf.createCompatibleImage(width, height);
}
//This is the right panel... It is composed by two cards: one for the labels and one for the image.
public static class RightPanel extends JPanel {
private static final String CARD_IMAGE = "IMAGE",
CARD_LABELS = "LABELS";
private final JPanel labels, imagePanel; //The two cards.
private final JLabel imageLabel; //The label in the second card.
private final int speed; //The speed to animate the motion of the divider.
private final SplitPaneAnimationTimer spat; //The Timer which animates the motion of the divider.
private String currentCard; //Which card are we currently showing?...
public RightPanel(final JSplitPane splitPane, final int delay, final int speed, final int rows, final int cols) {
super(new CardLayout());
super.setBorder(BorderFactory.createLineBorder(Color.red));
spat = new SplitPaneAnimationTimer(delay, splitPane);
this.speed = Math.abs(speed); //We only need a positive (absolute) value.
//Label and panel of second card:
imageLabel = new JLabel();
imageLabel.setHorizontalAlignment(JLabel.CENTER);
imageLabel.setVerticalAlignment(JLabel.CENTER);
imagePanel = new JPanel(new GridBagLayout());
imagePanel.add(imageLabel);
//First card:
labels = new JPanel(new ToggleGridLayout(rows, cols));
for (int i = 0; i < rows * cols; ++i)
labels.add(new JLabel("|"));
//Adding cards...
final CardLayout clay = (CardLayout) super.getLayout();
super.add(imagePanel, CARD_IMAGE);
super.add(labels, CARD_LABELS);
clay.show(this, currentCard = CARD_LABELS);
}
//Will flip the cards.
private void flip() {
final CardLayout clay = (CardLayout) getLayout();
final ToggleGridLayout labelsLayout = (ToggleGridLayout) labels.getLayout();
if (CARD_LABELS.equals(currentCard)) { //If we are showing the labels:
//Disable the laying out...
labelsLayout.setEnabled(false);
//Take a picture of the current panel state:
final BufferedImage pic = createBufferedImage(labels.getWidth(), labels.getHeight(), true);
final Graphics2D g2d = pic.createGraphics();
labels.paint(g2d);
g2d.dispose();
imageLabel.setIcon(new ImageIcon(pic));
imagePanel.revalidate();
imagePanel.repaint();
//Flip the cards:
clay.show(this, currentCard = CARD_IMAGE);
}
else { //Else if we are showing the image:
//Enable the laying out...
labelsLayout.setEnabled(true);
//Revalidate and repaint so as to utilize the laying out of the labels...
labels.revalidate();
labels.repaint();
//Flip the cards:
clay.show(this, currentCard = CARD_LABELS);
}
}
//Called when we need to animate fully left motion (ie until reaching left side):
public void goLeft() {
final JSplitPane splitPane = spat.getSplitPane();
final int currDivLoc = splitPane.getDividerLocation(),
minDivLoc = splitPane.getMinimumDividerLocation();
if (CARD_LABELS.equals(currentCard) && currDivLoc > minDivLoc) { //If the animation is stopped:
flip(); //Show the image label.
spat.play(minDivLoc, -speed, Math::max, ignore -> flip()); //Start the animation to the left.
}
}
//Called when we need to animate fully right motion (ie until reaching right side):
public void goRight() {
final JSplitPane splitPane = spat.getSplitPane();
final int currDivLoc = splitPane.getDividerLocation(),
maxDivLoc = splitPane.getMaximumDividerLocation();
if (CARD_LABELS.equals(currentCard) && currDivLoc < maxDivLoc) { //If the animation is stopped:
flip(); //Show the image label.
spat.play(maxDivLoc, speed, Math::min, ignore -> flip()); //Start the animation to the right.
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));
int rows, cols;
rows = cols = 60;
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
final RightPanel rightPanel = new RightPanel(splitPane, 10, 3, rows, cols);
splitPane.setLeftComponent(leftPanel);
splitPane.setRightComponent(rightPanel);
JButton left = new JButton("Go left"),
right = new JButton("Go right");
left.addActionListener(e -> rightPanel.goLeft());
right.addActionListener(e -> rightPanel.goRight());
final JPanel buttons = new JPanel(new GridLayout(1, 0));
buttons.add(left);
buttons.add(right);
frame.add(splitPane, BorderLayout.CENTER);
frame.add(buttons, BorderLayout.PAGE_START);
frame.setSize(1000, 800);
frame.setMaximumSize(frame.getSize());
frame.setLocationByPlatform(true);
frame.setVisible(true);
splitPane.setDividerLocation(0.5);
});
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63158480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Django REST Framework: nested serializers and deserializing I'm again stuck with Django REST Framework and its serializers.
Basically, what I want to be able to do is stick the following incoming data into a serializers.Serializer instance:
data = {
"thing_id": 715,
"sub_things": [
{
"id": 1,
"name": "bob"
},
{
"id": 2,
"name": "mike"
}
]
}
sub_things are handled by a serializers.ModelSerializer called SubThingSerializer. This is how it looks like.
class SubThingSerializer(serializers.ModelSerializer):
class Meta:
model = SubThing
fields = ('id', 'name')
read_only_fields = ('id', 'name')
Serialization of Thing is handled by a ThingSerializer, which I've for now handled as below:
class ThingSerializer(serializers.Serializer):
thing_id = serializers.IntegerField()
sub_things= SubThingSerializer(many=True)
Now, when I do
serializer = ThingSerializer(data=data)
I get empty OrderedDicts like:
{'sub_things': [OrderedDict(), OrderedDict()], 'thing_id': 715}
I guess it's wise to say that ThingSerializer will not need to get stored into a database, but it does use sub_things from database. These will not be written into db either. This is just to keep track of what sub_things the thing contains, pass this data back and forth between a browser client and a Python object for some calcualtions. And maybe store it in the session.
edit 1:
Most likely there's something I need to add to the create method of my ThingSerializer. So, I guess the ultimate question is: what's the correct syntax to pass sub_thing data to SubThingSerializers?
edit 2:
I dug a bit more. Seems that empty OrderedDicts get passed in validated_data to ThingSerializer.create() for some reason. Serializer validates alright with serializer.is_valid(). I could access the necessary data from initial_data, but that doesn't seem very solid.
edit 3:
Also tested around with serializers.ListField() for sub_things. Still seeing empty OrderedDicts in validated_data inside the create method.
A: Finally figured this out. read_only_fields on my SubThingSerializer prevented the data from getting through the validation resulting in empty dicts being created. I used read_only_fiels to prevent non-existent sub_thing data from being passed to my code, but I guess I'll need to find another way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42656608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Reading values from a text file to a linked list (no array of structs) to use for a stack; advice? I have a question. I am trying to read integer values from a file into a linked list, which will then be used for push and pop functions. I've done my push and pop functions, but I am trying to figure out if I have done the reading correctly. With my code so far, I used fscanf to read the file and printed it and it's printing all values. When I do my push function, it's not printing that correctly. Any advice on what I may be doing wrong.
4
2
1
6
1
5
2
3
3
1
6
1
\\values to be read from file
code below:
//linked list with place to store values and nodes
struct stack_list {
int list_values;
struct stack_list *node;
};
struct stack_list *head_node = NULL; //empty list
void stack_print(struct stack_list *); //prototype to print list
struct stack_list * push(struct stack_list * n, struct stack_list * c); //prototype to push values
int main(int argc, char* argv[]) {
FILE * fp; //opening file
fp = fopen("filename", "r"); //gives name of file to open
struct stack_list * mock = (struct stack_list *)malloc(sizeof(struct stack_list));
//int values[12]; //array to be used to collect values to pass to my list
//int n, t;
if (fp == NULL){
printf("File not provided.");
}
else if (fp != NULL) {
printf("Printing values first: \n");
while (fscanf(fp,"%d", &mock->list_values) == 1) {
mock->node = head_node;
printf("%d\n", mock->list_values);
}
}
push(mock, constructor_stack(mock));
stack_print(mock);
}
struct stack_list * constructor_stack(int j){
struct stack_list * my_node = (struct stack_list *)malloc(sizeof(struct stack_list));
my_node->list_values = j;
my_node->node = NULL;
return my_node;
}
struct stack_list * push(struct stack_list * num_list, struct stack_list * check_nodes) {
printf("Added values to stack:\n");
printf("Push: %d\n", check_nodes->list_values);
check_nodes->list_values = num_list;
return check_nodes;
}
This is part of what I have so far. I did attempt to use an array to just store the values and pass to my list, but that didn't work either.
int values[12]; //array to be used to collect values to pass to my list
int n, t;
while (fscanf(fp,"%d", &values[n]) == 1) {
n++;
}
}
for (t = 0; t < 12; ++t) { //iterating over array where values are stored
head_node = values[t]; //inputting values into the empty list
printf("%d\n", head_node); //printing values passed to empty list for reference
}
This is the output that I receive.
Printing values first:
4
2
1
6
1
5
2
3
3
1
6
1
Added values to stack:
Push: 136352
Printing stack:
1111111111111111111111
This printed the values but did not work in my push function either. I appreciate any advice!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58350646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why ARM Process IPI at the end of ISR I am studying IRQ handling on Linux.
I have a question, why we need to handle IPI at the end of each ISR[for SMP].
Is there something special with IPI? why not we process in do_asm_IRQ with other interrupts.
Any suggestion would be appreciated.
6 .macro arch_irq_handler_default
7 get_irqnr_preamble r6, lr
8 1: get_irqnr_and_base r0, r2, r6, lr
9 movne r1, sp
10 @
11 @ routine called with r0 = irq number, r1 = struct pt_regs *
12 @
13 adrne lr, BSYM(1b)
14 bne asm_do_IRQ
15
16 #ifdef CONFIG_SMP
17 /*
18 * XXX
19 *
20 * this macro assumes that irqstat (r2) and base (r6) are
21 * preserved from get_irqnr_and_base above
22 */
23 ALT_SMP(test_for_ipi r0, r2, r6, lr)
24 ALT_UP_B(9997f)
25 movne r1, sp
26 adrne lr, BSYM(1b)
27 bne do_IPI
28 #endif
http://lxr.oss.org.cn/source/arch/arm/include/asm/entry-macro-multi.S?v=3.5.2;a=arm
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13658676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to generate a random binary matrix where only one bit in each row has value 1? I want to use MATLAB to generate a random binary matrix A (n x m) which satisfies a condition:
Each row contains one position with value 1. Other positions are value 0. The position having 1 value is random position.
I tried this code
n=5;m=10;
%% A = randi([0 1], n,m);
A=zeros(n,m);
for i=1:n
rand_pos=randperm(m);
pos_one=rand_pos(1); % random possition of 1 value
A(i,pos_one)=1;
end
Is it correct?
A: The solution works, but it is inefficient.
You are using randperm to create a vector (array), and then use only the first element of the vector.
You can use randi to create a scalar (single element) instead:
n=5;m=10;
A=zeros(n,m);
for i=1:m
%rand_pos gets a random number in range [1, n].
rand_pos = randi([1, n]);
A(rand_pos, i)=1;
end
You can also use the following "vectorized" solution:
rand_pos_vec = randi([1, n], 1, m);
A(sub2ind([n, m], rand_pos_vec, 1:m)) = 1;
The above solution:
*
*Creates a vector of random values in range [1, n].
*Use sub2ind to convert "row index" to "matrix index".
*Place 1 in "matrix index".
A: You can do it in one line using bsxfun and randi:
A = double(bsxfun(@eq, 1:m, randi(n, n, 1)));
This compares the row vector [1 2 ... m] with an n×1 random vector of values from 1 to n. The comparison is done element-wise with singleton expansion. For each row, exactly one of the values of [1 2 ... m] equals that in the random vector.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39178569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Decode a string - Quote marks issue I am supposed to decode the string below in a script I have made (it is a task from a webpage). In order to ensure that the decoded word will be correct, I can not change the string in any way. Since the quote marks affects the string, parts like q90:;AI is not a string, which results in a syntax error.
q0Ø:;AI"E47FRBQNBG4WNB8B4LQN8ERKC88U8GEN?T6LaNBG4GØ""N6K086HB"Ø8CRHW"+LS79Ø""N29QCLN5WNEBS8GENBG4FØ47a
Is there a way I can decode the encrypted message without changing it? As of now I am just getting syntax error when I define the string in a variable.
A: You can surround the string with single quotes, since double quotes are used in the string already:
>>> print 'q0Ø:;AI"E47FRBQNBG4WNB8B4LQN8ERKC88U8GEN?T6LaNBG4GØ""N6K086HB"Ø8CRHW"+LS79Ø""N29QCLN5WNEBS8GENBG4FØ47a'
q0Ã:;AI"E47FRBQNBG4WNB8B4LQN8ERKC88U8GEN?T6LaNBG4GÃ""N6K086HB"Ã8CRHW"+LS79Ã""N29QCLN5WNEBS8GENBG4FÃ47a
>>>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29374262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Foregin key constraint error but shouldn't be occuring I have a list table with 5 entries in it, the first column in the identity column (PK), within a parent table is a column that is related to this list table by ID (FK). I am using C# in a web app to run an ExecuteScalar with a stored procedure to insert the items into the parent table.
This is within a SQL database
LIST TABLE:
ID INT (PK),
SKILL_SET_NAME VARCHAR
PARENT TABLE:
ID INT,
SKILL_SET_ID INT (FK)
ITEMS WITHIN LIST TABLE:
1, SOMETHING
2, ANOTHER
3, ELSE
INSERT STATEMENT INTO PARENT TABLE
INSERT INTO PARENT TABLE
(ID, SKILL_SET_ID)
VALUES
([NUMBER], 1)
ACTUAL CODE (changed the ExecuteScalar to NonQuery, and the SkillSetID is the foreign key)
public static void SetRIPSSkillSetDetails(int HDR_ID, int SkillSetID, string SkillSetOptional, int SkillSetRating)
{
ArrayList al = new ArrayList();
al.Add(new DictionaryEntry("@HDR_ID", HDR_ID));
al.Add(new DictionaryEntry("@SKILL_SET_ID", SkillSetID));
al.Add(new DictionaryEntry("@SKILL_SET_OPTIONAL", SkillSetOptional));
al.Add(new DictionaryEntry("@SKILL_SET_RATING", SkillSetRating));
Core.RunNonQuery("web", "[IPAM_GLOBAL_INSERT_PARTICIPANT_RATING_DTL]", al);
When the code runs the ExecuteScalar I get the Foreign key constraint error, Please help
A: The stored procedure was bombing out, someone said you can step through sql storec procedures from VS, how do I do that?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4036077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Color TdCalendarView rows I am using TdCalendarView code by Tinyfool in my project in which all calendar is designed using core graphics.I want to color rows of this calendar with two alternate colors.How can I do that?
A: You need to change the stroke fill color here for either even value of i in for loop or odd value
-(void)drawDateWords
{
CGContextRef ctx=UIGraphicsGetCurrentContext();
int width=self.frame.size.width;
int dayCount=[self getDayCountOfaMonth:currentMonthDate];
int day=0;
int x=0;
int y=0;
int s_width=width/7;
int curr_Weekday=[self getMonthWeekday:currentMonthDate];
// Normaly big Font
[array_Date addObject:@""];
[array_Month addObject:@""];
[array_Year addObject:@""];
[array_Desc addObject:@""];
[array_LastDate addObject:@""];
[self.array_Name addObject:@""];
UIFont *weekfont=[UIFont boldSystemFontOfSize:20];
for(int i=1;i<dayCount+1;i++)
{
day=i+curr_Weekday-2;
x=day % 7;
y=day / 7;
NSString *date=[[[NSString alloc] initWithFormat:@"%d",i] autorelease];
for (int j=0; j<[array_Date count]; j++) {
NSString *date1 = [array_Date objectAtIndex:j];
int month1 = [[array_Month objectAtIndex:j] intValue];
int year1 = [[array_Year objectAtIndex:j] intValue];
if ([date isEqualToString:date1] && currentMonthDate.month == month1 && currentMonthDate.year == year1)
{
//[@"*" drawAtPoint:CGPointMake(x*s_width+18,y*itemHeight+headHeight+18) withFont:[UIFont boldSystemFontOfSize:25]];
//[date drawAtPoint:CGPointMake(x*s_width+18,y*itemHeight+headHeight+18) withFont:[UIFont boldSystemFontOfSize:25]];
[[UIColor redColor] set];
}
else{
//[[UIColor redColor] set];
[date drawAtPoint:CGPointMake(x*s_width+15,y*itemHeight+headHeight) withFont:weekfont];
}
}
if([self getDayFlag:i]==1)
{
CGContextSetRGBFillColor(ctx, 1, 0, 0, 1);
[@"." drawAtPoint:CGPointMake(x*s_width+19,y*itemHeight+headHeight+6) withFont:[UIFont boldSystemFontOfSize:25]];
}
else if([self getDayFlag:i]==-1)
{
CGContextSetRGBFillColor(ctx, 0, 8.5, 0.3, 1);
[@"." drawAtPoint:CGPointMake(x*s_width+19,y*itemHeight+headHeight+6) withFont:[UIFont boldSystemFontOfSize:25]];
}
CGContextSetRGBFillColor(ctx, 0, 0, 0, 1);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6353951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Istio 1.4.3 to 1.5.6 upgrade using istioctl and Istio operator Can I make an existing Istio open source installable compatible with the (Istioctl + Operator) ? I currently have Istio 1.4.3 installed via istioctl .. and need to make existing deployment Istio operator aware as well before I upgrade to Istio 1.5.6+ . Any specific steps to be followed here ?
A: There shouldn't be any problem with that, I have tried that on my test cluster and everything worked just fine.
I had a problem with upgrading immediately from 1.4.3 to 1.5.6, so with below steps you're first upgrading from 1.4.3 to 1.5.0, then from 1.5.0 to 1.5.6
Take a look at below steps to follow.
1.Follow istio documentation and install istioctl 1.4, 1.5 and 1.5.6 with:
curl -L https://istio.io/downloadIstio | ISTIO_VERSION=1.4.0 sh -
curl -L https://istio.io/downloadIstio | ISTIO_VERSION=1.5.0 sh -
curl -L https://istio.io/downloadIstio | ISTIO_VERSION=1.5.6 sh -
2.Add the istioctl 1.4 to your path
cd istio-1.4.0
export PATH=$PWD/bin:$PATH
3.Install istio 1.4
istioctl manifest apply --set profile=demo
4.Check if everything works correct.
kubectl get pod -n istio-system
kubectl get svc -n istio-system
istioctl version
5.Add the istioctl 1.5 to your path
cd istio-1.5.0
export PATH=$PWD/bin:$PATH
6.Install istio operator for future upgrade.
istioctl operator init
7.Prepare IstioOperator.yaml
nano IstioOperator.yaml
apiVersion: install.istio.io/v1alpha1
kind: IstioOperator
metadata:
namespace: istio-system
name: example-istiocontrolplane
spec:
profile: demo
tag: 1.5.0
8.Before the upgrade use below commands
kubectl -n istio-system delete service/istio-galley deployment.apps/istio-galley
kubectl delete validatingwebhookconfiguration.admissionregistration.k8s.io/istio-galley
9.Upgrade from 1.4 to 1.5 with istioctl upgrade and prepared IstioOperator.yaml
istioctl upgrade -f IstioOperator.yaml
10.After the upgrade use below commands
kubectl -n istio-system delete deployment istio-citadel istio-galley istio-pilot istio-policy istio-sidecar-injector istio-telemetry
kubectl -n istio-system delete service istio-citadel istio-policy istio-sidecar-injector istio-telemetry
kubectl -n istio-system delete horizontalpodautoscaler.autoscaling/istio-pilot horizontalpodautoscaler.autoscaling/istio-telemetry
kubectl -n istio-system delete pdb istio-citadel istio-galley istio-pilot istio-policy istio-sidecar-injector istio-telemetry
kubectl -n istio-system delete deployment istiocoredns
kubectl -n istio-system delete service istiocoredns
11.Check if everything works correct.
kubectl get pod -n istio-system
kubectl get svc -n istio-system
istioctl version
12.Change istio IstioOperator.yaml tag value
nano IstioOperator.yaml
apiVersion: install.istio.io/v1alpha1
kind: IstioOperator
metadata:
namespace: istio-system
name: example-istiocontrolplane
spec:
profile: demo
tag: 1.5.6 <---
13.Upgrade from 1.5 to 1.5.6 with istioctl upgrade and prepared IstioOperator.yaml
istioctl upgrade -f IstioOperator.yaml
14.Add the istioctl 1.5.6 to your path
cd istio-1.5.6
export PATH=$PWD/bin:$PATH
15.I have deployed a bookinfo app to check if everything works correct.
kubectl label namespace default istio-injection=enabled
kubectl apply -f samples/bookinfo/platform/kube/bookinfo.yaml
kubectl apply -f samples/bookinfo/networking/bookinfo-gateway.yaml
16.Results
curl -v xx.xx.xxx.xxx/productpage | grep HTTP
HTTP/1.1 200 OK
istioctl version
client version: 1.5.6
control plane version: 1.5.6
data plane version: 1.5.6 (9 proxies)
Let me know if have any more questions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64102230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Mac: Installing app from Internet has an exception I want to install Firefox in my MacBook, downloaded from Internet.
After a series of clicking, I can use it with an exception.
It is not in the LaunchPad. Looks like it is installed on an other disk.
Here is image:
How to fix it?
A: Drag it to the Applications folder (as the green arrow suggests), and then run it from that folder rather than from the disk image.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52240660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: AWS dynamodb with Ruby SDK I have tables in dynamodb. I am new to 'AWS'.now my site is getting very slow. I couldn't find the solution. I suspect DynamoDB. So I need to know some details about DynamoDB. What is Read and write capacity, latency, CPU utilization? How to handle these all? to get DB gets fast?
A: When you create a table, you specify the provisioned capacity for read and write. This will limit the number of records you can read per second and number of records you can write per second. Your use-case will determine your actual needs. You can modify the provisioned capacity of a table after you have created, while it is being used and it will not affect access. This hot upgrade is a powerful feature of DynamoDB.
If you are exceeding your provisioned capacity, then DynamoDB will throttle your API calls. The aws-sdk gem will automatically retry throttled DynamoDB calls up to 10 times, using an exponential backoff strategy, sleeping between attempts.
To configure the retry limit for DynamoDB:
Aws.config[:dynamodb] = { retry_limit: 5 }
You can tell if your request is getting retried by inspecting the response object:
ddb = Aws::DynamoDB::Client.new
resp = ddb.get_item(table_name: 'aws-sdk', key: { id: '123' })
resp.context.retires
#=> 0
Also, you can enable logging:
require 'logger'
ddb = Aws::DynamoDB::Client.new(logger: Rails.logger)
ddb.get_item(table_name: 'aws-sdk', key: { id: '123' })
# sent to the rails logger
[Aws::DynamoDB::Client 200 0.008879 0 retries] get_item(table_name:"aws-sdk",key:{"id"=>{s:"123"}})
The log message contains the service client call, the HTTP status code (200), the time spent waiting on the call, the number of retires and the operation name and params called. You can of course configure the :log_level and a :log_formatter to modify when and what things are logged.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29314850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a more straightforward way to search for a string while ignoring spaces? I am working on a function that searches a searches a string for one of a list of given words. The string being searched is generated by OCR software, that occasionally adds extra spaces between letters (depending on the font) which I need to ignore.
I currently have a function that looks like this:
function searchSomeText($searchTerms, $stringToBeSearched)
{
$matches = array();
for($i=0; $i < count($searchTerms); ++ $i)
{
$searchTerms[$i] = substr(chunk_split($searchTerms[$i],1,"\s*"), 0, -3);
}
$searchTermsString = implode("|", $searchTerms);
if (preg_match("/\b($searchTermsString)\b/", $stringToBeSearched, $matches))
{
return $matches;
}
else { return false; }
}
*
*Is there any way to ignore spaces besides adding '\s*' between every character in the search terms?
*If there isn't, is there a more efficient method to add '\s*' after every character in the search terms but the last one other than using chunk_split() to add it after every character, and then chopping it off from the end?
Edit
I prefer not to just strip the spaces from the $stringToBeSearched because in the majority of cases, where the spacing is correct, I don't want a match where a search term is contained inside of another word (hence the '\b's)
A: Here is my recommended strategy for what I understand of your task:
*
*Do not mutate the haystack string. Often the the string to be searched is much much longer than the needle(s) used in the search. This potentially heavy lifting should be avoided when possible.
*Your search terms appear to be dynamic (and likely to be coming from user input), so the characters must be escaped to prevent regex pattern breakage. Use preg_quote() for this process.
*Insert \s* between all non-whitespace characters in the escaped search terms (ignoring escaping slashes).
*Then convert all sequences of one or more whitespaces to \s+ in the search terms.
*Now that the terms are prepared, glue them together using pipes. Wrap the piped expression in parentheses, then wrap that capture group in wordboundary markers (\b).
*Though not mentioned in your question, I recommend using case-insensitive matching. If multibyte/unicode characters may be involved, add the u pattern modifier as well.
Recommended Code: (Demo)
function searchSomeText(array $searchTerms, string $stringToBeSearched): bool
{
foreach ($searchTerms as &$searchTerm) {
$searchTerm = preg_replace(
['/\\\\?\S\K(?=\S)/', '/\s+/'],
['\\s*', '\\s+'],
preg_quote($searchTerm, '/')
);
}
$pattern = '/\b(' . implode("|", $searchTerms) . ')\b/i';
echo $pattern . "\n";
return (bool)preg_match($pattern, $stringToBeSearched);
}
var_export(
searchSomeText(
['at', 'cat ', 'the'],
'The catheter in the hat'
)
);
Output: (dynamic regex pattern & return value)
/\b(a\s*t|c\s*a\s*t\s+|t\s*h\s*e)\b/i
true
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25491296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: deployment of persistence unit failed issue wHEN I AM DEPLOYING MY CRUDWEB web application it is throwing like below:
SEVERE: Exception while deploying the app [CRUBWEB] : Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [CRUBWEBPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Problem compiling [SELECT e FROM custt e].
[14, 19] The abstract schema type 'custt' is unknown.
Please help Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34239777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails AASM does not rollback when validation returns false I have a model Booking that changes the status using AASM
models/booking.rb
before_validation :item_availability, if: -> { pending? || approved? }
enum status: [:pending, :approved, :rejected, :on_loan, :returned]
aasm column: :status, enum: true, whiny_transitions: true do
state :pending, initial: true
state :approved
event :approve do
transitions from: :pending, to: :approved
end
end
private
def item_availability
if quantity.to_f > item.quantity.to_f
errors.add(:base, "Not enough quantity for #{item.name} only #{item.quantity} left")
false
end
end
and I have a service that triggers the approve! event
def run
booking.transaction do
booking.approve!
booking.item.decrement!(:quantity, booking.quantity)
BookingsMailer.send_approval(booking).deliver_now
end
rescue ActiveRecord::RecordInvalid => e
errors.add(:base, e.message)
false
end
The problem here is the validation is being hit because the quantity is greater than the booking's quantity but the transaction in my service does not rollback.
According to documentation
Saving includes running all validations on the Job class. If
whiny_persistence flag is set to true, exception is raised in case of
failure.
I already set whiny_transitions to true but
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53367524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IClassFactory failed due to the following error: 800a0153 I'm trying to reference a com component and it is throwing the below error.
Creating an instance of the COM component with CLSID {xxx} from the IClassFactory failed due to the following error: 800a0153.
Specifically the error gets thrown when I try to instantiate an object. I checked that
*
*The project being built for x86 processors which it is
*The com object is registered using regsvr32, and is available in the registry.
I can also see the methods in the object browser, so I know .net is finding it.
Any ideas on what I'm missing?
A: This is an error code that's specific to the component. If you don't have documentation that explains what the code might mean then you'll need support from the vendor.
A: As noted in my comment to Hans' answer, this error code is FACILITY_CONTROL, which is supposed to relate to OLE/ActiveX controls, and has an error code which lies in the standard range (i.e. for Microsoft use) defined in OleCtl.h, but is not documented in the Win32 header files so is probably internal to a Microsoft product such as Visual Basic.
Can you tell us anything else about the COM component you are trying to use?
If the COM component was written using Visual Basic, I think it's probable that what you are seeing is equivalent to the Runtime Error 339 which users of Visual Basic see if they try to reference an OCX control which has some of its dependencies missing. You might look at the dependencies of the COM server's DLL/EXE using Depends.exe and see whether you have them all present on your machine.
A: Back when I had to do a lot of COM work, I used COM Explorer quite a bit from these guys:
http://download.cnet.com/COM-Explorer/3000-2206_4-10022464.html?tag=mncol;lst
I had to install it last year to debug a bizarre COM registration issue with Office plugins.
Also, I have no affiliation with these guys whatsoever (and it looks like the company might be toast anyway).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5033774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why MySQL InnoDB can handle concurrent updates and PostgreSQL can't? Let's imagine you have a table with this definition:
CREATE TABLE public.positions
(
id serial,
latitude numeric(18,12),
longitude numeric(18,12),
updated_at timestamp without time zone
)
And you have 50,000 rows in such table. now for testing purposes you will run an update like this:
update positions
set updated_at = now()
where latitude between 234.12 and 235.00;
that statement will update 1,000 rows from the 50,000 (in this specific dataset)
if you run such query in 30 different threads, MySQL innodb will succeed and postgres will fail with lots of deadlocks.
why?
A: Plain old luck, I would say.
If thirty threads go ahead and want to update the same 1000 rows, they can either access these rows in the same order (in which case they will lock out each other and do it sequentially) or in different orders (in which case they will deadlock).
That's the same for InnoDB and PostgreSQL.
To analyze why things work out different in your case, you should start by comparing the execution plans. Maybe then you get a clue why PostgreSQL does not access all rows in the same order.
Lacking this information, I'd guess that you are experiencing a feature introduced in version 8.3 that speeds up concurrent sequential scans:
*
*Concurrent large sequential scans can now share disk reads (Jeff Davis)
This is accomplished by starting the new sequential scan in the middle of the table (where another sequential scan is already in-progress) and wrapping around to the beginning to finish. This can affect the order of returned rows in a query that does not specify ORDER BY. The synchronize_seqscans configuration parameter can be used to disable this if necessary.
Check if your PostgreSQL execution plan uses sequential scans and see if changing synchronize_seqscans avoids the deadlocks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39940825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Correct usage of $.ajaxComplete and $.ajaxError? I've been using the following snippet on my ajax form submits:
$.ajax({
url: "",
data: ilmoittautumisdata,
type: "POST",
success:function(){
});
error:function(){
});
});
However, I remember that I was told to stop using success and error within it, as they're deprecated (?) and instead use $.ajaxComplete(); and $.ajaxError();.
However, reading the docs isn't helping me as I want to use both of them, and this isn't working for me.
$('#ilmoittuminen').submit(function(){
var ilmoittautumisdata = $('#ilmoittuminen').serialize();
$.ajax({
//url: "",
data: ilmoittautumisdata,
type: "POST"
});
$.ajaxComplete(
function(){
$('#ilmoittuminen').slideUp();
});
$.ajaxError(
function(){
});
return false;
});
How I should do it?
http://jsfiddle.net/D7qgd/
A: Firstly, the word you're looking for is "deprecated". As far as I'm aware, the success and error properties are definitely not deprecated. You can (and should, in your case) continue to use them.
The problem with your attempt to use ajaxError and ajaxComplete is that they are implemented as instance methods, rather than static methods on the jQuery object itself. For that reason, you need to select some element and call the methods on that collection. The element itself doesn't matter at all:
$("#someElement").ajaxComplete(function () {
// Do stuff
});
The next problem, which you haven't come across yet, is that the ajaxError and related methods register global AJAX event handlers. Each time you call one of those methods, you add a new event handler to the global set, and every time an AJAX event is fired, all of your registered handlers will be executed.
Update (Thanks @DCoder)
Looks like the success and error properties are deprecated as of jQuery 1.8. Instead, you can use the fail, done and always methods of the jQuery modified XHR object. Any objects that inherit from the deferred object can use these methods (the jqXHR object is one of these):
$.ajax(ajaxSetupObject).done(function () {
// Handle success
}).error(function () {
// Handle error
});
A: This code handles a success and error inside the ajax method.if there is a success it prints out success, with the object you receive, and vica versa.
$.ajax({
type: 'json',
url: 'foobar.com',
success: function(s) {
console.log('success' + s);
},
error: function(e) {
console.log('error' + e);
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12881072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Can c#/Razor work with DyGraph WITHOUT Javascript? In this question:
Previous DyGraph question
There is still the need to go to JavaScript to call DyGraph:
<script type="text/javascript">
g = new Dygraph(document.getElementById("readingGraph"), @data,{ labels: ["Sample Number", "Reading"] });
</script>
Is there anyway to remove JavaScript completely?
I would like a fully c# solution...
A: Ah, OBVIOUSSLY not. DyGraph is a javascript library. If you want to remove Javascript completely, you need to use a graph library that generates the graph on the server and sends the picture down to the client. Given that DyGraph is a javascript library - the obvious answer is no, it can not be used while at the same time totally disabling javascript.
Literally on the homepage it says: "dygraphs is a fast, flexible open source JavaScript charting library.".
A: If you want 100% C# and no Javascript, MudBlazor has some charting capabilities: https://mudblazor.com/components/barchart#api
As another answer states, "Given that DyGraph is a javascript library - the obvious answer is no, it can not be used while at the same time totally disabling javascript"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60547921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: localStorage.getItem retrieves 'null' I'm trying to get a counter for the number of times a button is pressed but when I try to retrieve it outside the function, it results in 'null' instead.
HTML:
<button class="signupbutton" onclick="counter()"> Yes I'm in!</button>
<div id="counter">
<p>Number of people that have signed up for the newsletter: </p>
<div id="counter1">0</div>
</div>
Javascript:
function counter() {
var elem = document.getElementById('counter1');
var count = localStorage.getItem('count');
if (count == null) {
count = 0;
}
count++;
localStorage.setItem('count', count);
elem.innerHTML = count;
}
console.log(localStorage.getItem('count'));
var count1 = localStorage.getItem('count');
var elem = document.getElementById('counter1');
elem.innerHTML = count1;
A: Make your code a bit more DRY would save you a bit of time, in validating that your counter has a "real" value. For the rest, the onclick inside an html element is not encouraged anymore, you can just update your code like
// wait until the page has loaded
window.addEventListener('load', function() {
// get your elements once
const counterElement = document.querySelector('#counter1');
const signupButton = document.querySelector('.signupbutton');
// assign a click event to your button
signupButton.addEventListener('click', updateCounter);
// function to retrieve the counter from your localStorage
function getKeyOrDefault( key, defaultValue = 0 ) {
return localStorage.getItem( key ) || defaultValue;
}
function updateCounter( e ) {
let counter = parseInt( getKeyOrDefault( 'counter' ) );
counter++;
counterElement.innerHTML = counter;
localStorage.setItem( 'counter', counter );
e.preventDefault();
}
// set the initial value
counterElement.innerHTML = getKeyOrDefault( 'counter' );
} );
Ofcourse, don't forget to change your html, to remove the counter function from the html element like
<button class="signupbutton"> Yes I'm in!</button>
<div id="counter">
<p>Number of people that have signed up for the newsletter: </p>
<div id="counter1">0</div>
</div>
A sample of this code can be found on this jsfiddle (it is not here, as stackoverflow doesn't support localstorage)
Now, the only thing I am really worried about, is the text of your HTML, note that the localStorage will be a personal storage for all clients, so, if this is a website run from the internet, all persons who arrive there once will start with null (or 0) and just increase by 1 each time they click the button, you will be none the wiser, as it is localStorage.
Ofcourse, if you handle it on 1 computer, where people have to input their data, then you have at least some data stored locally, but still, this isn't a real storage you can do something with ;)
A: The code does work. However, you have to make sure, that the counter function is interpreted before the page has loaded. Put the JS at the end of the document head, or rewrite the onlick using addEventListener.
A: You should convert to integer ..
function counter() {
var elem = document.getElementById('counter1');
var count = localStorage.getItem('count');
if (count == null) {
count = 0;
}
count = parseInt(count);
count++;
localStorage.setItem('count', count);
elem.innerHTML = count;
}
console.log(localStorage.getItem('count'));
var count1 = localStorage.getItem('count');
var elem = document.getElementById('counter1');
elem.innerHTML = count1;
Please Try again
A: getItem/setItem are unavailable until didFinish will have executed unless
Read local storage data using WKWebView
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51697301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can we create a custom wrapper for mock annotation of jmockit? Can we create a custom wrapper for mock annotation or MockUp class of jmockit ? If its possible can you explain how can we done it.
A: You can create a "custom wrapper" for JMockit's @Tested annotation (ie, use it as a meta-annotation), but not for any of the other annotations, @Mock included. So, the answer is no, it's not possible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44259252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sync Azure AD users to SQL Server on vm or Sql Database Users Table How can we synchronize Azure AD users with a user table in the database?
A: To Sync Azure AD users to SQL make sure each property stored in the data source maps properly to an AD user's attribute.
This article by Adam Bertram has code and whole process to Sync Azure AD users to Sql Database.
As per official documentation
Azure role-based access control (Azure RBAC) applies only to the portal and is not propagated to SQL Server.
Note
Database users (with the exception of administrators) cannot be
created using the Azure portal. Azure roles are not propagated to the
database in SQL Database, the SQL Managed Instance, or Azure Synapse.
Azure roles are used for managing Azure Resources, and do not apply to
database permissions. For example, the SQL Server Contributor role
does not grant access to connect to the database in SQL Database, the
SQL Managed Instance, or Azure Synapse. The access permission must be
granted directly in the database using Transact-SQL statements.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69388643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do you serve a static website using Google Cloud CDN, Google Cloud Storage, and a custom domain? I'd like to set up a static website with files stored in a Google Storage bucket. I already own a custom domain and have, at a minimum, some barebone files to see if the site is setup successfully.
Ideally, I'd like to serve the content via SSL when accessing that custom domain and have the content cached from Google Storage utilizing Google Cloud CDN so that end users are served content from the CDN as opposed to being served from Cloud Storage directly.
I haven't been able to find the perfect setup for this yet or even solidify if Google enables/supports this scenario at this point (I've read that there may be a need to leverage a load balancer to support SSL, but nothing conclusive).
So far I have created a Google Storage bucket and uploaded the desired files. I then made the bucket publicly readable to ensure there aren't any permissions issues. From there I set up a load balancer to leverage my custom domain with the checkbox of Google Cloud CDN checked, the storage bucket just created, set as the backend, and the host file mapping set to the default settings.
UPDATE:
It turned out just a few more steps were required. First, I needed to turn "Requestor Pays" off for the Storage bucket being utilized. Secondly, I needed to add permissions of "Storage Object Viewer" for "allUsers" (the legacy permission won't work here). Lastly, I had to both set the "A" and "AAAA" records to the IPV4 and IPV6 addresses of my Load Balancer for the DNS config on my domain name (and clear all previous values so that they were only referring to the new ones). After all of this was completed, everything is working as it should be :)
Thanks to both Cloud Ace (for leading me in the right direction) and a Google Customer Engineer that I met last week (for referring me to this article for reference: https://medium.com/@marco_37432/create-a-custom-domain-cdn-with-google-beta-7ad9531dfbae)!
A: When you create HTTP(S) Load Balancer, there should be a Certificate section in Frontend configuration if you set the protocol to HTTPS, also preserve a static IP. Then you can configure the DNS to point the domain to this IP.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56160391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Controling the look and feel of JButtons on Mac For my assignment I need a 2 dimensional array of JButtons in a grid JPanel in a JFrame. The JButtons must change color when clicked. I cannot get them to hold any color.
I implemented the solutions proposed in a previous thread and found that the work around only produced border color:
JButton button = new JButton("test");
button.setBackground(Color.RED);
button.setOpaque(true);
unpainting the border:
button.setBorderPainted(false);
simply causes the entire JFrame to be red.
This issue is only with MAC computers and not the intended problem of the assignment.
Any thoughts?
A: Remember : The Swing toolkit is pretty good at getting the system look and feel "almost right". If you really need the system feel, however, there are other options like SWT that are a little better suited.
If you want consistency then Swing can always default to the old school applet look which, although a little boring, is pretty reliable . The upside of this is that, when we roll back to this more simplistic looking gui toolkit, platform specific quirks magically seem to disappear .
I think you might find your problem solved quite easily if you simply set the look and feel to the standard swing style look and feel.
The Solution
I would suggest a call to
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
In the static code block where you initialize your application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8221976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Getting the icon for an audio device In the Sound Control Panel in Windows, and in the Volume Mixer, all audio devices have a specific icon set.
Is it possible to get which icon is set for a device through the Windows API?
Sound Control Panel
Volume Mixer
A: As suggested by Simon Mourier in the comments above, there is a PKEY that can access that data.
You can follow along with most of this sample and just replace PKEY_Device_FriendlyNamewith PKEY_DeviceClass_IconPath.
In short, it's something like this:
// [...]
IMMDevice *pDevice; // the device you want to look up
HRESULT hr = S_OK;
IPropertyStore *pProps = NULL;
PROPVARIANT varName;
hr = pDevice->OpenPropertyStore(STGM_READ, &pProps);
EXIT_ON_ERROR(hr);
PropVariantInit(&varName);
hr = pProps->GetValue(PKEY_DeviceClass_IconPath, &varName);
EXIT_ON_ERROR(hr);
// [...]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59811716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to display graph from database values using php? I want to create graph using php. I have tested jpgraph example. But it display error
like
> The image “http://localhost/test/jpgraphtest.php” cannot be displayed
> because it contains errors.
<?php
include('phpgraphlib.php');
$graph = new PHPGraphLib(500,350);
$data = array(12124, 5535, 43373, 22223, 90432, 23332, 15544, 24523,
32778, 38878, 28787, 33243, 34832, 32302);
$graph->addData($data);
$graph->setTitle('Widgets Produced');
$graph->setGradient('red', 'maroon');
$graph->createGraph();
?>
A: check this link I think its perfect.
http://pchart.sourceforge.net/
(also you should configure php to enable image creating).
In Windows, you'll include the GD2 DLL php_gd2.dll as an extension in php.ini. The GD1 DLL php_gd.dll was removed in PHP 4.3.2. Also note that the preferred truecolor image functions, such as imagecreatetruecolor(), require GD2.
check these links.
http://www.php.net/manual/en/image.requirements.php
http://www.php.net/manual/en/image.installation.php
http://www.php.net/manual/en/image.configuration.php
examples:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16392270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Prevent spring boot resolving properties to scientific notation I have a Spring Boot v2.1.0.RELEASE application with the following application.yml properties file:
example:
aws:
account: 845216416540
sqs:
endpoint: https://sqs.us-west-2.amazonaws.com/${example.aws.account}
Then I use the property like this:
@Component public class Example {
@Value("${example.aws.sqs.endpoint}")
private String endpoint;
public void test()
{
System.out.println(endpoint);
// prints -> https://sqs.us-west-2.amazonaws.com/8.4521641654E10
}
}
*
*No that is not my actual aws account (spare me the lecture)
Here is what I can't seem to figure out...
1) Why does spring by default interpolate the the value of the account as scientific notation?
2) How can I configure or prevent this from happening?
A: Spring is inferring the value to be a number. You can force the value to be treated as a string in YAML config by quoting it ie "845216416540"
This answer covers YAML convention in detail: https://stackoverflow.com/a/22235064/13172778
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56549903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to fixed header with in table? Hi all I want to fix (or) freezthead header on top and want to scroll tbody values only in table, as of now in table while scroll the page everything gets scrolled, but expecting to scroll only the tbody values ... My Demo
HTML
<tr ng-repeat="sryarnorder in sryarnorder.colorshades">
<td>{{$index+1}}</td>
<td> <input type="text" ng-model="sryarnorder.color" style="display:none;">
<div style="text-align:center;" ng-repeat="dyedyarnreferencenumber in dyedyarnreferencenumbers | filter:sryarnorder.color">
<p>{{dyedyarnreferencenumber.shade}}</p>
</div> </td>
<td> <input type="text" ng-model="sryarnorder.color" style="display:none;">
<div style="text-align:center;" ng-repeat="dyedyarnreferencenumber in dyedyarnreferencenumbers | filter:sryarnorder.color">
<p>{{dyedyarnreferencenumber.buyers_reference}}</p>
</div> </td>
<td> <input type="text" ng-model="sryarnorder.color" style="display:none;">
<div style="text-align:center;" ng-repeat="dyedyarnreferencenumber in dyedyarnreferencenumbers | filter:sryarnorder.color">
<p>{{dyedyarnreferencenumber.approved_supplier_ref}}</p>
</div> </td>
<td> <input type="text" ng-model="sryarnorder.color" style="display:none;">
<div style="text-align:center;" ng-repeat="dyedyarnreferencenumber in dyedyarnreferencenumbers | filter:sryarnorder.color">
<p>{{dyedyarnreferencenumber.category}}</p>
</div> </td>
<td> <input type="text" ng-model="sryarnorder.color" style="display:none;">
<p>{{sryarnorder.order_quantity}} {{sryarnorder.order_quantity_unit}}</p>
</div> </td>
<td> <input type="text" ng-model="sryarnorder.color" style="display:none;">
<p>{{sryarnorder.price_per_kg_currency}} {{sryarnorder.price_per_kg}}</p>
</div> </td>
<td> <input type="text" ng-model="sryarnorder.color" style="display:none;">
<p>{{sryarnorder.order_quantity * sryarnorder.price_per_kg}}</p>
</div> </td>
</tr>
CSS
table tbody, table thead
{
display: block!important;
}
table tbody
{
overflow: auto!important;
height: 100px!important;
}
table {
width: 100%!important;
}
th
{
width: auto!important;
}
Data
$scope.sryarnorders = [{"_id":"573d7fa0760ba711126d7de5","user":{"_id":"5721a378d33c0d6b0bb30416","displayName":"ms ms"},"__v":1,"colorshades":[{"_id":"573d7fc3760ba711126d7de6","price_per_kg_currency":"Inr","price_per_kg":"2","order_quantity_unit":"kg","order_quantity":"23","color":"56ffc46dab97a73d1066b792","quality":"Home Textiles","count":"yarn count"}],"created":"2016-05-19T08:56:00.997Z","remarks":"approved","actual_delivery_date":"2016-05-19","ex_india_date":"2016-05-19","ex_factory_date":"2016-05-19","lc_details_date":"2016-05-19","lc_details":"tooo much","po_delivery_date":"2016-05-19","sales_contract_date":"2016-05-19","sales_contract":"bioler","purchase_order_no_date":"2016-05-19","purchase_order_no":"1234","supplier_name":"Fsa","buyer_name":"e21"},{"_id":"56ffc6d5ab97a73d1066b798","user":{"_id":"56ff7bece2b9a1d10cd074a3","displayName":"saravana kumar"},"__v":1,"colorshades":[{"_id":"56ffc723ab97a73d1066b799","price_per_kg_currency":"Inr","price_per_kg":"120","order_quantity_unit":"kg","order_quantity":"25","color":"56ffc46dab97a73d1066b792","quality":"Home Textiles","count":"yarn count"}],"created":"2016-04-02T13:19:17.746Z","remarks":"pending","actual_delivery_date":"2016-04-02","ex_india_date":"2016-04-04","ex_factory_date":"2016-04-02","lc_details_date":"2016-04-02","lc_details":"lc","po_delivery_date":"2016-04-02","sales_contract_date":"2016-04-02","sales_contract":"required","purchase_order_no_date":"2016-04-02","purchase_order_no":"125","supplier_name":"Fsa","buyer_name":"Binary hand"},{"_id":"56ffc5e0ab97a73d1066b796","user":{"_id":"56ff7bece2b9a1d10cd074a3","displayName":"saravana kumar"},"__v":1,"colorshades":[{"_id":"56ffc608ab97a73d1066b797","price_per_kg_currency":"usd","price_per_kg":"5","order_quantity_unit":"kg","order_quantity":"20","color":"56ffc46dab97a73d1066b792","quality":"yarn quality","count":"yarn count"}],"created":"2016-04-02T13:15:12.876Z","remarks":"clear","actual_delivery_date":"2016-04-02","ex_india_date":"2016-04-02","ex_factory_date":"2016-04-02","lc_details_date":"2016-04-02","lc_details":"free","po_delivery_date":"2016-04-02","sales_contract_date":"2016-04-02","sales_contract":"required","purchase_order_no_date":"2016-04-02","purchase_order_no":"12345","supplier_name":"Fsa","buyer_name":"e21"}];
});
A: Try this: https://codepen.io/tjvantoll/pen/JEKIu
(you need to set fixed column widths)
HTML:
<table class="fixed_headers">
<thead>
<tr>
<th>Name</th>
<th>Color</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Red</td>
<td>These are red.</td>
</tr>
<!-- more stuff -->
</tbody>
</table>
CSS:
.fixed_headers {
width: 750px;
table-layout: fixed;
border-collapse: collapse;
}
.fixed_headers th {
text-decoration: underline;
}
.fixed_headers th,
.fixed_headers td {
padding: 5px;
text-align: left;
}
.fixed_headers td:nth-child(1),
.fixed_headers th:nth-child(1) {
min-width: 200px;
}
.fixed_headers td:nth-child(2),
.fixed_headers th:nth-child(2) {
min-width: 200px;
}
.fixed_headers td:nth-child(3),
.fixed_headers th:nth-child(3) {
width: 350px;
}
.fixed_headers thead {
background-color: #333;
color: #FDFDFD;
}
.fixed_headers thead tr {
display: block;
position: relative;
}
.fixed_headers tbody {
display: block;
overflow: auto;
width: 100%;
height: 300px;
}
.fixed_headers tbody tr:nth-child(even) {
background-color: #DDD;
}
.old_ie_wrapper {
height: 300px;
width: 750px;
overflow-x: hidden;
overflow-y: auto;
}
.old_ie_wrapper tbody {
height: auto;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44282116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.