text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Bug : SwipeRefreshLayout view doesn't get removed from Fragment container My application contains a drawer with two Fragments. Each Fragment contains a layout with SwipeRefreshLayout view.
If I replace Fragment in container when SwipeRefreshLayout is refreshing, the view of the fragment gets stuck in the FrameLayout container and appears above the new Fragment View. However, old fragment is removed from the FragmentManager.
Application works fine if I replace the Fragment in container when SwipeRefreshLayout is not refreshing. You can access the demo bug project here.
Any workaround or help would be appreciated.
A: Calling 'clearAnimation()' of your SwipeRefreshLayout before you replace the Fragment should do the trick.
A: It's a bug in SwipeRefreshLayout which is not fixed from long time despite having enough stars. You can keep track of issue here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33867546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: wrong p-value when calculating by stats.ttest_ind I have tried to calculate the p-value of two pandas series- Ref_for_avg and CNOGA_for_avg. I also calculated the mean and std of both series. The mean and std calculations are correct, however for some reason the, p-value which is calculated on the same 2 series is not correct.
I have these messages when I run the program:
" RuntimeWarning: Degrees of freedom <= 0 for slice
warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning)"
"RuntimeWarning: invalid value encountered in double_scalars"
"RuntimeWarning: invalid value encountered in greater return (self.a < x) & (x < self.b)"
"RuntimeWarning: invalid value encountered in less
return (self.a < x) & (x < self.b)"
"RuntimeWarning: invalid value encountered in less_equal
cond2 = cond0 & (x <= self.a)"
this is a part from my code:
for j_of_ErrDiffRange in ErrDiffRange_cols:
if np.isinf(j_of_ErrDiffRange):
ind_err = ErrDiff > ErrDiffRange_cols[-2]
else:
ind_err = ErrDiff <=j_of_ErrDiffRange
inError_bool=ind_err
Ref_inRange_bool=ind_err & ind_ref
CNOGA_inRange_bool=ind_err & ind_CNOGA
Ref_for_avg=Ref[Ref_inRange_bool]
Ref_for_totalrow=Ref[inError_bool]
CNOGA_for_avg=CNOGA[CNOGA_inRange_bool]
CNOGA_for_totalrow=CNOGA[inError_bool]
t, p_value= stats.ttest_ind(Ref_for_avg, CNOGA_for_avg,
equal_var=False)
t_tot, p_value_tot= stats.ttest_ind(Ref_for_totalrow,
CNOGA_for_totalrow, equal_var=False)
Can you please help me to find the problem?
Thanks alot.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44949568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to test a controller in Node.js using Chai, Sinon, Mocha I've been learning how to write better unit tests. I am working on a project where controllers follow the style of 'MyController' shown below. Basically an 'async' function that 'awaits' on many external calls and returns a status with the results. I have written a very basic test for an inner function 'dbResults'. However, I am unsure of how to go about testing if the entire controller function itself returns a certain value. In the example below. I was wondering if anyone can help me figure out what is the proper way to test the final result of a function such as 'getUserWithId'. The code written below is very close but not exactly what I have implemented. Any suggestions would be appreciated.
Controller
export const MyController = {
async getUserWithId(req, res) {
let dbResults = await db.getOneUser(req.query.id);
return res.status(200).json({ status: 'OK', data: dbResults });
}
}
Current Test
describe ('MyController Test', () => {
describe ('getUserWithId should return 200', () => {
before(() => {
// create DB stub
});
after(() => {
// restore DB stub
});
it('should return status 200', async () => {
req = // req stub
res = // res stub
const result = await MyController.getUserWithId(req, res);
expect(res.status).to.equal(200);
});
});
});
A: I would suggest using an integration-test for testing your controller rather than a unit-test.
integration-test threats the app as a black box where the network is the input (HTTP request) and 3rd party services as dependency that should be mocked (DB).
*
*Use unit-test for services, factories, and utils.
*Use integration-test for external interfaces like HTTP and WebSockets
You can add e2e-test as well but if you have only one component in your setup you integration-test will suffice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63896281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Some weird transformation to pandas dataframe My dataframe:
df = pd.DataFrame({'a':['A', 'B'], 'b':[{5:1, 11:2}, {5:3}]})
Expected output (Each Key will be transformed to 'n' keys. Example row 1, key =5 (with value =2) get transformed to 5, 6. This change also need to reflect on 'a' column)
df_expected = pd.DataFrame({'a':['A1', 'A2', 'A1', 'A2', 'B1', 'B2', 'B3'], 'key':[5, 6, 11, 12, 5, 6, 7]})
My present state:
df['key']=df.apply(lambda x: x['b'].keys(), axis=1)
df['value']=df.apply(lambda x: max(x['b'].values()), axis=1)
df = df.loc[df.index.repeat(df.value)]
Stuck here. What should be next step?
Expected output:
df_expected = pd.DataFrame({'a':['A1', 'A2', 'A1', 'A2', 'B1', 'B2', 'B3'], 'key':[5, 6, 11, 12, 5, 6, 7]})
A: This will do your transform, outside of pandas.
d = {'a':['A', 'B'], 'b':[{5:1, 11:2}, {5:3}]}
out = { 'a':[], 'b':[] }
for a,b in zip(d['a'],d['b']):
n = max(b.values())
for k in b:
for i in range(n):
out['a'].append(f'{a}{i+1}')
out['b'].append(k+i)
print(out)
Output:
{'a': ['A1', 'A2', 'A1', 'A2', 'B1', 'B2', 'B3'], 'b': [5, 6, 11, 12, 5, 6, 7]}
A: First you need to preprocess your input dictionary like this
import pandas as pd
d = {'a':['A', 'B'], 'b':[{5:2, 11:2}, {5:3}]} # Assuming 5:2 instead of 5:1.
res = {"a": [], "keys": []}
for idx, i in enumerate(d['b']):
res['a'].extend([f"{d['a'][idx]}{k}" for j in i for k in range(1,i[j]+1) ])
res['keys'].extend([k for j in i for k in range(j, j+i[j])])
df = pd.DataFrame(res)
output
{'a': ['A1', 'A2', 'A1', 'A2', 'B1', 'B2', 'B3'], 'keys': [5, 6, 11, 12, 5, 6, 7]}
A: For a pandas solution:
df2 = (df.drop(columns='b')
.join(pd.json_normalize(df['b'])
.rename_axis(columns='key')
.stack().reset_index(-1, name='repeat')
)
.loc[lambda d: d.index.repeat(d.pop('repeat'))]
)
g = df2.groupby(['a', 'key']).cumcount()
df2['a'] += g.add(1).astype(str)
df2['key'] += g
print(df2)
Output:
a key
0 A1 5
0 A1 11
0 A2 6
0 A2 12
0 A3 7
0 A3 13
1 B1 5
1 B2 6
1 B3 7
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74212442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unexpected response code 403 for https://www.googleapis.com/games/v1/players/xxxxx LibGDX Android I'm making a Android game with LibGDX and I want to use the Google Play Game Services API but I can't get it working.
Here's what happens when I try to login:
06-12 20:08:47.745: E/Volley(4046): [253] tk.a: Unexpected response code 403 for https://www.googleapis.com/games/v1/players/115171141636978128288
06-12 20:08:47.846: E/SignInIntentService(4046): Access Not Configured. Please use Google Developers Console to activate the API for your project.
06-12 20:08:47.846: E/SignInIntentService(4046): ebw
06-12 20:08:47.846: E/SignInIntentService(4046): at dwp.a(SourceFile:146)
06-12 20:08:47.846: E/SignInIntentService(4046): at dfx.a(SourceFile:390)
06-12 20:08:47.846: E/SignInIntentService(4046): at dfx.a(SourceFile:371)
06-12 20:08:47.846: E/SignInIntentService(4046): at dex.a(SourceFile:719)
06-12 20:08:47.846: E/SignInIntentService(4046): at ecp.a(SourceFile:250)
06-12 20:08:47.846: E/SignInIntentService(4046): at com.google.android.gms.games.service.GamesSignInIntentService.onHandleIntent(SourceFile:389)
06-12 20:08:47.846: E/SignInIntentService(4046): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
06-12 20:08:47.846: E/SignInIntentService(4046): at android.os.Handler.dispatchMessage(Handler.java:102)
06-12 20:08:47.846: E/SignInIntentService(4046): at android.os.Looper.loop(Looper.java:136)
06-12 20:08:47.846: E/SignInIntentService(4046): at android.os.HandlerThread.run(HandlerThread.java:61)
06-12 20:08:47.846: E/LoadSelfFragment(9533): Unable to sign in - application does not have a registered client ID
06-12 20:08:47.846: W/SignInActivity(9533): onSignInFailed()...
06-12 20:08:47.846: W/SignInActivity(9533): ==> Returning non-OK result: 10004
I checked if the app is linked and if the SHA1 key is the same between my keystore and in the Google Developers Console and I checked if I was been a tester of the app who was allowed to use the API.
Now I don't know where to look for to get this working.
Thank you for your help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24191311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to get value of checked radio? HTML:
<div id="chips">
<label>
<input type="radio" name="pet_chipped" class="chipped" value="Yes" id="chipyes" checked> Yes</label>
<label>
<input type="radio" name="pet_chipped" class="chipped" value="No" id="chipno"> No</label>
</div>
jQuery:
$("input[name='pet_chipped']:checked").val();
when I am alerting 'pet_chipped' it displaying undefined.
A:
//onload event
$(document).ready(function(){
/*show alert on load time*/
alert($('[name="pet_chipped"]:checked').val());
})
// on change radio button value fire event
$(document).on('change', '[name="pet_chipped"]', function(){
//show value of radio after changed
alert($('[name="pet_chipped"]:checked').val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chips">
<label> <input type="radio" name="pet_chipped" class="chipped" value="Yes" id="chipyes" checked> Yes</label>
<label><input type="radio" name="pet_chipped" class="chipped" value="No" id="chipno"> No</label>
</div>
A: Try this
HTML :
<input type="radio" name="pet_chipped" class="chipped" value="Yes"> Yes</label>
<label>
<input type="radio" name="pet_chipped" class="chipped" value="No" checked> No</label>
<input type="submit" onclick="getChecked()" />
Jquery :
<script type="text/javascript">
function getChecked(){
var checked = $("input[name='pet_chipped']:checked").val();
alert(checked);
}
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43384574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IIFE Syntax best practice This is from MDN web docs
(function () {
//statements
})();
But i've seen this usage down below too
(function() {
//statements
}());
It seems both works. But which is best practice and why is there such difference? First one seems more appropriate imo
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62314925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Running Bat file from Excel VBA I have the following VBA code which works:
Sub TfrSec()
Dim argh As Double
argh = Shell("C:\Users\Avishen\Desktop\Transfer Rates File.bat", vbNormalFocus)
End Sub
I want to change Avishen so that it picks up automatically the current user which is login on windows.
Thanks for helping
A: Use the Environ function to retrieve the environment variables that are set in Windows.
Sub TfrSec()
Dim argh As Double
argh = Shell(Environ("USERPROFILE") & "\Desktop\Transfer Rates File.bat", vbNormalFocus)
End Sub
See here for a list of available variables in Windows 10.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68342944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MySQL: What is the most performant way of storing a whole year (365 elements) in MySQL? Within a project, I have to store the daily availability of different meeting rooms. So let's suppose around 1.000.000 meeting rooms, where each meeting room is in a city, and a city could have hundreds of meeting rooms.
I would also like to be able to make SELECT Queries entering the city and the availability that I need, so I would like to get a list of the available meeting rooms for a day, or set of continues days, in a concrete city.
I have one table called "MeetingRoom", when I store the city and the name of the meeting room, but my design question is how to design the availability part:
*
*Is it better in terms of performance to have a binary array that stores the 365 days of the year with a '1' or '0' according to the availability of the meeting room?
*Is it better in terms of performance to have another table called "Availability" that stores a DATE and a BIT with the availability, and then JOIN both tables for each meeting room that exists in a city?
*Could it better another option I don't have in mind?
I wonder what querying time would be optimal having around 1.000.000 meeting rooms, and searching for the meeting rooms in a city and available for concrete days. Is it crazy about thinking in database responses below 100 ms?
Some colleagues told me that I should also consider to migrate to MongoDB or NoSQL approach. I don't know if a change of DB could fit better with my issues, or if it don't. Any comment about this?
Thank you very much for the help!!
A: I don't know if this will help, but if it doesn't, please write me to delete the answer.
Instead of these options you may want to consider that in the "Availability" table to store only the id(surrogate) of the room and the date on which it is reserved. So when you select the data and join both tables you will get only the reserved rooms. I personally think that there is no point of storing all of the room-date relations with status.
Moreover, to improve the performance you can create non-clustered index on the City column for instance.
A: Please don't fill your database with lots of rows which are default values.
so you don't store availability of a meeting room, you store booking of a meeting room.
primary key of booking table is date and room id , other fields are who booked this room, when booking was asked, a booking id...
If it is possible to book meeting room for part of the day then primary key should be start_date and room id, end date is stored in another field of the table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44949803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python Hyperlinks function I'm trying to create a function in python which reads an html and then takes out only the hyperlink and the theme of the hyperlink..The html page is specific and the function is only for this page..So as i'm a really amateur in python learning i thought something like this..
def fun("string","start of hyper","end of hyper")
.And when i call this function,i'll read the html file,and pop up only the parts which have tha classic html words for start and finish hyperlinks <a,</a> .Also i must not use any modules like beautiful soup for this function!!Thanks for any response
A: This might be the complete solution as you are looking for.
This code is from the udacity computer science course (CS101)
It uses simulated webpages using method get_page(url):
Run in your computer once and read the code
It also try to remove duplicate urls
def get_page(url):
# This is a simulated get_page procedure so that you can test your
# code on two pages "http://xkcd.com/353" and "http://xkcd.com/554".
# A procedure which actually grabs a page from the web will be
# introduced in unit 4.
try:
if url == "http://xkcd.com/353":
return '<?xml version="1.0" encoding="utf-8" ?><?xml-stylesheet href="http://imgs.xkcd.com/s/c40a9f8.css" type="text/css" media="screen" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>xkcd: Python</title> <link rel="stylesheet" type="text/css" href="http://imgs.xkcd.com/s/c40a9f8.css" media="screen" title="Default" /> <!--[if IE]><link rel="stylesheet" type="text/css" href="http://imgs.xkcd.com/s/ecbbecc.css" media="screen" title="Default" /><![endif]--> <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="/atom.xml" /> <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="/rss.xml" /> <link rel="icon" href="http://imgs.xkcd.com/s/919f273.ico" type="image/x-icon" /> <link rel="shortcut icon" href="http://imgs.xkcd.com/s/919f273.ico" type="image/x-icon" /> </head> <body> <div id="container"> <div id="topContainer"> <div id="topLeft" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s">\t<ul> <li><a href="http://xkcd.com/554"">Archive</a><br /></li>\t <li><a href="http://blag.xkcd.com/">News/Blag</a><br /></li> <li><a href="http://store.xkcd.com/">Store</a><br /></li> <li><a href="/about/">About</a><br /></li> <li><a href="http://forums.xkcd.com/">Forums</a><br /></li> </ul> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> <div id="topRight" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <div id="topRightContainer"> <div id="logo"> <a href="/"><img src="http://imgs.xkcd.com/s/9be30a7.png" alt="xkcd.com logo" height="83" width="185"/></a> <h2><br />A webcomic of romance,<br/> sarcasm, math, and language.</h2> <div class="clearleft"></div> <br />XKCD updates every Monday, Wednesday, and Friday. </div> </div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> </div> <div id="contentContainer"> <div id="middleContent" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"><h1>Python</h1><br/><br /><div class="menuCont"> <ul> <li><a href="/1/">|<</a></li> <li><a href="/352/" accesskey="p">< Prev</a></li> <li><a href="http://dynamic.xkcd.com/random/comic/" id="rnd_btn_t">Random</a></li> <li><a href="/354/" accesskey="n">Next ></a></li> <li><a href="/">>|</a></li> </ul></div><br/><br/><img src="http://imgs.xkcd.com/comics/python.png" title="I wrote 20 short programs in Python yesterday. It was wonderful. Perl, Im leaving you." alt="Python" /><br/><br/><div class="menuCont"> <ul> <li><a href="/1/">|<</a></li> <li><a href="/352/" accesskey="p">< Prev</a></li> <li><a href="http://dynamic.xkcd.com/random/comic/" id="rnd_btn_b">Random</a></li> <li><a href="/354/" accesskey="n">Next ></a></li> <li><a href="/">>|</a></li> </ul></div><h3>Permanent link to this comic: http://xkcd.com/353/</h3><h3>Image URL (for hotlinking/embedding): http://imgs.xkcd.com/comics/python.png</h3><div id="transcript" style="display: none">[[ Guy 1 is talking to Guy 2, who is floating in the sky ]]Guy 1: You39;re flying! How?Guy 2: Python!Guy 2: I learned it last night! Everything is so simple!Guy 2: Hello world is just 39;print "Hello, World!" 39;Guy 1: I dunno... Dynamic typing? Whitespace?Guy 2: Come join us! Programming is fun again! It39;s a whole new world up here!Guy 1: But how are you flying?Guy 2: I just typed 39;import antigravity39;Guy 1: That39;s it?Guy 2: ...I also sampled everything in the medicine cabinet for comparison.Guy 2: But i think this is the python.{{ I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I39;m leaving you. }}</div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> <div id="middleFooter" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <img src="http://imgs.xkcd.com/s/a899e84.jpg" width="520" height="100" alt="Selected Comics" usemap=" comicmap" /> <map name="comicmap"> <area shape="rect" coords="0,0,100,100" href="/150/" alt="Grownups" /> <area shape="rect" coords="104,0,204,100" href="/730/" alt="Circuit Diagram" /> <area shape="rect" coords="208,0,308,100" href="/162/" alt="Angular Momentum" /> <area shape="rect" coords="312,0,412,100" href="/688/" alt="Self-Description" /> <area shape="rect" coords="416,0,520,100" href="/556/" alt="Alternative Energy Revolution" /> </map><br/><br />Search comic titles and transcripts:<br /><script type="text/javascript" src="//www.google.com/jsapi"></script><script type="text/javascript"> google.load(\"search\", \"1\"); google.setOnLoadCallback(function() { google.search.CustomSearchControl.attachAutoCompletion( \"012652707207066138651:zudjtuwe28q\", document.getElementById(\"q\"), \"cse-search-box\"); });</script><form action="//www.google.com/cse" id="cse-search-box"> <div> <input type="hidden" name="cx" value="012652707207066138651:zudjtuwe28q" /> <input type="hidden" name="ie" value="UTF-8" /> <input type="text" name="q" id="q" autocomplete="off" size="31" /> <input type="submit" name="sa" value="Search" /> </div></form><script type="text/javascript" src="//www.google.com/cse/brand?form=cse-search-box&lang=en"></script><a href="/rss.xml">RSS Feed</a> - <a href="/atom.xml">Atom Feed</a><br /> <br/> <div id="comicLinks"> Comics I enjoy:<br/> <a href="http://www.qwantz.com">Dinosaur Comics</a>, <a href="http://www.asofterworld.com">A Softer World</a>, <a href="http://pbfcomics.com/">Perry Bible Fellowship</a>, <a href="http://www.boltcity.com/copper/">Copper</a>, <a href="http://questionablecontent.net/">Questionable Content</a>, <a href="http://achewood.com/">Achewood</a>, <a href="http://wondermark.com/">Wondermark</a>, <a href="http://thisisindexed.com/">Indexed</a>, <a href="http://www.buttercupfestival.com/buttercupfestival.htm">Buttercup Festival</a> </div> <br/> Warning: this comic occasionally contains strong language (which may be unsuitable for children), unusual humor (which may be unsuitable for adults), and advanced mathematics (which may be unsuitable for liberal-arts majors).<br/> <br/> <h4>We did not invent the algorithm. The algorithm consistently finds Jesus. The algorithm killed Jeeves. <br />The algorithm is banned in China. The algorithm is from Jersey. The algorithm constantly finds Jesus.<br />This is not the algorithm. This is close.</h4><br/> <div class="line"></div> <br/> <div id="licenseText"> <!-- <a rel="license" href="http://creativecommons.org/licenses/by-nc/2.5/"><img alt="Creative Commons License" style="border:none" src="http://imgs.xkcd.com/static/somerights20.png" /></a><br/> --> This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc/2.5/">Creative Commons Attribution-NonCommercial 2.5 License</a>.<!-- <rdf:RDF xmlns="http://web.resource.org/cc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns "><Work rdf:about=""><dc:creator>Randall Munroe</dc:creator><dcterms:rightsHolder>Randall Munroe</dcterms:rightsHolder><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:source rdf:resource="http://www.xkcd.com/"/><license rdf:resource="http://creativecommons.org/licenses/by-nc/2.5/" /></Work><License rdf:about="http://creativecommons.org/licenses/by-nc/2.5/"><permits rdf:resource="http://web.resource.org/cc/Reproduction" /><permits rdf:resource="http://web.resource.org/cc/Distribution" /><requires rdf:resource="http://web.resource.org/cc/Notice" /><requires rdf:resource="http://web.resource.org/cc/Attribution" /><prohibits rdf:resource="http://web.resource.org/cc/CommercialUse" /><permits rdf:resource="http://web.resource.org/cc/DerivativeWorks" /></License></rdf:RDF> --> <br/> This means you\"re free to copy and share these comics (but not to sell them). <a href="/license.html">More details</a>.<br/> </div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> </div> </div> </body></html> '
elif url == "http://xkcd.com/554":
return '<?xml version="1.0" encoding="utf-8" ?> <?xml-stylesheet href="http://imgs.xkcd.com/s/c40a9f8.css" type="text/css" media="screen" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>xkcd: Not Enough Work</title> <link rel="stylesheet" type="text/css" href="http://imgs.xkcd.com/s/c40a9f8.css" media="screen" title="Default" /> <!--[if IE]><link rel="stylesheet" type="text/css" href="http://imgs.xkcd.com/s/ecbbecc.css" media="screen" title="Default" /><![endif]--> <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="/atom.xml" /> <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="/rss.xml" /> <link rel="icon" href="http://imgs.xkcd.com/s/919f273.ico" type="image/x-icon" /> <link rel="shortcut icon" href="http://imgs.xkcd.com/s/919f273.ico" type="image/x-icon" /> </head> <body> <div id="container"> <div id="topContainer"> <div id="topLeft" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <ul> <li><a href="/archive/">Archive</a><br /></li> <li><a href="http://blag.xkcd.com/">News/Blag</a><br /></li> <li><a href="http://store.xkcd.com/">Store</a><br /></li> <li><a href="/about/">About</a><br /></li> <li><a href="http://forums.xkcd.com/">Forums</a><br /></li> </ul> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> <div id="topRight" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <div id="topRightContainer"> <div id="logo"> <a href="/"><img src="http://imgs.xkcd.com/s/9be30a7.png" alt="xkcd.com logo" height="83" width="185"/></a> <h2><br />A webcomic of romance,<br/> sarcasm, math, and language.</h2> <div class="clearleft"></div> XKCD updates every Monday, Wednesday, and Friday. <br /> Blag: Remember geohashing? <a href="http://blog.xkcd.com/2012/02/27/geohashing-2/">Something pretty cool</a> happened Sunday. </div> </div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> </div> <div id="contentContainer"> <div id="middleContent" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <h1>Not Enough Work</h1><br/> <br /> <div class="menuCont"> <ul> <li><a href="/1/">|<</a></li> <li><a href="/553/" accesskey="p">< Prev</a></li> <li><a href="http://dynamic.xkcd.com/random/comic/" id="rnd_btn_t">Random</a></li> <li><a href="/555/" accesskey="n">Next ></a></li> <li><a href="/">>|</a></li> </ul> </div> <br/> <br/> <img src="http://imgs.xkcd.com/comics/not_enough_work.png" title="It39;s even harder if you39;re an asshole who pronounces <> brackets." alt="Not Enough Work" /><br/> <br/> <div class="menuCont"> <ul> <li><a href="/1/">|<</a></li> <li><a href="/553/" accesskey="p">< Prev</a></li> <li><a href="http://dynamic.xkcd.com/random/comic/" id="rnd_btn_b">Random</a></li> <li><a href="/555/" accesskey="n">Next ></a></li> <li><a href="/">>|</a></li> </ul> </div> <h3>Permanent link to this comic: http://xkcd.com/554/</h3> <h3>Image URL (for hotlinking/embedding): http://imgs.xkcd.com/comics/not_enough_work.png</h3> <div id="transcript" style="display: none">Narration: Signs your coders don39;t have enough work to do: [[A man sitting at his workstation; a female co-worker behind him]] Man: I39;m almost up to my old typing speed in dvorak [[Two men standing by a server rack]] Man 1: Our servers now support gopher. Man 1: Just in case. [[A woman standing near her workstation speaking to a male co-worker]] Woman: Our pages are now HTML, XHTML-STRICT, and haiku-compliant Man: Haiku? Woman: <div class="main"> Woman: <span id="marquee"> Woman: Blog!< span>< div> [[A woman sitting at her workstation]] Woman: Hey! Have you guys seen this webcomic? {{title text: It39;s even harder if you39;re an asshole who pronounces <> brackets.}}</div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> <div id="middleFooter" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <img src="http://imgs.xkcd.com/s/a899e84.jpg" width="520" height="100" alt="Selected Comics" usemap=" comicmap" /> <map name="comicmap"> <area shape="rect" coords="0,0,100,100" href="/150/" alt="Grownups" /> <area shape="rect" coords="104,0,204,100" href="/730/" alt="Circuit Diagram" /> <area shape="rect" coords="208,0,308,100" href="/162/" alt="Angular Momentum" /> <area shape="rect" coords="312,0,412,100" href="/688/" alt="Self-Description" /> <area shape="rect" coords="416,0,520,100" href="/556/" alt="Alternative Energy Revolution" /> </map><br/><br /> Search comic titles and transcripts:<br /> <script type="text/javascript" src="//www.google.com/jsapi"></script> <script type="text/javascript"> google.load("search", "1"); google.search.CustomSearchControl.attachAutoCompletion( "012652707207066138651:zudjtuwe28q", document.getElementById("q"), "cse-search-box"); }); </script> <form action="//www.google.com/cse" id="cse-search-box"> <div> <input type="hidden" name="cx" value="012652707207066138651:zudjtuwe28q" /> <input type="hidden" name="ie" value="UTF-8" /> <input type="text" name="q" id="q" autocomplete="off" size="31" /> <input type="submit" name="sa" value="Search" /> </div> </form> <script type="text/javascript" src="//www.google.com/cse/brand?form=cse-search-box&lang=en"></script> <a href="/rss.xml">RSS Feed</a> - <a href="/atom.xml">Atom Feed</a> <br /> <br/> <div id="comicLinks"> Comics I enjoy:<br/> <a href="http://threewordphrase.com/">Three Word Phrase</a>, <a href="http://oglaf.com/">Oglaf</a> (nsfw), <a href="http://www.smbc-comics.com/">SMBC</a>, <a href="http://www.qwantz.com">Dinosaur Comics</a>, <a href="http://www.asofterworld.com">A Softer World</a>, <a href="http://buttersafe.com/">Buttersafe</a>, <a href="http://pbfcomics.com/">Perry Bible Fellowship</a>, <a href="http://questionablecontent.net/">Questionable Content</a>, <a href="http://www.buttercupfestival.com/buttercupfestival.htm">Buttercup Festival</a> </div> <br/> Warning: this comic occasionally contains strong language (which may be unsuitable for children), unusual humor (which may be unsuitable for adults), and advanced mathematics (which may be unsuitable for liberal-arts majors).<br/> <br/> <h4>We did not invent the algorithm. The algorithm consistently finds Jesus. The algorithm killed Jeeves. <br />The algorithm is banned in China. The algorithm is from Jersey. The algorithm constantly finds Jesus.<br />This is not the algorithm. This is close.</h4><br/> <div class="line"></div> <br/> <div id="licenseText"> <!-- <a rel="license" href="http://creativecommons.org/licenses/by-nc/2.5/"><img alt="Creative Commons License" style="border:none" src="http://imgs.xkcd.com/static/somerights20.png" /></a><br/> --> This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc/2.5/">Creative Commons Attribution-NonCommercial 2.5 License</a>. <!-- <rdf:RDF xmlns="http://web.resource.org/cc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns "><Work rdf:about=""><dc:creator>Randall Munroe</dc:creator><dcterms:rightsHolder>Randall Munroe</dcterms:rightsHolder><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:source rdf:resource="http://www.xkcd.com/"/><license rdf:resource="http://creativecommons.org/licenses/by-nc/2.5/" /></Work><License rdf:about="http://creativecommons.org/licenses/by-nc/2.5/"><permits rdf:resource="http://web.resource.org/cc/Reproduction" /><permits rdf:resource="http://web.resource.org/cc/Distribution" /><requires rdf:resource="http://web.resource.org/cc/Notice" /><requires rdf:resource="http://web.resource.org/cc/Attribution" /><prohibits rdf:resource="http://web.resource.org/cc/CommercialUse" /><permits rdf:resource="http://web.resource.org/cc/DerivativeWorks" /></License></rdf:RDF> --> <br/> This means you"re free to copy and share these comics (but not to sell them). <a href="/license.html">More details</a>.<br/> </div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> </div> </div> </body> </html> '
except:
return ""
return ""
def get_next_target(page):
start_link = page.find('<a href=')
if start_link == -1:
return None, 0
start_quote = page.find('"', start_link)
end_quote = page.find('"', start_quote + 1)
url = page[start_quote + 1:end_quote]
return url, end_quote
def union(p,q):
for e in q:
if e not in p:
p.append(e)
def get_all_links(page):
links = []
while True:
url,endpos = get_next_target(page)
if url:
links.append(url)
page = page[endpos:]
else:
break
return links
def crawl_web(seed):
tocrawl = [seed]
crawled = []
while tocrawl:
page = tocrawl.pop()
if page not in crawled:
union(tocrawl, get_all_links(get_page(page)))
crawled.append(page)
return crawled
print crawl_web('http://xkcd.com/353')
A: Do you want to extract urls from a html file? Then this is what you need:
http://youtu.be/MagGZY7wHfU?t=1m54s
Its a great course by the way. Maybe you are interested.
A: To parse html file you should use XML parsing library. See: https://docs.python.org/2/library/xml.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26436961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IOException error when creating a socket in java I am working on a chat client and I have created a registration Jframe where a user gets to register.
when registering, it is supposed to connect to server so that server can check if the userid already exists or not.
when I am creating a new socket it keeps giving me an error.
the code for the socket creation is:
try
{
String serverIP;
int Port = 5000;
Socket socks;
serverIP = String.valueOf(InetAddress.getLocalHost());
socks = new Socket(serverIP, Port);
InputStreamReader streamreader = new InputStreamReader(socks.getInputStream());
reader = new BufferedReader(streamreader);
writer = new PrintWriter(socks.getOutputStream());
writer.println(inputUsername + ":"+inputPassword+":"+inputConfirmPassword+":Register");
writer.flush(); // flushes the buffer
}
catch(IOException io)
{
System.err.println(io.getMessage()+"---connection error 1");
}
catch(SecurityException se)
{
System.err.println(se.getMessage()+"---connection error 2");
}
catch(IllegalArgumentException ae)
{
System.err.println(ae.getMessage()+"---connection error 3");
}
catch(NullPointerException ne)
{
System.err.println(ne.getMessage()+"---connection error 4");
}
when I execute, i get the following error:
Dell/172.16.3.24---connection error 1
this is generated by the IOException catch statement.
Can anyone tell me why this is happening and also how to rectify it?
thanks a lot.
A: IOException definition from javadoc
Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.
While I don't have access to your full stacktrace, the statement Dell/127.16.3.24 let me believe that this is the IP address that was given when creating the socket.
I think you might want to try using InetAddress.getLocalHost().getHostAddress which will return only the IP while InetAddress.getLocalHost() will also return the hostname of the system.
InetAddress.getLocalHost from javadoc
Returns the address of the local host. This is achieved by retrieving
the name of the host from the system, then resolving that name into an
InetAddress.
Note that if you already know that you want local host ip, you can simply pass "127.0.0.1" when creating the socket and it should also fix the problem.
You should also consider adding the flush statement in a finally block to make sure the stream is flushed even if exception occurs. And for sure add a close statement in that block too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27215079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Deploy asp.net to iis i try to publish my asp.net application to iis (v10.0), i get error in logs when running the application, maybe there is a problem with the database connection, but when I run my application on visual studio code 2022 there is no problem,
the logs info is, :
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: C:\inetpub\wwwroot\mytubesite\
warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
Failed to determine the https port for redirect.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 6.0.2 initialized 'ApplicationDBContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer:6.0.2' with options: None
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
An error occurred using the connection to database 'ASP.NETCoreIdentityCustom' on server 'DESKTOP-MA0E5C6'.
this my ApplicationDBContext :
using ASP.NETCoreIdentityCustom.Areas.Identity.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ASP.NETCoreIdentityCustom.Models;
namespace ASP.NETCoreIdentityCustom.Areas.Identity.Data;
public class ApplicationDBContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options)
: base(options)
{
}
public DbSet<Movie> Movie { get; set; }
public DbSet<Comment> Comment { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
builder.ApplyConfiguration(new ApplicationUserEntityConfiguration());
}
}
public class ApplicationUserEntityConfiguration : IEntityTypeConfiguration<ApplicationUser>
{
public void Configure(EntityTypeBuilder<ApplicationUser> builder)
{
builder.Property(u => u.FirstName).HasMaxLength(255);
builder.Property(u => u.LastName).HasMaxLength(255);
}
}
and the program.cs :
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using ASP.NETCoreIdentityCustom.Areas.Identity.Data;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("ApplicationDBContextConnection");builder.Services.AddDbContext<ApplicationDBContext>(options =>
options.UseSqlServer(connectionString));builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDBContext>();
// Add services to the container.
//builder.Services.AddControllers();
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
//app.UseDefaultFiles();
//app.UseStaticFiles();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
//app.MapControllers();
app.MapRazorPages();
app.Run();
and the appsetting.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ApplicationDBContextConnection": "Data Source=DESKTOP-MA0E5C6;Initial Catalog=ASP.NETCoreIdentityCustom;Integrated Security=True",
"MvcMovieContext": "Server=(localdb)\\mssqllocaldb;Database=MvcMovieContext-cb93973d-d78f-4665-bef9-e5d55c116ab1;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71478668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: python script won't run at startup ubuntu I try to run my python scrip at startup but it doesn't work.
Here is my python script(doesn't work):
#!/usr/bin/env python
import paho.mqtt.publish as publish
from datetime import datetime
t = str(datetime.now())
print t
with open("/home/james/mqtt/log.txt", "a+") as f:
f.write("it works " + t + "\n")
Here is my python script(works):
#!/usr/bin/env python
from datetime import datetime
t = str(datetime.now())
print t
with open("/home/james/mqtt/log.txt", "a+") as f:
f.write("it works " + t + "\n")
Here is my rc.local files(also try crontab and setting up service in /ect/init.d):
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
# /bin/mqtt_test.py &
# mosquitto_sub -t "mqtt"
/home/james/mqtt/script.sh
# /etc/mqtt/mqtt_test.py
exit 0
It look like by importing paho.mqtt.publish can make my script stop working, I am new to Linux, I have no idea why. Can someone help me out? Thanks for your help.
Ubuntu 16.04
Let me know if you need more info.
A: I have faced this problem myself. For me the problem was path. I could get it working by using a shell script to launch a python script and launch the shell script from crontab.
Here is my launcher.sh. You may not use sudo if you do not want. home/pi/record_data is the path where my file resides.
cd /
cd home/pi/record_data
sudo python record_video.py
In this case record_video.py is the python file I want to run at startup. In the crontab edit, I added this line below.
@reboot sh /home/pi/record_data/launcher.sh &
Do try this out if it work for you :) Good luck.
I have not got the logging the error into files working yet though.
A: it looks to me like you need to set/change the write permissions of the file before your python scrypt do this:
f.write("it works " + t + "\n")
for you is working because (maybe you are the owner of the file).
typical linux file permission is described as:
do use the chmod with the property flags, so linux has the rights to write the file too, please refer to the ubuntu help :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43580182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: CKEditor inside jQuery Dialog, how do I build it? So, I'm working with CKEditor and jQuery, trying to build a pop-out editor.
Below is what I have coded so far, and I can't seem to get it working the way I want it to.
Basically, click the 'Edit' link, dialog box pops up, with the content to edit loaded into the CKEditor.
Also, not required, but helpful if you can suggest how to do it. I can't seem to find out how to make the save button work in CKEditor (though I think the form will do it).
Thanks in advance for any help.
$(document).ready(function(){
var config = new Array();
config.height = "350px";
config.resize_enabled = false;
config.tabSpaces = 4;
config.toolbarCanCollapse = false;
config.width = "700px";
config.toolbar_Full = [["Save","-","Cut","Copy","Paste","-","Undo","Redo","-","Bold","Italic", "-", "NumberedList","BulletedList","-","Link","Unlink","-","Image","Table"]];
$("a.opener").click(function(){
var editid = $(this).attr("href");
var editwin = \'<form><div id="header"><input type="text"></div><div id="content"><textarea id="content"></textarea></div></form>\';
var $dialog = $("<div>"+editwin+"</div>").dialog({
autoOpen: false,
title: "Editor",
height: 360,
width: 710,
buttons: {
"Ok": function(){
var data = $(this).val();
}
}
});
//$(this).dialog("close");
$.getJSON("ajax/" + editid, function(data){
alert("datagrab");
$dialog.("textarea#content").html(data.content).ckeditor(config);
alert("winset");
$dialog.dialog("open");
});
return false;
});
});
A: After doing some more digging and research, I have hacked together a working solution to my problem. I'm posting here in case anyone else needs to do something like this:
function redirect(url, outsite){if(outsite){location.href = url;}else{location.href = 'http://siteurl.com/' + url;}}
function editdialog(editid){
var editwin = '<div><form action="formprocess/'+editid+'" method="post" class="inform"><div id="editorheader"><label for="coltitle">Column Title: </label><input type="text" name="coltitle" id="coltitle"></div><br><div id="editorcontent"><textarea id="ckeditcolcontent"></textarea></div><input type="hidden" value="edit"></form></div>';
var $dialog = $(editwin).dialog({
autoOpen: false, title: "Editor",
height: 520, width: 640,
closeOnEscape: false, modal: true,
open: function(event, ui){
$(this).parent().children().children(".ui-dialog-titlebar-close").hide();
},
buttons: {
"Save and Close": function(){
var editor = $("#ckeditcolcontent").ckeditorGet();
var coltitle = $("#coltitle").val();
var colcontent = $("#ckeditcolcontent").val();
$.post("formprocess/"+editid, {
coltitle: coltitle,
colcontent: colcontent
}, function(data){
redirect(location.href, 1);
}
);
},
"Cancel": function(){
redirect(location.href, 1);
}
}
});
$.getJSON("ajax/" + editid, function(data){
$("#coltitle").attr("value", data.header);
$("#ckeditcolcontent").val(data.content).ckeditor(config);
$("<div></div>").addClass("ui-widget-overlay").appendTo(document.body).css({width:$(document).width(),height:$(document).height()});
$dialog.dialog("open");
});
}
var config = new Array();
config.height = "280px";
config.resize_enabled = false;
config.tabSpaces = 4;
config.toolbarCanCollapse = false;
config.width = "600px";
config.toolbar_Full = [["Cut","Copy","Paste","-","Undo","Redo","-","Bold","Italic","Underline", "-", "NumberedList","BulletedList","-","Link","Unlink","-","Image","Table"]];
$(document).ready(function(){
$("a.admineditlink").click(function(){
var editid = $(this).attr("href");
editdialog(editid);
return false;
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2434540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: .redirect() from mounted middleware with relative destination fails I want to restrict a certain subtree only to authenticated users. The basic setup is as follows (fat removed):
app.use(express.bodyParser())
.use(express.cookieParser('MY SECRET'))
.use(express.cookieSession())
.use('/admin', isAuthenticatedHandler)
.use('/admin', adminPanelHandler);
Where the handler functions is:
isAuthenticatedHandler = function(req, res, next) {
if (!req.session.username) {
res.redirect('login');
} else {
next();
}
};
The problem is that even though I provide the redirect destination as a relative path 'login', it doesn't lead to <mount_point>/login i.e. /admin/login but to /login which of course throws a 404.
From the expressjs API reference:
This next redirect is relative to the mount point of the application.
For example if you have a blog application mounted at /blog, ideally
it has no knowledge of where it was mounted, so where a redirect of
/admin/post/new would simply give you `http://example.com/admin/post/new`,
the following mount-relative redirect would give you
`http://example.com/blog/admin/post/new`:
res.redirect('admin/post/new');
Am I misreading this?
A: What are you trying to achieve? Why not just redirect to '/admin/login' ? And the mount point they are talking about is the place where your Express app is located, not necessarily the current URL. So /blog might be setup on your server to be the root of your app while / might be a totally different app. At least that's the way I read this.
A: The issue here is that while you are using your middleware off of /admin, your app itself is not mounted at /admin. Your app is still off of the root, and your configuration simply says to only use your isAuthenticatedHandler middleware if the request comes in off the /admin path.
I whipped together this gist. Notice how it uses 2 Express applications, one mounted inside the other (line 23 pulls this off). That is an example of mounting the application at a different point rather than just putting a given middleware at a given point. As presently written, that example will give you an endless redirect, since the isAuthenticatedHandler fires for everything off of / in the child application, which equates to /admin overall. Using 2 separate applications might introduce other issues you're not looking to deal with, and I only include the example to show what Express means when it talks about mounting entire applications.
For your present question, you'll either need to follow what Yashua is saying and redirect to /admin/login or mount your admin interface as a separate Express application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21104154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to print asterisk triangles side-by-side in python? I am trying to print 4 star triangle side-by-side using nested for-loops in python. I included the code I am using now that prints the triangles vertically, but I do not know how to print them horizontally.
n = 0
print ("Pattern A")
for x in range (0,11):
n = n + 1
for a in range (0, n-1):
print ('*', end = '')
print()
print ('')
print ("Pattern B")
for b in range (0,11):
n = n - 1
for d in range (0, n+1):
print ('*', end = '')
print()
print ('')
enter image description here
A: maximum = 10
a, b, c, d = 1, maximum, maximum, 1
while a <= maximum:
print('*'*a + ' '*(maximum-a) + ' '*2 + '*'*b + ' '*(maximum-b) + ' '*2 + ' '*(maximum-c) + '*'*c + ' '*2 + '*'*d + ' '*(maximum-d))
a += 1
d += 1
b -= 1
c -= 1
A: Thanks to @AzBakuFarid the main idea is to print every line of shapes from the top to the last together. @AzBakuFarid code had a very little mistake that you can see the corrected one below :
maximum = 10
a, b, c, d = 1, maximum, maximum, 1
while a <= maximum:
print('*'*a + ' '*(maximum-a) + ' '*2 + '*'*b + ' '*(maximum-b) + ' '*2 + ' '*(maximum-c) + '*'*c + ' '*2 + ' '*(maximum-d) + '*'*d)
a += 1
d += 1
b -= 1
c -= 1
As u wanted to be with for-loops I came up with this :
longest = int(input())
asterisk_a = 1
spaces_a = longest - 1
asterisk_b = longest
spaces_b = 0
asterisk_c = longest
spaces_c = 0
asterisk_d = 1
spaces_d = longest - 1
for i in range(0,longest):
print(asterisk_a * '*' + spaces_a * ' ' + ' ' + asterisk_b * '*' + spaces_b * ' ' + ' ' + spaces_c * ' ' + asterisk_c * '*' + ' ' + spaces_d * ' ' + asterisk_d * '*')
asterisk_a += 1
spaces_a -= 1
asterisk_b -= 1
spaces_b += 1
asterisk_c -= 1
spaces_c += 1
asterisk_d += 1
spaces_d -= 1
In the first line you should give the number of asterisks in the longest case.
I tried to use meaningful variable names for better understanding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60748012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
} |
Q: setTimeout("window.close()", 100) not working in Firefox I am a learner on HTML, PHP, Javascript.
I am currently working on a barcode scanning system. The steps are simple, scan in an order number, the system(form) will then generate another sequence number and print it out along with the scanned order number right away so that the warehouse worker can stick the print out on the scanned parcel.
Same steps keep on until the whole log of cargo done.
We have created a simplified program, and test it. If it works then we can follow the same logic to create the actual form.
Up to this point, we have successfully scan in the bar code, the form then jump into another form by using windows.open. Inside this pop up windows, it is a PDF document which's created by FPDF. By enable FIREFOX silence print feature. The pop up form can printout the label automatically. Everything good except we cannot close the popup windows. We have already drilled out every possibilities and search thru the net...couldn't find anything.
We did turn on the Firefox option dom.allow_scripts_to_close_windows to TRUE
first form
<?PHP
session_start();
if (isset($_POST['submit'])){
$_SESSION['CUSTNO']=$_REQUEST['CUSTNO'];
$_SESSION['ORDERNO']=$_REQUEST['ORDERNO'] ;
//header('Location:TESTwai.php');
echo "myFunction();";
}
?>
<html>
<body>
<form action="" method="post" name="form1"><br>
<input type="text" id="CUSTNO" name="CUSTNO" style="font-size: 24pt"/>
<input type="text" id="ORDERNO" name="ORDERNO" style="font-size: 24pt"/>
<br>
<input name="submit" type="submit" value="SUBMIT" onclick="return myFunction()"></form>
</body>
</html>
<script>
function myFunction() {
//window.open("ex.php","", "width=200, height=100");
window.open("ex.php","", "width=1000, height=1000");
myWindow.close(); // Closes the new window
}
</script>
Second pop up window form
I have put the setTimeout, close.window inside or out PHP script and still no luck.
<?php
require('pdf_js.php');
class PDF_AutoPrint extends PDF_JavaScript
{
function AutoPrint($dialog=false)
{
//Open the print dialog or start printing immediately on the standard printer
//$param=($dialog ? 'true' : 'false');
//echo $param;
//$script="print($param);";
$script="print(false);";
$this->IncludeJS($script);
}
}
$pdf=new PDF_AutoPrint();
$pdf->AddPage();
$pdf->SetFont('Arial','',20);
$pdf->Text(90, 50, 'Print me!');
//Open the print dialog
$pdf->AutoPrint('false');
ob_end_clean();
$pdf->Output();
?>
<script>
setTimeout("window.close()", 100);
</script>
Please ignore those customer, orderno. They are just dummy input...
The actual testing is just
1) press the submit button
2) pop up windows
3) auto print the label out without any system prompt
4) close the pop up windows and get back to the first form (stuck here)
A: It is not a issue with setTimeout method. This is the issue with window.close() . It is not a good practice to close the window within itself.Still if you its very necessary you can try the below code:
window.open('','_parent',''); //fool the browser that it was opened with a script
window.close();
You can put this in a function and call it use in setTimeout .Helpful link
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30208714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: reading and deleting lines in python I am trying to read all the lines in a specific file, and it prints the number of the line as an index.
What I am trying to do is to delete the line by inputting the number of the line by the user.
As far as it is now, it prints all the lines with the number of that line, but when I enter the number of the line to be deleted, it's not deleted.
This is the code of the delete function:
def deleteorders ():
index = 0
fh = open ('orders.txt', 'r')
lines = fh.readlines()
for line in lines:
lines = fh.readlines()
index = index+1
print (str(index) + ' ' + line)
try:
indexinp = int(input('Enter the number of the order to be deleted, or "B" to go back: '))
if indexinp == 'B':
return
else:
del line[indexinp]
print (line)
fh = open ('orders.txt', 'w')
fh.writelines(line)
fh.close()
except:
print ('The entered number is not in the range')
return
A: This should work (you'll need to add the error handling back in):
lines = enumerate(open('orders.txt'))
for i, line in lines:
print i, line
i = int(input(">"))
open('orders.txt', 'w').write(''.join((v for k, v in lines if k != i)))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47891517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Make two divs share one scrollbar Here is my code:
<div class="mycontent">
<div class="textarea" id="ingId" style="position:relative;">
<div id="idComm" style="position: absolute; z-index: 100; width: 450px; height: 151px; right: 18px; top: 1px;">
</div>
</div>
</div>
How to make them share the same scrollbar? I tried this
But it didn't work, since in the first div I have tinymce.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11644179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Formatting input value and restrictions for user (JavaScript) How I could create an <input type="text" /> with following restrictions for the User and formatting extensions, namely using JavaScript or jQuery?
*
*The User can use only numeric chars. Nothing else.
*The User can't delete the dot. Never. Is it possible? If it isn't and the user will remove the dot, how to give the dot back automatically on losing focus?
*On blur (lose focus), if the decimal places are empty, script will fill it with zeros (↓).
*I need this pattern for view: X XXX.XX
(toFixed(2) I can use for two decimal places, but I don't know way to separate string according pattern).
Certainly you've noticed, that the text field should be the price. The script should operate on multiple input fields with class "pr-dec".
<input type="text" class="pr-dec" size="8" value="0.00" />
Thanks a lot for any help, your time and suggestions.
jsfiddle can facilitate it.
A: Google Translate says he said:
"Matus know the těchhle point I stopped, I'm a beginner and do not know what I stand on it all night"
Sounds like you need to read up on some JavaScript and jQuery tutorials. I began with something like this: jQuery for Absolute Beginners: The Complete Series
Really hope this helps.
A: You have a number of problems you need to solve.
Break them down into smaller chunks and tackle it from there.
Only numbers
You could watch the field (check out .on) for a change and then delete any character that's not part of the set [\d] or [0-9], but that could get messy.
A better idea might be to watch for a keydown event and only allow the keys that represent numbers.
The Dot
Trying to dynamically stop the user from deleting the dot is messy, so let's just focus on adding it back in when the field is blurred.
That's pretty easy, right? Just check for a . and if there isn't one, append ".00" to the end of the field.
Decimal Places
This is really the same problem as above. You can use .indexOf('.') to determine if the dot is present, and if it is, see if there are digits after it. If not, append "00" if so, make sure there's 2 digits, and append a "0" if there's only 1.
String Pattern
This could really be solved any number of ways, but you can reuse your search for the decimal place from above to split the string into "Full Dollar" and "Decimal" parts.
Then you can use simple counting on the "Full Dollar" part to add spaces. Check out the Javascript split and splice functions to insert characters at various string indexes.
Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22432888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Is it necessary to create 151 connections to the server when displaying 150 images in a RecyclerView, stored in Firebase Storage's 'Images' folder? Suppose you have 150 images stored in the images folder within your Firebase Storage. Each image should have a title, which will be inserted during the uploading process. Now, let's say you want to display all of these images in a RecyclerView. In this scenario, you would need to create 151 separate connections to the server instead of just one. This may seem counterintuitive, so allow me to explain.
The first connection is to retrieve all the images using the following line of code: FirebaseStorage.getInstance().getReference().child("Images/").listAll(). This will return a list of all the images in the folder.
For each image, you would need to make another connection to the server to retrieve the metadata for that image. This means that for every single image, you would need to make a separate call to the server, resulting in a total of 151 connections.
Here is a preview of the code for this scenario:
FirebaseStorage.getInstance().getReference().child("Images/").listAll().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
for (int i = 0; i < 150; i++) {
task.getResult().getItems().get(0).getMetadata().addOnCompleteListener(task1 -> {
if (task1.isSuccessful()) {
task1.getResult().getCustomMetadata("title"); //Finally I got the image title that stored inside image, it is cumbersome process.
} else {
//Handle error
}
});
}
} else {
//Handle error
}
});
However, it's possible that I may be missing something. Is this really the way it works, or is there a better solution? I don't want to name the image directly as the file name because I've tried that before and found that the length is not enough.
I would greatly appreciate any suggestions or alternative solutions to this problem. Thank you in advance!
Additionally, I would like to express my gratitude to OpenAI's GPT-3 for helping me write this clear and concise question.
A: First of all, FirebaseStorage.getInstance() is a singleton, which will always create a single instance.
Furthermore, while Mauricio Gracia Gutierrez's will work, please see below a solution that uses Tasks#whenAllSuccess(Collection> tasks):
StorageReference imagesRef = FirebaseStorage.getInstance().getReference().child("Images/");
imagesRef.listAll().addOnCompleteListener(new OnCompleteListener<ListResult>() {
@Override
public void onComplete(@NonNull Task<ListResult> task) {
if (task.isSuccessful()) {
List<StorageReference> storageReferenceList = task.getResult().getItems();
List<Task<StorageMetadata>> tasks = new ArrayList<>();
storageReferenceList.forEach(item ->
tasks.add(item.getMetadata())
);
Tasks.whenAllSuccess(tasks).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
@Override
public void onSuccess(List<Object> objects) {
for (Object object : objects) {
String title = ((StorageMetadata) object).getCustomMetadata("title");
Log.d("TAG", title);
}
}
});
} else {
Log.d(TAG, task.getException().getMessage()); //Never ignore potential errors!
}
}
});
In this way, you'll wait until you have a List full of titles.
A: You can create a backend API method that returns the list of titles for you in a single call
I know now that your code was demostration purposes only but....
*
*your code says task.getResult().getItems().get(0) meaning that only the first item is being used 150 times
*Calling task.getResult().getItems() inside the for, means that you are calling something that only needs to be called once 150 times
*Using harcoded 150 instead of the items.length is not a good idea
When you see that your code cumbersome or hard to read, follow the "Single Responsability" to split it into simpler methods.
In the code below I'm using type "Item" because I dont now the name of the type returned by task.getResult().getItems()
void getAllImagesMetadata() {
FirebaseStorage.getInstance().getReference().child("Images/").listAll().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Item []items = task.getResult().getItems() ;
for (int i = 0; i < items.length ; i++) {
title[i] = getTitle(items[i] ;
}
} else {
//Handle error
}
// Make sure the connection to get list of all items is closed here
}
string getTitle(Item item) {
string title ;
item.getMetadata().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
title = task.getResult().getCustomMetadata("title");
} else {
//Handle error
}
// Make sure the connection to get the metada is closed here
return title ;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75344799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to store the large amount data in windows phone 8.1? in android for storing data we are using array list,hash map...etc.
in windows how we save the large amount of data? what about collections in windows phone development. Please any one explain me how to store the data in windows phone 8.1 development.
A: Here you have the main type of collections available in C#: https://msdn.microsoft.com/en-us/library/ybcx56wz.aspx
All of them can be used in Windows Phone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31202806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Standard ml function in datatype problem I have to create a function about peano numbers defined as the following datatype:
datatype 'a peano = P of ('a -> 'a) * 'a -> 'a
val zero = P(fn (f, x) => x)
The function that I have to implement finds the succesive peano number of the peano parameter P(p). This is what I have written:
fun suc (P(p)) = case P(p) of P(fn(f,x)=>x) => P(fn(f,x)=>f(x));
The problem is that i get these errors:
stdIn:4.33-4.36 Error: syntax error: deleting FN LPAREN
stdIn:4.43 Error: syntax error found at RPAREN
I don't know what Im doing wrong. Please help!
A: There are a number of problems in this code. The one the compiler is whining about is that you have a function definition
fn (f,x) => x
on the left-hand side of a case arm, where only patterns are permitted.
Some other problems:
*
*Redundant parentheses make the code hard to read (advice is available on removing them).
*Your case expression is redundant; in the function definition
fun suc (P p) = ...
it should be possible just to compute with p without any more case analysis.
*Since P carries a function, you will probably have an easier time if you write
fun suc (P f) = ...
and make sure that in the result, f is applied to a pair (as required by the datatype declarations).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2207154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: VS Code Node.js - Run and Debug opens automatically when encountering a break point whenever I debug Node.JS in VS Code and a breakpoint is encountered, the "Run and Debug" window open automatically (as if I pressed Ctrl+Shift+D). It is very annoying, how can I disable it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72916763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iframe won't show up unless domain has www I have a site with an iframe. The iframe shows up if the address url is www.mysite.com, but not if I use mysite.com. The iframe location is www.mysite.com/thepage.html
The JS error I get is.
Load denied by X-Frame-Options: the site page does not permit
cross-origin framing.
On my server (webfaction) I have the site setup to recognize both with and without the www -- a control panel item on webfaction.
How do I get mysite.com to show the iframe?
A: I'm afraid the webmaster of the domain has set XSS protection. So to load a XSS protected site with javascript is simply can't be done.
Update: XSS only allow access to data if both frames (iframe/parent frame) they are on the same protocol, have the exact domain name (mysite.com == mysite.com, but www.mysite.com != mysite.com they are considered different) and both of frames running on the same port. But though, you can ive it a try by placing document.domain on all pages so it allows communication even on different subdomains.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24093761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to store value of pointer in a recursive function? Let say now I would like to write a function that search a certain node in a linked list recursively. When I successfully reached the targeted node, this function will return the ID and another information of it by reference, where its ID will be stored by struct:
struct P{
int ID;
int some_info;
P* next_node;
}
The function will be something like
void search(int targeted_ID, P*& current_node){
P* c = current_node;
if(c->ID == targeted_ID){
current_node = c;
}
if(c->next_node == nullptr){
return;
}
else{
search(ID, current_node->next_node);
}
}
And the output statement will be something like
cout << "The targeted node have ID= " << current_node->ID << "with" << current_node->some_info << endl;
However, this function will recursively called by itself until all node has been reached and checked, and the value of pointer current_node will constantly changed throughout the process.
The main question is how can I remain the value of it unchanged when doing recursion.
p.s. There are constraints that:
*
*Cannot add any global variable
*Cannot use any static variable
*Cannot add any parameters in the void function
*Cannot use array
*Cannot changed the struct's content
*The output statement cannot be changed
*Cannot use goto
A: I just coded a bit, as @Ted Lyngmo pointed out, you have to return a value, so you can't use a void-function.
Here is the code:
#include <iostream>
struct P {
int ID;
int some_info;
P* next_node;
};
P* newNode(int ID, int some_info) {
P* temp = new (std::nothrow) P;
if (temp == nullptr){
return nullptr;
}
else {
temp->ID = ID;
temp->some_info = some_info;
temp->next_node = nullptr;
return temp;
}
}
P* search(int targeted_ID, P* current_node) {
// check if current node is valid
if (current_node == nullptr) {
return nullptr;
}
// check for ID of current node
else if (current_node->ID == targeted_ID) {
return current_node;
}
// this node isn't the desired one --> go to nex node
else {
return search(targeted_ID, current_node->next_node);
}
}
void freeMem(P* list) {
P* tmp = nullptr;
while (list != nullptr) {
tmp = list->next_node;
delete list;
list = tmp;
}
}
int main()
{
P* list = nullptr;
P* tmp = nullptr;
P* lastNode = nullptr;
// populate list
for (int i = 0; i < 10; ++i) {
tmp = newNode(i, i * 10);
if (tmp == nullptr) {
// error occured
// free memory
freeMem(list);
list = nullptr;
return -1;
}
if (list == nullptr) {
// first node
list = tmp;
lastNode = list;
}
else {
lastNode->next_node = tmp;
lastNode = tmp;
}
}
tmp = nullptr;
lastNode = nullptr;
int ID_to_find = 1;
P* node = search(ID_to_find, list);
if (node == nullptr) {
// node not found ...
std::cout << "node not found" << std::endl;
}
else {
// node found
std::cout << "node found at: " << node << std::endl;
}
freeMem(list);
list = nullptr;
return 0;
}
This code works, but it is not really C++, it is more like C. If you want to write C++-Code use STL-Containers and don't write your own list, because it will be much more readable and the chance to have a bug is much smaller. Also consider to use exceptions instead of (std::nothrow).
A: Recursive:
void search(int targeted_ID, P*& current_node) {
if(current_node && current_node->ID != targeted_ID) {
current_node = current_node->next_node;
search(targeted_ID, current_node);
}
}
But I suggest a non-recursive version to not get stack overflow when searching a long linked list:
void search(int targeted_ID, P*& current_node) {
while(current_node && current_node->ID != targeted_ID)
current_node = current_node->next_node;
}
Demo
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67554745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Powershell: Unquoting arguments when invoking an external command Consider the following cmd.exe batch script:
testpar.cmd
@echo [%1] [%2]
If we call it it in Powershell, these results are rather obvious:
PS> .\testpar.cmd arg1 arg2
[arg1] [arg2]
PS> .\testpar.cmd "arg1 arg2"
["arg1 arg2"] []
But, when passing a variable:
PS> $alist= "arg1 arg2"
PS> .\testpar.cmd $alist
["arg1 arg2"] []
It seems that $alist is passed with quotes.
One solution:
PS> $alist= "`"arg1`" `"arg2`""
PS> .\testpar.cmd $alist
["arg1"] ["arg2"]
which identifies arguments, but without stripping quotes.
Another possibility:
PS> Invoke-Expression (".\testpar.cmd " + $alist)
[arg1] [arg2]
This works, but is very convoluted. Any better way?
In particular is there a way to unquote a string variable?
A: I found a similar question here
What you can do is use a comma: $alist = "a,b"
The comma will be seen as a paramater seperator:
PS D:\temp> $arglist = "a,b"
PS D:\temp> .\testpar.cmd $arglist
[a] [b]
You can also use an array to pass the arguments:
PS D:\temp> $arglist = @("a", "c")
PS D:\temp> .\testpar.cmd $arglist
[a] [c]
A: The most convenient way to me to pass $alist is:
PS> .\testpar.cmd $alist.Split()
[arg1] [arg2]
In this way I don't need to change the way I build $alist.
Besides Split() works well also for quoted long arguments:
PS> $alist= @"
>> "long arg1" "long arg2"
>> "@
This is:
PS> echo $alist
"long arg1" "long arg2"
and gives:
PS> .\testpar.cmd $alist.Split()
["long arg1"] ["long arg2"]
A: In general, I would recommend using an array to build up a list of arguments, instead of mashing them all together into a single string:
$alist = @('long arg1', 'long arg2')
.\testpar.cmd $alist
If you need to pass more complicated arguments, you may find this answer useful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26357587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: split(regexp_replace ) Like Function In Presto : 331 Is there any way to split values based on consecutive 0's in presto.Minimum 6 digits should be there in first split, if digit count is less than 6 than need to consider some 0's as digit then split if digit count is >= 6 then just need to split in 2 groups.
below query is working as expected in Hive.But I am not able to do the same using presto.
select low as orginal_Value,
split(regexp_replace(low,'(\\d{6,}?)(0+)$','$1|$2'),'\\|') Output_Value from test;
Presto Query:
presto> SELECT regexp_split('1234567890000', '(\d{6,}?)(0+)$') as output;
output
[1234567890000]
(1 row)
A: It worked Now.
select split(regexp_replace('1234567890000','(\d{6,}?)(0+)$','$1|$2'), '|') as output;
enter code here
output
-------------------
[123456789, 0000]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71586778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why global variable inside jQuery each() function is breaking up my rollover effect? I'm trying to accomplish a rollover effect through jQuery in which when I hover over a black & white image, it gets replaced by the colored one & when I move out of the image, the original B&W image appears again. The code I'm using is :
var origImgSrc;
$('#gallery img').each(function() {
origImgSrc = $(this).attr('src');
var imgExt = /(\.\w{3,4}$)/;
var newImg = origImgSrc.replace(imgExt, '_h$1');
$(this).hover(function() {
$(this).attr('src', newImg);
}, function() {
$(this).attr('src', origImgSrc);
}); // end hover
}); // end each
I have two copies of each image(one B&W, one colored). For example, green.jpg (B&W), green_h.jpg (colored). A regular expression replaces the name of image & whole code is written directly inside $(document).ready() method.
The code somewhat works, when I hover over any of the image, it gets replaced by its corresponding colored one but on mouseout, irrespective of the image, the original image now gets replaced by the last image in the markup, the actual corresponding B&W image doesn't come back.
I came down to a working solution i.e. instead of declaring var origImgSrc; variable outside the each function, I should define it inside the each function. The rollover effect now works perfectly but I want to find what exactly goes wrong here & the possible reason I came across for this behaviour is Asynchronous flow of JS or the Asynchronicity. Completely read about it & understood it but still I can't relate this problem to it.
Can anybody please explain in any way what's going wrong here? Whether by taking the help of JS runtime's Call Stack, WebAPIs, Callback Queue, etc. I understand these concepts but in context of quite easy examples, just can't relate in this case.
A: Because when hover callback runs it use global variable origImgSrc.
Variable origImgSrc rewrites every iteration and equals last image src after all.
Just put origImgSrc into your each.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35361846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: sqlite3 autoincrement - am I missing something? I want to create unique order numbers for each day. So ideally, in PostgreSQL for instance, I could create a sequence and read it back for these unique numbers, because the readback both gets me the new number and is atomic. Then at close of day, I'd reset the sequence.
In sqlite3, however, I only see an autoincrement for the integer field type. So say I set up a table with an autoincrement field, and insert a record to get the new number (seems like an awfully inefficient way to do it, but anyway...) When I go to read the max back, who is to say that another task hasn't gone in there and inserted ANOTHER record, thereby causing me to read back a miss, with my number one too far advanced (and a duplicate of what the other task reads back.)
Conceptually, I require:
*
*fast lock with wait for other tasks
*increment number
*retrieve number
*unlock
...I just don't see how to do that with sqlite3. Can anyone enlighten me?
A: In SQLite, autoincrementing fields are intended to be used as actual primary keys for their records.
You should just it as the ID for your orders table.
If you really want to have an atomic counter independent of corresponding table records, use a table with a single record.
ACID is ensured with transactions:
BEGIN;
SELECT number FROM MyTable;
UPDATE MyTable SET number = ? + 1;
COMMIT;
A: ok, looks like sqlite either doesn't have what I need, or I am missing it. Here's what I came up with:
*
*declare zorder as integer primary key autoincrement, zuid integer in orders table
this means every new row gets an ascending number, starting with 1
*generate a random number:
rnd = int(random.random() * 1000000) # unseeded python uses system time
*create new order (just the SQL for simplicity):
'INSERT INTO orders (zuid) VALUES ('+str(rnd)+')'
*find that exact order number using the random number:
'SELECT zorder FROM orders WHERE zuid = '+str(rnd)
*pack away that number as the new order number (newordernum)
*clobber the random number to reduce collision risks
'UPDATE orders SET zuid = 0 WHERE zorder = '+str(newordernum)
...and now I have a unique new order, I know what the correct order number is, the risk of a read collision is reduced to negligible, and I can prepare that order without concern that I'm trampling on another newly created order.
Just goes to show you why DB authors implement sequences, lol.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18320422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What would be a globally accepted regular expression to match e-mail addresses I have seen many examples, with many 'no, you missed something' comments. What is the right way to match an e-mail address?
For Sanity sake, only fully-qualified domain names, no @localhost allowed. (or, both ways)
Subdomains must be allowed ([email protected])
A: It is impossible to do so in a pure regex. Regexen cannot match nested parentheses, which the full RFC spec requires. (The latest RFC on this matter is RFC5322, only released a few months ago.)
Full validation of email addresses requires something along the lines of a CFG, and there are a few more things to be wary of; for example, email addresses can contain '\0', the null character... so you can't use any of C's normal string functions on them.
I actually feel a bit weird answering a question with a link to something I've written, but as it so happens, I have one I prepared earlier: a short and (as far as I can tell) fully-compliant validator, in Haskell; you can see the source code here. I imagine the code could be easily ported to any similar parsing library (perhaps C++’s Boost.Spirit), or just as easily hooked into from another language (Haskell has a very simple way for C to use Haskell code, and everything can use C bindings...)
There are also extensive test cases in the source code (I didn't export them from the module), which are due to Dominic Sayers, who has his own version of an RFC-compliant parser in PHP. (Several of the tests fail, but they are more strict than RFC5322 specifies, so I'm fine with that at the moment.)
A: That was asked here a couple of weeks ago. What it comes down to is, there are many legal addresses that an easy regex won't match. It takes a truly insane regex to match the majority of legal addresses. And even then, a syntactically legal address doesn't guarantee the existence of an account behind it - take [email protected], for example.
A: Not to mention that Chinese/Arabic domain names are to be allowed in the near future. Everyone has to change the email regex used, because those characters are surely not to be covered by [a-z]/i nor \w. They will all fail.
After all, best way to validate the email address is still to actually send an email to the address in question to validate the address. If the email address is part of user authentication (register/login/etc), then you can perfectly combine it with the user activation system. I.e. send an email with a link with an unique activation key to the specified email address and only allow login when the user has activated the newly created account using the link in the email.
If the purpose of the regex is just to quickly inform the user in the UI that the specified email address doesn't look like in the right format, best is still to check if it matches basically the following regex:
([^.@]+)(\\.[^.@]+)*@([^.@]+\\.)+([^.@]+)
Simple as that. Why on earth would you care about the characters used in the name and domain?
A: Unfortunately, it's not a regex, but... The right way to validate an email address is to send it a message and see if the user replies.
If you really, really want to verify that an address is syntactically-valid/RFC-compliant, then a regex is still unlikely to be the right tool for the job. You could most likely create a parser in fewer characters than the length of a regex with a similar level of RFC compliance and the parser would probably run faster to boot.
Even with a perfect test of RFC compliance, [email protected] is perfectly-formed and refers to an existing domain, so you're not going to know whether the address you're given is actually valid or not unless you send it a message.
A: General advice is don't
It's probably worth a simple check that they entered "[email protected]" just to check they put the email in the right box.
Beyond that most of the official regex allow for so many obscure cases that they have a huge false positive rate (they will allow technically legal but extremely unlikely
entries)
A: From http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html :
The grammar described in RFC 822 is suprisingly complex. Implementing validation with regular expressions somewhat pushes the limits of what it is sensible to do with regular expressions, although Perl copes well:
(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:
\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(
?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[
\t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\0
31]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\
](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+
(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:
(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)
?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\
r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[
\t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)
?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t]
)*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[
\t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*
)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)
*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+
|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r
\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:
\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t
]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031
]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](
?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?
:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?
:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?
:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?
[ \t]))*"(?:(?:\r\n)?[ \t])*)*:(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\]
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|
\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>
@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"
(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t]
)*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?
:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[
\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-
\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(
?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;
:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([
^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"
.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\
]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\
[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\
r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\]
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]
|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \0
00-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\
.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,
;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?
:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*
(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".
\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[
^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]
]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)(?:,\s*(
?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(
?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[
\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t
])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t
])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?
:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|
\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:
[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\
]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)
?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["
()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)
?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>
@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[
\t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,
;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t]
)*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?
(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".
\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:
\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[
"()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])
*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])
+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\
.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(
?:\r\n)?[ \t])*))*)?;\s*)
A: This regular expression complies with the grammar described in RFC 2822, it's very long, but the grammar described in the RFC is complex...
A: If you're using Perl, I believe the Regex::Common module would be the one you want to use, and in particular, Regex::Common::Email::Address.
A: I had to recently build some RSS feeds, and part of that included going over the Xml schema, including the items for Webmaster and ManagingEditor, both of which are defined as an e-mail address matching this pattern:
([a-zA-Z0-9_\-])([a-zA-Z0-9_\-\.]*)@(\[((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}|((([a-zA-Z0-9\-]+)\.)+))([a-zA-Z]{2,}|(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/210945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: CSS-only masonry layout I need to implement a masonry layout. However, for a number of reasons I don't want to use JavaScript to do it.
Parameters:
*
*All elements have the same width
*Elements have a height that cannot be calculated server side (an image plus various amounts of text)
*I can live with a fixed number of columns if I have to
there is a trivial solution to this that works in modern browsers, the column-count property.
The problem with that solution is that elements are ordered in columns:
While I need the elements to be ordered in rows, at least approximately:
Approaches I've tried that don't work:
*
*Making items display: inline-block: wastes vertical space.
*Making items float: left: lol, no.
Now I could change the server side rendering and reorder the items dividing the number of items by the number of columns, but that's complicated, error-prone (based on how browsers decide to split the item list into columns), so I'd like to avoid it if possible.
Is there some flexbox magic that makes this possible?
A: I find This solution, It is most probably compatible with all browsers.
Note: if anyone finds any error or browser support issues. please update this answer Or comments
CSS Profpery Support reference:
column-count, gap, fill break-inside, page-break-inside
Note: page-break-inside This property has been replaced by the break-inside property.
.container {
-moz-column-count: 1;
column-count: 1;
-moz-column-gap: 20px;
column-gap: 20px;
-moz-column-fill: balance;
column-fill: balance;
margin: 20px auto 0;
padding: 2rem;
}
.container .item {
display: inline-block;
margin: 0 0 20px;
page-break-inside: avoid;
-moz-column-break-inside: avoid;
break-inside: avoid;
width: 100%;
}
.container .item img {
width: 100%;
height: auto;
}
@media (min-width: 600px) {
.container {
-moz-column-count: 2;
column-count: 2;
}
}
@media (min-width: 900px) {
.container {
-moz-column-count: 3;
column-count: 3;
}
}
@media (min-width: 1200px) {
.container {
-moz-column-count: 4;
column-count: 4;
}
}
CSS-Only Masonry Layout
<div class="container">
<div class="item"><img src="https://placeimg.com/600/400/animals" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/600/arch" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/300/nature" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/450/people" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/350/tech" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/800/animals/grayscale" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/650/arch/sepia" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/300/nature/grayscale" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/400/people/sepia" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/600/tech/grayscale" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/200/animals/sepia" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/700/arch/grayscale" alt=""></div>
</div>
A: Finally a CSS-only solution to easily create masonry layout but we need to be patient since there is no support for it for now.
This feature was introduced in the CSS Grid Layout Module Level 3
This module introduces masonry layout as an additional layout mode for CSS Grid containers.
Then
Masonry layout is supported for grid containers by specifying the value masonry for one of its axes. This axis is called the masonry axis, and the other axis is called the grid axis.
A basic example would be:
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
grid-template-rows: masonry; /* this will do the magic */
grid-gap: 10px;
}
img {
width: 100%;
}
<div class="container">
<img src="https://picsum.photos/id/1/200/300">
<img src="https://picsum.photos/id/17/200/400">
<img src="https://picsum.photos/id/18/200/100">
<img src="https://picsum.photos/id/107/200/200">
<img src="https://picsum.photos/id/1069/200/600">
<img src="https://picsum.photos/id/12/200/200">
<img src="https://picsum.photos/id/130/200/100">
<img src="https://picsum.photos/id/203/200/100">
<img src="https://picsum.photos/id/109/200/200">
<img src="https://picsum.photos/id/11/200/100">
</div>
This will produce the following result on Firefox if you enable the feature like explained here: https://caniuse.com/?search=masonry
*
*open Firefox and write about:config in the url bar
*do a search using masonry
*you will get one flag, make it true
If we reduce the screen screen, the reponsive part is perfect!
A: 2021 Update
CSS Grid Layout Level 3 includes a masonry feature.
Code will look like this:
grid-template-rows: masonry
grid-template-columns: masonry
As of March 2021, it's only available in Firefox (after activating the flag).
*
*https://drafts.csswg.org/css-grid-3/#masonry-layout
*https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Masonry_Layout
end update; original answer below
Flexbox
A dynamic masonry layout is not possible with flexbox, at least not in a clean and efficient way.
Flexbox is a one-dimensional layout system. This means it can align items along horizontal OR vertical lines. A flex item is confined to its row or column.
A true grid system is two-dimensional, meaning it can align items along horizontal AND vertical lines. Content items can span across rows and columns simultaneously, which flex items cannot do.
This is why flexbox has a limited capacity for building grids. It's also a reason why the W3C has developed another CSS3 technology, Grid Layout.
row wrap
In a flex container with flex-flow: row wrap, flex items must wrap to new rows.
This means that a flex item cannot wrap under another item in the same row.
Notice above how div #3 wraps below div #1, creating a new row. It cannot wrap beneath div #2.
As a result, when items aren't the tallest in the row, white space remains, creating unsightly gaps.
column wrap
If you switch to flex-flow: column wrap, a grid-like layout is more attainable. However, a column-direction container has four potential problems right off the bat:
*
*Flex items flow vertically, not horizontally (like you need in this case).
*The container expands horizontally, not vertically (like the Pinterest layout).
*It requires the container to have a fixed height, so the items know where to wrap.
*As of this writing, it has a deficiency in all major browsers where the container doesn't expand to accommodate additional columns.
As a result, a column-direction container is not an option in this case, and in many other cases.
CSS Grid with item dimensions undefined
Grid Layout would be a perfect solution to your problem if the various heights of the content items could be pre-determined. All other requirements are well within Grid's capacity.
The width and height of grid items must be known in order to close gaps with surrounding items.
So Grid, which is the best CSS has to offer for building a horizontally-flowing masonry layout, falls short in this case.
In fact, until a CSS technology arrives with the ability to automatically close the gaps, CSS in general has no solution. Something like this would probably require reflowing the document, so I'm not sure how useful or efficient it would be.
You'll need a script.
JavaScript solutions tend to use absolute positioning, which removes content items from the document flow in order to re-arrange them with no gaps. Here are two examples:
*
*Desandro Masonry
Masonry is a JavaScript grid layout library. It
works by placing elements in optimal position based on available
vertical space, sort of like a mason fitting stones in a wall.
source: http://masonry.desandro.com/
*
*How to Build a Site that Works Like Pinterest
[Pinterest] really is a cool site, but what I find interesting is how these pinboards are laid out... So the purpose of this tutorial is to re-create this responsive block effect ourselves...
source: https://benholland.me/javascript/2012/02/20/how-to-build-a-site-that-works-like-pinterest.html
CSS Grid with item dimensions defined
For layouts where the width and height of content items are known, here's a horizontally-flowing masonry layout in pure CSS:
grid-container {
display: grid; /* 1 */
grid-auto-rows: 50px; /* 2 */
grid-gap: 10px; /* 3 */
grid-template-columns: repeat(auto-fill, minmax(30%, 1fr)); /* 4 */
}
[short] {
grid-row: span 1; /* 5 */
background-color: green;
}
[tall] {
grid-row: span 2;
background-color: crimson;
}
[taller] {
grid-row: span 3;
background-color: blue;
}
[tallest] {
grid-row: span 4;
background-color: gray;
}
grid-item {
display: flex;
align-items: center;
justify-content: center;
font-size: 1.3em;
font-weight: bold;
color: white;
}
<grid-container>
<grid-item short>01</grid-item>
<grid-item short>02</grid-item>
<grid-item tall>03</grid-item>
<grid-item tall>04</grid-item>
<grid-item short>05</grid-item>
<grid-item taller>06</grid-item>
<grid-item short>07</grid-item>
<grid-item tallest>08</grid-item>
<grid-item tall>09</grid-item>
<grid-item short>10</grid-item>
<grid-item tallest>etc.</grid-item>
<grid-item tall></grid-item>
<grid-item taller></grid-item>
<grid-item short></grid-item>
<grid-item short></grid-item>
<grid-item short></grid-item>
<grid-item short></grid-item>
<grid-item tall></grid-item>
<grid-item short></grid-item>
<grid-item taller></grid-item>
<grid-item short></grid-item>
<grid-item tall></grid-item>
<grid-item short></grid-item>
<grid-item tall></grid-item>
<grid-item short></grid-item>
<grid-item short></grid-item>
<grid-item tallest></grid-item>
<grid-item taller></grid-item>
<grid-item short></grid-item>
<grid-item tallest></grid-item>
<grid-item tall></grid-item>
<grid-item short></grid-item>
</grid-container>
jsFiddle demo
How it works
*
*Establish a block-level grid container. (inline-grid would be the other option)
*The grid-auto-rows property sets the height of automatically generated rows. In this grid each row is 50px tall.
*The grid-gap property is a shorthand for grid-column-gap and grid-row-gap. This rule sets a 10px gap between grid items. (It doesn't apply to the area between items and the container.)
*The grid-template-columns property sets the width of explicitly defined columns.
The repeat notation defines a pattern of repeating columns (or rows).
The auto-fill function tells the grid to line up as many columns (or rows) as possible without overflowing the container. (This can create a similar behavior to flex layout's flex-wrap: wrap.)
The minmax() function sets a minimum and maximum size range for each column (or row). In the code above, the width of each column will be a minimum of 30% of the container and maximum of whatever free space is available.
The fr unit represents a fraction of the free space in the grid container. It's comparable to flexbox's flex-grow property.
*With grid-row and span we're telling grid items how many rows they should span across.
Browser Support for CSS Grid
*
*Chrome - full support as of March 8, 2017 (version 57)
*Firefox - full support as of March 6, 2017 (version 52)
*Safari - full support as of March 26, 2017 (version 10.1)
*Edge - full support as of October 16, 2017 (version 16)
*IE11 - no support for current spec; supports obsolete version
Here's the complete picture: http://caniuse.com/#search=grid
Cool grid overlay feature in Firefox
In Firefox dev tools, when you inspect the grid container, there is a tiny grid icon in the CSS declaration. On click it displays an outline of your grid on the page.
More details here: https://developer.mozilla.org/en-US/docs/Tools/Page_Inspector/How_to/Examine_grid_layouts
A: This is recently discovered technique involving flexbox: https://tobiasahlin.com/blog/masonry-with-css/.
The article makes sense to me, but I haven't tried to use it, so I don't know if there are any caveats, other than mentioned in Michael's answer.
Here's a sample from the article, making use of the order property, combined with :nth-child.
Stack snippet
.container {
display: flex;
flex-flow: column wrap;
align-content: space-between;
/* Your container needs a fixed height, and it
* needs to be taller than your tallest column. */
height: 960px;
/* Optional */
background-color: #f7f7f7;
border-radius: 3px;
padding: 20px;
width: 60%;
margin: 40px auto;
counter-reset: items;
}
.item {
width: 24%;
/* Optional */
position: relative;
margin-bottom: 2%;
border-radius: 3px;
background-color: #a1cbfa;
border: 1px solid #4290e2;
box-shadow: 0 2px 2px rgba(0,90,250,0.05),
0 4px 4px rgba(0,90,250,0.05),
0 8px 8px rgba(0,90,250,0.05),
0 16px 16px rgba(0,90,250,0.05);
color: #fff;
padding: 15px;
box-sizing: border-box;
}
/* Just to print out numbers */
div.item::before {
counter-increment: items;
content: counter(items);
}
/* Re-order items into 3 rows */
.item:nth-of-type(4n+1) { order: 1; }
.item:nth-of-type(4n+2) { order: 2; }
.item:nth-of-type(4n+3) { order: 3; }
.item:nth-of-type(4n) { order: 4; }
/* Force new columns */
.break {
flex-basis: 100%;
width: 0;
border: 1px solid #ddd;
margin: 0;
content: "";
padding: 0;
}
body { font-family: sans-serif; }
h3 { text-align: center; }
<div class="container">
<div class="item" style="height: 140px"></div>
<div class="item" style="height: 190px"></div>
<div class="item" style="height: 170px"></div>
<div class="item" style="height: 120px"></div>
<div class="item" style="height: 160px"></div>
<div class="item" style="height: 180px"></div>
<div class="item" style="height: 140px"></div>
<div class="item" style="height: 150px"></div>
<div class="item" style="height: 170px"></div>
<div class="item" style="height: 170px"></div>
<div class="item" style="height: 140px"></div>
<div class="item" style="height: 190px"></div>
<div class="item" style="height: 170px"></div>
<div class="item" style="height: 120px"></div>
<div class="item" style="height: 160px"></div>
<div class="item" style="height: 180px"></div>
<div class="item" style="height: 140px"></div>
<div class="item" style="height: 150px"></div>
<div class="item" style="height: 170px"></div>
<div class="item" style="height: 170px"></div>
<span class="item break"></span>
<span class="item break"></span>
<span class="item break"></span>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44377343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "223"
} |
Q: How can I get translateZ to work in svg groups? I have created a svg image animation. I am trying to make some nice effects with mouseover. I want to move the svg depending on mouse position. The rotate part works fine so far. But I also want to move the <g> inside the svg in z-axis (popout) so they comes out in "different layers". Should be possible with translateZ(). But I can not get it to work.
const container = document.querySelector('.container');
const image = document.querySelector('.image');
const sun = document.querySelector('.sun');
const cloudBehind = document.querySelector('.cloud-center');
const cloudLeft = document.querySelector('.cloud-left');
const cloudRight = document.querySelector('.cloud-right');
const devideAxis = 10;
container.addEventListener('mousemove', e => {
let xAxis = ~(window.innerWidth / 2 - e.pageX) / devideAxis;
let yAxis = (window.innerHeight / 2 - e.pageY) / devideAxis;
image.style.transform = `rotateY(${xAxis}deg) rotateX(${yAxis}deg)`;
});
container.addEventListener('mouseenter', e => {
image.style.transition = 'none';
//popout
cloudLeft.style.transform = 'translateZ(400px)'
})
container.addEventListener('mouseleave', e => {
image.style.transition = 'all 0.5s ease';
image.style.transform = `rotateY(0deg) rotateX(0deg)`
cloudLeft.style.transform = 'translateZ(0)'
})
body,html {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
perspective: 300px;
}
.container {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.image {
width: 50%;
transform-style: preserve-3d;
}
.cloud-left {
transition: all .5s ease-out
}
.cloud-left,
.cloud-right,
.cloud-center {
transition: transform .5s;
}
.cloud-center{
fill:url(#CLOUD-CENTER);
}
.cloud-right{
fill:url(#CLOUD-FRONT);
}
.cloud-left{
fill:url(#CLOUD-FRONT);
}
.sun{
fill:url(#SUN);
}
.shine{
fill:url(#SHINE);
}
<div class="container">
<div class="image">
<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 500 250" >
<g id="wheather">
<radialGradient id="SHINE" cx="100" cy="100" r="100" gradientUnits="userSpaceOnUse">
<stop offset="0.7568" style="stop-color:#FFFFFF"/>
<stop offset="1" style="stop-color:#FFF3AB"/>
</radialGradient>
<linearGradient id="SUN" gradientUnits="userSpaceOnUse" x1="27.6083" y1="98.0519" x2="169.5758" y2="98.0519">
<stop offset="0" style="stop-color:#FFF3AB"/>
<stop offset="1" style="stop-color:#FFF2C0"/>
</linearGradient>
<linearGradient id="CLOUD-CENTER" gradientUnits="userSpaceOnUse" x1="0" y1="66.2549" x2="288.0558" y2="66.2549">
<stop offset="0" style="stop-color:#8EABBF"/>
<stop offset="1" style="stop-color:#ECF1F7"/>
</linearGradient>
<linearGradient id="CLOUD-FRONT" gradientUnits="userSpaceOnUse" x1="0" y1="62.1091" x2="294.4617" y2="62.1091">
<stop offset="5.759445e-07" style="stop-color:#FFFFFF"/>
<stop offset="1" style="stop-color:#C5D6E5"/>
</linearGradient>
<!-- SUN -->
<g transform="translate(250 0)" class="sun">
<path class="shine" d="M162.4,147.8l22,0.9l-9.8-15.5c-0.2-0.5-0.5-1-0.8-1.5v0c-3.1-4.9-1.6-11.1,3-14.2l20.3-8.1l-14.9-9.9
c-0.5-0.5-1-0.9-1.5-1.3h0c-4.9-3.3-6-9.8-2.8-14.5l15-15.3l-17.3-2.9c-0.7-0.3-1.4-0.5-2.2-0.6h0c-6-1-9.7-6.9-8.4-12.6l7.3-19.6
l-16.9,4.3c-0.7,0-1.5,0.1-2.2,0.3h0c-6.3,1.6-12.5-2.9-12.9-9.4v0c0-0.2,0-0.3,0-0.4l-1.2-19.1l-13.8,10.9
c-0.6,0.3-1.1,0.7-1.7,1.1c-5.1,4-12.6,2.4-15.6-3.3l0,0c-0.2-0.5-0.5-0.9-0.8-1.3L98.6,0l-8.4,16c-0.3,0.4-0.6,0.9-0.8,1.3v0
c-3,5.8-10.5,7.4-15.6,3.3h0c-0.5-0.4-1.1-0.8-1.7-1.1L58.3,8.6l-1.2,19.1c0,0.1,0,0.3,0,0.4v0c-0.4,6.5-6.6,11-12.9,9.4h0
c-0.8-0.2-1.5-0.3-2.2-0.3l-16.9-4.3l7.3,19.6c1.3,5.7-2.4,11.6-8.4,12.6h0c-0.8,0.1-1.5,0.3-2.2,0.6L4.3,68.5l15,15.3
c3.2,4.7,2.1,11.2-2.8,14.5c-0.6,0.4-1.1,0.8-1.5,1.3L0,109.5l20.3,8.1c4.6,3,6.1,9.3,3,14.2l0,0c-0.3,0.5-0.6,1-0.8,1.5l-9.8,15.5
l22-0.9c5.4,0.9,9.3,6,8.4,11.7v0c0,0.3-0.1,0.6-0.1,0.9l-2.8,19l19.7-9.8c5-1.3,10.3,1.3,12.2,6.1l5.7,20.4l13.8-16.7
c3.9-3.4,9.7-3.4,13.5,0l13.8,16.7l5.7-20.4c2-4.9,7.3-7.4,12.2-6.1l19.7,9.8l-2.8-19c0-0.3,0-0.6-0.1-0.9v0
C153.2,153.8,157,148.7,162.4,147.8z">
<animateTransform
attributeName="transform"
attributeType="XML"
type="rotate"
from="0 100 100"
to="360 100 100"
dur="80s"
repeatCount="indefinite"
/>
</path>
<circle class="sun-inside" cx="98.6" cy="98.1" r="71"/>
</g>
<!-- / SUN -->
<!-- CLOUD BEHIND -->
<g transform="translate(70 70)">
<path class="cloud-center" style="transform: " d="M261.5,79.4c-3.4,0-6.6,0.6-9.6,1.8c-1.9-5.5-6-10-11.3-12.5c0-0.2,0-0.3,0-0.5c0-27.1-21.9-49-49-49
c-0.6,0-1.2,0-1.8,0c-9-11.7-23.1-19.2-39-19.2c-18,0-33.8,9.7-42.3,24.1c-3.8-3.1-8.6-5-13.8-5c-11.1,0-20.3,8.4-21.6,19.2
c-3.7-1.1-7.7-1.7-11.7-1.7C39,36.6,21,54.6,21,76.9c0,2.8,0.3,5.6,0.9,8.3C9.6,86.1,0,96.3,0,108.8c0,13.1,10.6,23.7,23.7,23.7
h237.8c14.7,0,26.6-11.9,26.6-26.6S276.2,79.4,261.5,79.4z">
<animateMotion
path="M50,0 -50,0 50,0 z"
dur="80s"
repeatCount="indefinite"
/>
</path>
</g>
<!-- / CLOUD BEHIND -->
<!-- CLOUD LEFT -->
<g transform="translate(10 126)">
<path class="cloud-left" d="M270.4,76.2C270.4,76.2,270.4,76.2,270.4,76.2c-1.1-22-19.3-39.6-41.6-39.6c-5.1,0-9.9,0.9-14.4,2.6
C206.9,16.4,185.5,0,160.2,0c-20.6,0-38.6,10.9-48.6,27.3c-4.6-1.5-9.4-2.3-14.5-2.3c-23.4,0-42.8,16.9-46.7,39.1
c-5.1-3.3-11.2-5.2-17.7-5.2C14.6,58.9,0,73.5,0,91.6c0,18,14.6,32.7,32.7,32.7h237.8c13.3,0,24-10.8,24-24
C294.5,86.9,283.7,76.2,270.4,76.2z M194.9,102.4h-0.2c0.1,0,0.1-0.1,0.2-0.1C194.9,102.4,194.9,102.4,194.9,102.4z">
<animateMotion
path="M30,0 0,0 00,0 30,0 z"
dur="15s"
repeatCount="indefinite"
/>
</path>
</g>
<!-- / CLOUD LEFT -->
<!-- CLOUD RIGHT -->
<g transform="translate(260 140)">
<path class="cloud-right" d="M228.8,73.7c0-19.9-16.1-36-36-36c-3.5,0-6.8,0.5-10,1.4c-4.4-18.7-21.2-32.7-41.3-32.7c-10.7,0-20.5,4-28,10.6
C104.6,6.6,91.4,0,76.7,0C49.9,0,28.3,21.7,28.3,48.4c0,1.6,0.1,3.2,0.2,4.8c-0.1,0-0.2,0-0.2,0C12.7,53.2,0,65.9,0,81.5
s12.7,28.3,28.3,28.3H198v-0.4C215.4,106.8,228.8,91.8,228.8,73.7z">
<animateMotion
path="M-40,0 0,0 -100,0 -40,0 z"
dur="60s"
repeatCount="indefinite"
/>
</path>
</g>
<!-- / CLOUD RIGHT -->
</g>
</svg>
</div>
</div>
Main code things:
So I have body, which has perspective: 300px;. Then I have .image which has transform-style: preserve-3d; and inside that element I have the <g>'s with classes.
As an example I have a .cloud-left.
So the structure is basically:
<body>
<div class="container">
<div class="image">
<svg>
<g id="wheather">
<g class="cloud-left">...</g>
...
</g>
</svg>
</div>
</div>
</body>
In javascript I have this (Shortned, to see all code, please see the fiddle above):
const cloudLeft = document.querySelector('.cloud-left'); // get the element
container.addEventListener('mouseenter', e => {
//popout
cloudLeft.style.transform = 'translateZ(400px)'
})
container.addEventListener('mouseleave', e => {
//popback
cloudLeft.style.transform = 'translateZ(0)'
})
But this does not work as I want.
I have also tried to set transform-style: preserve-3d; on <g id="weather"> which is the direct parent to the other <g>'s, but no difference.
I am not getting the <g> to move/popout in z-axis. Am I missing something in the svg or does this not work in svg groups?
I have another example where this works, but it is not an svg: https://jsfiddle.net/saturday99/94o5j8ts/
A: Ok, so as I suspected. It worked with svg's instead of groups/paths. Paths/groups are 2D only, as figured out. But svg's are possible to make 3D and use translateZ on. Down here is the answer for the future ones looking for answer. Ps. The code could be cleaned up a bit, but it works.
So the basic structure is now split into many svg's instead of one svg containing many groups:
<body>
<div class="container">
<div class="image">
<svg class="sun">
<g>
...
</g>
</svg>
<svg class="cloud-left">
<g>
...
</g>
</svg>
...
</div>
</div>
</body>
And here is the "finale" code and solution: https://jsfiddle.net/saturday99/fkrh6bzm/. Feel free to fork the code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67191234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Entity Framework Core, one-to-many relationship, collection always empty I'm trying to do a simple one to many relationship in a InMemory database that is built up in runtime by http requests. I'm new to Entity Framework Core, so I'm unsure if the is a proper way of working with it.
ValuesController.cs
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly DataListContext _Context;
public ValuesController(DataListContext context)
{
_Context = context;
}
[HttpGet]
public ActionResult<IEnumerable<DataList>> Get()
{
// Datas keeps is value
Console.WriteLine("Root Count: " + _Context.RootDatas.Count());
if (_Context.RootDataLists.Count() > 0)
{
// InsideDatas is always
Console.WriteLine("Inside Count: " + _Context.RootDataLists.First().InsideDatas.Count);empty next request
}
return _Context.RootDataLists.ToList();
}
[HttpPost]
public void Post([FromBody] string value)
{
var data = new Data() { Id = Guid.NewGuid() };
_Context.RootDatas.Add(data);
var dataList = new DataList();
dataList.Name = value;
dataList.InsideDatas.Add(data);
_Context.RootDataLists.Add(dataList);
_Context.SaveChanges();
// InsideDatas has an element
Console.WriteLine("Inside Count: " + _Context.RootDataLists.First().InsideDatas.Count);
}
}
public class DataListContext : DbContext
{
public DbSet<DataList> RootDataLists { get; set; }
public DbSet<Data> RootDatas { get; set; }
public DataListContext(DbContextOptions<DataListContext> options) : base(options) { }
}
public class Data
{
[Key] public Guid Id { get; set; }
}
public class DataList
{
public DataList()
{
InsideDatas = new List<Data>();
}
[Key]
public string Name { get; set; }
public ICollection<Data> InsideDatas { get; set; }
}
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataListContext>(options => options.UseInMemoryDatabase(databaseName: "DataList"));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
My problem if that the InsideDatas list is always empty in the next call, but not RootDatas. The DbSet RootDatas in DataListContext is not really anything I would need in my application, but I though it would make the database keep the InsideDatas element. But no.
So I'm I using this all wrong? My use case is a server listing, built up in runtime by hosts posting it's presence to the listing service. My plan is to swap the InMemoryDatabase for redis to be able to scale this properly if needed. (This code is just a slimmed version of the actual one with he same problem)
A: You need to tell EF Core to load related entities. One way is through eager loading:
// notice the Include statement
_Context.RootDataLists.Include(x => x.InsideDatas).First().InsideDatas
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56824959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Dynamically generated hash keys are not displaying correctly when using render json in controller render json: is not displaying my hash key correctly and I am not sure exactly why. I will post the controller code and the view output below.
merger = {}
stops = OpsHeader.joins(
ops_stop_rec: :driver_header
)
.select(
:pb_net_rev,
:pbbname,
:ops_driver1,
:pb_id,
:ops_stop_id,
:dh_first_name,
:dh_last_name
)
.where(
:ops_stop_rec => {
ops_arrive_time: params[:startDate] .. params[:endDate]
})
OpsStopRec.joins(
:ops_line_items
).select(
:opl_amount,
:ops_type,
:ops_stop_id,
:ops_order_id,
:ops_driver1
)
.where(
:ops_stop_rec => {
ops_arrive_time: params[:startDate] .. params[:endDate]
}
).each do |lines|
stops.each do |stop|
if (lines.ops_stop_id == stop.ops_stop_id && lines.ops_driver1 == stop.ops_driver1)
merger[stop] = (merger[stop] ||= []) << lines
end
if (!merger.key?(stop))
merger[stop] = merger[stop]
end
end
end
render json: merger
Here is the actual output of my render json::
#<OpsHeader:0x0a61cdd8>: [
{
ops_stop_id: 260772,
ops_order_id: "129215.0",
ops_type: "P",
ops_driver1: 97,
opl_amount: "625.0"
},
{
ops_stop_id: 260772,
ops_order_id: "129215.0",
ops_type: "P",
ops_driver1: 97,
opl_amount: "112.5"
}
],
If I am looping over the record collection and using the looped elements as keys in my merger hash, how come it is still not displaying correctly in the view?
What is odd is the values that you see are also from a looped collection but they seem to display correctly. It will display correctly in binding.pry() but not in the view.
Any ideas?
Let me give you a better example of what I am referring to. This is close to what I want but it's still not rendered to json. In this case, I am using the attributes method to display the key:
{"pb_id"=>0.133204e6, "pbbname"=>"AMARR INC", "pb_net_rev"=>0.24259e4, "ops_driver1"=>61, "ops_stop_id"=>268970, "dh_first_name"=>"MARK", "dh_last_name"=>"STAYTON"}: null,
{"pb_id"=>0.133203e6, "pbbname"=>"AMARR INC", "pb_net_rev"=>0.251647e4, "ops_driver1"=>89, "ops_stop_id"=>268966, "dh_first_name"=>"RICHARD", "dh_last_name"=>"STROEMER"}: null,
{"pb_id"=>0.133203e6, "pbbname"=>"AMARR INC", "pb_net_rev"=>0.251647e4, "ops_driver1"=>89, "ops_stop_id"=>268967, "dh_first_name"=>"RICHARD", "dh_last_name"=>"STROEMER"}: null,
{"pb_id"=>0.133203e6, "pbbname"=>"AMARR INC", "pb_net_rev"=>0.251647e4, "ops_driver1"=>89, "ops_stop_id"=>268968, "dh_first_name"=>"RICHARD", "dh_last_name"=>"STROEMER"}: null,
{"pb_id"=>0.133204e6, "pbbname"=>"AMARR INC", "pb_net_rev"=>0.24259e4, "ops_driver1"=>61, "ops_stop_id"=>268971, "dh_first_name"=>"MARK", "dh_last_name"=>"STAYTON"}: null,
{"pb_id"=>0.133204e6, "pbbname"=>"AMARR INC", "pb_net_rev"=>0.24259e4, "ops_driver1"=>61, "ops_stop_id"=>268972, "dh_first_name"=>"MARK", "dh_last_name"=>"STAYTON"}: null,
{"pb_id"=>0.133204e6, "pbbname"=>"AMARR INC", "pb_net_rev"=>0.24259e4, "ops_driver1"=>61, "ops_stop_id"=>268973, "dh_first_name"=>"MARK", "dh_last_name"=>"STAYTON"}: [
{
ops_stop_id: 268973,
ops_order_id: "133204.0",
ops_type: "P",
ops_driver1: 61,
opl_amount: "2375.9"
},
{
ops_stop_id: 268973,
ops_order_id: "133204.0",
ops_type: "P",
ops_driver1: 61,
opl_amount: "50.0"
},
{
ops_stop_id: 268973,
ops_order_id: "133204.0",
ops_type: "P",
ops_driver1: 61,
opl_amount: "0.0"
}
As you can see, some are nested and others have null values, which is fine.
A: So in JSON format, a key has to be a string. Just that ruby allows you to have pretty much anything as a key of the hash, doesn't mean it will be compatible with the JSON standard. I will suggest you to change the format of your data so you can produce something like this:
# It is JSON, not ruby
{
"ops_headers": [ # each of your OpsHeader instances
{
"pb_id": 133204,
"pbbname": "AMARR INC",
"pb_net_rev": 2425.9,
"ops_driver1": 61,
"ops_stop_id": 268970,
"dh_first_name": "MARK",
"dh_last_name": "STAYTON",
"ops_stop_recs": [ # contains array of their OpsStopRec instances
{
"ops_stop_id": 268973,
"ops_order_id": "133204.0",
"ops_type": "P",
"ops_driver1": 61,
"opl_amount": "2375.9"
},
{
"ops_stop_id": 268973,
"ops_order_id": "133204.0",
"ops_type": "P",
"ops_driver1": 61,
"opl_amount": "2375.9"
}
]
}
]
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67025688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Breaking the loop after checking the result from observable in angular I would like to break the loop after checking the condition from the return of observable. When the status is False, I want to exit the loop. I have the below code:
var response = Observable<responseService>;
var i;
for (i =0; i < lin.length; i++){
response = this.http.post<responseService>(this.Url, {}, options).pipe(
map(data => {
return data;
}),
catchError((err) => {
return of(null);
}
));
var res = response.map(x => x.status);
console.log(res);
if (res === "False" || res === null) {
response{
status: "FALSE",
message: "ERROR"
}
return of(response);
}
}
return response;
But I am getting error for the if condition as below
"The condition will always return false since the types 'Observable <>' and 'string' has no overlap".
I would greatly appreciate if anyone knows what I am doing wrong or have solution. Thank you!
A: *
*You aren't subscribing the observable and trying to compare an observable to a string. When you compare if (res === "False" || res === null), res variable is still an observable.
*Having nested subscriptions isn't a good practice. And it won't help you here if you wish to make each request sequentially until one request emits False or if null.
You could try create an array of requests and subscribe to it sequentially using RxJS from function and concatMap operator. Then break the sequence using the takeUntil operator if the condition is satisfied. Try the following
import { Subject, from, of } from 'rxjs';
import { takeUntil, concatMap } from 'rxjs/operators';
private getData() {
let closeRequest$ = new Subject<any>();
let response = Observable<responseService>;
let requests = Observable<responseService>[];
for (let i =0; i < lin.length; i++) {
requests.push(this.http.post<responseService>(this.Url, {}, options)) // <-- don't map response here
}
from(requests).pipe(
concatMap(request => of(request)),
takeUntil(closeRequest$)
).subscribe(
response => {
if (!response['status'] && response['status'] === "False") { // <-- check for `response.status` truthiness
// response is false
this.someVar = { status: "FALSE", message: "ERROR" };
this.closeRequest$.next();
this.closeRequest$.complete();
} else {
this.someVar = status;
}
},
error => { }
);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62446705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Setup PhpStorm's to reformat code based on phpcs (codesniffer-rules from Squizlabs) I've taken over a code base, where most of the code is following the codesniffer settings from squizlabs/PHP_CodeSniffer.
How do I setup PhpStorm to automatically reformat the code upon saving files; so I always follow those standards. Ideally I would only reformat files that I save (and not unchanged files).
I'm imagining that I'm looking for a 'Import code style from phpcs.xml.dist' or something like that. But I'm not sure.
I'm trying to avoid having going to through all the code styles line for line, figuring out if it should be if ( $blah ) { or if($blah){, and adjusting the values in Settings one setting at the time.
And bonus points, if one can point out how to do this is VSCode, while I'm at it (to help my colleagues).
Attempt 1: Read online ressources
*
*Reformat and rearrange code
*Configuring code style
*EditorConfig for PhpStorm
*Copy code style settings
Attempt 2: Read around 'Settings'
I went to 'Settings' >> 'Editor' >> 'Code Style' (and also >> 'PHP'). I found the 'Set from'-button, so I could set it to follow Symfony2's code style. But I'm not sure if that follows squidlabs conventions.
I also read around, to see if I could find a 'Generate code styles from code'.
Attempt 3: Generate code style from code
I know that it's a tall order, but I would have been cool, if I could have pointed PhpStorm to a couple of correctly formatted files - and then get PhpStorm to automatically generate the code style from those files. I couldn't find this.
I tried this by trying to copy some of the well-formatted code from the project into the editor in the settings-box, to see if a 'Adjust values based on example code'. But I couldn't find this.
A: I found the answer by carefully reading this post here: PHP_CodeSniffer.
There are several steps to it - and it's highly customizable:
*
*Only 'flag' editted lines
*Only 'flag' editted files
*Which standards to use
*Should it show it as a warning or an error.
Etc...
That combined with: The 'reformat on save' I found in 'Settings' >> 'Actions on save'.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74274142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create Multi-pages in PDF file created with JSPDF from a html page I have a html page containing many text in tables. I'm using jspdf version 1.5 and higher and html2canvas libraries for creating a pdf when clicking on a button "generate the pdf".
The pdf is correctly generated.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Template 01</title>
<link id="BootstrapCSS" rel="stylesheet" type="text/css" href="bootstrap.min.css">
</head>
<body id="toPDF">
<div id="result">
<div id="target">
<div class="container-fluid">
<p id="generateButton" style="display: none;"><button type="button" class="btn btn-primary btn-lg" onclick="download()">Generate PDF</button></p>
<div id="content">
<table id="table01" class="table table-bordered table_border">
...
</table>
<table id="table02" class="table table-bordered table_border">
...
</table>
...
</div>
</div>
</div>
</div>
</body>
<script src="jspdf.umd.js"></script>
<script src="jquery-2.1.4.min.js"></script>
<script src="html2canvas.min.js"></script>
<script>
function download() {
let pdf = new jspdf.jsPDF('p', 'pt', 'a4')
let srcwidth = document.getElementById('toPDF').scrollWidth;
pdf.html(document.getElementById('toPDF'), {
html2canvas: {
scale: 595.26 / srcwidth, //595.26 is the width of A4
scrollY: 0
},
filename: 'jspdf',
x: 0,
y: 0,
callback: function () {
window.open(pdf.output('bloburl'));
}
});
}
</script>
</html>
And the jsfiddle code: http://jsfiddle.net/amadese57/17npbu4y
My problem is the tables are sometimes broken at the bottom of the page (and at the top of the next page).
I would like to create automatically a break when the tables cannot be entirely on the page.
I don't know how to do that and if I can do that in the function pdf.html() that I used.
Could you help me please with that ?
Thanks in advance for your help
A: you have added the width of the PDF file, try to add the height of the PDF file. And add some more information to the meta data
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63556566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Check of two list have colliding element? Is there a way to check if one list collides with another? ex:
bool hit=false;
foreach(var s in list2)
{
if (list1.Contains(s))
{
hit = true;
break;
}
}
if (!hit)
{
A: .NET has a number of set operations that work on enumerables, so you could take the set intersection to find members in both lists. Use Any() to find out if the resulting sequence has any entries.
E.g.
if(list1.Intersect(list2).Any())
A: You can always use linq
if (list1.Intersect(list2).Count() > 0) ...
A: If you're able to use Linq then if(list1.Intersect(list2).Count > 0) {...collision...}.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3682729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: load image to JPanel not working For two days I was trying to load an image into JPanel from a file. I couldn't!
I used JLabel and Icon and it's loaded okay, but I need to load the image to a JPanel directly, is that impossible?
Because almost I saw many and many related problems like this and many people recommended the person who asks the question to load the image into a label!
this is the code :
public class ReadingImage extends JPanel {
JPanel panel;
JFrame frame;
JPanel secPanel;
private BufferedImage img;
public ReadingImage(String path){
frame = new JFrame();
frame.setVisible(true);
frame.setLocation(300, 300);
frame.setSize(300, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
secPanel = new JPanel();
secPanel.setVisible(true);
//secPanel.setLayout(new FlowLayout());
secPanel.repaint();
frame.getContentPane().add(secPanel);
try{
FileImageInputStream fi = new FileImageInputStream(new File(path));
//System.out.println(path);
img = ImageIO.read(fi);
this.repaint();
}
catch (IOException io ){ io.printStackTrace();}
}
@Override
protected void paintComponent(Graphics g){
super.paintComponents(g);
if (img!=null){
g.drawImage(img, 0, 0, this);
repaint();
}
}
}
It's not throwing any exception, but it's not displaying the image in the JPanel!
I adjusted the code many and many times..
any help in this :)
thanks,
A: Classic confusion caused by extending JPanel and using another JPanel. Replace frame.getContentPane().add(secPanel) with frame.add(this , BORDERLAYOUT.CENTER) and everything should work fine.
A: You are calling super.paintComponents(g); in paintComponent, not the s at the end, this is going to cause a StackOverflowException eventually, but don't actually ever add the ReadingImage JPanel to anything, so it's never actually painted
This means that there doesn't seem to be any point any point to the secPane
You should also avoid creating frames from within other components, especially from within the constructor, it provides a very limit use case for the component
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageInputStream;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ReadingImage extends JPanel {
private BufferedImage img;
public ReadingImage(String path) {
try {
FileImageInputStream fi = new FileImageInputStream(new File(path));
img = ImageIO.read(fi);
this.repaint();
} catch (IOException io) {
io.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, this);
repaint();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame();
frame.add(new ReadingImage("Your image"));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(300, 300);
frame.setSize(300, 500);
frame.setVisible(true);
}
});
}
}
I'm not sure exactly what you are trying to achieve, but I would also encourage you to override the ReadingImage's getPreferredSize method and return the size of the image, this makes it easier to layout
A: first load the image in Image Icon, lets say the object as 'pic'.
panel1.add(new JLabel(pic));
add and set panel1 to visible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29430901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Docker deployment workflow of new application release without loosing database state? I have an app called A that uses MongoDB for state. My plan is to use Docker and perhaps create one container for the app and one for MongoDB and then link A with MongoDB (possibly using fig). From what I understand I ought to use a data volume or "data-only containers" for MongoDB state. But if I understand it correctly you link to an image (MongoDB image in this case). Does this mean that I need to restart MongoDB when I deploy a new version of A?
What I want to do is to deploy changes to A (A') without loosing MongoDB state and (possibly) without taking MongoDB down. Without Docker I would just bring A down and deploy A' and have it connect to the same MongoDB instance (that would still be running). This is especially important if I run multiple instances of A behind a load balancer. How would I achieve this in a good way using the Docker infrastructure? Is linking only a good option if I run a single instance of A?
A: You would need to restart MongoDB and/or data containers only if they are linked to container A. So in your case, the steps I would follow:
*
*Start your 'Data Volume Container' with a volume mounted for the data.
*Start your MongoDB container(s), using the docker option --volumes-from to have access to the data of the first container.
*Start your application container A, linking to the MongoDB container(s).
There is no need of restarting the data or MongoDB containers because they are not linked directly to your container application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27685171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Nuxt generate command create an empty html My application works with "npm run dev" command, but when i try to build for production with "npm run generate" in .nuxt/dist folder i have index.html with this content:
<!DOCTYPE html>
<html {{ HTML_ATTRS }}>
<head>
{{ HEAD }}
</head>
<body {{ BODY_ATTRS }}>
{{ APP }}
</body>
</html>
i miss some configuration?
A: The build result of nuxt generate is in the /dist folder, not in the .nuxt/dist folder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44428771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Weird behaviour working on a skip list using void pointers void insertSkipList(SkipList* list, void* I){
Node* new_node=createNode(I, randomLevel(list->max_level));
if (new_node->size > list->max_level)
Node* actual_node=list->head;
unsigned int k;
for (k = list->max_level;k>=1;k--){
if (actual_node->next[k] == NULL || list->compare(I, actual_node->next[k]->item)<0){
if (k < new_node->size) {
new_node->next[k] = actual_node->next[k];
actual_node->next[k]=new_node;
}
else{
actual_node->next = &actual_node->next[k];
k=k+1;
}
}
}
}
I'm having troubles with the command list->compare(I, actual_node->next[k]->item
as it doesn't execute at all. The problem is most likely here actual_node->next[k]->item but I can't see why.
These are the definitions of node and list
typedef struct _SkipList SkipList;
typedef struct _Node Node;
struct _SkipList {
Node *head;
unsigned int max_level;
int (*compare)(void*, void*);
};
struct _Node {
Node **next;
unsigned int size;
void *item;
};
The complete minimal reproducible example contained within the question itself is:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_LENGTH 20
#define MAX_HEIGHT 5
typedef struct _SkipList SkipList;
typedef struct _Node Node;
struct _SkipList {
Node *head;
unsigned int max_level;
int (*compare)(void*, void*);
};
struct _Node {
Node **next;
unsigned int size;
void *item;
};
unsigned int randomLevel(unsigned int height);
static int compare_int(void* x_void,void* y_void){
int x=(int)x_void;
int y=(int)y_void;
return x-y;
}
static Node* createNode(void* item, unsigned int lvl) {
Node* n = (Node*) malloc(sizeof(Node));
if(n == NULL) {
printf("\nError! Node memory not allocated.");
exit(0);
}
n->item = item;
n->next = NULL;
n->size = lvl;
return n;
}
SkipList* createSkipList(unsigned int height, int (*compare)(void*, void*)){
SkipList* skiplist = (SkipList*) malloc(sizeof(SkipList));
if(skiplist == NULL) {
printf("\nError! Skiplist memory not allocated.");
exit(0);
}
skiplist->head=createNode(NULL,height);
skiplist->max_level=1;
skiplist->compare=(*compare);
return skiplist;
}
void insertSkipList(SkipList* list, void* I){
Node* new_node=createNode(I, randomLevel(list->max_level));
if (new_node->size > list->max_level)
list->max_level = new_node->size;
Node* actual_node=list->head;
unsigned int k;
printf("here it's before the loop\n");
for (k = list->max_level;k>=1;k--){
if (actual_node->next[k] == NULL || list->compare(I, actual_node->next[k]->item)<0){ //here the code stops completely
if (k < new_node->size) {
new_node->next[k] = actual_node->next[k];
actual_node->next[k]=new_node;
}
}
else{
actual_node->next = &actual_node->next[k];
k=k+1;
}
}
printf("here it's after the loop (and actually this wont get printed idk why\n");
}
unsigned int randomLevel(unsigned int height){
unsigned int lvl = 1;
time_t t;
srand((unsigned) time(&t));
while (rand() < 0.5 && lvl < height)
lvl = lvl + 1;
return lvl;
}
int main() //creates a skiplist that goes from 0 to MAX_LENGTH
{
skiplist=createSkipList(MAX_HEIGHT,(*compare_int));
int found[MAX_LENGTH];
int expected[MAX_LENGTH];
for(int i=0;i<MAX_LENGTH;i++){
insertSkipList(skiplist,(void*) i);
}
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73346065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adjusting X-Axis Labels for Dates ChartJS I have the following piece of js:
var canvas_link = document.getElementById("chart1").getContext("2d");
var myChart = new Chart(canvas_link, {
type: 'bar',
data: {
labels: xvalues,
datasets: [{
label: area_option,
data: data,
backgroundColor: 'rgba(255, 99, 132, 1)',
}]
},
})
This piece of code outputs the following graph:[![enter image description here][1]][1]
The labels underneath are really crowded and I wanted to just have a quarterly range on the x axis. The labels are currently in string format. Any advice will be very much appreciated since im having a hard time to understand the documentation. I tried to remove some of the values in the array for labels but that just results in unordered blanks. Thank you!
A: There is a special type of axis - time and it can be used to automatically scale the X axis labels.
The time scale is used to display times and dates.
When building its ticks, it will automatically calculate the most comfortable unit based on the size of the scale.
labels option is not needed and data should be reshaped into array of { x: new Date('2020-12-01'), y: 123 }.
const data = [
{ x: new Date('2020-12-01'), y: 123 },
{ x: new Date('2020-12-02'), y: 134 },
{ x: new Date('2020-12-03'), y: 154 },
// etc.
],
X axis also needs to be configured to use time type (it does not seem to detect it automatically)
var myChart = new Chart(canvas_link, {
type: 'bar',
data: {
// labels: xvalues, (not needed)
datasets: [{
label: area_option,
data: data, // note: should be new data not the old one
backgroundColor: 'rgba(255, 99, 132, 1)',
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
display: true,
scaleLabel: {
display: true,
labelString: 'Date'
},
ticks: {
major: {
fontStyle: 'bold',
fontColor: '#FF0000'
}
}
}],
}
}
})
You can find my code here.
UPDATED: X axis shows only quarters/months.
Adding unit: 'quarter' or unit: 'month' can group X axis labels by quarter or month.
Other supported units can be found in docs.
Updated version can be found here
var myChart = new Chart(canvas_link, {
type: 'bar',
data: {
datasets: [{
data: data,
label: 'Data',
backgroundColor: 'rgba(255, 99, 132, 1)',
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
display: true,
scaleLabel: {
display: true,
labelString: 'Date'
},
time: {
unit: 'quarter',
},
ticks: {
major: {
fontStyle: 'bold',
fontColor: '#FF0000'
}
}
}],
}
}
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65450854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: BeautifulSoup, ignore tags and get al the text inside I want to get all the text inside every <p> tag which belongs to news1
import requests
from bs4 import BeautifulSoup
r1 = requests.get("http://www.metalinjection.net/shocking-revelations/machine-heads-robb-flynn-addresses-controversial-photo-from-his-past-in-the-wake-of-charlottesville")
data1 = r1.text
soup1 = BeautifulSoup(data1, "lxml")
news1 = soup1.find_all("div", {"class": "article-detail"})
for x in news1:
print x.find("p").text
this get the first <p> text and only that..when called find_all it gives following error
AttributeError: ResultSet object has no attribute 'find_all'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?
so I made a list.but still getting the same error??
text1 = []
for x in news1:
text1.append(x.find_all("p").text)
print text1
A: The error i get when running your code is: AttributeError: 'ResultSet' object has no attribute 'text', which is reasonable as a bs4 ResultSet is basically a list of Tag elements. You can get the text of every 'p' tag if you loop over that iterable.
text1 = []
for x in news1:
for i in x.find_all("p"):
text1.append(i.text)
Or as a one-liner, using list comprehensions:
text1 = [i.text for x in news1 for i in x.find_all("p")]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45754993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Request location updates from BOOT_COMPLETED Receiver? I need to get location updates form onReceive method. When the the onReceive() called the GPS start for 2-3 second and gone, why??
HOW to fix it?? i want to get location updates. help please.
NOTE: onReceive method is called when restarting my phone
The java code:
public class BootReceiver extends BroadcastReceiver implements LocationListener {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()))
{
LocationManager LM2=(LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
LM2.requestLocationUpdates("gps",5000, 0, this);
}
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// 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
}
}
Manifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<receiver android:name="com.my.package.BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
A: Thanx guys for your help, all i needed was to make a Service
the onReceive method will be
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()))
{
Intent i= new Intent(context, MyService.class);
context.startService(i);
}
}
MyService class
public class MyService extends Service implements LocationListener {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
LocationManager LM2=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LM2.requestLocationUpdates("gps",5000, 0, this);
return Service.START_STICKY;
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// 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
}
}
and i need to register my service in the manifest.xml
<service
android:name="com.my.package.MyService"
android:icon="@drawable/icon"
android:label="Service name"
>
</service>
A:
When the the onReceive() called the GPS start for 2-3 second and gone, why?
Because your process was terminated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21338140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to check 'selected' of an item in JCheckBoxTree after pressing the button I have a customised JCheckBoxTree which its code is taken from this source.
So I want to have access to the status of each CheckBox of this tree. For example, I want to set an item of the tree as 'SELECTED' by pressing a button. I think I need to make a loop to go through the DefaultMutableTreeNode and if the node file is equal to the specified file/string then change its state to SELECTED. However I am not sure if it is the right way of doing such a thing and also could not achieve it.
This is what I tried, (doesn't work):
public void finder(DefaultMutableTreeNode root){
JTreeModification treeClass = new JTreeModification();
Enumeration en = root.depthFirstEnumeration();
//if(){}
while (en.hasMoreElements()) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) en.nextElement();
if(node.equals("file4.json")){
treeClass.new CheckBoxNode(new File(node.getParent(), node), JTreeModification.Status.SELECTED);
}
}
}
The following lines are related codes from my main file:
JTreeModification treeClass = new JTreeModification();
File myTest = new File("D:\\Documents\\A X");
DefaultMutableTreeNode root = new DefaultMutableTreeNode();
final DefaultTreeModel treeModel = new DefaultTreeModel(root);
for (File fileSystemRoot: myTest.listFiles()) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(treeClass.new CheckBoxNode(fileSystemRoot, JTreeModification.Status.DESELECTED));
root.add(node);
}
treeModel.addTreeModelListener(treeClass.new CheckBoxStatusUpdateListener());
final JTree tree = new JTree(treeModel) {
@Override public void updateUI() {
setCellRenderer(null);
setCellEditor(null);
super.updateUI();
//???#1: JDK 1.6.0 bug??? Nimbus LnF
setCellRenderer(treeClass.new FileTreeCellRenderer());
setCellEditor(treeClass.new CheckBoxNodeEditor());
}
};
tree.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
tree.setRootVisible(false);
tree.addTreeSelectionListener(treeClass.new FolderSelectionListener());
tree.setEditable(true);
tree.expandRow(0);
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panel.add(new JScrollPane(tree), BorderLayout.CENTER);
Here is the class that I think is related to my issue:
public enum Status { SELECTED, DESELECTED, INDETERMINATE }
class CheckBoxNode {
public final File file;
public Status status;
public CheckBoxNode(File file) {
this.file = file;
status = Status.INDETERMINATE;
}
public CheckBoxNode(File file, Status status) {
this.file = file;
this.status = status;
}
@Override public String toString() {
return file.getName();
}
}
In the provided GitHub link, there is method starting from line 72, that does something similar to what I want, but I could not merge it to my method.
So is there any idea about how to change the status of a tree's item programatically ?
EDIT:
public void finder(DefaultMutableTreeNode root){
JTreeModification treeClass = new JTreeModification();
Object o = root.getLastChild();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) o;
o = node.getUserObject();
CheckBoxNode check = (CheckBoxNode) o;
System.out.println(check);
if(check.toString().equals("Video1.avi")){
check.status = JTreeModification.Status.SELECTED;
//treeModel.addTreeModelListener(treeClass.new CheckBoxStatusUpdateListener());
}
System.out.println(check.status);
Enumeration e = node.children();
while (e.hasMoreElements()) {
finder(root);
}
}
I just noticed the above code can assign "SELECTED" to the first file of the iteration if its name is same as the one in the if statement. (Video1.avi) in this example. So I am sure check.status = JTreeModification.Status.SELECTED; can do the job. But there are two problems still, first it does not loop all over the nodes. and secondly, although it assigns Selected to the file and I could recognise that in the console print, but it does not show it in the UI until I check or press another item in the tree then it updates the ui and set Video1.avi. So it needs to loop all over the nodes and update the UI.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28889024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to sum of particular column with month and year wise I have following data in my table :
uniqueId d_date amount
1 2018-02-01 100.25
2 2019-03-01 456.5
3 2018-02-01 455
4 2019-05-01 200.48
5 2018-06-01 100
6 2019-07-01 200
7 2018-12-01 6950
Now i want output like :
Year Jan Feb Mar Apr May Jun July Aug Sept Oct Nov Dec Total
2018 - 555.25 - - - 100 - - - - - 6950 7605.25
2019 - - 456.5 - 200.48 - 200 - - - - - 856.98
How can i do this ?
A: You can pivot with conditional aggregation:
select
year(d_date) yr,
sum(case when month(d_date) = 1 then amount end) Jan,
sum(case when month(d_date) = 2 then amount end) Feb,
sum(case when month(d_date) = 3 then amount end) Mar,
...
sum(case when month(d_date) = 12 then amount end) Dec,
sum(amount) total
from mytable
group by year(d_date)
order by yr
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61096631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: AVAudioPlayer not working. Error Domain=NSOSStatusErrorDomain Code=1954115647 "(null)" in swift2 I am downloading artwork, title and audio data file from server and able to display in table cell.
On click of play button in table cell, saving audio data into local file and then trying to play from documents file path. Audio is not playing and getting error at AVAudioPlayer.
Searched a lot but didn't find solution so far. Could you please correct my code and help in fixing this issue. Below is my code.
class AudioViewController: UIViewController,UITableViewDataSource, UITableViewDelegate, AVAudioPlayerDelegate {
var audioPlayer: AVAudioPlayer?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let myCell:AudioTableViewCell = tableView.dequeueReusableCellWithIdentifier("audioCell", forIndexPath: indexPath) as! AudioTableViewCell
myCell.lblAudioTitle.text = arrDictAudios[indexPath.row]["title"] as? String
let artworkData = arrDictAudios[indexPath.row]["artwork"] as? NSData
myCell.imgArtwork.image = UIImage(data: artworkData!)
myCell.btnOutletPlay.tag = indexPath.row
myCell.btnOutletPlay.addTarget(self, action: "playButtonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
return myCell
}
func playButtonClicked(sender: AnyObject) {
let buttonRow = sender.tag
let buttonRowNSNumber = buttonRow as NSNumber
let audioData = arrDictAudios[buttonRow]["data"] as? NSData
print(audioData?.length)
let audioFileNameWithExt = NSString(format: "/%@.m4a",buttonRowNSNumber.stringValue)
var documentsDirectory:String?
var paths:[AnyObject] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
if paths.count > 0 {
documentsDirectory = paths[0] as? String
let savePath = documentsDirectory! + (audioFileNameWithExt as String)
NSFileManager.defaultManager().createFileAtPath(savePath, contents: audioData, attributes: nil)
print("savedPath %@", savePath)
/var/mobile/Containers/Data/Application/8A6AEAAE-B144-4EB2-A70C-99520A0AD9D3/Documents/1.m4a
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: savePath), fileTypeHint: AVFileTypeAppleM4A)
audioPlayer!.prepareToPlay()
audioPlayer!.play()
}
catch let error as NSError{
print(error.description)
//Error Domain=NSOSStatusErrorDomain Code=1954115647 "(null)"
}
}
}
}
A: Please try this code .
func play() {
if let data = NSData(contentsOfURL: savePath) {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: .AllowBluetooth)
try AVAudioSession.sharedInstance().setActive(true)
audioPlayer = try AVAudioPlayer(data: data, fileTypeHint: AVFileTypeAppleM4A)
audioPlayer!.prepareToPlay()
audioPlayer!.play()
} catch let error as NSError {
print("Unresolved error \(error.debugDescription)")
}
}
}
A: My example. I wrote a very long time, so the code is horrible, but it works
class PlayMusicVC: UIViewController, AVAudioPlayerDelegate, ADBannerViewDelegate {
// MARK: - override functions
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.tabBar.hidden = true
mpVolumeView()
play()
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "timeForLabels", userInfo: nil, repeats: true)
bannerView.delegate = self
bannerView.hidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.tabBarController?.tabBar.hidden = true
self.becomeFirstResponder()
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
// timer.invalidate()
self.resignFirstResponder()
UIApplication.sharedApplication().endReceivingRemoteControlEvents()
}
override func canBecomeFirstResponder() -> Bool {
return true
}
override func remoteControlReceivedWithEvent(event: UIEvent?) {
if event!.type == UIEventType.RemoteControl {
switch event!.subtype {
case UIEventSubtype.RemoteControlPlay:
play()
case UIEventSubtype.RemoteControlPause:
pause()
case UIEventSubtype.RemoteControlNextTrack:
next()
case UIEventSubtype.RemoteControlPreviousTrack:
previous()
default: break
}
}
}
// MARK: - var and let
var timer: NSTimer!
var fileManager = NSFileManager.defaultManager()
// var (UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer = AVAudioPlayer()
var nameSongForLabel: String!
var artistSongForLabel: String!
var albumSongForLabel: String!
var dataImageForImageView: NSData!
// data from table
var currentIndex = Int()
var arrayOfSongs = [String]()
// MARK: - IBOutlet weak
@IBOutlet weak var nameSongLabel: UILabel!
@IBOutlet weak var imageOfArtwork: UIImageView!
@IBOutlet weak var durationView: UIView!
@IBOutlet weak var switchView: UIView!
@IBOutlet weak var volumeView: UIView!
// button
@IBOutlet weak var playPauseButton: UIButton!
// left and right labels
@IBOutlet weak var leftLabelTime: UILabel!
@IBOutlet weak var rightLabelTime: UILabel!
@IBOutlet weak var sliderDuration: UISlider!
// MARK: - ADBanner
@IBOutlet weak var bannerView: ADBannerView!
// MARK: - IBAction func and switch functions
@IBAction func previousTrack(sender: UIBarButtonItem) {
previous()
}
var playingSong = true
@IBAction func playTrack(sender: UIBarButtonItem) {
if playingSong == false /* true*/ {
play()
playingSong = true
controlCenter()
} else {
pause()
playingSong = false
controlCenter()
}
}
@IBAction func nextTrack(sender: UIBarButtonItem) {
next()
}
@IBAction func sliderD(sender: UISlider) {
(UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer.currentTime = NSTimeInterval(sender.value)
controlCenter()
}
func previous() {
maximumCount = false
// var allDigit = arrayOfSongs.count-1
if currentIndex > 0 {
newIndex = currentIndex-- - 1
}
play()
controlCenter()
}
// MARK: - data for control
var titleSongForControl: String!
var titleArtistForControl: String!
var currentPause: NSTimeInterval!
var imageForControlCenter: UIImage!
var maximumCount = false
func play() {
playPauseButton.setImage(UIImage(named: "Pause32.png"), forState: UIControlState.Normal)
var currentSong: String!
if newIndex == nil {
currentSong = arrayOfSongs[currentIndex]
if currentIndex == arrayOfSongs.endIndex-1 {
maximumCount = true
}
} else {
currentSong = arrayOfSongs[newIndex]
if newIndex == arrayOfSongs.endIndex-1 {
maximumCount = true
}
newIndex = nil
}
let directoryFolder = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)
var superURL: NSURL!
let url: NSURL = directoryFolder.first!
superURL = url.URLByAppendingPathComponent(currentSong)
let playerItem = AVPlayerItem(URL: superURL)
let commonMetaData = playerItem.asset.commonMetadata
for item in commonMetaData {
if item.commonKey == "title" {
nameSongForLabel = item.stringValue
}
if item.commonKey == "artist" {
artistSongForLabel = item.stringValue
}
if item.commonKey == "album" {
albumSongForLabel = item.stringValue
}
if item.commonKey == "artwork" {
dataImageForImageView = item.dataValue
}
}
titleSongForControl = nameSongForLabel
titleArtistForControl = artistSongForLabel
nameSongLabel.text = "\(artistSongForLabel) - \(nameSongForLabel)"
if dataImageForImageView != nil {
imageOfArtwork.image = UIImage(data: dataImageForImageView)
imageForControlCenter = UIImage(data: dataImageForImageView)
} else {
imageOfArtwork.image = UIImage(named: "Notes100.png")
}
(UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer = try? AVAudioPlayer(contentsOfURL: superURL)
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch _ {
}
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
}
if currentPause == nil {
(UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer.play()
controlCenter()
} else {
(UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer.currentTime = currentPause
(UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer.play()
currentPause = nil
}
}
func timeForLabels() {
let timeForRightLabel: NSTimeInterval = (UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer.duration - (UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer.currentTime
let timeForLeftLabel = (UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer.currentTime
let calendar: NSCalendarUnit = [NSCalendarUnit.Minute, NSCalendarUnit.Second]
// var time: NSTimeInterval = 0
let dateFormatter = NSDateComponentsFormatter()
dateFormatter.unitsStyle = NSDateComponentsFormatterUnitsStyle.Positional
dateFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehavior.Pad
dateFormatter.allowedUnits = calendar
let timeRight = dateFormatter.stringFromTimeInterval(timeForRightLabel)!
rightLabelTime.text = "-\(timeRight)"
let timeLeft = dateFormatter.stringFromTimeInterval(timeForLeftLabel)!
leftLabelTime.text = timeLeft
sliderDuration.minimumValue = 0.0
sliderDuration.value = Float((UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer.currentTime)
sliderDuration.maximumValue = Float((UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer.duration)
// auto next sound
if rightLabelTime.text == "-0:00" && maximumCount == false {
next()
}
//
if (UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer.playing == false {
playPauseButton.setImage(UIImage(named: "Play32.png"), forState: UIControlState.Normal)
playingSong = false
}
}
func pause() {
playPauseButton.setImage(UIImage(named: "Play32.png"), forState: UIControlState.Normal)
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch _ {
}
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
}
(UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer.pause()
currentPause = (UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer.currentTime
}
var newIndex: Int!
var newSong: String!
func next() {
let allDigit = arrayOfSongs.count-1
if arrayOfSongs.count > 1 {
if currentIndex < allDigit {
if newIndex == nil {
newIndex = currentIndex++ + 1
} else {
newIndex = currentIndex++
}
play()
controlCenter()
} else if currentIndex == arrayOfSongs.endIndex {
(UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer.stop()
}
}
}
func controlCenter() {
let mpPlaysCenter = MPNowPlayingInfoCenter.defaultCenter()
mpPlaysCenter.nowPlayingInfo = [MPMediaItemPropertyArtist: titleArtistForControl, MPMediaItemPropertyTitle: titleSongForControl, MPMediaItemPropertyPlaybackDuration: (UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer.duration, MPMediaItemPropertyPlayCount: (UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer.currentTime, MPNowPlayingInfoPropertyElapsedPlaybackTime: (UIApplication.sharedApplication().delegate as! AppDelegate).mainAudioPlayer.currentTime]
}
// MARK: - swipe functions
@IBAction func leftSwipe(sender: UISwipeGestureRecognizer) {
sender.direction = UISwipeGestureRecognizerDirection.Left
next()
}
@IBAction func rightSwipe(sender: UISwipeGestureRecognizer) {
sender.direction = UISwipeGestureRecognizerDirection.Right
previous()
}
// MARK: - functions
func mpVolumeView() {
let mpView = MPVolumeView(frame: CGRectMake(8, 15, self.view.bounds.size.width-16, self.volumeView.bounds.size.height))
volumeView.addSubview(mpView)
}
// MARK: - banner view function
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
NSLog("Banner error is %@", error)
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
bannerView.hidden = false
}
func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
return true
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35593059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ddply and summing over values in a data.frame as part of the function I have a data.frame that looks similar to this:
Y date value1 value2
a 2013-01-01 28.857326 9.0206351
a 2013-01-02 13.675526 5.7823725
a 2013-01-03 20.115434 9.3267285
a 2013-01-04 -4.255547 0.9174301
a 2013-01-05 20.898522 9.7821027
b 2013-01-01 5.478783 27.0027194
b 2013-01-02 21.195939 -14.8786857
b 2013-01-03 -4.407236 18.9189197
b 2013-01-04 25.910805 1.0627444
b 2013-01-05 -2.511209 39.0908554
I'd like to calculate the following (value1 * value2) / sum(value1) where sum(value1) should only be summing values for each date e.g. the first row of data should be calculated as:
(28.857326 * 9.0206351) / (28.857326 + 5.478783).
I've tried both:
ddply(x, .(date), summarize, freq=length(date), calc=(value1 * value2) / sum(value1))
and
ddply(x, .(date), summarize, calc=(value1 * value2) / sum(value1))
but I'm receiving an error for the first call and wrong results for the 2nd.
Here's the code to generate the dummy data:
a <- rnorm(10, 10, 10)
b <- rnorm(10, 10, 10)
x <- data.frame(y=c(rep("a", times=5), rep("b", times=5)), date=c(seq(as.Date("2013-01-01"), as.Date("2013-01-05"), by="days")), value1=a, value2=b)
A: Your second line works and gives the "expected" result. The first fails because the result of length(date) is a vector of length 2 rather than a single value. since you want a result for each row of your data.frame, you should use transform rather than summarise:
ddply(x, .(date), transform, freq=length(date), calc=(value1 * value2) / sum(value1))
y date value1 value2 freq calc
1 a 2013-01-01 8.0886946 -4.498656 2 -2.376917
2 b 2013-01-01 7.2203152 1.222322 2 0.576494
3 a 2013-01-02 7.9971361 -5.675020 2 -1.757606
4 b 2013-01-02 17.8242945 26.489059 2 18.285152
5 a 2013-01-03 3.0401349 10.495623 2 1.283746
6 b 2013-01-03 21.8153403 14.648083 2 12.856439
7 a 2013-01-04 14.4831518 -2.812941 2 -2.685447
8 b 2013-01-04 0.6875999 27.397730 2 1.241776
9 a 2013-01-05 6.2625381 19.979980 2 8.386698
10 b 2013-01-05 8.6569681 11.385124 2 6.606161
A: Using data.table
library(data.table)
x<-data.table(x)
x[,list(freq=length(date),cal=(value1*value2)/sum(value1)),keyby="date"]
date freq cal
1: 2013-01-01 1 -3.94483543
2: 2013-01-01 1 10.83779796
3: 2013-01-02 1 2.33439622
4: 2013-01-02 1 10.62941740
5: 2013-01-03 1 2.97776304
6: 2013-01-03 1 0.06035661
7: 2013-01-04 1 1.59372587
8: 2013-01-04 1 7.17029644
9: 2013-01-05 1 -0.64156778
10: 2013-01-05 1 -1.23650898
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18793249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to solve the issue with preloader and session storage in jQuery? I have a problem with the pre-loader. I was trying to set it up as once per session. It works first time, but when you refresh the website the pre-loader does not stop at all and it is impossible to see the content of the website until the moment I will delete the data from the session storage. Adding visibility: invisible in to stylesheet does not work at all.
canvas {
display: none;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #000000;
z-index: 99;
}
<canvas id="c"><img id="logo" width="1280" height="1024" alt="logo"></canvas>
<div>
content
</div>
if (sessionStorage.getItem('dontLoad') == null){
jQuery("#c").delay(1000).fadeOut('slow', function(){
jQuery( "body" ).animate({
visibility: visible
}, 1000);
});
sessionStorage.setItem('dontLoad', 'true');
}
A: The problem is that you need to change the CSS. I will try to explain.
In your CSS, you have set the canvas to display: none. In your jQuery, you try to use the fadeOut animation. This won't work because the element is not displayed, it is basically removed from the document, so jQuery can't change it.
What you need to do is set the canvas to display: block. So that the 'preloader' is visible when the user accesses the website. Then the 'preloader' will fade out.
Here is the updated CSS.
canvas {
display: block;
position: fixed;
top: 0; left: 0; right: 0; bottom: 0;
background-color: #000000;
z-index: 99;
}
JavaScript
if (sessionStorage.getItem('dontLoad') == null)
{
jQuery("#c").delay(1000).fadeOut('slow', function()
{
jQuery( "body" ).animate({
visibility: visible
})
}, 1000);
}
if (sessionStorage.getItem('dontLoad') == true)
{
$('#c').css('display', 'none');
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45140918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Swift/AppleTV4: How to connect AVPlayer function to AVPlayerViewController? Here is a rudimentary playMe function calling AVPlayer, playing a MP3, MP4 or Wav via Swift with AppleTV. How do I combine this with the AVPlayerViewController - i.e., how do I make the playMe("video", "mp4") play inside an AVPlayerViewController, what are the required steps to make a connection between the Main.storyboard and the AVPlayerViewController, in the GUI and in the Swift code?
func playMe(inputfile: String, inputtype: String) {
let path = NSBundle.mainBundle().pathForResource(inputfile, ofType:inputtype)!
let videoURL = NSURL(fileURLWithPath: path)
let player = AVPlayer(URL: videoURL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
}
A: One way you could do this is by subclassing AVPlayerViewController. AVPlayerViewController has an AVPlayer property named player. A subclass of AVPlayerViewController might look something like this:
import UIKit
import AVKit
class MyPlayerViewController: AVPlayerViewController {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let path = NSBundle.mainBundle().pathForResource("myVideo", ofType:"mov")!
let videoURL = NSURL(fileURLWithPath: path)
player = AVPlayer(URL: videoURL)
}
}
This implementation would show the default playback controls and would work out of the box with the Siri remote.
Here is the code to do this via a button press using prepareForSegue:
import UIKit
import AVFoundation
import AVKit
let playerViewControllerSegue = "play";
class MyViewController: UIViewController {
@IBAction func playMovie(sender: UIButton) {
self.performSegueWithIdentifier(playerViewControllerSegue, sender: self);
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == playerViewControllerSegue){
let path = NSBundle.mainBundle().pathForResource("7second", ofType:"mp4")!
let videoURL = NSURL(fileURLWithPath: path)
let player = AVPlayer(URL: videoURL)
let playerViewController = segue.destinationViewController as! AVPlayerViewController
playerViewController.player = player
playerViewController.player?.play()
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34525804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sorting doesnt work for resources in resourceTimeGridPlugin fullcalender Resources list is sorted when provided to full calender component but it gets randomly sorted automatically.
A: Could it be you are using more or less random ids for your resources? It seems that by default resources are being sorted by id. Just stumbled across the same issue.
Also you can change the ordering: https://fullcalendar.io/docs/resourceOrder
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67291668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Why closing event not working after resuming wpf application from system tray? My problem is, I am hiding my app in system tray when close event is fired,
User can resume it by double clicking on notify icon. Close event only works for the first time in my wpf app.
private void SparkWindow_Closing(object sender, CancelEventArgs e)
{
DialogResult dr = MessageBox.Show("Do you really want to close application?","Confirmation",MessageBoxButton.YesNo,MessageBoxIcon.Question);
if(dr==DialogResult.No)
{
e.Cancel = true;
this.Hide();
notifyIcon.Visibility = System.Windows.Visibility.Visible;
}
else
{
Application.Current.ShutDown();
}
}
this is how i handle the closing event.
and below given code is used to bring it back in front of from system tray.
private void OnNotifyIconDoubleClick(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
this.Show();
this.WindowState = this.lastWindowState;
this.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
}
}
but when it resumes it doesn't fire the closing event 2nd time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34920266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I code my Nunit tests to run from command line? I am writing some C# tests with Nunit and would like to write a Main method to be able to run them from a command line.
After googling a lot I saw a few old posts with the following code, however it seems that Nunit.core was deprecated, therefore I cannot use it anymore.
I created a separate Console project to run the tests, called TestRunner and put the mentioned code that does not work. The framework project and the tests projects are both .Net framework class library:
public static void Main(String[] args)
{
String pathToTestLibrary = "C:\\dev\\oneshore.Tests.DLL"; //get from command line args
TestRunner runner = new TestRunner();
runner.run(pathToTestLibrary);
}
public void run(String pathToTestLibrary)
{
CoreExtensions.Host.InitializeService();
TestPackage testPackage = new TestPackage(@pathToTestLibrary);
testPackage.BasePath = Path.GetDirectoryName(pathToTestLibrary);
TestSuiteBuilder builder = new TestSuiteBuilder();
TestSuite suite = builder.Build(testPackage);
TestResult result = suite.Run(new NullListener(), TestFilter.Empty);
Console.WriteLine("has results? " + result.HasResults);
Console.WriteLine("results count: " + result.Results.Count);
Console.WriteLine("success? " + result.IsSuccess);
}
A: You can use NUnit Console to run the tests from command line. So first download the NUnit Console ZIP package from here and unzip binaries. Create a new .net Console project as you have done it and call nunit3-console.exe to run tests through process.start method, as below:
public static void Main(String[] args)
{
RunTests();
}
private static void RunTests()
{
string outputFolder = @"E:\OutputFolder";
string testDllPath = @"E:\Projects\TestProj\bin\Debug\netcoreapp3.1\TestProjTests.dll";
//exeFilePath is where you unzipped NUnit console binaries
string exeFilePath = @"E:\Tools\NUnit.Console-3.12.0\bin\netcoreapp3.1\nunit3-console.exe";
//or E:\Tools\NUnit.Console-3.12.0\bin\net35 for .net framework based tests proj
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = exeFilePath;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "\"" + testDllPath + "\" --work=\"" + outputFolder + "\"";
try
{
// Start the process with the info we specified.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch (Exception ex)
{
// Log error.
string msg = ex.Message;
}
}
Once completed you will get the TestResult.xml file generated in outputFolder
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68028707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Apache Camel XML-to-JSON I have simple XML file and need to convert it to JSON using camel-xmljson JAR. I have started camel context using:
Main main = new Main();
main.addRouteBuilder(new ConvertXmlToJson());
main.enableHangupSupport();
main.run();
And my configure method looks like:
@Override
public void configure() throws Exception {
XmlJsonDataFormat xmlJsonFormat = new XmlJsonDataFormat();
xmlJsonFormat.setForceTopLevelObject(true);
// from XML to JSON
//#1
from("direct:marshal").marshal(xmlJsonFormat).to("mock:json");
//#2
//from("file:resources/SimpleFile.xml").marshal(xmlJsonFormat).to("file:resources/JsonOutput.txt");
}
Now I am not able to understand where should I exactly pass my xml object? Is #2 looks correct? Nothing happens when I execute any one of them.
It will be fine as well to print converted JSON on the console rather than file.
Thanks in advance for the help.
A: Just change your route to:
from("file:resource/inbox").marshal(xmlJsonFormat).to("file:resource/outbox");
Then copy SimpleFile.xml into resource/inbox, run the application and you will get JSON in resource/outbox
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25060938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: VB.NET: determining the datatype of a field in query resultset? I have numeric data that I am getting from a database. They are all numeric, but they are a mix of int, money and real.
Using VB.NET, how can you programmatically determine the datatype of a field in a resultset?
A: Assuming this table:
CREATE TABLE TestTable
(
Col1 int,
Col2 dec(9,2),
Col3 money
)
With these values:
INSERT INTO TestTable VALUES (1, 2.5, 3.45)
You can use the following code to get the types as .Net types:
Dim DSN = "SERVER=XYZ;UID=XYZ;PWD=XYZ;DATABASE=XYZ"
Using Con As New SqlConnection(DSN)
Con.Open()
Using Com As New SqlCommand("SELECT * FROM TestTable", Con)
Com.CommandType = CommandType.Text
Using RDR = Com.ExecuteReader()
If RDR.Read Then
Trace.WriteLine(RDR.GetProviderSpecificFieldType(0)) 'Returns System.Data.SqlTypes.SqlInt32
Trace.WriteLine(RDR.GetProviderSpecificFieldType(1)) 'Returns System.Data.SqlTypes.SqlDecimal
Trace.WriteLine(RDR.GetProviderSpecificFieldType(2)) 'Returns System.Data.SqlTypes.SqlMoney
End If
End Using
End Using
Con.Close()
End Using
You can also use this to just get the SQL text version of the type:
Dim DSN = "SERVER=XYZ;UID=XYZ;PWD=XYZ;DATABASE=XYZ"
Using Con As New SqlConnection(DSN)
Con.Open()
Using Com As New SqlCommand("SELECT * FROM TestTable", Con)
Com.CommandType = CommandType.Text
Using RDR = Com.ExecuteReader()
If RDR.Read Then
Using SC = RDR.GetSchemaTable()
Trace.WriteLine(SC.Rows(0).Item("DataTypeName")) 'Returns int
Trace.WriteLine(SC.Rows(1).Item("DataTypeName")) 'Returns decimal
Trace.WriteLine(SC.Rows(2).Item("DataTypeName")) 'Returns money
End Using
End If
End Using
End Using
Con.Close()
End Using
EDIT
Here's how to do type comparison along with a helper function that formats things. Outputs once again assume the above SQL.
Dim DSN = "SERVER=XYZ;UID=XYZ;PWD=XYZ;DATABASE=XYZ"
Using Con As New SqlConnection(DSN)
Con.Open()
Using Com As New SqlCommand("SELECT * FROM TestTable", Con)
Com.CommandType = CommandType.Text
Using RDR = Com.ExecuteReader()
If RDR.Read Then
Trace.WriteLine(FormatNumber(RDR.Item(0), RDR.GetProviderSpecificFieldType(0))) '1
Trace.WriteLine(FormatNumber(RDR.Item(1), RDR.GetProviderSpecificFieldType(1))) '2.50
Trace.WriteLine(FormatNumber(RDR.Item(2), RDR.GetProviderSpecificFieldType(2))) '$3.45
End If
End Using
End Using
Con.Close()
End Using
Private Shared Function FormatNumber(ByVal number As Object, ByVal type As Type) As String
If number Is Nothing Then Throw New ArgumentNullException("number")
If type Is Nothing Then Throw New ArgumentNullException("type")
If type.Equals(GetType(System.Data.SqlTypes.SqlInt32)) Then
Return Integer.Parse(number)
ElseIf type.Equals(GetType(System.Data.SqlTypes.SqlDecimal)) Then
Return Decimal.Parse(number.ToString()).ToString("N")
ElseIf type.Equals(GetType(System.Data.SqlTypes.SqlMoney)) Then
Return Decimal.Parse(number.ToString()).ToString("C")
End If
Throw New ArgumentOutOfRangeException(String.Format("Unknown type specified : " & type.ToString()))
End Function
A: With access to only the underlying value and not the structure of the database, it's not possible to definitively tell what type the value is. The reason why is that there is an overlap in the domain of Money, Real and Int values. The number 4 for example could be both a Real an Int and likely a Money.
Can you give us some more context on the issue? Are you trying to convert a raw database value into a Int style value in VB.Net? Can you show us some code?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2186532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Software Product Lines (SPL) for Domain Specific Languages (DSL) Does it make sense to focus on Domain Specifics Languages (DSL) development following a Software Product Line approach?
Does anyone know any other approach to create and maintain several related Domain Specifics Languages at the same time? Note that to support a custom language, requires support multiple tools, from parser, compilers, interpreters, to current state of art IDE, etc.
A: I think it makes sense to focus on DSLs following a Software Product Line approach. If you define the DSL correctly, it will essentially define a framework for creating applications within in a domain and an operating environment in which they execute in. By operating environment, I mean the OS, hardware, and database, as well as the code that implements the semantics or run time environment of the DSL. The framework and operating environment will be the artifacts that get reused across product lines. You may have to create an operating environment that consists of run time environments for multiple DSLs to support multiple product lines.
A: Our DMS Software Reengineering Toolkit is exactly this idea. DMS provides generic parsing, tree building, analyzes (name resolution, control flow anlaysis, data flow analyis, call graphs and points-to analysis, custom analyzers, arbitrary transformations). It has a variety of legacy language front ends, as well as some DSLs (e.g., HTML, XML, temporal logic equations, industrial controller languages, ...) off-the-shelf, but has very good support for defining other DSLs.
We use DMS both to build custom analyzers and transformation tools, but also as product-line generator. For example, we provide test coverage, profilers, smart differencers, and clone detections for a wide variety of languages... because DMS makes this possible. Yes, this lowers our dev and maintenance costs because each of these tool types uses DMS directly as a foundation. Fundamentally, it allows the amortization of language parsers, analyzers and transformers not only across specific languages, but across dialects of those languages and even different languages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3753417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Entity Framework save big image I am creating a field :
public Byte[] Image { get; set; }
This will create a fields called Image with data type varbinary and length is 4000.
When I save a record, it will fail to save because the image is hugh to save in varbinary(4000).
How do I make it to image datattype or bigger binary length?
I am using sqlserver ce 4.
A: You must change the mapping for your property to use image type in the database. You can do that either with data annotations:
[Column(TypeName = "image")]
public Byte[] Image { get; set; }
or with fluent API:
modelBuilder.Entity<...>().Property(e => e.Image).HasColumnType("image");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11757154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ignoring the first column of the kmeans cluster input data
INPUT DATA
(key,datapoints)
A,1,2,0,1,2,1,2,1
B,2,2,3,1,1,1,1,0
C,3,1,2,3,4,5,0,1
D,1,2,0,1,2,5,0,1
....
I have the input data in the above format. I want to perform Kmeans cluserting of the above data ignoring the first column and would like to identify which centre each of the record belongs to. I have discarded the first col (key) and able to find the cluster centres using below code, but I'm expecting the output in below format
(key,cluster_centre)
A,0
B,2
C,1
D,0
...
Code:
data = sc.textFile("/home/user/inputfile.txt")
parsedData = data.map(lambda line: array([long(x.strip()) for x in line.split(',')]))
model = KMeans.train(parsedData, 3, maxIterations=10, runs=10, initializationMode="random")
centers = model.clusterCenters
for center in centers: print(center)
A: filtered_cols = parsed_data.map(lambda x: x[1])
model = KMeans.train(filtered_cols, 3, maxIterations=10, runs=10, initializationMode="random")
centers = model.clusterCenters
for center in centers: print(center)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39631023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Uneven line-height in TextFlow control? I've switched from the regular TextField to the new TextLayout framework, thus using the new TextFlow control. Everything is great except that lines for some reason don't snap horizontally to pixels. Meaning, the line-height varies due to rounding and the selection rectangle becomes blurry. I've looked up and down the documentation and can't find anything that would explain this, nor do I find anything on the mighty google.
I haven't done anything strange and it's still a minimal implementation so I don't see what I personally could've done wrong: http://pastebin.com/hBxR1eVS ... setting the line-height works partially (although far from ideal), but there is still something causing a non-integer height. I'm compiling against Flex SDK 4.5.1 with FlashDevelop.
There must be a way to force lines to snap to pixels... right?
EDIT: Apparently this is present even in their own demo swf: http://sourceforge.net/projects/tlf.adobe/files/3.0/current/Flow.swf/download
So basically, the question is then... can it be fixed/corrected by making some custom implementation of some class or perhaps make some adjustment to the TextLayout-framework itself?
As you can see here, the spacing between the lines varies between 5 and 6 pixels, and the selection rectangle is blurred (everything is selected, the background is grey).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7462891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Write a for loop in a function to get a matrix I need to put delta.vec and sigma.vec values through my required.replicates function and store them in my practice1 matrix.
But I get NULL.
sigma.vec <- c(2,4,6,8,10,12)
delta.vec <- c(1,2,5,8,10)
practice1 <- matrix(0, nrow=length(delta.vec), ncol=length(sigma.vec))
required.replicates <- function(delta, sigma, z.alpha = 1.959964, z.beta=0.8416212) {
for(i in 1:length(delta.vec)) {
for(j in 1:length(sigma.vec))
practice1[i,j] <- ceiling((2*(z.alpha + z.beta)^2)* (sigma[j]/delta[i])^2)
}
}
practice1 <- required.replicates(delta=delta.vec, sigma=sigma.vec)
practice1
A: This is more efficient:
required.replicates <- function (delta, sigma, z.alpha, z.beta) {
oo <- 1 / outer(delta, sigma, "/")
ceiling(oo ^ 2 * 2 * (z.alpha + z.beta) ^ 2)
}
practice1 <- required.replicates(delta.vec, sigma.vec, 1.959964, 0.8416212)
Fix to your original code
required.replicates <- function(delta, sigma, z.alpha = 1.959964, z.beta=0.8416212) {
oo <- matrix(0, nrow=length(delta), ncol=length(sigma))
for(i in 1:length(delta))
for(j in 1:length(sigma))
oo[i,j] <- ceiling((2*(z.alpha + z.beta)^2)* (sigma[j]/delta[i])^2)
return(oo)
}
practice1 <- required.replicates(delta.vec, sigma.vec, 1.959964, 0.8416212)
Thanks! One more question, if I want any value in the matrix less than 3 to have a value of 3 and any value more than a 1000 to return as NA what additions should I make?
practice1[practice1 < 3] <- 3
practice1[practice1 > 1000] <- NA
practice1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44604762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python K-means fails to fit data when over 100 samples I am very new to sklearn (and python in general) but needs to work on some project involving clustering of over 10k samples. Using the following code with the test dataset of less than 100 samples with k = 4, the clustering went as expected. However, when I started using more than 100 samples, the 6/8 centroids appear to be repeating at the origin (0,0) i.e. it failed to generate cluster. Any advice for something that could have gone wrong?
Screenshot:
86 Samples,
150 samples
Code:
data = pd.read_csv('parsed.txt', sep="\t", header=None)
data.columns = ["x", "y"]
kmeans = KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=1000,
n_clusters=k, n_init=10, n_jobs=1, precompute_distances='auto',
random_state=None, tol=0.0001, verbose=0)
kmeans.fit(data)
labels = kmeans.predict(data)
centroids = kmeans.cluster_centers_
fig = plot.figure(figsize=(5, 5))
colmap = {(x+1): [(np.sin(0.3*x + 0)*127+128)/255,(np.sin(0.3*x + 2)*127+128)/255,(np.sin(0.3*x + 4)*127+128)/255] for x in range(k)} # making rainbow colormap
colors = map(lambda x: colmap[x+1], labels) #color for each label
plot.scatter(data['x'], data['y'], color=colors, alpha=0.5, edgecolor='k')
for idx, centroid in enumerate(centroids):
plot.scatter(*centroid, color=colmap[idx+1])
plot.xlim(0, 4000)
plot.ylim(0, 10000)
plot.show()
@ 150 samples, I printed the labels (almost all 2s) and centroid coordinates (most at origins) shown below:
[2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2]
[[ 7.51619277e+09 7.51619277e+09]
[ 1.00000000e+27 1.00000000e+27]
[ 0.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 0.00000000e+00]]
More details (08/20/17)
Here are the GIF showing clusters from k = 1 to 10 for 86 and 150 samples respectively. As seen here, 86 set works well but not for 150 set which only present at origin. Note that the color change in 150 set at k=4 frame resulted from how I defined colormap, so not a part of the issue.
,
A: Did you try checking out first if there actually are so many clusters in your data as you trying to find ? Simply increasing the number of samples does not necessarily mean that the number of clusters will increase as well. If no. of clusters you are giving as input to the algorithm is greater than the actual no. of clusters in the dataset, then it is possible that the algorithm may not converge properly, or the the clusters may simply overlap (completely) over each other.
To find the optimal no. of clusters for your dataset, we use a technique called as elbow method. There are different variations of this method, but the main idea is that for different values of K (no. of clusters) you find the cost function that is most appropriate for you application (Example, Sum of Squared distance of all the points in a cluster to it's centroid for all values of K say 1 to 8, or any other error/cost/variance function. Based on the function you have chosen , you will see that after a certain point, the difference in the values will be negligible. The idea is that we chose that value of 'K' at which the value of the chosen cost function changes abruptly.
For the value K=4 the variance is changing abruptly. So K=4 is the chosen to be an appropriate value.
Image Source : Wikipedia
There are several other methods on cluster validation as well. There exists several packages in R specifically for this purpose.
To learn more from the following links :
*
*Coursera Lecture on Elbow Method
*D3js visualization of D3js
*Quora answer on elbow method
*Python implementation of elbow method
*Wikipedia Link
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45779257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Pricing initialization in SOline dac I am looking for the best possibility to initialize the tarifs.
using the fielddefaulting event, the amount stays at 0
protected void SOLine_CuryUnitPrice_FieldDefaulting(PXCache cache, PXFieldDefaultingEventArgs e)
{
var row = (SOLine)e.Row;
SOOrder order = (SOOrder) Base.Document.Current;
BAccount un_compte=PXSelect<BAccount , Where<BAccount.bAccountID, Equal<Required<BAccount.bAccountID>>>>.Select(this.Base,row.CustomerID);
if (row.InventoryID!=null)
{
InventoryItem un_article=PXSelect<InventoryItem, Where<InventoryItem.inventoryID, Equal<Required<InventoryItem.inventoryID>>>>.Select(this.Base,row.InventoryID);
string taxe=Convert.ToString(order.TaxCalcMode);
if ((un_compte!=null) && (un_article!=null))
{
if ((un_compte.GetExtension<BAccountExt>().Usrcattarifaireclient=="cat1") && (taxe=="N"))
{
decimal? tmp=un_article.GetExtension<InventoryItemExt>().Usrprxht1;
e.NewValue=tmp;
}
if ((un_compte.GetExtension<BAccountExt>().Usrcattarifaireclient=="cat1") && (taxe=="G"))
{
decimal? tmp=un_article.GetExtension<InventoryItemExt>().Usrprxttc1;
e.NewValue=tmp;
}
}
}
}
A: I finally used the event : SOLine_UOM_FieldUpdated.
Everything works perfectly, including the webservices
protected void SOLine_UOM_FieldUpdated(PXCache cache, PXFieldUpdatedEventArgs e)
{
var row = (SOLine)e.Row;
row.CuryUnitPrice=tmp;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74349692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get the last four weeks including current week using an sql query I want to fetch last 4 weeks results including this week. so let say i have a stat table which is full of stats of last month April, now its 4 May... when I write this query:
I want to fetch unique visitors:
SELECT COUNT(distinct ip ) AS uni, (
date_added
) AS wday, FROM_UNIXTIME( date_added ) AS cusotms
FROM `site_stats`
WHERE FROM_UNIXTIME( date_added ) >= DATE_SUB( SYSDATE( ) , INTERVAL 4 WEEK )
GROUP BY WEEK( FROM_UNIXTIME( date_added ) )
It found following results:
uni wday cusotms
2 1333819740 2012-04-07 22:29:00
6 1333906140 2012-04-08 22:29:00
7 1334510940 2012-04-15 22:29:00
7 1335115740 2012-04-22 22:29:00
5 1336089600 2012-05-04 05:00:00
But I want last 4 weeks including this week. I dont know why this is showing me record of 4 may, 22 april, 15 april and then 8 and 7 april. I was thinking something like below
is this correct result for last 4 weeks group by week? I was thinking it should be something like 4 may,
4 may
4-7 = 28 april
4-14days = 21 april
and then 14 april
and last 7 april
??
I need to put this output in graph for showing last week stats... Any help would be really appreciated.
Thanks in advance !
A: You fetch the exact date, it seems like you want to fetch the week:
SELECT COUNT(distinct ip ) AS uni, (
date_added
) AS wday, WEEK( FROM_UNIXTIME( date_added ) ) AS cusotms
A: Here is the solution:
SELECT COUNT( DISTINCT ip ) AS uni, (
date_added
) AS wday, FROM_UNIXTIME( date_added ) AS cusotms
FROM `site_stats`
WHERE FROM_UNIXTIME( date_added ) >= CURDATE( ) - INTERVAL DAYOFWEEK( CURDATE( ) ) -3WEEK
GROUP BY WEEK( FROM_UNIXTIME( date_added ) )
LIMIT 0 , 30
hope it helps :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10448742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Days function working in Jaspersoft Studio but not with JasperReports library I have few reports which are using the built-in function DAYS(DATE1, DATE2) to calculate number of days between two dates.
My expression is (DAYS(new SimpleDateFormat("dd/MM/yyyy").parse($F{DATE_DEBUT_ABSENCE}),new SimpleDateFormat("dd/MM/yyyy").parse($V{date_fin_sejour}))+1).
It's working well and without error on Jaspersoft studio 6.4.0 but when i try to generate the same report with JasperReports 6.2.0 i have an error:
net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression for source text: DAYS(new SimpleDateFormat("dd/MM/yyyy").parse($F{DATE_DEBUT_ABSENCE_1}),new SimpleDateFormat("dd/MM/yyyy").parse($V{date_de_fin_absence}))+1
- UUID : D22C5C66-1B4F-4DF4-BD44-1E639D1F5197
com.mysoftware.core.shared.exception.SysException: net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression for source text: DAYS(new SimpleDateFormat("dd/MM/yyyy").parse($F{DATE_DEBUT_ABSENCE_1}),new SimpleDateFormat("dd/MM/yyyy").parse($V{date_de_fin_absence}))+1
at sun.reflect.GeneratedConstructorAccessor1706.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamReader.instantiate(ServerSerializationStreamReader.java:1110)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamReader.deserialize(ServerSerializationStreamReader.java:682)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamReader.readObject(ServerSerializationStreamReader.java:592)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamReader$ValueReader$8.readValue(ServerSerializationStreamReader.java:149)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamReader.deserializeValue(ServerSerializationStreamReader.java:434)
at com.google.gwt.user.server.rpc.RPC.decodeRequest(RPC.java:312)
at com.mysoftware.core.server.service.RemoteServiceDispatcher.processCall(RemoteServiceDispatcher.java:64)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:373)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:751)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:844)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:280)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:254)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:136)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:341)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:25)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at com.mysoftware.core.server.servlet.filter.RoutingFilter.doFilter(RoutingFilter.java:93)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3367)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3333)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2220)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2146)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2124)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1564)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:254)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:295)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:254)
And the POM.xml
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.2.0</version>
<exclusions>
<exclusion>
<artifactId>ecj</artifactId>
<groupId>org.eclipse.jdt.core.compiler</groupId>
</exclusion>
<exclusion>
<groupId>bouncycastle</groupId>
<artifactId>bcmail-jdk14</artifactId>
</exclusion>
<exclusion>
<groupId>bouncycastle</groupId>
<artifactId>bcprov-jdk14</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-functions</artifactId>
<version>6.2.0</version>
</dependency>
I use JAVA as a language for expressions
How that expression can work properly on Jaspersoft Studio and not on JasperReports?
A: Thanks everyone and especially @AlexK who make search about library.
The problem was not the missing of the jasperreports-functions libs but the missing of the joda-time library which is used by jasperreports-functions inside DAYS(), YEARS() and MONTHS() methods.
Adding https://github.com/JodaOrg/joda-time/releases/download/v2.9.9/joda-time-2.9.9.jar solved my problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46641506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: EnumDropDownListFor using Reflection throwing "Return type 'System.Object' is not supported." I'm trying to build out a settings page using reflection. Some options are enums, but the standard @Html.EditorFor() gives a text box rather than a dropdown on these properties. I have an approach sort-of working using @Html.DropDownList(), but I want the "for" helper to get the benefits of having the value pre-selected.
Classes
public class CycleSettings
{
//a bunch of sub-objects, like:
public SurveyConfiguration Survey { get; set; }
}
public class SurveyConfiguration
{
[JsonConverter(typeof(StringEnumConverter))]
[DisplayName("Display Survey Data")]
public DataDisplayFullOptions Data { get; set; }
}
public enum DataDisplayFullOptions
{
Available,
[Display(Name = "Coming Soon")]
ComingSoon,
Report
}
View
@foreach (var property in typeof(CycleSettings).GetProperties()) {
object temp = property.GetValue(Model.Settings.CycleSettings[Model.CurrentYear][Model.CurrentCycle]);
@Html.Label(property.Name)
<div style="padding-left: 20px">
@foreach (var subprop in temp.GetType().GetProperties())
{
object temp2 = subprop.GetValue(temp);
var label = Attribute.GetCustomAttribute(subprop, typeof (DisplayNameAttribute));
@Html.Label(label != null ? ((DisplayNameAttribute)label).DisplayName : subprop.Name,new {@style="padding-right: 20px"})
@(temp2.GetType().IsEnum ? Html.EnumDropDownListFor((m) => temp2) : Html.EditorFor((m) => temp2)) //error occurs here on EnumDropDownListFor path
/*Html.DropDownList(subprop.Name, EnumHelper.GetSelectList(temp2.GetType()))*/ //this worked, but I am trying to use the EnumDropDownListFor to get the correct property selected on load
<br/>
}
</div>
}
Stack Trace
[ArgumentException: Return type 'System.Object' is not supported.
Parameter name: expression]
System.Web.Mvc.Html.SelectExtensions.EnumDropDownListFor(HtmlHelper`1
htmlHelper, Expression`1 expression, String optionLabel, IDictionary`2
htmlAttributes) +1082
System.Web.Mvc.Html.SelectExtensions.EnumDropDownListFor(HtmlHelper`1
htmlHelper, Expression`1 expression, String optionLabel) +90
EDIT: Just tried this-- no more error, but still not selecting the right value:
Html.DropDownListFor((m) => temp2, EnumHelper.GetSelectList(temp2.GetType()))
A: The answer turned out to be pretty simple. I was close with this attempt:
Html.DropDownListFor((m) => temp2, EnumHelper.GetSelectList(temp2.GetType()))
I just needed to override the GetSelectList:
Html.DropDownListFor((m) => temp2, EnumHelper.GetSelectList(temp2.GetType(), (Enum)temp2))
A: Here is my enum extensions I usually use. Hope it can help.
public enum Gender
{
[EnumDescription("Not selected")]
NotSelected,
[EnumDescription("Male")]
Male,
[EnumDescription("Female")]
Female
}
In your view (you can omit "data-bind" Knockout binding)
@Html.DropDownList(
"gender",
SelectListExt.ToSelectList(typeof(Gender)),
new
{
data_bind = "value: Gender",
})
Select list helper class:
public static class SelectListExt
{
public static SelectList ToSelectList(Type enumType)
{
return ToSelectList(enumType, String.Empty);
}
public static SelectList ToSelectList(Type enumType, string selectedItem)
{
List<SelectListItem> items = new List<SelectListItem>();
foreach (var item in Enum.GetValues(enumType))
{
FieldInfo fi = enumType.GetField(item.ToString());
var attribute = fi.GetCustomAttributes(typeof(EnumDescription), true).FirstOrDefault();
var title = attribute == null ? item.ToString() : ((EnumDescription)attribute).Text;
// uncomment to skip enums without attributes
//if (attribute == null)
// continue;
var listItem = new SelectListItem
{
Value = ((int)item).ToString(),
Text = title,
Selected = selectedItem == ((int)item).ToString()
};
items.Add(listItem);
}
return new SelectList(items, "Value", "Text", selectedItem);
}
}
And the attribute itself:
public class EnumDescription : Attribute
{
public string Text { get; private set; }
public EnumDescription(string text)
{
this.Text = text;
}
}
You can also use my extension class to convert enums to their string descriptions:
public static class EnumExtensions
{
public static string ToDescription(this Enum enumeration)
{
Type type = enumeration.GetType();
MemberInfo[] memInfo = type.GetMember(enumeration.ToString());
if (null != memInfo && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(EnumDescription), false);
if (null != attrs && attrs.Length > 0)
return ((EnumDescription)attrs[0]).Text;
}
else
{
return "0";
}
return enumeration.ToString();
}
}
This code is not perfect, but it works for me. Feel free to refactor and post updates!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28725764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: style attribute of XSSFWorkbook cell of Apache POI show compilation errors I use Apache poi to generate excel data which can be accessed outside the app. I have a problem with creating style. Some methods of the style properties keeps showing error when I added the expected values.
XSSFWorkbook wb = new XSSFWorkbook();
BorderStyle thin = BorderStyle.THIN;
short black = IndexedColors.BLACK.getIndex();
CellStyle style = wb.createCellStyle();
style.setBorderRight(thin);
style.setRightBorderColor(black);
style.setBorderBottom(thin);
style.setBottomBorderColor(black);
style.setBorderLeft(thin);
style.setLeftBorderColor(black);
style.setBorderTop(thin);
style.setTopBorderColor(black);
style.setAlignment(HorizontalAlignment.CENTER_SELECTION);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
I have the following errors when I tried to compile the code:
error: incompatible types: HorizontalAlignment cannot be converted to
short
error: incompatible types: FillPatternType cannot be converted to
short
error: incompatible types: BorderStyle cannot be converted to short
error: incompatible types: BorderStyle cannot be converted to short
error: incompatible types: BorderStyle cannot be converted to short
error: incompatible types: BorderStyle cannot be converted to short
A: Following @Gagravarr suggestion, I realised the problem was from mixing two versions of the Apache POI library. There seems to be comflict while trying to build the project. After some digging around the web, I came across a far more simple solution https://github.com/SUPERCILEX/poi-android (written in Kotlin). I just added the maven repository, dependencies and System.setProperties. Then, android studio downloaded the need libraries.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55968289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android: Two actvities as launchers I'm developing locker application. I created service and receiver to hide default android locker. But for few days I have problem with settings activity. I'm looking for a solution, how to make two activites as launchers. I want to make something like that:
Locker activity is only launched when phone is locked. And Settings activity only when I press app icon in menu. Is it possible to programme?
Thanks for help.
A: You can try to launch the same activity but changing the content view (into onCreate) for each situation. Something like:
if (isLocked()) {
setContentView(R.layout.locker_activity);
} else {
setContentView(R.layout.settings_activity);
}
A: You can use just one activity as launcher and use Fragments to load what you want. Something like this:
public class LauncherActivity extends FragmentActivity {
super.onCreate(savedInstanceState);
Fragment fragment;
if (isLocked()) {
fragment = new LockerFragment();
}
else {
fragment = new SettingsFragmentFragment();
}
getFragmentManager().beginTransaction().add(R.id.container_id,fragment).commit();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20496088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get case sensitive column names from MySQL query using funcool/clojure.jdbc When retrieving items from a MySQL table using funcool/clojure.jdbc, all the column names are lower case, even though the table has been created with mixed case column names. I have found various answers that indicate double quoting, backticking, etc., ought to do something, but they don't. The client side is Windows. The MySQL server side is Linux.
For example, this screenshot from HeidSQL shows a few column names:
I can query the column names in the Clojure REPL with show columns from tablename:
arena-rest.sql> (map :field (fetch "show columns from EEComponents"))
("Number" "Category" "Footprint" "Footprint path" ...
However when I query the data, I get lowercase field names in the return map:
arena-rest.sql> (fetch "select Number from EEComponents")
[{:number "120-00001"} {:number "190-99999"} {:number "180-00002"}
{:number "180-00003"}]
I expect a response like
[{:Number "120-00001"} {:Number "190-99999"} {:Number "180-00002"}
{:Number "180-00003"}]
I have tried select "Number" from EEComponents, select Number AS "Number"... etc. including using backticks, but no luck.
I have found some SO questions/answers which indicate that it is normal behavior for all SQL implementations to lowercase column names in returned items, however when I run the query using another means, such as directly in the MySQL command line, the case is preserved in the returned data:
So I'm not sure whether it's in the java or the clojure part. Some searches indicate the column case ought to be preserved in the Java ResultSet. So I'm thinking this is local to the funcool/clojure.jdbc wrapper.
My clojure project is:
(defproject arena-rest "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:dependencies [[org.clojure/clojure "1.9.0"]
[clj-http "3.9.1"]
[cheshire "LATEST"]
[crouton "LATEST"]
[mysql/mysql-connector-java "8.0.12"]
[funcool/clojure.jdbc "0.9.0"]
[org.clojure/tools.trace "0.7.9"]
[org.flatland/ordered "1.5.6"]]
:main arena-rest.core)
My clojure file starts like this:
(ns arena-rest.sql
(:require [jdbc.core :as jdbc]
[clojure.string :as str]
[clojure.pprint :refer [pprint]]
[clojure.repl :refer [doc]] ... and other stuff
So, is it possible to return properly cased column names using funcool/clojure.jdbc, or do I need to use another one such as org.clojure/java.jdbc ?
A: This is the relevant code that's determining how to coerce column names in result sets, which is converting the strings to lower-case by default.
Try (fetch "select Number from EEComponents" {:identifiers identity}) to leave the strings as-is, or {:identifiers keyword} to turn them into keywords.
(I'd also consider using https://github.com/clojure/java.jdbc)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53015972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Neo4j Return all Nodes and Relationships where Sender sent more than 10 emails I am working with email data in neo4j. I would like to find all relationships and nodes where the emails failed to be delivered and the recipient list was over 10 recipients.
Below returns just the Senders that sent these emails:
MATCH (a:Sender)-[:FAILED_TO]->(r:Recipient)
WITH a, count(r) AS failed_to_count
WHERE failed_to_count > 10
RETURN a
How can I modify this to get back the senders, relationship and recipients?
Like the following:
A: One approach is to collect the "failed" paths for each sender, and return the path collections that have more than 10 items:
MATCH path = (a:Sender)-[:FAILED_TO]->(r:Recipient)
WITH a, COLLECT(path) AS paths
WHERE SIZE(paths) > 10
RETURN paths
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58310918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Local path doesn't exist...and apk file is not generating When i run application on my connected device, after selecting an device it shows unexpected error,local path doesn't exist.
A: In build.gradle check if gradle is updated to latest.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.1'
}
}
After that clean and rebuild your project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35501692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: GPU vs CPU memory usage in RAPIDS I understand that GPU and CPU have their own RAM, but what I dont understand is why the same dataframe, when loaded in pandas vs RAPIDS cuDF, have drastically different memory usage. Can somebody explain?
A: As noted in Josh Friedlander's comment, in cuDF the object data type is explicitly for strings. In pandas, this is the data type for strings and also arbitrary/mixed data types (such as lists, dicts, arrays, etc.). This can explain this memory behavior in many scenarios, but doesn't explain it if both columns are strings.
Assuming both columns are strings, there is still likely to be a difference. In cuDF, string columns are represented as a single allocation of memory for the raw characters, an associated null mask allocation to handle missing values, and an associated allocation to handle row offsets, consistent with the Apache Arrow memory specification. So, it’s likely that whatever is represented in these columns is more efficient in this data structure in cuDF than as the default string data structure in Pandas (which is going to be true essentially all the time).
The following example may be helpful:
import cudf
import pandas as pd
Xc = cudf.datasets.randomdata(nrows=1000, dtypes={"id": int, "x": int, "y": int})
Xp = Xc.to_pandas()
print(Xp.astype("object").memory_usage(deep=True), "\n")
print(Xc.astype("object").memory_usage(deep=True), "\n")
print(Xp.astype("string[pyarrow]").memory_usage(deep=True))
Index 128
id 36000
x 36000
y 36000
dtype: int64
id 7487
x 7502
y 7513
Index 0
dtype: int64
Index 128
id 7483
x 7498
y 7509
dtype: int64
Using the Arrow spec string dtype in pandas saves quite a bit of memory and generally matches cuDF.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73772464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Repetition in data constructor I can define a binary tree data structure:
data Tree a = Leaf | Node a (Tree a) (Tree a)
Now I want to create a tree such that each Node has 10 sub-trees. I could so so by writing out 10 (Tree a)s, but is there a more consise way? I'm thinking type families might help here but I'm not sure.
A: It seems like you want a tree whose branching factor is determined on the type level, and can be any natural number. This is fairly straightforward with GADTs:
data Nat = Z | S Nat
data Vec (n :: Nat) a where
Nil :: Vec 'Z a
(:>) :: a -> Vec n a -> Vec ('S n) a
infixr 5 :>
data Tree k a = Leaf | Node a (Vec k (Tree k a))
Vec is the standard way to encode a homogenous length-indexed vector with GADTs (found e.g. here). A node in a tree is then an element of type a and a vector of length k, where each element of the vector is a subtree.
Binary trees are simply
type BinaryTree = Tree ('S ('S 'Z))
and constructing is simply
tree = Node 1 (Node 2 (Leaf :> Leaf :> Nil) :> Leaf :> Nil)
the inferred type will be Num a => Tree ('S ('S 'Z)) a.
But if you really need 10 nodes, writing out ten 'S is still too tedious, so you may want to use type literals:
import qualified GHC.TypeLits as TL
...
type family N (n :: TL.Nat) :: Nat where
N 0 = 'Z
N n = 'S (N (n TL.- 1))
type Tree10 = Tree (N 10)
This not only gives you trees with any branching factor you like, but it allows you to write functions which are polymorphic in the branching factor, and even more, GHC give you all the following for free:
-- With StandaloneDeriving, DeriveFunctor, DeriveFoldable, DeriveTraversable
deriving instance Functor (Vec k)
deriving instance Foldable (Vec k)
deriving instance Traversable (Vec k)
deriving instance Functor (Tree k)
deriving instance Foldable (Tree k)
deriving instance Traversable (Tree k)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39870813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: EVP AES Encryption on PSP I am trying to make a MMORPG for PSP and I will be encrypting al data sent over the network in some form. I have chosen AES for this.
I have this code:
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext){
int len;
int ciphertext_len;
/* Create and initialise the context */
EVP_CIPHER_CTX_init(&ctx);
appendLog("CTX Init", LOG_CRYPTO);
/* Initialise the encryption operation. IMPORTANT - ensure you use a key
* and IV size appropriate for your cipher
* In this example we are using 256 bit AES (i.e. a 256 bit key). The
* IV size for *most* modes is the same as the block size. For AES this
* is 128 bits */
if(1 != EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, key, iv))
printLastError("2");
appendLog("Encrypt started", LOG_CRYPTO);
/* Provide the message to be encrypted, and obtain the encrypted output.
* EVP_EncryptUpdate can be called multiple times if necessary
*/
if(1 != EVP_EncryptUpdate(&ctx, ciphertext, &len, plaintext, plaintext_len))
printLastError("3");
ciphertext_len = len;
appendLog("Mid encrypt", LOG_CRYPTO);
/* Finalise the encryption. Further ciphertext bytes may be written at
* this stage.
*/
if(1 != EVP_EncryptFinal_ex(&ctx, ciphertext + len, &len)) printLastError("4");
ciphertext_len += len;
appendLog("Encrypt final", LOG_CRYPTO);
/* Clean up */
EVP_CIPHER_CTX_cleanup(&ctx);
appendLog("CTX Cleanup", LOG_CRYPTO);
return ciphertext_len;
}
It freezes my PSP after writing "Mid encrypt" to the logs. I was wondering if there is anything noticeably wrong with this code. I am using openSSL v0.9.7j for PSP.
The original AES encrypt code:
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext){
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())) exit(0);
/* Initialise the encryption operation. IMPORTANT - ensure you use a key
* and IV size appropriate for your cipher
* In this example we are using 256 bit AES (i.e. a 256 bit key). The
* IV size for *most* modes is the same as the block size. For AES this
* is 128 bits */
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
exit(0);
/* Provide the message to be encrypted, and obtain the encrypted output.
* EVP_EncryptUpdate can be called multiple times if necessary
*/
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
exit(0);
ciphertext_len = len;
/* Finalise the encryption. Further ciphertext bytes may be written at
* this stage.
*/
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) exit(0);
ciphertext_len += len;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
The PSPSDK openSSL does not have functions EVP_CIPHER_CTX_new() or EVP_CIPHER_CTX_free() and my EVP_CIPHER_CTX is declared globally and not in the function anymore.
My function call:
char *newS;
char AESKey[32];
char IV[16];
sprintf(AESKey, "12345678901234567890123456789012");
sprintf(IV, "1234567890123456");
encrypted_length = encrypt("HelloFromPSP", strlen("HelloFromPSP"), AESKey, IV, newS);
Can anyone help me figure out why the EVP_EncryptFinal_ex is frezing?
EDIT: Somehow managed to fix by going back to my old code(which was also freezing, odd)
char encrypted[4098]; //Could be smaller but is this size because it holds RSA data at some points in the code
char AESKey[32]; //Recieved from server, no sprintf filling this
char IV[16]; //Recieved from server, no sprintf filling this
encrypted_length = encrypt("HelloFromPSP", strlen("HelloFromPSP"), AESKey, IV, encrypted);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26352051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In Java, I can't add code after the return statement in a method I'm new at Java, I'm learning about methods with a return statement.
My IDE says:
This method must return a result of type boolean
However my method returns only boolean values. How to fix that ?
public class Test {
public static void main(String[] aargs) {
debug(4, 5);
}
public static boolean debug(int a, int b) {
if(a+b == 12) {
return true;
}else if(a+b == 18){
return false;
}
a = 8;
}
}
A: It is the design pattern of java. We cannot write any code after return statement. If you are trying to compile with this code, compilation will fail. It is same for throwing exception.
This is because after return or throwing exception statement the control will goes to the caller place. So those lines cannot be executed.
In your case you must return some Boolean values.
Code should be like this,
public static boolean debug(int a, int b) {
boolean flag = false;
if(a+b == 12) {
flag = true;
}else if(a+b == 18){
flag = false;
}
a = 8;
return flag;
}
A: You don't have any code after a return. The warning is saying you're missing a return
Note: It's not recommended to alter your parameters a = 8;, but if neither your if statements are entered, you must return something. In this case true or false after that line
You might also want to capture the result of debug(4, 5);
A: The compiler is trying to tell you (in its own way) that the else case (a+b != 12 && a+b != 18) is falling through to the a=8 line and that branch of code is missing a return statement.
Java compiler is extremely smart with program flow analysis, so when it tells something is wrong then something is indeed wrong.
A: Every possible execution path should end with a return statement.
In this case, not all your paths return a value. If a+b is neither 12 nor 18, it'll fall through to the line a=8. That is not followed by a return statement, it just falls through to the end of the method. The compiler doesn't know what it should return in this case, so it issues an error.
A: Think what happens if you call debug(0, 0). Neither of the if statements are executed so the debug method is not returning nothing.
You must return some boolean value in each possible ramification.
A: What will return if the both the if the condition fails?. The code is not returning anything if both if the condition fails. So you should return something for that. You must return value for every condition possible.
A: Return will be the last statement of your method if you want to return any value. Your method need to return some value here.
Lets take a scenario : What if both your if else condition is wrong then what will your method return.
A: you can write a =8; inside else block.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52628784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Write a function that reads line by line from the console and prints the number of characters for each line loaded Write a function that reads line by line from the console and prints the number of characters for each line loaded, The maximum length of the line being read should be 20 characters.
I have someting that just goes throught loop and print over and over to input string.
I'm having problem with - Print number of characters after each user input and set max character input to 20 for exampe. Someone to help me?
char str[str_size];
int alp, digit, splch, i;
alp = digit = splch = i = 0;
printf("\n\nCount total number of alphabets, digits and special characters :\n");
printf("--------------------------------------------------------------------\n");
do {
printf("Input the string : ");
fgets(str, sizeof str, stdin);
} while (str[i] != '\0');
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
{
alp++;
}
else if (str[i] >= '0' && str[i] <= '9')
{
digit++;
}
else
{
splch++;
}
i++;
printf("Number of Alphabets in the string is : %d\n", alp + digit + splch);
}
A: I do not understand what you do with do while loop in your code. So i just propose another loop for your case. I'm not sure but hope that code is what you want.
int main() {
char str[22];
int alp, digit, splch, i;
printf("\n\nCount total number of alphabets, digits and special characters :\n");
printf("--------------------------------------------------------------------\n");
printf("Input the string : ");
while (fgets(str, sizeof str, stdin)){
alp = digit = splch = 0;
for (i = 0; i < strlen(str); i++ ) {
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
{
alp++;
}
else if (str[i] >= '0' && str[i] <= '9')
{
digit++;
}
else if(str[i] != '\n')
{
splch++;
}
}
printf("alp = %d, digit = %d, splch = %d\n", alp, digit, splch);
printf("Input the string : ");
}
return 0;
}
OT, for determine the alpha or digit, you can use isdigit() and isalpha() functions. It's more simple than something you used in your code.
A: It seems the program can look the following way
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
enum { str_size = 22 };
char str[str_size];
puts( "\nCount total number of alphabets, digits and special characters");
puts( "--------------------------------------------------------------");
while ( 1 )
{
printf( "\nInput a string less than or equal to %d characters (Enter - exit): ",
str_size - 2 );
if ( fgets( str, str_size, stdin ) == NULL || str[0] == '\n' ) break;
unsigned int alpha = 0, digit = 0, special = 0;
// removing the appended new line character by fgets
str[ strcspn( str, "\n" ) ] = '\0';
for ( const char *p = str; *p != '\0'; ++p )
{
unsigned char c = *p;
if ( isalpha( c ) ) ++alpha;
else if ( isdigit( c ) ) ++digit;
else ++special;
}
printf( "\nThere are %u letters, %u digits and %u special characters in the string\n",
alpha, digit, special );
}
return 0;
}
The program output might look like
Count total number of alphabets, digits and special characters
--------------------------------------------------------------
Input a string less than or equal to 20 characters (Enter - exit): April, 22, 2020
There are 5 letters, 6 digits and 4 special characters in the string
Input a string less than or equal to 20 characters (Enter - exit):
If the user will just press the Enter key the loop will finish.
Pay attention to that the program considers white space and punctuation characters as special characters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61370288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Most efficient way to strip comments from a string javascript I am looking for an efficient way to strip HTML comments from a string representation of HTML:
<div>
<!-- remove this -->
<ul>
<!-- and this -->
<li></li>
<li></li>
</ul>
</div>
I do not want to convert the string to actual nodes, the content is originally a string and the filesize is around 600mb.
Curious if anyone has had this problem before and found an efficient, and easily generalized solution.
A: assuming the variable s represents your html string, a RexExp replace as follows should work just fine.
s = s.replace(/<!--[\s\S]+?-->/g,"");
Variable s should now have comments removed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17793077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Asynchronous Add/Update save method not updating I am building a .NET page for a project that adds a new City and State for a new user or updates the City and state if their ID is already in the database. Everything is working fine except for the fact that if a past user clicks submit to update their information, an entirely new entry is added to the database.
I have created the method already in the repository listed below.
public async Task<LocationViewModel> SaveLocationAsync(LocationViewModel model)
{
try
{
var location = new Location()
{
City = model.City,
State = model.State
};
if (model.Id != 0)
{
location.Id = model.Id;
}
_dbcontext.Location.AddOrUpdate(location);
await _dbcontext.SaveChangesAsync();
return model;
}
catch (Exception ex)
{
model.Error = true;
model.ErrorMessages = new List<string>()
{
string.Format("Something went wrong - Message: {0} \n Stack Trace: {1}", ex.Message,
ex.StackTrace)
};
return model;
}
}
I have also built a controller that saves and updates existing records asynchronously shown below.
[System.Web.Mvc.AllowAnonymous]
[System.Web.Http.HttpPost]
public async Task<LocationViewModel> SaveLocationApiAsync(LocationViewModel model)
{
var result = new LocationViewModel();
if (ModelState.IsValid)
{
result = await _locationRepository.SaveLocationAsync(model);
}
return result;
}
In addition, I have added added all of my routes and references.
Why is a new entry put in the database instead of the current one updating? The Javascript is shown below.
self.Submit = function () {
if (self.errors().length !== 0) {
self.errors.showAllMessages();
return;
}
if (isNumber(locationId)) {
self.Location().LocationId(locationId);
swal("Success", "Thank you for your submission \nYour information has been updated.", "success");
}
var newData = ko.mapping.toJSON(self.Location());
var url = "/Admin/SaveLocationApiAsync/Post/";
$.ajax({
url: url,
method: "POST",
data: newData,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (result.Error === true) {
swal("Error", result.ErrorMessages.join('\n'), "error");
} else {
//TOdo
}
},
error: function () {
swal("Error", "Something went wrong.\nPlease contact help.", "error");
}
});
};
I apologize if it is a lot. I have checked everything repeatedly and have fixed all bugs. I am out of ideas.
Thanks in advance.
A: Your url looks to the controller action seems incorrect. You have var url = "/Admin/SaveLocationApiAsync/Post/"; when it should be var url = "/Admin/SaveLocationApiAsync";
Another approach to getting the correct url would be:
var url = '@Url.Action("SaveLocationApiAsync", "<ControllerName>")';
Also, in your ajax error handler you can get the HTTP status code and error message, which would help.
error: function (jqXHR, textStatus, errorThrown) {
swal("Error", "Something went wrong.\nPlease contact help.", "error");
}
EDIT:
I should have prefaced that using Url.Action works when your JavaScript is in a view (assuming Razor view in this case).
Fiddler is great tool to use when debugging ajax calls.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34969979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Networked Aframe - Screen Sharing Bug While developing a multi-user VR room with networked-aframe, i run into a bug with the screen sharing option simmilar to the one in the file: /examples/basic-multi-streams.html
I've tried different approaches and tests but couldn't get that one fixed.
The networked-aframe repo:
https://github.com/networked-aframe/networked-aframe
There is also a thread about this bug on github:
https://github.com/networked-aframe/networked-aframe/issues/299
Here you can find the example file where the bug exists:
https://naf-examples.glitch.me/basic-multi-streams.html
There is a note in this example file describing the bug:
Known issues with this demo, some cases are not handled:
- If participant A shares their screen, the partipant B sees the other participant's screen.
When participant A stops their screen share, the other participant will see a frozen screen, the last image received.
- If participant A starts screen share, stops, and restarts the screen share, the other participant won't see it.
Here is the full repo with all the example source files.
https://glitch.com/edit/#!/remix/naf-examples
I would love to fix this issue so the users could make presentations of their screen content easily in the VR scene.
Thanks for any help in advance!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70309606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: groupby count same values in two columns in pandas? I have the following Pandas dataframe:
name1 name2
A B
A A
A C
A A
B B
B A
I want to add a column named new which counts name1 OR name2 keeping the merged columns (distinct values in both name1 and name2). Hence, the expected output is the following dataframe:
name new
A 7
B 4
C 1
I've tried
df.groupby(["name1"]).count().groupby(["name2"]).count(), among many other things... but although that last one seems to give me the correct results, I cant get the joined datasets.
A: You can use value_counts with df.stack():
df[['name1','name2']].stack().value_counts()
#df.stack().value_counts() for all cols
A 7
B 4
C 1
Specifically:
(df[['name1','name2']].stack().value_counts().
to_frame('new').rename_axis('name').reset_index())
name new
0 A 7
1 B 4
2 C 1
A: Let us try melt
df.melt().value.value_counts()
Out[17]:
A 7
B 4
C 1
Name: value, dtype: int64
A: Alternatively,
df.name1.value_counts().add(df.name2.value_counts(), fill_value=0).astype(int)
gives you
A 7
B 4
C 1
dtype: int64
A: Using Series.append with Series.value_counts:
df['name1'].append(df['name2']).value_counts()
A 7
B 4
C 1
dtype: int64
value_counts converts the aggregated column to index. To get your desired output, use rename_axis with reset_index:
df['name1'].append(df['name2']).value_counts().rename_axis('name').reset_index(name='new')
name new
0 A 7
1 B 4
2 C 1
A: python Counter is another solution
from collections import Counter
s = pd.Series(Counter(df.to_numpy().flatten()))
In [1325]: s
Out[1325]:
A 7
B 4
C 1
dtype: int64
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59546513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Character stuck underneath world So I've been able to use bullet physics to bind a rigid body to a cube and have it fall while being rendering, but when I tried to "attach" a rigid body to the player it got the player stuck underneath the world, unable to move.
I was originally going use kinematic bodies but after research and trying them seems like their incomplete.
My question in the end would be am I handling the data correctly to update my camera's position and also changing the rigid bodies.
-Below is the code I use create the rigid body, and below that is the code to update both of their positions.
btTransform t;
t.setIdentity();
t.setOrigin(btVector3(0, 0, 0));
btCapsuleShape* player = new btCapsuleShape(1, 1);
btVector3 inertia(1, 0, 0);
player->calculateLocalInertia(20, inertia);
btMotionState* motion = new btDefaultMotionState(t);
btRigidBody::btRigidBodyConstructionInfo info(20, motion, player, inertia);
PlayerBody = new btRigidBody(info);
world->addRigidBody(PlayerBody);
bodies.push_back(PlayerBody);
PlayerBody->setAngularVelocity(btVector3(0,0,0));
And the code to update the position of therigid body and camera
gCamera.GetInput(window);
btVector3 t;
t = physics.PlayerBody->getLinearVelocity();
gCamera.position.x = t.getX();
gCamera.position.y = t.getY();
gCamera.position.z = t.getZ();
//Set
physics.PlayerBody->setLinearVelocity(btVector3(gCamera.position.x, gCamera.position.y, gCamera.position.z));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22133164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Outline not working properly on Firefox I am trying to put some custom outline in order to reach some web accessibility suggestions. But I can't make with Firefox.
This is how it looks on Chrome:
And that icon is actually an anchor.
On Firefox, it is only outlining the whole document, like this:
On Firefox it is outlining the document and in the next tab it focuses on the search bar again.
Here you may see a Codepen I did: https://codepen.io/maketroli/pen/owRWag
Or a code Snippet:
// This function sets outline on tab and removes it on click
var elArr = Array.from ? Array.from(document.querySelectorAll("a")) : Array.prototype.slice.call(document.querySelectorAll("a")); // Fallback for IE because as usual nothing works there!
elArr.forEach(function(a) {
return a.addEventListener("click", function() {
$(a).addClass("no-outline").removeClass('custom-outline');
});
});
elArr.forEach(function(a) {
return a.addEventListener("focus", function() {
$(a).removeClass("no-outline").addClass('custom-outline');
});
});
// END
CSS
.wrapper {
margin-top: 50px;
display: flex;
}
a {
border: 1px solid red;
padding: 20px;
margin-right: 10px;
}
.no-outline {
outline: 0 !important;
}
.custom-outline:focus {
outline: 2px dotted blue !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<a href="#">one</a>
<a href="#">two</a>
<a href="#">three</a>
</div>
Any suggestions?
A: Are you using a mac? OS X has a system-wide preference which Firefox honors (Chrome does not) that changes the behavior of the tab key in windows and dialogs. It is probably set to tab only to text boxes -- skipping anchor tags.
Search System Preferences for "full keyboard access" and you'll find it, or refer to the screenshot below:
.
Set to "All Controls" to make Firefox behave like Chrome on OSX.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45157366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to retrieve GCP Stackdriver human readable logs? GCP stackdriver logging api provides the log messages in json format. But in the console, under "Home", under the "Activity" tab, it provides the logs in human readable format
[email protected] has retrieved data from BigQuery table bq_table_name
Is there a way to get these Human readable logs instead of the complete JSON log messages?
A: Unfortunately there's no way to get the templated message for audit logs provided by http://console.cloud.google.com/home/activity apart from the UI itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56573686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to check if the .sig file is correct ? I issued the following commands to create a signature for a file (linux kernel) :
*
*openssl req -newkey rsa -keyout codesign.key -out codesign.req
*openssl ca -config ca.cnf -extensions codesigning -in codesign.req -out codesign.crt
*openssl cms -sign -binary -noattr -in vmlinuz -signer codesign.crt -inkey codesign.key -certfile ca.crt -outform DER -out vmlinuz.sig
The ca.cnf file is for my own private CA infrastructure and it has digitalSignature key usage extension and the codeSigning extended key usage extension enalbed.
How can i verify that the vmlinuz.sig is the signature of the vmlinuz ??
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36442594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: DIH in SOLR based on primary key of a table currently am using DIH for pulling data from MSSQL server to SOLR. Where in am using dataimporter.last_index_time to pull the records which are into database only after last_index_time. So i was exploring if there are any other option for DIH to use instead of using last_index_time may be something like last_pk_id.
Is such option available? could anyone let me know.
A: not provided by Solr itself.
But nothing prevents you from doing this:
*
*set your DIH sql for the delta like this:
WHERE (last_pk_id > '${dataimporter.request.LAST_PK_ID}')
*when you run some indexing, store, outside Solr, the last_pk_id value you indexed, say 333.
*next time you need to delta index, add to your request
...&clean=false&LAST_PK_ID=333
*store your new LAST_PK_ID (you can query solr for this)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43060493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating test payment gateway with react and stripe Hey i am working on payment gateway on my website maded with react so i am using stripe js (for test) i have wraped my payment component in Elements in app.js
const promise = loadStripe("my stipe publishable key")
<Route path='/payment'>
<Header/>
<Elements stripe={promise}>
<Payment/>
</Elements>
</Route>
and my code in payment component is
import React, { useEffect, useState } from 'react';
import CheckoutProduct from './CheckoutProduct';
import "./Payment.css";
import { useStateValue } from "./StateProvider";
import { Link, useHistory } from "react-router-dom";
import { CardElement, useStripe, useElements } from "@stripe/react-stripe-js";
import CurrencyFormat from "react-currency-format";
import { getBasketTotal } from './Reducer';
import axios from "./axios"
function Payment() {
const [{ basket, user }, dispatch] = useStateValue();
const history = useHistory();
const stripe = useStripe();
const elements = useElements();
const [succeeded, setSucceeded] = useState(false);
const [processing, setProcessing] = useState("");
const [error, setError] = useState(null);
const [disabled, setDisabled] = useState(true);
const [clientSecret, setClientSecret] = useState(true);
useEffect(() => {
// generate the special stripe secret which allows us to charge a customer
const getClientSecret = async () => {
const response = await axios({
method: 'post',
url: `/payment/create?total=${getBasketTotal(basket) * 100}`
});
setClientSecret(response.data.clientSecret)
}
getClientSecret();
}, [basket])
console.log('THE SECRET IS >>>', clientSecret)
const handleSubmit = async (event) => {
event.preventDefault();
setProcessing(true);
const payload = await stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: elements.getElement(CardElement)
}
}).then(({ paymentIntent }) => {
//paymentIntent = Payment confirmation
setSucceeded(true);
setError(null)
setProcessing(false)
history.replace('/order')
})
};
const handleChange = event => {
// This will listen for changes in the CardElement
// and then display any errors as the customer types their card details
setDisabled(event.empty);
setError(event.error ? event.error.message : "");
}
return (
<div className="payment">
<div className="payment__container">
<h1>
Checkout (<Link to="/checkout">{basket?.length} items</Link>)
</h1>
{/* Payment section - delivery address*/}
<div className="payment__section">
<div className="payment__title">
<h1>Delivery address</h1>
</div>
<div className="payment__address">
<p>{user?.email}</p>
<p>123 React Lane</p>
<p>Los Angeles, CA</p>
</div>
</div>
{/* Payment section - Review Items */}
<div className="payment__section">
<div className="payment__title">
<h1>Review items and delivery</h1>
</div>
<div className="payment__items">
{basket.map(item => (
<CheckoutProduct
id={item.id}
title={item.title}
image={item.image}
price={item.price}
rating={item.rating}
/>
))}
</div>
</div>
{/* Payment section - Payment method */}
<div className="payment__section">
<div className="payment__title">
<h3>Payment Method</h3>
</div>
<div className="payment__details">
<form onSubmit={handleSubmit}>
<CardElement onChange={handleChange} />
<div className="payment__priceContainer">
<CurrencyFormat
renderText={(value) => (
<>
<h3>Order Total: {value}</h3>
</>
)}
decimalScale={2}
value={getBasketTotal(basket)}
displayType={"text"}
thousandSeparator={true}
prefix={"$"}
/>
<button disabled={processing || disabled ||succeeded}>
<span>{processing ? <p>Processing</p> :"Buy Now" }</span>
</button>
</div>
{error && <div>{error}</div>}
</form>
</div>
</div>
</div>
</div>
)
}
export default Payment
and i am using firebase hosting as backend so my running command firebase init a folder is created named function ("because i selected function option after running firebase init")and for axios i have written this code in my axios.js file
import axios from "axios";
const instance = axios.create({
baseURL: "http://localhost:5001/*****/******/api"
});
export default instance;
and baseURL used here i get by writing some code in index.js in function folder created by running firebase init the code i wrote in index.js is
const functions = require('firebase-functions');
const express = require("express");
const cors = require("cors");
const stripe = require("stripe")('my stripe secret key here')
//API
//App config
const app = express();
//Middlewares
app.use(cors({origin: true}));
app.use(express.json());
//API routes
app.get('/', (request, response) => response.status(200).send('hello world'))
app.post('/payment/create', async(request, response) => {
const total = request.query.total;
console.log('Payment Request Recieved BOOM!!! for this amount', total)
const paymentIntent = await stripe.paymentIntents.create({
amount: total,
currency: "usd",
});
//OK Created
response.status(201).send({
clientSecret: paymentIntent.client_secret,
})
})
//Listen command
exports.api = functions.https.onRequest(app)
from here i got my api that is use as base url in terminal functions[api]: http function initialized (http://localhost:5001/abcdabcdabcd/abcabcd/api).
now all thing is setup i got on my website running on local host then when i go to /payment then is console it is comming
THE SECRET IS >>> true
THE SECRET IS >>> true
THE SECRET IS >>> true
THE SECRET IS >>> pi_fgdhfdgsdfgfg_secret_fgsdgfdgdfgdg
THE SECRET IS >>> pi_fgdhfdgsdfgfg_secret_fgsdgfdgdfgdg
and whenever i enter 424242.... (used to test in stripe js) so whenever i type first 42 then my THE SECRET IS >>> pi_fgdhfdgsdfgfg_secret_fgsdgfdgdfgdg is repeating 3 times i have no problem with this but when i click on buy now button yes it is redirecting me to /orders page which i have not maded so it redirecting me on home page but when i check my account on stripe js (test account)no test money is added there and in my console it is comming:-
THE SECRET IS >>> pi_fgdhfdgsdfgfg_secret_fgsdgfdgdfgdg
THE SECRET IS >>> pi_fgdhfdgsdfgfg_secret_fgsdgfdgdfgdg
THE SECRET IS >>> pi_fgdhfdgsdfgfg_secret_fgsdgfdgdfgdg
THE SECRET IS >>> pi_fgdhfdgsdfgfg_secret_fgsdgfdgdfgdg
THE SECRET IS >>> pi_fgdhfdgsdfgfg_secret_fgsdgfdgdfgdg
**shared-a0382af03b7a06522c9bc0f5c75b552d.js:1 POST https://api.stripe.com/v1/payment_intents/pi_fgdhfdgsdfgfg/confirm 400***
(anonymous) @ shared-a0382af03b7a06522c9bc0f5c75b552d.js:1
f @ shared-a0382af03b7a06522c9bc0f5c75b552d.js:1
Q @ controller-207a0a1b39a190f1e22c08ab25c9f3ee.js:1
$ @ controller-207a0a1b39a190f1e22c08ab25c9f3ee.js:1
rt @ controller-207a0a1b39a190f1e22c08ab25c9f3ee.js:1
(anonymous) @ controller-207a0a1b39a190f1e22c08ab25c9f3ee.js:1
Promise.then (async)
confirmPaymentIntent @ controller-207a0a1b39a190f1e22c08ab25c9f3ee.js:1
(anonymous) @ controller-207a0a1b39a190f1e22c08ab25c9f3ee.js:1
(anonymous) @ controller-207a0a1b39a190f1e22c08ab25c9f3ee.js:1
Gt._respondUsingPromise @ controller-207a0a1b39a190f1e22c08ab25c9f3ee.js:1
Gt.handleAction @ controller-207a0a1b39a190f1e22c08ab25c9f3ee.js:1
value @ controller-207a0a1b39a190f1e22c08ab25c9f3ee.js:1
(anonymous) @ controller-207a0a1b39a190f1e22c08ab25c9f3ee.js:1
THE SECRET IS >>> pi_fgdhfdgsdfgfg_secret_fgsdgfdgdfgdg
THE SECRET IS >>> pi_fgdhfdgsdfgfg_secret_fgsdgfdgdfgdg
THE SECRET IS >>> pi_fgdhfdgsdfgfg_secret_fgsdgfdgdfgdg
please tell me how to solve this
A: A few things to consider here:
*
*By putting your call to /payment/create in your useEffect hook, you are creating a new PaymentIntent every time your component updates. This is quite inefficient and will leave you with many unused PaymentIntents, cluttering up your Stripe account. Instead you should only create the PaymentIntent when your user intends to purchase something, like when they click the "buy" button.
*You are passing in the total amount to be charged from the client. This means that it is trivial for a malicious user to add many things to their basket and then edit that request to ensure that they are charged a much lower amount than you expect. All logic pertaining to calculating amount totals should be done on the server, not the client.
*Your server logs don't show any failure in actual payments. Since you are confirming on the client, it's possible that you are getting an error there but redirecting before you see the error. You should listen for the error object instead of immediately redirecting:
stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: elements.getElement(CardElement)
}
}).then((result) => {
if (result.error) {
// payment failed, do something with the error
console.log(result.error.message);
} else {
setSucceeded(true);
setError(null)
setProcessing(false)
history.replace('/order')
});
You can also inspect your Stripe logs by looking at your dashboard: https://dashboard.stripe.com/test/logs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64399872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to seprate alphanumeric string into number and alphabets For example string is JD85DS8796
There are 4 text views and I want to set each text view like:
In 1st text-view JD, in 2nd text-view 85, in 3rd text-view DS, in 4th text-view 8796.
A: First of all, yes there is a crazy regex you can give to String.split:
"[^A-Z0-9]+|(?<=[A-Z])(?=[0-9])|(?<=[0-9])(?=[A-Z])"
What this means is to split on any sequence of characters which aren't digits or capital letters as well as between any occurrence of a capital letter followed by a digit or any digit followed by a capital letter. The trick here is to match the space between a capital letter and a digit (or vice-versa) without consuming the letter or the digit. For this we use look-behind to match the part before the split and look-ahead to match the part after the split.
However as you've probably noticed, the above regex is quite a bit more complicated than your VALID_PATTERN. This is because what you're really doing is trying to extract certain parts from the string, not to split it.
So finding all the parts of the string which match the pattern and putting them in a list is the more natural approach to the problem. This is what your code does, but it does so in a needlessly complicated way. You can greatly simplify your code, by simply using Pattern.matcher like this:
private static final Pattern VALID_PATTERN = Pattern.compile("[0-9]+|[A-Z]+");
private List<String> parse(String toParse) {
List<String> chunks = new LinkedList<String>();
Matcher matcher = VALID_PATTERN.matcher(toParse);
while (matcher.find()) {
chunks.add( matcher.group() );
}
return chunks;
}
If you do something like this more than once, you might want to refactor the body of this method into a method findAll which takes the string and the pattern as arguments, and then call it as findAll(toParse, VALID_PATTERN) in parse.
A: Try this way, this will gives you digits value, then remaining string can be separated as string
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("JD85DS8796");
m.find();
String inputInt = m.group();
textview.setText(inputInt);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20492788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Table '[database-name].sessions' doesn't exist - using express-session Here is some sample code that outlines my issue. I'm trying to get express-session / connect-session-sequelize to work for a website with login functionalities.
However, when I try to call my POST request, I get the following error:
I can only assume it's trying to store session data onto my database, but cannot find a table. I can bypass this by going in and creating the table manually with all the columns it wants, but I'm wondering if there's an issue in my code preventing the package from working properly (or if this is how it's supposed to work.)
require('dotenv').config({ path: './config/.env' })
const express = require('express')
const session = require('express-session')
const mysql = require('mysql2')
const Sequelize = require('sequelize')
const path = require('path')
const SequelizeStore = require('connect-session-sequelize')(session.Store)
const app = express()
const PORT = 9999
app.use(express.json())
app.use(express.static(path.join(__dirname, 'public')))
// Allowing connection to database in Workbench
const db = new Sequelize('somedatabase', 'root', process.env.PASSWORD, {
host: 'localhost',
dialect: 'mysql'
})
db.authenticate()
.then(() => {
console.log('Connected...')
}).catch(error => {
console.log('Failed to connect...', error)
})
// Setting up session
app.use(session({
secret: 'shhh',
store: new SequelizeStore({
db: db
}),
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 1000000
}
}))
// Sample model
const User = db.define('user', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
username: Sequelize.STRING,
password: Sequelize.STRING
})
// Sample request
app.post('/api/create', async (req, res) => {
const newUser = {
username: john,
password: verysecurepassword
}
await User.create(newUser)
})
app.listen(PORT, () => {
console.log(`Listening on localhost:${PORT}...`)
})
A: In this code, you are using several packages: express-session, which manages the session itself but delegates how the session is saved to connect-session-sequelize.
So the problem is that connect-session-sequelize is trying to save session data in the database, but it cannot because there is no table for sessions.
As written in the documentation of this package (https://www.npmjs.com/package/connect-session-sequelize):
If you want SequelizeStore to create/sync the database table for you, you can call sync() against an instance of SequelizeStore along with options if needed.
So try creating the store, attaching it to the session manager, and then
initializing it (I did not test this code):
// Setting up session
var myStore = new SequelizeStore({
db: db
});
app.use(
session({
secret: "shhh",
store: myStore,
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 1000000
}
})
);
myStore.sync();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69549436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Axios: Network Error and not sending request I am trying to send a get request with auth headers to api from Vue using axios.
When I try to send it, it gives me a Network Error with no info about it. I have also check network tab and the request is not sending at all.
Before I checked the url using postman and https://www.hurl.it/ and it worked as expected.
Also, I have sent a request to this api using axios to get a token.
Thank you.
const token = "token";
let options = {
method: 'GET',
url: 'http://smev.test-it-studio.ru/api/analytics/PortfolioStructure',
headers: {
'Authorization': `Bearer ${token}`
},
};
axios(options).then((data) => {
console.log(data);
}).catch((error) => {
console.log(error.config);
});
EDIT: Here is the error I get:
Error
columnNumber: 15
config: {…}
adapter: function xhrAdapter()
baseURL: "http://smev.test-it-studio.ru"
data: undefined
headers: Object { Accept: "application/json", Authorization: "Bearer token"}
maxContentLength: -1
method: "GET"
timeout: 0
transformRequest: Object [ transformRequest() ]
transformResponse: Object [ transformResponse() ]
url: "http://smev.test-it-studio.ru/api/analytics/PortfolioStructure"
validateStatus: function validateStatus()
xsrfCookieName: "XSRF-TOKEN"
xsrfHeaderName: "X-XSRF-TOKEN"
__proto__: Object { … }
fileName: "http://uralsib-lk.dev/dist/build.js"
lineNumber: 19074
message: "Network Error"
response: undefined
stack: "createError@http://uralsib-lk.dev/dist/build.js:19074:15\nhandleError@http://uralsib-lk.dev/dist/build.js:18962:14\n"
__proto__: Object { … }
build.js:18589:24
A: I had this problem in rails. It was cors as mentioned above.
The rails server won't show logs so it looks like axios isn't sending the request at all.
Thankfully it's an easy fix.
For rails add this to your gemfile:
gem 'rack-cors'
Then add this to config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0,Rack::Cors do
allow do
origins 'localhost:8080'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
Note: Update orgins to the origin of your front end app.
A: With the help from Soleno, I found out that it was AdBlock what was blocking the request.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48226030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to find the first incident of any signature in a list/array within an email? I want to give credit to an agent, if they're the one that sent the message, but only if their signature is at the top of the email.
Here is what I have. The search order is off. The code searches for one name at a time, and clear through the document. I need it to search for All names, the first one that hits in the body of the email.
Sub CountOccurences_SpecificText_In_Folder()
Dim MailItem As Outlook.MailItem
Dim strSpecificText As String
Dim tmpStr As String
Dim x As Integer
Dim Count As Integer
Dim HunterCnt As Integer
Dim SunmolaCnt As Integer
Dim RodriguezCnt As Integer
Dim MammedatyCnt As Integer
Dim MitchellCnt As Integer
Dim TannerCnt As Integer
Dim TAYLORCnt As Integer
Dim WilsonCnt As Integer
Dim WilliamsCnt As Integer
Dim GrooverCnt As Integer
Dim TyreeCnt As Integer
Dim ChapmanCnt As Integer
Dim LukerCnt As Integer
Dim KlinedinstCnt As Integer
Dim HicksCnt As Integer
Dim NATHANIALCnt As Integer
Dim SkinnerCnt As Integer
Dim SimonsCnt As Integer
Dim AgentNames(14) As Variant
AgentNames(0) = "Simons"
AgentNames(1) = "Skinner"
AgentNames(2) = "Mammedaty"
AgentNames(3) = "Hunter"
AgentNames(4) = "Sunmola"
AgentNames(5) = "Rodriguez"
AgentNames(6) = "Mitchell"
AgentNames(7) = "Tanner"
AgentNames(8) = "Taylor"
AgentNames(9) = "Wilson"
AgentNames(10) = "Williams"
AgentNames(11) = "Groover"
AgentNames(12) = "Tyree"
AgentNames(13) = "Chapman"
AgentNames(14) = "Luker"
x = 0
While x < ActiveExplorer.Selection.Count
x = x + 1
Set MailItem = ActiveExplorer.Selection.item(x)
tmpStr = MailItem.Body
For Each Agent In AgentNames
If InStr(tmpStr, Agent) <> 0 Then
If Agent = "Assunta" Then
HunterCnt = HunterCnt + 1
GoTo skip
End If
If Agent = "Sunmola" Then
SunmolaCnt = SunmolaCnt + 1
GoTo skip
End If
If Agent = "Rodriguez" Then
RodriguezCnt = RodriguezCnt + 1
GoTo skip
End If
If Agent = "Mammedaty" Then
MammedatyCnt = MammedatyCnt + 1
GoTo skip
End If
If Agent = "Mitchell" Then
MitchellCnt = MitchellCnt + 1
GoTo skip
End If
If Agent = "Tanner" Then
TannerCnt = TannerCnt + 1
GoTo skip
End If
If Agent = "Taylor" Then
TAYLORCnt = TAYLORCnt + 1
GoTo skip
End If
If Agent = "Wilson" Then
WilsonCnt = WilsonCnt + 1
GoTo skip
End If
If Agent = "Williams" Then
WilliamsCnt = WilliamsCnt + 1
GoTo skip
End If
If Agent = "Groover" Then
GrooverCnt = GrooverCnt + 1
GoTo skip
End If
If Agent = "Tyree" Then
TyreeCnt = TyreeCnt + 1
GoTo skip
End If
If Agent = "Chapman" Then
ChapmanCnt = ChapmanCnt + 1
GoTo skip
End If
If Agent = "Luker" Then
LukerCnt = LukerCnt + 1
GoTo skip
End If
If Agent = "Hicks" Then
HicksCnt = HicksCnt + 1
GoTo skip
End If
End If
Next
skip:
Count = Count + 1
Wend
MsgBox "Found " & vbCrLf & "Hunter Count: " & HunterCnt & vbCrLf & "Sunmola Count: " & SunmolaCnt & vbCrLf & "Rodriguez Count: " & RodriguezCnt & vbCrLf & "Mammedaty Count: " & MammedatyCnt & vbCrLf & "Mitchell Count: " & MitchellCnt & vbCrLf & "Tanner Count: " & TannerCnt & vbCrLf & "Taylor Count: " & TAYLORCnt & vbCrLf & "Wilson Count: " & WilsonCnt & vbCrLf & "Williams Count: " & WilliamsCnt & vbCrLf & "Groover Count: " & GrooverCnt & vbCrLf & "Tyree Count: " & TyreeCnt & vbCrLf & "Chapman Count: " & ChapmanCnt & vbCrLf & "Luker Count: " & LukerCnt & vbCrLf & " in: " & Count & " emails"
End Sub
A: InStr returns positional information. While it is difficult to find the first occurrence of an array member within the text (you would need to build and compare matches), you can find the first position of each name then find which came first.
For example (untested)
Sub CountOccurences_SpecificText_In_Folder()
Dim MailItem As Outlook.MailItem
Dim i As Long, x As Long, position As Long, First As Long
Dim AgentNames() As String
AgentNames = Split("Simons,Skinner,Mammedaty,Hunter,Sunmola,Rodriguez,Mitchell,Tanner,Taylor,Wilson,Williams,Groover,Tyree,Chapman,Luker", ",")
Dim AgentCount(LBound(AgentNames) To UBound(AgentNames)) As Long
For i = LBound(AgentCount) To UBound(AgentCount)
AgentCount(i) = 0
Next i
For Each MailItem In ActiveExplorer.Selection
x = 0
For i = LBound(AgentNames) To UBound(AgentNames)
position = InStr(MailItem.Body, AgentNames(i))
If x > 0 Then
If position < x Then
x = position
First = i
End If
Else
If position > 0 Then
x = position
First = i
End If
End If
Next i
AgentCount(First) = AgentCount(First) + 1
Next MailItem
For i = LBound(AgentNames) To UBound(AgentNames)
Debug.Print AgentNames(i) & " Count: " & AgentCount(i)
Next i
End Sub
A: The idea in the previous answer may be better implemented like this:
Option Explicit
Sub CountOccurences_SpecificText_SelectedItems()
Dim objItem As Object
Dim objMail As MailItem
Dim i As Long
Dim j As Long
Dim x As Long
Dim position As Long
Dim First As Long
Dim AgentNames() As String
AgentNames = Split("Simons,Skinner,Mammedaty,Hunter,Sunmola,Rodriguez,Mitchell,Tanner,Taylor,Wilson,Williams,Groover,Tyree,Chapman,Luker", ",")
ReDim AgentCount(LBound(AgentNames) To UBound(AgentNames)) As Long
For j = 1 To ActiveExplorer.Selection.Count
Set objItem = ActiveExplorer.Selection(j)
' Verify before attempting to return mailitem poroperties
If TypeOf objItem Is MailItem Then
Set objMail = objItem
Debug.Print
Debug.Print "objMail.Subject: " & objMail.Subject
x = Len(objMail.Body)
For i = LBound(AgentNames) To UBound(AgentNames)
Debug.Print
Debug.Print "AgentNames(i): " & AgentNames(i)
position = InStr(objMail.Body, AgentNames(i))
Debug.Print " position: " & position
If position > 0 Then
If position < x Then
x = position
First = i
End If
End If
Debug.Print "Lowest position: " & x
Debug.Print " Current first: " & AgentNames(First)
Next i
If x < Len(objMail.Body) Then
AgentCount(First) = AgentCount(First) + 1
Debug.Print
Debug.Print AgentNames(First) & " was found first"
Else
Debug.Print "No agent found."
End If
End If
Next
For i = LBound(AgentNames) To UBound(AgentNames)
Debug.Print AgentNames(i) & " Count: " & AgentCount(i)
Next i
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64883724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SignalR - How to declaratively disable transport protocol on server Is it possible to declaratively disable some transport protocol like ForeverFrame in SignalR on the server side? I don't want to change any code but would like to do it in some config file...
I found how to do it code but as mentioned this is not an option for me: SignalR - How do I disable WebSockets
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40263141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Connecting DB with my Firefox OS app using JS I'm developing an app for Firefox OS and I need to retrieve/sent data from/to my DB. I also need to use this data in my logic implementation which is in JS.
I've been told that I cannot implement PHP in Firefox OS, so is there any other way to retrieve the data and use it?
PS: This is my first app that I'm developing, so my programming skills are kind of rough.
A: You should hold on the basic communication paradigms when sending/receiving data from/to a DB. In your case you need to pass data to a DB via web and application.
Never, ever let an app communicate with your DB directly!
So what you need to do first is to implement a wrapper application to give controlled access to your DB. Thats for example often done in PHP. Your PHP application then offers the interfaces by which external applications (like your FFOS app) can communicate with the DB.
Since this goes to very basic programming knowledge, please give an idea of how much you know about programming at all. I then consider offering further details.
A: You can use a local database in JS, e.g. PouchDB, TaffyDB, PersistenceJS, LokiJS or jStorage.
You can also save data to a backend server e.g. Parse or Firebase, using their APIs.
Or you can deploy your own backend storage and save data to it using REST.
A: It might be a bit harder to do than you expect but it can be easier than you think. Using mysql as a backend has serious implication. For example, mysql doesn't provide any http interfaces as far as I know. In other words, for most SQL based databases, you'll have to use some kind of middleware to connect your application to the database.
Usually the middleware is a server that publish some kind of http api probably in a rest way or even rpc such as JSONrpc. The language in which you'll write the middleware doesn't really matter. The serious problem you'll face with such variant is to restrict data. Prevent other users to access data to which they shouldn't have access.
There is also an other variant, I'd say if you want to have a database + synchronization on the server. CouchDB + PouchDB gives you that for free. I mean it's really easy to setup but you'll have to redesign some part of your application. If your application does a lot of data changes it might end up filling your disks but if you're just starting, it's possible that this setup will be more than enough.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28718049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google sheets -- format rows x color if column A is x/y/z value I have a google sheet and it looks something like this.
# | quant | percent
1 | 10 | 10%
2 | 5 | 5%
3 | 10 | 10%
...
22| 3 | 3%
Etc
What I want to do is for EACH row, paint columns A/B/C the same color as column A. Column A should be: Green if # < 5, Yellow if between 5 and 10. Red if >10.
Thus column A should look something like this but with all columns having the same color as this row:
Is this even possible
A: After an actual 2 hours of googling here's a rule that can use the fill handle to satisfy this
=IF($A:$A<=5, true)
And then adapt for between / greater than.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52104584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mapping the Rules & Metrics in Sonarqube I am trying to find out a way of mapping between Rules in SonarQube (Declared on Different Languages) and given lists of Metrics (Complexity, maintainability, Reliability, etc). Is there any way to find such categorization in Sonarqube!
A: Short Answer : There are no such mapping.
Some rules might rely on those metrics (for instance an issue can be raised if coverage is <= X% (even though it is better to rely on quality gate for this)) but those metrics are distinct from rules.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39071718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get attrs value in customview kotlin class when format="reference" I have created one CustomView class where I want to get drawable dynamically. So for that have created attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomView">
<attr name="myImage" format="reference"/>
</declare-styleable>
</resources>
And then set this attrs through xml file like below:
<com.example.myapplication.CustomView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:myImage="@drawable/my_icon"/>
Now I want to get this myImage value in my CustomView class how can i get it?
I have already tried many ways to get it by TypedValue and TypedArray but not able to get it.
val typedValue = TypedValue()
context.theme.resolveAttribute(R.attr.myImage, typedValue, true)
val imageResId = ContextCompat.getDrawable(context,typedValue.resourceId)
val typedArray =
context.theme.obtainStyledAttributes(attrs, R.styleable.CustomView, 0, 0)
val imageResId = typedArray.getResourceId(R.styleable.CustomView_myImage,0)
A: You are almost there, this is a working code:
val typedArray = context.obtainStyledAttributes(it, R.styleable.CustomView, 0, 0)
val image = typedArray.getResourceId(R.styleable.CustomView_ myImage, -1) // the -1 parameter could be your placeholder e.g. R.drawable.placeholder_image
and then you have the resource of your drawable that you can work with, as for the example:
imageView.setImageDrawable(ContextCompat.getDrawable(context, image))
or if you would like to get a drawable directly call:
val image = typedArray.getDrawable(R.styleable.CustomView_myImage)
but remember that this way your drawable might be null.
Enjoy coding!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71483453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Generate value not in mysql table I have used following query that use to generate random value not in mysql table.
SELECT FLOOR( RAND()*1000 + 50 ) AS temp FROM tempcode WHERE 'temp' NOT IN ( SELECT code FROM tempcode ) LIMIT 1
but when I reduce the value to RAND()*4 for checking purpose using dummy data that not functioning well.
SELECT FLOOR( RAND()*1000 + 50 ) AS temp FROM tempcode WHERE 'temp' NOT IN ( SELECT code FROM tempcode ) LIMIT 1
What would be the reason? Any suggestions to generate value not in mysql table?
A: This is not elegant, but it works as requested until all 1000 codes are used:
select x from
(select concat(hundreds, tens, ones) x from
(select 1 as ones union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9 union select 0) ones,
(select 1 as tens union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9 union select 0) tens,
(select 1 as hundreds union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9 union select 0) hundreds) thousand
where thousand.x not in
(select code from tempcode)
order by rand() limit 1;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29225032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: setState not updating React component state I have below in component's constructor:
constructor(props){
super(props);
this.state={
post: {},
deleteModal: false
}
}
I am updating the state as below in componentDidmount:
componentDidMount(){
fetch('https://snaptok.herokuapp.com/fetchPost/'+this.props.postId,{
method: 'GET'
}).then(response => {
if (response.ok) {
return response;
} else {
var error = new Error('Error ' + response.status + ': ' + response.statusText);
error.response = response;
throw error;
}
},
error => {
throw error;
}).then(res=>res.json()).then(res=>this.setState({
post: res
})).catch(err=>{console.log(err);})
}
This is the res object:
{"_id":"60c0ac493175c10014e178d4","author":"Vipul Tyagi","email":"[email protected]","uid":"0FGD6CWHi6YnaE7an0MW0z9yk7p1","title":"This is a title","description":"This is a description.","file":"","fileType":"","subGratis":"Cricket","dateOfPost":"9-6-2021","likes":0,"comments":[],"__v":0}
But in the render method, this.state.post is still {}. I can confirm that res is not empty object( I have checked in network tab).
I don't know what is the problem in my code, is it the right way to set state of an empty object.
Please help me to correct the error, if any, in my code.
Thank You.
EDIT:
I put componentWillUnmount in the above component and found that this component is getting unmounted for no reason. And then it is not getting mounted again.
A: I expect that the problem is in function context this.
May be you can try such that:
componentDidMount(){
const setState = this.setState;
fetch('https://snaptok.herokuapp.com/fetchPost/'+this.props.postId,{
method: 'GET'
}).then(response => {
if (response.ok) {
return response;
} else {
var error = new Error('Error ' + response.status + ': ' + response.statusText);
error.response = response;
throw error;
}
},
error => {
throw error;
}).then(res=>res.json()).then(res=>setState({
post: res
})).catch(err=>{console.log(err);})
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67904320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Netbeans to use pom.xml (Maven) instead of build.gradle (Gradle) Our team has a Netbeans 11.0 project that (at the root level) contains both a pom.xml file and a build.gradle file. When opening the project within Netbeans it assumes it is a Gradle project and treats it as such. However the default should be to open as a Maven project, allowing the pom.xml to take precedence.
Is there any configuration within Netbeans that will tell it that this is a Maven project (to use the pom.xml file) and treat it as such?
(note, if we close the project, temporarily delete the build.gradle file, then re-open in Netbeans, it does open as expected as a Maven project)
A: Now on newer versions (using 12 here), in Tools/Options/Java/Gradle exists a checkbox "Prefer Maven Projects over Gradle (needs restart)", check that and you have the solution.
A: It seems that Netbeans 11 and newer will consider the project as gradle if both pom.xml and build.gradle files exist in the project.
I had the same problem and found no option to tell Netbeans that I want to treat my project as being maven and not gradle.
Solution is (as @skomisa commented) to rename build.gradle and settings.gradle to something else like build.gradle_disabled, settings.gradle_disabled and then Netbeans will see your project as maven
A: The only way I managed to convince netbeans 11 to use my pom.xml:
Close the project, close netbeans.
Clean up the cache folder (in Linux: ~/.cache/netbeans/11.0)
Restart netbeans, reopen the project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58205734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Using PHP sessions causes page to expire from cache when returning from another site I have a form in which the first button posts back to the form; the second button posts to a form at another website; the third button posts to another form at my website.
I am trying to pass a variable from form1.php to form2.php using sessions. The problem is that if I click the second button and then click `Back' to get back to my site, the browser says that the page is not in the cache and I have to reload it. Of course, If I comment out both calls to session_start, I get back to my page as I left it.
What am I doing wrong? See code below.
form1.php
<?php
session_start();
?>
<html>
<head></head>
<body>
<form id="form1" action="form1.php" method="post">
<! -- various controls -->
<input type="submit" onclick="form1.action='form1.php';" />
<input type="submit" onclick="form1.action='http://server.anotherdomain/form';" />
<input type="submit" onclick="form1.action='form2.php'; return true;" />
</form>
</body>
</html>
form2.php
<?php
session_start();
$form1Var = $_SESSION["form1Var"];
/* etc. */
?>
<html>
<head></head>
<body>
<form action="form2.php" method="post">
<input type="hidden" value="<?php echo $form1Var?>" />
</form>
</body>
</html>
A: The solution is to call string session_cache_limiter ([ string $cache_limiter ] ) with an appropriate value for $cache_limiter before calling session_start. I am using "private_no_expire", which ensures that the Expire header is never sent to the browser.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32799309",
"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.