source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0035661024.txt"
] | Q:
Get service in appends attribute
I have a Model that looks something like this:
Rewards Earned Model:
class RewardsEarnedModel extends BaseModel{
protected $appends = ['readable_date'];
public function getReadableDateAttribute(){
// How do I access the User Service?
return $this->userService->dateTime($this->attributes['created_at'])->readableDate;
}
public function scopeSums($query, User $user, $offset = 0, $limit = 50){
return $query-> /* add items here (snipped) */;
}
}
I then run the model like this from my controller:
Rewards Controller:
public function getRewards(Request $request, User $user, $date = null){
$rewards = new RewardsEarnedModel;
$rewards = $rewards->Sums($user);
$sums = $rewards->get()->toArray();
}
My User service class has a Time trait attached to it. In that trait there is the function dateTime, and I would like to access it from my getReadableDateAttribute method, but I can not seem to do so. What can I do to access it from my User service?
User Service:
namespace App\Services;
class User {
use Time;
}
Time trait:
namespace App\Traits;
trait Time{
public function dateTime($datetime = null){
/* Snipped code */
}
}
A:
I was able access the User service by doing app()->User here is the final result:
public function getReadableDateAttribute(){
return app()->User->dateTime($this->attributes['created_at'])->readableDate;
}
|
[
"workplace.stackexchange",
"0000037105.txt"
] | Q:
Internal vacancy - how to phrase email asking to be considered
My background is that I was interviewed for a place on a project team within my company. I essentially passed the interview and was about to be offered the job when someone the people who interviewed me worked with on a daily basis asked if the casual mention of a role was still open. So I was turned down (I know all this through a friend who works at the company prior to me joining)
I then received an offer to join the company but on a different team, which I accepted. Over the past 12 months, without sounding boastful, I've performed very well and exceeded all expectations/been a mentor to many people
The project team is looking to expand again yet no one has come and speak to me about joining
My specific question is: how best should I phrase an email to the project team manager (who originally interviewed me) that I want to join the team, or at the very least, be considered for the role should an interview be required again. The role has not changed one bit from the one I was going to be offered
Or is the fact that they are not beating down my door (we work on different floors and don't really see other teams that much) be a hint?
Many thanks
A:
When they start the expansion/interview process they start fresh. They may review resumes from a previous round of interviews, but a year is a very long time to hang on to that kind of administrative "weight". It is most likely that they'll start entirely fresh. You may have a slight leg up if the same people will be interviewing you who had a positive impression of you before. You will also have the benefit of being within the company and almost certainly will have a managerial endorsement from your current manager.
You should consider if the position has been posted to an internal company job board. Consult with the HR team to see what listing they have for it and how they prefer to handle it. I would initiate this verbally, I'm assuming you know at least one person in the HR department who would help with this. If they want you to resubmit an official resume have it prepared and ready to submit immediately.
Speak to your current manager, and let him/her know of your intentions to pursue the position. Things will go better for you if you can get them to "cheer" for you. Once you have all of your ducks in a row, and you're ready to pursue it officially, send a brief, to-the-point email to the manager of that team. State your previous candidacy, your understanding of the new position and that you'd like to be considered. Ask for guidance on properly submitting your new candidacy. They might like you to go through proper HR channels, they might just want you to walk your resume over and have a chat. It depends on how the company culture is.
Mr. Hamplehopper,
It's come to my attention that your team will be expanding in the near
future, and a position is being created for senior widget
smack-packager. Approximately a year ago, I was considered for an
identical position, and I would like to pursue this opportunity again.
I feel my qualifications and experience within the company over this
last year will make me a great candidate for your team.
I have discussed this with my current manager, Ms. Jazzlescamper, and
she has given her support. Please let me know what I need to do to
submit my candidacy officially, and if there is anything I can do to
help streamline the process don't hesitate to call on me.
Sincerely,
{you}
If your company has a very formal culture, they'll expect you to submit your resume to HR, listing references, etc. If it's a less formal culture, the manager might just stop by your workstation and chat you up about it, maybe collect your resume. So make sure you have everything in a row before you make the first contact.
Chance favors only the prepared mind. - Louis Pasteur
|
[
"dba.stackexchange",
"0000224169.txt"
] | Q:
SSMS can't connect to Azure database
I got a new Windows 10 machine and installed the latest version of SQLEXPRESS and then the latest version of SSMS (17.9.1).
When trying to connect to my Azure database, I'm getting the following error.
Error connecting to 'mydb.database.windows.net'.
------------------------------ ADDITIONAL INFORMATION:
Failed to retrieve data for this request.
(Microsoft.SqlServer.Management.Sdk.Sfc)
An exception occurred while executing a Transact-SQL statement or
batch. (Microsoft.SqlServer.ConnectionInfo)
A transport-level error has occurred when receiving results from the
server. (provider: TCP Provider, error: 0 - An existing connection was
forcibly closed by the remote host.) (Microsoft SQL Server, Error:
10054)
An existing connection was forcibly closed by the remote host
What I've tried so far:
Uninstall/Reinstall - nope. I did this twice
Turn off firewall - didn't work. Besides, I can connect to the database fine through Visual Studio 2017, so it isn't a firewall issue. I also validated with netstat that port was open after I telnet-ed to the server.
Different version - I tried downgrading to SSMS version 17.9, but I get the same error. I'm in the process of bringing up 18.0 (preview 5) just to see if something will work for me. I may update here whether that works for me or not.
Different database - I have two Azure servers, I can't access either. I can connect to my local SQLEXPRESS instance without any issues.
My Google-foo has failed me on this so far. What am I missing? My current theory is that the SQLEXPRESS installation is colliding with SSMS install, but I don't know how to know that for sure - it was just something I read that used to be a problem.
Update
18 Preview 5 didn't help me. Same error :(
Others that appear to have this same issue without a resolution:
https://www.reddit.com/r/SQLServer/comments/9vfos7/issue_with_ssms_cant_connect_to_specific_server/
https://stackoverflow.com/questions/52885575/ssms-connect-to-azure-failure
Update 2
Uninstalling SQLEXPRESS and using IISCrypto to add specific TLS entries into the registry didn't help either.
Update 3 (After the answer below)
I installed SSDT and everything broke again :(. However, I did find that I can connect a single query in SSMS with no problem, but I cannot connect to a Server in the Object Explorer. Go figure.
I'll update here if there is something else I discover.
A:
Update: I found that connecting to AWS failed too which led me to yet another Google search which led me here: https://www.sqlservercentral.com/Forums/1891503/Unable-to-connect-to-SQL-2008-Servers-from-SSMS-2017
Following the instructions from the last post in the referenced site, I downloaded IISCrypto and enabled all of the Ciphers. Bingo.
https://www.nartac.com/Products/IISCrypto/Download
I'll leave my previous answer below in case it brings comfort to anyone who went through sleepless nights and a couple of keyboards.
Old Update - After installing SSDT 15.8.2 the solution below stopped working for me :(
After days of:
MS Azure SQL Support - not helpful (they just referred me to this post. The one I made.)
Uninstalling SQL Server Express/Developer and three different versions of SSMS - all with the same results
Creating a VM on my computer with Win 10 Pro - SSMS worked on it no problem
Wiping the computer and starting from absolute nothing (using the MSI recovery) - still same issue
Inspecting TLS packets to ensure version 1.2 - it was 1.2
Trying to connect with SqlPackage.exe - never worked for me, same error as SSMS
Trying to connect with SQLCMD - it worked!
Trying to connect with SQL Native Client - also worked!
... I did finally get it to work. Good news is that it works. Bad news is that I don't know exactly why.
I currently have a fresh Win 10 Pro install with SSMS 17.9.1. I do not have any SQL Server instance installed. My default Windows Firewall is enabled and Norton AntiVirus is managing it (default with the computer). All Windows Updates have been applied as of this writing. I also downloaded and installed the SQL Server 2012 Native Client https://www.microsoft.com/en-us/download/confirmation.aspx?id=50402
When it started working, I had just used SQLCMD and connected to the Azure SQL Server master database and was querying the sys.event_log table. Immediately before that, I had used SQLCMD to connect to a different database on that same server. When I didn't see anything in the sys.event_log table I went back to SSMS and it worked for all of my servers (we have three).
TL;DR Connect with SQLCMD for a while and see if that helps??
|
[
"stackoverflow",
"0017075222.txt"
] | Q:
How to flatten folder in php
In my server I have folders and sub-directory
I want to call a flatten methode to a directory to move every files at the same level and remove all empty folders
Here is what i've done so far:
public function flattenDir($dir, $destination=null) {
$files = $this->find($dir . '/*');
foreach ($files as $file) {
if(!$destination){
$destination = $dir . '/' . basename($file);
}
if (!$this->isDirectory($file)) {
$this->move($file, $destination);
}else{
$this->flattenDir($file, $destination);
}
}
foreach ($files as $file) {
$localdir = dirname($file);
if ($this->isDirectory($localdir) && $this->isEmptyDirectory($localdir) && ($localdir != $dir)) {
$this->remove($localdir);
}
}
}
public function find($pattern, $flags = 0) {
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
$files = array_merge($files, $this->find($dir . '/' . basename($pattern), $flags));
}
return $files;
}
This code dont show any error on run, but the resukt is not as expected.
For exemple if I have /folder1/folder2/file I want to have /folder2/file as a result but here the folders still like they where ...
A:
I finally make my code works, I post it here in case it help someone
I simplified it to make it more efficient. By the way this function is part of a filemanager classe I made, so I use function of my own class, but you can simply replace $this->move($file, $destination); by move($file, $destination);
public function flattenDir($dir, $destination = null) {
$files = $this->find($dir . '/*');
foreach ($files as $file) {
$localdir = dirname($file);
if (!$this->isDirectory($file)) {
$destination = $dir . '/' . basename($file);
$this->move($file, $destination);
}
if ($this->isDirectory($localdir) && $this->isEmptyDirectory($localdir) && ($localdir != $dir)) {
$this->remove($localdir);
}
}
}
|
[
"stackoverflow",
"0005504619.txt"
] | Q:
ajaxComplete not working on $(window)
I'm using jQuery version 1.5.1 and this isn't working for me:
$(window).ajaxComplete(function() {
console.log('hello');
});
but this is:
$(document).ajaxComplete(function() {
console.log('hello');
});
Why can't I attach the event handler to $(window)?
Note: this code is working with jQuery v1.3.2 but not with v1.5.1
A:
Probably because window is
1.) Not an element
2.) Somewhat 'protected' by the browser's js engine
3.) a bad idea when looking for something to attach an AJAX event to
Why can't you use document or an element instead?
|
[
"stackoverflow",
"0039944297.txt"
] | Q:
Dimple.js: How to color the background of groups in a grouped bar chart?
Please refer to the screenshot:
I would like to know how I can color a group in a grouped bar chart with a background color.
I am aware series.afterDraw as shown in Advanced Custom Styling Example here can be a way to do such customization. But need help in identifying the coordinates that make up each group.
Or is there any other way I can achieve the same?
A:
I could get this done by:
calculating the max value of each group
draw a background chart with max values on y axis
overlay the grouped bar chart with original data on top of background chart
The code for the same is:
// Create the svg and set the dimensions
var svg = dimple.newSvg("#chartContainer", 400, 400);
// Sample data for grouped bar chart
var data = [
{id: 1, type: "t1", count: 10},
{id: 1, type: "t2", count: 5},
{id: 1, type: "t3", count: 6},
{id: 2, type: "t1", count: 5},
{id: 2, type: "t2", count: 7},
{id: 2, type: "t3", count: 3}];
// Calculate maximum of each group.
// This will be the y axis value of background chart
var maximums = [{id: 1, max: 10}, {id: 2, max: 7}];
// Create background chart
var chart1 = new dimple.chart(svg, maximums);
var x1 = chart1.addCategoryAxis("x", "id");
var y1 = chart1.addMeasureAxis("y", "max");
chart1.addSeries(null, dimple.plot.bar);
chart1.defaultColors = [new dimple.color("#D3D3D3")];
chart1.draw();
// Remove axis titles of the background chart
x1.titleShape.remove();
y1.titleShape.remove();
// Overlay the actual chart on top of background chart
var chart2 = new dimple.chart(svg, data);
chart2.addCategoryAxis("x", ["id", "type"]);
chart2.addMeasureAxis("y", "count");
chart2.addSeries("type", dimple.plot.bar);
chart2.draw();
Following is the screenshot of the chart:
Fiddle for the same is available here
|
[
"stackoverflow",
"0039942340.txt"
] | Q:
Laravel 5.3 How does bootstrap interpret and display items without internet
I'm still learning Laravel 5.3 and started studying it a few days ago. One tutorial project I'm following made use of Fontawesome and Bootstrap where bootstrap link and fontawesome link was included within the <head></head> tag.
So I thought that if I disconnect the internet connection, it will fail to display the icons from fontawesome since no library file was downloaded and imported to project. But I was surprised that it still was able to display the fontawesome icons.
That's when I of thought of asking this simple question since I'm a beginner with Laravel and web programming. (Java programmer)
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>@yield('title')</title>
<!-- bootstrap link -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- fontawesome link -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css">
<!-- app.css link -->
<link rel="stylesheet" href="{{ URL::to('css/app.css') }}">
@yield('styles')
</head>
I read something from Laravel 5.3 documentation about the bootstrap directory that stores cached information. Is the caching the reason the fontawesome icons still displays even when it is not connected to the internet?
The Bootstrap Directory
The bootstrap directory contains files that bootstrap the framework
and configure autoloading. This directory also houses a cache
directory which contains framework generated files for performance
optimization such as the route and services cache files.
I'd appreciate any explanation to this so I can better understand how it works.
A:
Your browser has cache too. Do hard refresh / reload - in Chrome you can do this by opening inspector and then right click on refresh button and click what suits you the most.
Describing what is actually going on would be too long for an answer.
Good description what is going on is here.
Google search terms: browser cache, web browser cache
If you use build system (gulp) you will most likely end up with large *.css file which contains bootstrap, font-awesome definitions etc.
More on that is right in documentation.
|
[
"askubuntu",
"0000064005.txt"
] | Q:
Launcher doesn't respect TMPDIR
In my .bashrc, I define TMPDIR=${HOME}/tmp so temporary files are under my encrypted $HOME. emacs, invoked from the launcher, doesn't see this definition, but emacsclient, invoked from a shell does.
So far, I know that
emacs (after (server-start)) opens a socket in '/tmp', 'emacsclient' tries to communicate with 'emacs' over a socket in '${HOME}/tmp', and does very poorly. How can I presuade the launcher (via emacsclient.desktop?) to pass the right value for TMPDIR?
A:
Try putting the variable definition in .profile instead of .bashrc. The latter has a statement near the top that causes it to exit very early when executed by a non-interactive shell. Log out and back in to see whether it works.
Also don't forget to add export like this:
export TMPDIR="$HOME/tmp"
If that doesn't work, modify the launcher (it's in /usr/share/applications) so that its Exec line says:
Exec=sh -c 'TMPDIR="$HOME/tmp" emacs'
|
[
"stackoverflow",
"0050081097.txt"
] | Q:
TypeError: Cannot read property 'message' of undefined - Twitter API
Below is the output when running app.js. This started occurring totally at random when everything was working fine. Absolutely no changes were made.
TypeError: Cannot read property 'message' of undefined
at /home/ec2-user/environment/rt-bot/app.js:78:48
at Request._callback (/home/ec2-user/environment/node_modules/twitter/lib/twitter.js:220:14)
at Request.self.callback (/home/ec2-user/environment/node_modules/request/request.js:186:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (/home/ec2-user/environment/node_modules/request/request.js:1163:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at IncomingMessage.<anonymous> (/home/ec2-user/environment/node_modules/request/request.js:1085:12)
at IncomingMessage.g (events.js:292:16)
I've tried creating new instances from my master branch (with no commits since last working) and even still getting this error. Any ideas?
The code causing the error, though this code was working previously.
T.get('search/tweets', query, function(err, data, response) {
// continue if no errors
if(!err){
// loop
for(let i = 0; i < data.statuses.length; i++){
// get latest tweet ID
let id = { id: data.statuses[i].id_str }
// try favorite
T.post('favorites/create', id, function(err, response){
// log failures
if(err){
console.log('Try Favorite - ', err[0].message);
}
// log success
else{
let username = response.user.screen_name;
let tweetId = response.id_str;
console.log('Favorited: ', `https://twitter.com/${username}/status/${tweetId}`)
}
});
Image of first occurrence. As you can see everything was functioning fine, then this error came out of nowhere with absolutely no changes to environment or codebase.
UPDATE:
Output when logging error with console.log('Try Favorite - ', err.message); rather than console.log('Try Favorite - ', err[0].message);
[[Apr 28 21:27:00.702]] [LOG] Try Favorite - HTTP Error: 429 Too Many Requests
[[Apr 28 21:27:00.705]] [LOG] Try Favorite - HTTP Error: 429 Too Many Requests
[[Apr 28 21:27:00.706]] [LOG] Try Favorite - HTTP Error: 429 Too Many Requests
[[Apr 28 21:27:00.707]] [LOG] Try Favorite - HTTP Error: 429 Too Many Requests
[[Apr 28 21:27:00.708]] [LOG] Try Favorite - HTTP Error: 429 Too Many Requests
[[Apr 28 21:27:00.709]] [LOG] Try Favorite - HTTP Error: 429 Too Many Requests
[[Apr 28 21:27:00.712]] [LOG] Try Favorite - HTTP Error: 429 Too Many Requests
[[Apr 28 21:27:00.713]] [LOG] Try Favorite - HTTP Error: 429 Too Many Requests
[[Apr 28 21:27:00.718]] [LOG] Try Favorite - HTTP Error: 429 Too Many Requests
[[Apr 28 21:27:00.793]] [LOG] Try Favorite - HTTP Error: 429 Too Many Requests
Also note that the retweet function uses the same console logging method. See code below, and outputs fine.
// try retweet
T.post('statuses/retweet', id, function(err, response){
// log failures
if(err){
console.log('Try Retweet - ', err[0].message);
}
A:
Twit uses request to send HTTP requests to Twitter API, so the error will be single object not an array, so your error handler will look like
if(err){
console.log('Try Favorite - ', err.message);
}
|
[
"superuser",
"0001479296.txt"
] | Q:
Windows is ignoring JAVA_HOME or PATH for java
Yeah, as title says, no matter what i do, Windows is refusing to change the path away from the 1.8 JRE.
The error started happening becouse i moved the JRE folder away to try and see if it would change, but it doesnt.
Folder layout
Error
My path only points to the 1.12.0.2 JDK, so i'm not sure what is going on...
A:
The solution was using the PowerShell Get-Command java line.
The results indicated there were mulltiple java.exe files on my system, which are added by default by Java, when it's installed. Deleting the other 2 from the PATH variable fixed my problem.
|
[
"tex.meta.stackexchange",
"0000008217.txt"
] | Q:
Should we mark historic questions somehow?
The TeX packages have developed a lot since the first questions were asked on sx. Many high voted questions from 2011 do not reflect the situation today.
The users who asked and answered the question do not monitor this.
It would be unfair to down vote the accepted answer.
Should we tag some of these historic questions as historic question?
Any ideas how to handle answers which were good in the past and wrong or bad in the present?
We should help the user who finds a 500 up question from 2011, which has to be rethought in 2019.
Somewhat related: Referring to new, similar questions in old posts
A:
Given that some old but no longer applicable answers really are great, it would be a shame to remove them. (They would be good grist for future TeX archaeologists.)
On the other hand, as has been pointed out in another answer here, adding a "warning" answer to a question with highly-upvoted answers would not necessarily be noticed readily by someone (in particular a newbie) as it will start off with zero votes, and the likelihood of it becoming the "top" answer is negligible.
What about trying to formulate a "stock" statement that can be added at the top of the question itself, that documents the fact that while the answers given were valid at the time, as of <date> they no longer apply for <reason>. Such a statement could be inserted with a colored background, and whoever adds it should sign it. Formulating such a "warning" statement would be a reasonable topic for a meta question.
I would be happy to do this, at least for questions for which I submitted an answer, if I happen to come across them, or if prompted by someone else who finds such a problem entry.
Edit: In a comment, @Skillmon points out that some old, highly upvoted answers are outdated, although the original question is still valid, so it would be misleading to mark the entire posting as obsolete. In such a case, it would be appropriate to mark the answer(s) only, leaving the question intact.
Even some "current answers" are bad, although they satisfy the OP and are accepted. I usually address those by adding a comment saying why they don't work (or don't work in a more general case). I suspect that such comments aren't often seen by a newbie looking for a quick fix, but I feel that editing the answer is bad manners. I don't feel that way about an answer that is several years old and outdated by an actual change in the core or a package.
A:
I would say that if someone downvotes an answer just because it made use of tools which were available at the time the question and answer were written, there is not much you can do. You can try to protect these answers by declaring them "historic" but, honestly, you will never prevent users of the above-mentioned type from doing harm. In addition, if an answer is tagged "historic" this may then lead to the impression that this answer is "not so good and requires to be protected", but many of these answers are great. For these reasons I am a bit skeptical about your proposal (but see of course the good intentions behind it).
After some chat with moewe, I believe to understand the purpose of your question/suggestion better: you seem to want a clean-up of old posts. I fully support this but still do not think a "historic" tag will be instrumental to achieve this. Rather, we need to have competent users who are able to judge what is outdated, and are passionate enough to go through the older posts to "clean up". Notice that this is a highly nontrivial task because it is often not black-white: method B is strictly superior to A. (To give you an example, the new command \tikzmarknode which comes with the newest version of the tikzmark library is clearly an improvement over some \tikznode commands that you can find on our main site since it detects the mode and color and so on. However, often you get to hear that the solution is not useful because the OP are using overleaf, so they do not have access to newer packages and libraries. SIGH.) Another complication is that those competent and passionate users who you expect to go through the older posts know all-too-well that what they are adding now is likely to be outdated in a few years.
So my proposal is that, in order to "clean up",
we may instruct newcomers that it can help to also look at the time stamp of a post, not only at the votes, and
we agree that if we add a new answer we explain what is better or new compared to existing posts (and give proper credit to them, of course).
A:
We could add the year when the question was asked to the title like "How to ... in 2011"
this leaves the old question in a good state
we can open a new question "How to ... in 2019" on demand and link the questions
a good question or answer will not see down votes if it was good in the past
transparent for the reader
|
[
"graphicdesign.stackexchange",
"0000005055.txt"
] | Q:
Mockups: Coding vs Drawing?
This isn't about web design but about interface design in general. Is better to code Interface Mockups or "draw" them in a graphics program, like GIMP, Photoshop, etc.?
A:
Ask yourself these questions:
How many UI layouts/options can you explore in 30 minutes by coding? How many can you explore by sketching?
How often do you get a UI design exactly right on the very first try? If not very often, how quick/easy is it to change a sketch versus a coded mockup?
Can you instantly identify a color just by looking at its hex/rgb code (not just a ballpark guess, but the exact shade/color)? When you picture a color in your mind, can you immediately translate that to hex? How fast can you pick out a color scheme by typing in hex codes versus using a real color picker?
The fact that you're asking this question tells me that you're most-likely a programmer, not a designer, by training. If you were a designer, then it would be as absurd as developing an application without planning out the class structure, database design, application architecture, etc. and just jumping right into coding—and if you're an experienced developer, then you know what kind of problems this sort of bottom-up development causes.
Similarly, if you jump straight to code without actually designing your UI first, then the results aren't going to be pretty, if only because it's impractical to perfect a good design by coding blindly.
A:
I'd vote for "drawing" first. In GUI, proper layout/presentation is the key and it calls for visual means to be designed. Designing GUI visually lets you rapidly change your design without having to "imagine" each change, "translate it to code" and finally test it. The other way is also possible, but it's rarely better (e.g. project is extremely small, like just a couple of buttons and you're familiar and used to working at "code" level; during design some patterns may emerge, that can be just reused with slight modification).
If you're designing for a specific widget toolkit, you can also use some "GUI designer" application if available. It'll speed up even more GUI design process, because it both shows exactly how designed GUI will look like in running program and can export ready to use GUI description at presentational level.
A:
For UI design I have three stages with different objectives:
Sketching. First, you want to get the basic idea down of what elements there will be and how they will fit together. Any fine detail or aesthetic perfectionism at this stage is a distraction. I use a whiteboard and fat erasable pen so it's impossible to get distracted by too much detail and easy to scribble loads of different ideas and start again at any time. I've heard of people who only sketch on small post-it notes or only use their off-hand (e.g. left hand if you're right handed) to force themselves to not pay any attention at all to the aesthetics and focus 100% on the idea and function. (image not mine, from Frank Prendegast)
(2!) Simulating. Second, you want to get the look down and get feedback, finding out as much as you can about what people's intuitions and unprompted responses are before you start the time consuming implementation work. This should be in whatever you work most effeciently in since if you're doing it right, you should be going 'back to the drawing board' often, seeking out criticism and aiming to identify as many unexpected issues as early as possible. If you're a crazy coding machine and it's what you work most comfortably in, then coding is fine, but most people will work faster in something like Fireworks, Photoshop, dedicated wireframing software, or maybe a UI-driven interface builder like Flash Catalyst (fine if the end product isn't Flash, the goal is to get good feedback before you begin implementation).
(3!) Implementing. Finally, you implement the thing and aim to do so in a way that allows you to get more feedback early and often.
These three parts of the project cycle have different aims so if it's a big project it makes sense to use the most suitable tool for the job in each stage.
|
[
"stackoverflow",
"0004847238.txt"
] | Q:
How to disable the Content-Length response header with Apache?
Let me preface this question by stating that I only want to temporarily disable the header and am fully aware of the implications to browsers, cache mechanisms, etc if the header is not present.
I have need to test some caching behavior when the Content-Length header is not present in an HTTP response. Is there a way to disable the header?
My first attempt was to simply try to set it to 0 using PHP and header("Content-Length: 0", true); but this is not the same as completely removing the header from the response.
Is it possible to disable/remove the header?
A:
Adding Content-Length is something marked in RFC 2616 (HTTP 1.1) as SHOULD. That means web servers generally are designed not to leave it out.
For instance with Apache HTTP Server you have to modify modules/http/http_filters.c. Searching for Content-Length from the source file practically shows you how to unset it forcibly (take a closer look at around line 1255). Just add the unset to the end of the filter chain and you're set.
Your other alternative is to use an other web server besides Apache that is either easier to modify or doesn't respect RFC 2616 as well.
|
[
"unix.stackexchange",
"0000402182.txt"
] | Q:
simple grep expressions
I have a few grep expressions that aren't working as I intended and I cannot figure out as to why.
The first expression is to find lines that start and end with the same character. This is the expression I am using...
grep -E '(.).*\1$' input
The second expression is very similar as it is to find lines that have the same 2nd character and second to last character...
grep -E '(.)(.).*\2.$' input
The last expression is to find lines with only a single word and end with a punctuation...
grep -E '(\w){1}.*[[:punct:]]$' input
I don't understand why these are not working, am i doing something terribly wrong or just a simple mistake?
A:
You left off the start-of-line anchor (caret symbol). Here are modified commands which only match entire lines (and won't match substrings):
grep -E '^(.).*\1$' input
grep -E '^(.)(.).*\2.$' input
grep -E '^(\w){1}.*[[:punct:]]$' input
You'll probably also want to modify your second and third commands.
The second command doesn't require two capture groups. You can do it with just one:
grep -E '^.(.).*\1.$' input
The third command is incorrect: it will match strings with multiple words. A corrected version might be:
grep -E '^\w+[[:punct:]]$' input
|
[
"stackoverflow",
"0038216851.txt"
] | Q:
debugger in Clion 2016.2 EAP is not like before
I just upgraded to the latest early access of Clion and the debugger is not working for me. It worked in earlier versions. Now I can run a minimal program and get the expected output.
/home/dac/.CLion2016.2/system/cmake/generated/cliontest-77d7a571/77d7a571/Debug/cliontest
hello
Process finished with exit code 0
But the debugger doesn't seem to work? I add breakpoints but there is no output and no break, the program just exits. Am I doing something wrong or is it a bug in this version 2016.2 EAP build 162.1120.17 of Clion? The debugger used to work better in version 2016.1, even though I got an error there that I'm trying to see if it is still in the latest version. What I got when debugging before was "Cannot collect variable" for certain variable and it is this error that I am investigating if it is still in newer versions. But now I have two problems: I can't even get the debugger to work in this newer version. It's like the debugger is just "silent".
/home/dac/.CLion2016.2/system/cmake/generated/cliontest-77d7a571/77d7a571/Debug/cliontest
During startup program exited normally.
Process finished with exit code 0
If I manually navigate in the shell to the generated executable, then it is runnable but I want to use the debugger.
Update
I opened an issue for this problem at Jetbrains https://youtrack.jetbrains.com/issue/CPP-7132
A:
The issue was resolved: The reason was that I was using my own custom shell that can't perform all shell functionality. When I switched to bash shell, then everything worked.
|
[
"stackoverflow",
"0004352561.txt"
] | Q:
Retain cycle on `self` with blocks
I'm afraid this question is pretty basic, but I think it's relevant to a lot of Objective-C programmers who are getting into blocks.
What I've heard is that since blocks capture local variables referenced within them as const copies, using self within a block can result in a retain cycle, should that block be copied. So, we are supposed to use __block to force the block to deal directly with self instead of having it copied.
__block typeof(self) bself = self;
[someObject messageWithBlock:^{ [bself doSomething]; }];
instead of just
[someObject messageWithBlock:^{ [self doSomething]; }];
What I'd like to know is the following: if this is true, is there a way that I can avoid the ugliness (aside from using GC)?
A:
Strictly speaking, the fact that it's a const copy has nothing to do with this problem. Blocks will retain any obj-c values that are captured when they are created. It just so happens that the workaround for the const-copy issue is identical to the workaround for the retain issue; namely, using the __block storage class for the variable.
In any case, to answer your question, there's no real alternative here. If you're designing your own block-based API, and it makes sense to do so, you could have the block get passed the value of self in as an argument. Unfortunately, this doesn't make sense for most APIs.
Please note that referencing an ivar has the exact same issue. If you need to reference an ivar in your block, either use a property instead or use bself->ivar.
Addendum: When compiling as ARC, __block no longer breaks retain cycles. If you're compiling for ARC, you need to use __weak or __unsafe_unretained instead.
A:
Just use:
__weak id weakSelf = self;
[someObject someMethodWithBlock:^{
[weakSelf someOtherMethod];
}];
For more information: WWDC 2011 - Blocks and Grand Central Dispatch in Practice.
https://developer.apple.com/videos/wwdc/2011/?id=308
Note: if that doesn't work you can try
__weak typeof(self)weakSelf = self;
A:
This might be obvious, but you only have to do the ugly self alias when you know you’ll get a retain cycle. If the block is just a one-shot thing then I think you can safely ignore the retain on self. The bad case is when you have the block as a callback interface, for example. Like here:
typedef void (^BufferCallback)(FullBuffer* buffer);
@interface AudioProcessor : NSObject {…}
@property(copy) BufferCallback bufferHandler;
@end
@implementation AudioProcessor
- (id) init {
…
[self setBufferCallback:^(FullBuffer* buffer) {
[self whatever];
}];
…
}
Here the API does not make much sense, but it would make sense when communicating with a superclass, for example. We retain the buffer handler, the buffer handler retains us. Compare with something like this:
typedef void (^Callback)(void);
@interface VideoEncoder : NSObject {…}
- (void) encodeVideoAndCall: (Callback) block;
@end
@interface Foo : NSObject {…}
@property(retain) VideoEncoder *encoder;
@end
@implementation Foo
- (void) somewhere {
[encoder encodeVideoAndCall:^{
[self doSomething];
}];
}
In these situations I don’t do the self aliasing. You do get a retain cycle, but the operation is short-lived and the block will get out of memory eventually, breaking the cycle. But my experience with blocks is very small and it might be that self aliasing comes out as a best practice in the long run.
|
[
"stackoverflow",
"0014074731.txt"
] | Q:
Are IRIs valid as HTML attribute values?
Is it valid HTML to use IRIs containing non-ASCII characters as attribute values (e.g. for href attributes) instead of URIs? Are there any differences among the HTML flavors (HTML and XHTML, 4 and 5)? At least RFC 3986 seems to imply that it isn't.
I realize that it would probably be safer (regarding older and IRI-unaware software) to use percent encoding, but I'm looking for a definitive answer with regards to the standard.
So far, I've done some tests with the W3C validator, and unescaped unicode characters in URIs don't trigger any warnings or errors with HTML 4/5 and XHTML 4/5 doctypes (but of course the absence of error messages doesn't imply the absence of errors).
At least chrome also supports raw UTF-8 IRIs, but percent-escapes them before firing an HTTP request. Also, my web server (lighttpd) seems to support UTF-8 characters in their percent-encoded as well as in unencoded form in an HTTP request.
A:
HTML 4.01 is straightforward enough. Different attributes have different rules as to what they can contain, but if we're dealing with the href attribute on an <a> element, then the HTML 4 spec, section B.2.1 Non-ASCII characters in URI attribute values says:
... the following href value is illegal:
<A href="http://foo.org/Håkon">...</A>
HTML5 is different. It says IRIs are valid providing they comply with some additional conditions.
A URL is a valid URL if at least one of the following conditions
holds:
The URL is a valid URI reference [RFC3986].
The URL is a valid IRI reference and it has no query component. [RFC3987]
The URL is a valid IRI reference and its query component contains no unescaped non-ASCII characters. [RFC3987]
The URL is a valid IRI reference and the character encoding of the URL's Document is UTF-8 or a UTF-16 encoding. [RFC3987]
XHTML 1.x follows the same rules as HTML 4.01.
XHTML5 is the same as HTML5.
|
[
"math.stackexchange",
"0003784314.txt"
] | Q:
On the definition of an algebra
An algebra is given by a triple $(A,\mu,\nu)$ where $A$ is a vector field over $k$, and
\begin{gather*}
\mu \colon A \otimes A \rightarrow A, \\
\nu \colon k \rightarrow A
\end{gather*}
are such that:
$\mu$ is a linear map satisfying $\mu \circ (\mu \otimes \mathrm{id}) = \mu \circ (\mathrm{id} \otimes \mu)$; which is to say that $\mu$ is associative.
The map $\nu$ satisfies $\mu \circ (\nu \otimes \mathrm{id}) = \gamma$ where $\gamma$ is the canonical isomorphism $\gamma \colon k \otimes A \rightarrow A$; this shows that $\nu(1)$ is a unit in $A$
Can somebody explain to me how the constraint on $\nu$ is equivalent to saying that $\nu(1)$ is a unit in $A$? Thanks!
A:
Both $\mu \circ ( \nu \otimes \mathrm{id} )$ and $\gamma$ are linear maps from $k \otimes A$ to $A$.
These maps coincide if and only if they are equal on simple tensors, i.e. we have $\mu \circ (\eta \otimes \mathrm{id}) = \gamma$ if and only if
$$
( \mu \circ (\nu \otimes \mathrm{id}) )(\lambda \otimes a)
=
\gamma(\lambda \otimes a)
$$
for all $\lambda \in k$ and $a \in A$.
In other words, we need that
$$
\nu(\lambda) \cdot a
=
\lambda a
$$
for all $\lambda \in k$ and $a \in A$.
Here we denote on the left hand side by $\cdot$ the multiplication on $A$ coming from $\mu$, and on the right hand side we have the scalar multiplication coming from the vector space structure of $A$.
By the linearity and $\nu$ and the bilinearity of the multiplication $\mu$ we can rewritte the left hand side of this required equation as
$$
\nu(\lambda) \cdot a
=
\nu(\lambda 1) \cdot a
=
( \lambda \nu(1) ) \cdot a
=
\lambda ( \nu(1) \cdot a ) \,.
$$
We can hence rewrite the above equality as
$$
\lambda ( \nu(1) \cdot a )
=
\lambda a
$$
for all $\lambda \in k$ and $a \in A$.
We see that this holds for all $\lambda$, $a$ if and only if it holds for $\lambda = 1$ and all $a$.
In other words, the identity $\mu \circ (\eta \otimes \mathrm{id}) = \gamma$ holds if and only if
$$
\nu(1) \cdot a
=
a
$$
for all $a \in A$.
But this condition means precisely that $\nu(1)$ is a multiplicative neutral element of $A$ with respect to $\mu$.
|
[
"stackoverflow",
"0001754360.txt"
] | Q:
Given a Surface, Find the Parts that are Cut Into Half By a Surface
Let's say I have a Surface(S1), and I have another surface (S2) that cuts through it. How to find the polyhedron formed by the intersection of the two, as shown?
In the above example, there should be two polyhedrons returned, one above S2, another below S1.
But S1 and S2 are defined by 3D coordinates. Let's say the coordinates for S1 is (P1,P2, P3, P4) and S2 is P5,P6, P7, P8, and the intersected points are P9 and P10. I want a program that returns me two polyhedrons:
P1,P2,P9,P10,P5,P6
and
P3,P4,P10,P9,P7,P8
I am aware that it is possible to get the intersection point of the two surfaces and form polyhedrons, but it would be good if I have a builtin matlab function for this
A:
Find the intersection of the 2 surfaces (assuming they are planes this is a parallelism-test, a cross product, and solving the linear equation to check where they actually intersect). Then you have all the points you need to construct the two polyhedrons. You will probably want to check that you're marrying up the 'correct' ends and the normals make sense, but in the case above there are 6 points for each polyhedron and 2 of those points are common from the planar intersection.
|
[
"stackoverflow",
"0042909065.txt"
] | Q:
how to download pictures and videos from instagram from post's link
I creating a Instagram download android app. how to i download pictures and videos from Instagram by copy share URL in android? or how to i get the download URL of pictures and videos in Instagram exactly?
Thanks.
A:
If you mean share URL such https://www.instagram.com/p/-vSJNUDKKD/ then it's easy, just add ?__a=1 to URL like https://www.instagram.com/p/-vSJNUDKKD/?__a=1 and you'll receive JSON contains image download address.
|
[
"stackoverflow",
"0038336542.txt"
] | Q:
swift Regular Expression and (.*?)
I want to extract substrings from a string that match a regex pattern.
The problem is this code : ("ytplayer.config = {(.*?)};").exec(responseStringC). It must match but return nil.
string.exec function :
extension String {
func exec (str: String) -> Array<String> {
do {
let regex = try NSRegularExpression(pattern: self, options: [.CaseInsensitive,.IgnoreMetacharacters])
let nsstr = str as NSString
let all = NSRange(location: 0, length: nsstr.length)
var matches : Array<String> = Array<String>()
regex.enumerateMatchesInString(str, options: NSMatchingOptions(rawValue: 0), range: all) {
(result : NSTextCheckingResult?, _, _) in
let theResult = nsstr.substringWithRange(result!.range)
matches.append(theResult)
}
return matches
} catch {
print("error")
return Array<String>()
}
}
}
"responseStringC" variable is :
http://pastebin.com/uvvq9ULA
the problem is return nil. Any Clue?
A:
Your exec code contains .IgnoreMetacharacters flag:
Treat the entire pattern as a literal string.
Remove it so that the pattern could be treated as a regex pattern.
Also, a good idea is to use a DOTALL modifier (?s) at the start of the pattern.
Also, remember that a dot matches any character, escape it to match a literal dot.
As for the pattern, I'd recommend
"(?s)ytplayer\\.config = \\{(.*?)\\};"
Or a much faster:
"(?s)ytplayer\\.config = \\{([^}]*(?:\\}(?!;)[^}]*)*)\\};"
See the regex demo
|
[
"stackoverflow",
"0032504459.txt"
] | Q:
User input in Python is not being written to database
Just for fun, I'm creating a website in Python and using the Google Datastore to create a website that lets users post a movie title and a review for the movie. I am also using Jinja2 templating. The problem is, the movie_name gets written to the databases on all occasions except one, which is in the class that says MoviePage. It seems like that is the only class that isn't reading the variable movie_name, not even the jinja template is reading that variable. However, I have other variables in my html that are being parsed by jinja2, it's only that one variable I'm having trouble with. Here is my code:
class MovieReviews(db.Model):
movie_name = db.StringProperty()
review = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
last_modified = db.DateTimeProperty(auto_now = True)
class MoviesOnWebsite(db.Model):
movie_name = db.StringProperty(required = True)
created = db.DateTimeProperty(auto_now_add= True)
class AddMovie(StrHandler):
def get_front(self,movie_name="",error=""):
add_movie = db.GqlQuery("SELECT * FROM MoviesOnWebsite")
self.render("add-movie.html",movie_name=movie_name,error=error,add_movie=add_movie)
def get(self):
self.get_front()
def post(self):
haveError = False
movie_name = self.request.get("movie_name")
params = dict(movie_name=movie_name)
if not movie_name:
params['error_movie_name'] = "Must write movie name"
haveError = True
if haveError:
self.render("add-movie.html", **params)
self.response.out.write('You have errors')
else:
addmovie = MoviesOnWebsite(movie_name=movie_name)
addmovie.put()
site_url = urllib.urlencode(dict(movie_name=movie_name))
self.redirect('/' + site_url)
class MoviePage(StrHandler):
def get_front(self, review="",error=""):
addmovie = AddMovie()
full_url = addmovie.site_url
movie_reviews = db.GqlQuery("SELECT * FROM MovieReviews")
self.render("movie_review_page.html", review=review,error=error,movie_reviews=movie_reviews)
def get(self,url):
self.get_front()
def post(self,url):
path = urlparse.urlparse(full_url).path
movie_name = self.request.get('movie_name')
review = self.request.get("review")
if review:
movie_rev = MovieReviews(path = path,review = review)
movie_rev.put()
else:
error = "You haven't submitted a review"
self.get_front(review,error)
And a small code snippet from my html page called movie_review_page.html to verify that the jinja syntax is correct:
<body>
<h1>{{movie_name}}</h1>
....
I'll explain what my code is doing. The classes MovieReviews and MoviesOnWebsite are just database models. The class AddMovie lets a user add a movie to the database if no one has ever submitted a review for that particular movie. After the user adds the movie name to the database, they get redirected to a url that looks like this: www.websitename.com/nameOfMovie. And from there, the class MoviePage has a form that lets users add a movie title and a review and adds it to the database. The problem as I mentioned before, when a user adds a movie title and review in the MoviePage class, only the review gets written to the database and the movie title is blank. The movie title that I want written to the database is the movie the user is doing a review for, namely, the name of the movie found in the url. The movie_name only gets written to the database in the class AddMovie. And the url with the path that has the name of the movie also works. The problem is in the MoviePage class. I should mention that add-movie.html has a textbox with the name movie_name and movie_review_page.html does not. If I change the variable from movie_name = self.request.get('movie_name') to movie_name="abcd" then abcd gets written to the database, but it doesn't work the other way around.
I'd appreciate any help.
A:
I am not sure what web framework you are using but the issue seems to be caused by query parameters vs url paramters.
The other values are included in the form and therefor retrieved successfully from
self.request.get. For movie_name you can't use the same call, you will need to extract it from the current url somehow, but this will cause problems if your movie has non standard characters in it or spaces.
Rather url encode the parameter and include it in the redirect:
Change the redirect to this:
import urllib
self.redirect('/?' + urllib.urlencode(dict(movie_name=movie_name))
The generated url should look like /?movie_name=The%20Terminator
Then retrieve the data like so:
self.request.get("movie_name")
|
[
"askubuntu",
"0000113352.txt"
] | Q:
I need help choosing hardware upgrades to get Ubuntu 12.04 3d to run
I have a Dell Dimension 3000
RAM: 512 MiB
CPU: Intel® Pentium(R) 4 2.80GHz
Graphics: Intel® 865G x86/MMX/SSE2
What do I have to upgrade to run Ubuntu 12.04 3d.
A:
You will need a supported graphics card.
Take a look at this list
https://wiki.ubuntu.com/HardwareSupportComponentsVideoCards
You can find a listing of graphics cards by vendor, and if 3d is supported in Ubuntu as of 11.10.
I would personally use the information to find a old (but not ancient) ATI or Nvidia card for cheap.
|
[
"stackoverflow",
"0010964244.txt"
] | Q:
Filtering a matrix in R by matching it a list
I have the matrix:
traits <- matrix(c(1,0,1, 1,0,0, 0,0,0), nrow = 3, ncol=3, byrow=TRUE,
dimnames = list(c("sp1", "sp2", "sp3"),c("Tr1", "Tr2", "Tr3")))
and a list
species <-c("sp1", "sp2")
how can I filter the 'traits' matrix so it returns just the matches i.e.
traits.filtered<-matrix(c(1,0, 1,1, 0,0), nrow = 2, ncol=3, byrow=TRUE,
dimnames = list(c("sp1", "sp2"),c("Tr1", "Tr2", "Tr3")))
Thank you,
-Elizabeth
A:
traits[row.names(traits)%in%species,]
A:
One obvious approach is to subset the traits matrix using species as follows:
traits[species, ]
However, this only works assuming that the row names are unique - if they're not, only the first match is returned.
For that reason, I'd strongly recommended using the more robust:
traits[rownames(traits) %in% species, ]
|
[
"stackoverflow",
"0032054420.txt"
] | Q:
Python Mechanize Add Value to Form Input without ID or Name
Have used mechanize before. Trying to fill out a form whose inputs have no name or id. They only have a class. Is there a way to do this maybe by number like you can do when selecting a form?
<form class="go-action-form">
<div class="go-action-form-no-auth">
<input class="firstname" type="text" placeholder="First Name" data-required />
<input class="lastname" type="text" placeholder="Last Name" data-required />
<input class="email" type="text" placeholder="Email" data-required data-validation="email" />
<input type="submit" class="submit-petition" id="submit-petition-embed-ub39aca073fec49a690c5f3acb4152aae" value="Submit My Name" />
</div>
</form>
This is what I have.
br = mechanize.Browser()
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
url = "https://generationopportunity.org/petitions/free-the-food-trucks-in-raleigh/?utm_content=bufferfa496&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer"
br.open(url)
br.select_form(nr = 1)
br.form.set_value(firstname, nr=0)
br.form.set_value(lastname, nr=1)
br.form.set_value(email, nr=2)
br.form.set_value(zip, nr=3)
print br.form.controls[0]
print br.form.controls[1]
print br.form.controls[2]
print br.form.controls[3]
br.submit()
EDIT
I figured out how to add values now in what i have above. Now i just can't figure out how to submit it. I try and it says br.submit() -- AttributeError: 'NoneType' object has no attribute 'click'
Thanks
A:
br.open(url)
# forms = [f for f in br.forms()]
# print forms[1]
# print forms[1].controls[0]
br.select_form(nr = 1)
br.form.set_all_readonly(False)
br.form.set_value(firstname, nr=0)
br.form.set_value(lastname, nr=1)
br.form.set_value(email, nr=2)
br.form.set_value(zip, nr=3)
br.submit()
|
[
"stackoverflow",
"0002063472.txt"
] | Q:
How can I tell at runtime that a Java 1.4 type or member is deprecated?
In Java 6 I can use a technique like this:
@Deprecated
public final class Test {
public static void main(String[] args) {
System.out.println(Test.class.isAnnotationPresent(Deprecated.class));
}
}
to decide if a type is deprecated. Is there any way at all to do this in 1.4 with the old style (Javadoc-based) deprecation?
A:
You can't make such a check on javadoc tags. Well, you can, if you distribute your source code, load the source file and parse it for the @deprecated tag, but this is not preferable.
The pre-Java5 way of indicating something is by using a marker interface. You can define your own:
public interface Deprecated {
}
and make deprecated classes implement it. You cannot use it on methods, of course.
public final class Test implements Deprecated
And then check whether Deprecated.class.isAssignableFrom(Test.class).
But deprecation is a purely indicative notion and should not be used at run-time to differentiate behaviour.
A:
No there is not, as JavaDoc is a comment and as such not available at runtime.
A:
The @deprecated tag is only used by the compiler but not put in the compiled java byte code, so you cannot detect it after compilation.
What is it you want to do?
|
[
"stackoverflow",
"0028978143.txt"
] | Q:
Is there a way to override setTimeout function so it uses microseconds instead of milliseconds
Since there is this function window.performance.now() that returns the current time in microseconds since the page started to load, is there a way to implement it's accuracy in to a more precise setTimeout function
A:
The short answer is no, there isn't. In addition, the millisecond granularity of setTimeout is misleading. Some browsers are far less accurate, although there are workarounds for this. In any case, setTimeout calls are only called after the current call stack finishes executing, which could be much longer than you want. setInterval actually has an interesting behavior where it will queue up multiple calls if they're deferred by other executing code, so that when they execute they'll all execute one after another with no delay in between.
|
[
"stackoverflow",
"0015897236.txt"
] | Q:
Extract the first (or last) n characters of a string
I want to extract the first (or last) n characters of a string. This would be the equivalent to Excel's LEFT() and RIGHT(). A small example:
# create a string
a <- paste('left', 'right', sep = '')
a
# [1] "leftright"
I would like to produce b, a string which is equal to the first 4 letters of a:
b
# [1] "left"
What should I do?
A:
See ?substr
R> substr(a, 1, 4)
[1] "left"
A:
The stringr package provides the str_sub function, which is a bit easier to use than substr, especially if you want to extract right portions of your string :
R> str_sub("leftright",1,4)
[1] "left"
R> str_sub("leftright",-5,-1)
[1] "right"
A:
You can easily obtain Right() and Left() functions starting from the Rbase package:
right function
right = function (string, char) {
substr(string,nchar(string)-(char-1),nchar(string))
}
left function
left = function (string,char) {
substr(string,1,char)
}
you can use those two custom-functions exactly as left() and right() in excel.
Hope you will find it useful
|
[
"askubuntu",
"0001209309.txt"
] | Q:
Network problems in Ubuntu 19.10
I have installed server 19.10 and the did the following:
sudo apt update
sudo apt upgrade
Then I did a reboot
I then did
sudo apt-get install ubuntu-desktop
All seems to go well
Then I confirmed that there were no additional updates...
Then I did a reboot
The system came up well.. and all seems to be great...
But.. Things like the settings option can not see the network and the software program to download programs can not see the network and suggests me look at the network setting..
The network interface is now seen with ip a and is no longer eth0 but follows a new standard...
Is there a new updated ubuntu-desktop package to install???
To save the question .. why install the server and then the desktop when the desktop version of ubuntu 19.10 works great!! I am planning to install UBUNTU 19.10 on my Raspberry PI 4 and want the desktop experience... I am testing the install on my faster PC..
Any insight would be helpful
Further to questions:
- cat /etc/netplan/*.yaml
network:
version: 2
renderer: NetworkManager
ethernets:
enp0s3:
match:
name: enp0s3
set-name: eth0
dhcp4: yes
# This file is generated from information provided by
# the datasource. Changes to it will not persist across an instance.
# To disable cloud-init's network configuration capabilities, write a file
# /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg with the following:
# network: {config: disabled}
network:
ethernets:
enp0s3:
dhcp4: true
version: 2
sudo lshw -class network
*-network
description: Ethernet interface
product: 82540EM Gigabit Ethernet Controller
vendor: Intel Corporation
physical id: 3
bus info: pci@0000:00:03.0
logical name: enp0s3
version: 02
serial: 08:00:27:e1:30:c6
size: 1Gbit/s
capacity: 1Gbit/s
width: 32 bits
clock: 66MHz
capabilities: pm pcix bus_master cap_list ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation
configuration: autonegotiation=on broadcast=yes driver=e1000 driverversion=7.3.21-k8-NAPI duplex=full ip=192.168.1.54 latency=64 link=yes mingnt=255 multicast=yes port=twisted pair speed=1Gbit/s
resources: irq:19 memory:f8200000-f821ffff ioport:d020(size=8)
A:
Your .yaml file is wrong, because you mix NetworkManager and networkd syntax.
The following two .yaml files are for a pure server installation... no Desktop, no GUI.
Your .yaml file should look like this...
network:
version: 2
renderer: networkd
ethernets:
enp0s3:
dhcp4: true
And if you REALLY want to use eth0:
sudo pico /etc/default/grub or sudo -H gedit /etc/default/grub
Search for "quiet splash" and change it to "quiet splash net.ifnames=0"
sudo update-grub
And then use this .yaml...
network:
version: 2
renderer: networkd
ethernets:
eth0:
dhcp4: true
Then...
sudo netplan --debug generate
sudo netplan apply
reboot
Update #1:
If you decide to use NetworkManager, and the GUI to setup your network, then you need this .yaml...
network:
version: 2
renderer: NetworkManager
Remember to always use the sudo netplan... commands that I gave earlier.
|
[
"askubuntu",
"0000765633.txt"
] | Q:
The Unicode look of disapproval no longer displays correctly in 16.04 - how do I fix this?
The Unicode look of disapproval no longer displays correctly within Chrome and Firefox in Ubuntu 16.04:
As you can see, the Unicode replacement character is shown instead of the correct symbol.
This was working fine in 15.04 - what do I need to do to get this fixed?
A:
The Unicode Look of Disapproval (U0CA0) uses the letter ttha from the Kannada language.
You can sudo apt install fonts-lohit-knda to provide the correct font.
You can then insert the character with Ctrl+Shift+U, then 0CA0
ಠ_ಠ
|
[
"stackoverflow",
"0007342670.txt"
] | Q:
Flash Builder 4.5.1 published android app does not run
Mobile application runs perfectly in the debug mode - I can test it on the device etc... The problem is with the release build - it simply does not run. When I manually install .apk I don't get any errors messages, simply a green check mark and "Application not installed" message. Any thoughts?
Running the latest version of air and Flash Builder 4.5.1
A:
I'm not 100%, but if I remember correctly, you need to uninstall the old application before installing the new one because of a name collision. Try that.
|
[
"stackoverflow",
"0003415581.txt"
] | Q:
How do I tune up my C# Skills, when I have spent the last decade coding in VB?
I started my career coding in C/C++ on a vax system, but got into a few contracts where it was all VB and then became a specialist in VB, then to VB.net. Now I am aspiring to work for Microsoft and it seems that every job they post is in C/C++/C# and I can barely read C# code, it looks like the most convoluted mess to me and the inline syntax almost hurts my feelings.
I am looking for positive, non-flaming, helpful suggestions on how to pick up C# skills again. Books..Labs..etc? I have been coding simple projects using Silverlight and C# to try and work it out but it is extremely frustrating since there are very few examples that I can find that illustrate what each code set looks like. I've Googled but have yet to find anything helpful other than channel9 labs and working through some of the example code/projects from mix10.
I am not looking for a shortcut, but a good solid skills understanding. I swear it is easier to translate English to Latin than VB to C#.
A:
I personally would start by converting a VB.NET project into C#, having done VB.NET it wouldn't be difficult once you got started as they both use the same underlying CLR.
Doing it this way step by step, looking up how to convert each bit you don't understand, you'll soon end up teaching yourself C# based on you're knowledge of VB.NET and you'll see they're really not that much different!
I find them very similar now I know them both, they just have a habit of doing things 'slightly' differently.
Also, have a look at this wiki page for a summary comparison of VB.NET and C#, and check out the examples at the bottom to see some basic syntax comparisons that will give you a starting point for converting VB.NET into C#.
A:
Since VB.NET and C# are both first-class object-oriented .NET languages that compile down to the nearly the same CIL code, I find it fairly easy to switch between the two. Most of the learning curve in .NET comes from learning the myriad APIs; syntax doesn't take terribly long to pick up.
I'd recommend a good book that focuses on the language of C# (that is, not a framework such as Winforms, Silverlight, or WPF). A book that I really liked was Illustrated C# 2008 by Daniel Solis. It's great at exposing the C# language from end to end. (NOTE: Although it says "Illustrated" in the title, it's not filled with lots of pretty pictures. "Illustrated" simply means that the author uses lots of helpful diagrams to explain concepts).
Also, I spent a good deal of time solving math problems at http://www.projecteuler.net in order to learn C#. It helps to have real problems to solve to learn a language and Project Euler offers problems that are small enough that you can still focus on learning different aspects of the language.
|
[
"math.stackexchange",
"0000385160.txt"
] | Q:
monotone convergence in real analysis
I need help with this analysis problem.
Define a sequence ${t_n}$ recursively by setting $t_1 = 1$ and $t_n = \sqrt{(t_{n-1} + 1)}$. Does this sequence converge? To what?
A:
Note that $t_n>0$ for all $n$ and let $\lim_{n\rightarrow\infty}t_{n}=L$, then you have that
$t_n=\sqrt{t_{n-1}+1}\implies t_n^2=t_{n-1}+1\implies \lim_{n\rightarrow\infty}t_n^2=\lim_{n\rightarrow\infty}t_{n-1}+1\implies L^2=L+1\implies L=(1+\sqrt{5})/2$
|
[
"stackoverflow",
"0034547333.txt"
] | Q:
What is the clear button on html5smartimage
I have inherited a scaffold form that contains an html5smartimage component. This is used to allow a user to select a display image for this page.
(I know this is not what this component is designed for, but I don't know what features the users are using and we are specifying a height.)
Here is the config info:
<featuredImage
jcr:primaryType="cq:Widget"
allowUpload="false"
ddGroups="[media]"
disableZoom="{Boolean}true"
fileNameParameter="./jcr:content/data/image/fileName"
fileReferenceParameter="./jcr:content/data/image/fileReference"
name="./jcr:content/data/image"
title="Featured Image"
height="400"
xtype="html5smartimage"/>
When an image is added, there is a clear button with a picture of a brush to sweep something away. I assume it is there to clear the image, but it is always disabled.
I cannot find this clear button referenced in any documentation.
Based on the answer below, I built the following that solves my problem:
<featuredImage
jcr:primaryType="cq:Widget"
allowUpload="false"
ddGroups="[media]"
disableZoom="{Boolean}true"
fileNameParameter="./jcr:content/data/image/fileName"
fileReferenceParameter="./jcr:content/data/image/fileReference"
name="./jcr:content/data/image"
title="Featured Image"
height="400"
xtype="html5smartimage">
<listeners
jcr:primaryType="nt:unstructured"
imagestate="function(imageComponent, state) {
if(state == 'originalavailable' || state == 'processedavailable') {
imageComponent.enableToolbar();
}
}"/>
</featuredImage>
A:
I came across a similar kind of issue when using a custom widget and not scaffold form. However the fix should work for this too.
Add a listener to your image as shown below
listeners: {
imagestate: function(imageComponent, state) {
if(state == 'originalavailable' || state == 'processedavailable') {
imageComponent.enableToolbar();
}
}
}
This would enable the clear button when you drop the image in the dialog.
|
[
"stackoverflow",
"0043436330.txt"
] | Q:
How to assign a bold(style) for a variable using ES6 string template in Angular?
I need to assign for my variable in ES6 string template a style[bold].
My code looks:
Component
export class AppComponent {
public keyword = '';
public text = '';
onKey(value) {
this.keyword = value;
this.text = `Search for ${this.keyword} with`;
};
}
Template
<input #box class="search-for" type="text" (keyup)="onKey(box.value)">
<p *ngIf="keyword " class="search-line ">{{ text }}</p>
For example, if user types “Angular” then the text will be “Search for Angular with:”
Thank you.
A:
ngModel and Input, that's what you need. Try this code:
import { Input } from '@angular/core';
export class AppComponent {
@Input() keyword: string;
}
<input class="search-for" type="text" [(ngModel)]="keyword">
<p *ngIf="keyword" class="search-line ">Search for <b>{{keyword}}</b> with:</p>
|
[
"stats.stackexchange",
"0000457726.txt"
] | Q:
Using prior knowledge about correlated variable in ridge regression
I am wondering what methods are available for incorporating prior knowledge of some variable that is correlated with the unknown regression coefficients in a ridge regression. I have a sparse matrix with a high level of multicollinearity. I have knowledge of variable which is correlated to my coefficients. However, the known variable ranges strictly 0-8 while the coefficients can vary from around -10 to 10 (without strict bounds). How can this known variable be incorporated into the regression?
I am currently using scikit-learn RidgeCV in Python for the analysis.
A:
If you want to include prior information into your model, using bayesian model is the standard way to go. In Bayesian setting, ridge regression is equivalent to using Normal priors. In this thread you can find an introduction to Bayesian linear regression. As about priors, using $\mathcal{N}(0, 10)$ prior for the parameters is equivalent to imposing your prior knowledge. On another hand, if you knew that the bounds are hard, i.e. parameters cannot go beyond them, you'd use a bounded prior, e.g. truncated normal distribution. Be warned however that the Bayesian formulation of ridge regression does not behave exactly the same, there were studies showing that using stronger priors may be needed to achieve the regularization effect.
|
[
"stackoverflow",
"0057025264.txt"
] | Q:
Installing docker on parrot os
I am new to Linux and using Parrot Os (Home Edition). I am trying to install Docker on the same. But have been unable to do so.
This is for running MySQL and I also think that it will be useful to me later. I tried installing docker using APT package manager as follows:
sudo apt-get install docker
The installation completes but after that it when i try to start the service, it says
Failed to start docker.service: Unit docker.service not found.
Since I am an newbie, please give detailed answer or place links so that i can read it myself?
Thanks.
A:
Just confirm the docker installation after sudo apt-get install docker is successful.
From the error, it seems docker.service file is not created after installation.
Try to create the docker.service file manually. Refer this.
You probably need to create /etc/systemd/system/docker.socket file with these contents. And /etc/systemd/system/docker.service file with these contents.
Hope this helps.
|
[
"bitcoin.stackexchange",
"0000079747.txt"
] | Q:
How do I calculate the witness commitment hash for a given block?
From my understanding, every SegWit enabled block has an added output script which is used as a place to store the "Witness commitment" specified in BIP 141.
One issue I've stumbled upon was calculating the commitment hash value only given the raw block/transaction data.
For example, I've chosen Block #542213 as it only has 4 total transactions (including the coinbase generation)
Coinbase witness commitment script:
OP_RETURN OP_PUSHDATA(36) [aa21a9ed4a657fcaa2149342376247e2e283a55a6b92dcc35d4d89e4ac7b74488cb63be2]
BIP141 states that the pushed data can be broken down to the following:
0xaa21a9ed - Commitment header (seemingly random)
0x4a657fcaa2149342376247e2e283a55a6b92dcc35d4d89e4ac7b74488cb63be2 - SHA256(SHA256(witness root hash|witness reserved value))
The documentation mentions that the witness root hash can be derived similarly to the merkle root in a block header, where each wtxid acts as the txid would in a traditional header merkle root.
To test this, I'm using this PHP script kindly provided on a different thread. This generates the merkle root used in the block header perfectly (that is not what I am trying to do, but what I have done to verify the code actually works).
Our example block has 4 transactions. Only two of which have witness data (coinbase and this tx).
The commitment structure states that the wtxid of the coinbase transaction is always:
0x0000000000000000000000000000000000000000000000000000000000000000
and every other wtxid act as a leaf.
My first question:
How are transactions that do not have witness data effected in the witness hash? Are they entirely omitted?
Assuming that the non-witness transactions are just omitted entirely from the merkle tree, I simply add the coinbase and the one transaction with witness data's wtxid into the array like so:
$txids = array(
'0000000000000000000000000000000000000000000000000000000000000000',
'6c6e3849acf1b570db352dc08f7776e99c344a56fbb2f019e1865d1b6e044889',
);
The result being: 3a84e2f2f1bcd42141b58f2acd9497296c9f2d710cc2164669ef6d7e3870dfe9
My second question:
Where does the (concatenated?) witness reserved value come from?
Here it states:
The witness reserved value currently has no consensus meaning, but in the future allows new commitment values for future softforks
But it is still unclear to me what this value actually is before the hash is computed.
Please feel free to correct any inconsistencies or problems with my train of thought so I can improve my understanding for this part of segregated witness.
A:
How are transactions that do not have witness data effected in the
witness hash? Are they entirely omitted?
It will still include transactions that are not witness, it will just compute the normal hash to use as a leaf in the tree. See BlockWitnessMerkleRoot() in src/consensus/merkle.cpp and ComputeWitnessHash() in src/primitives/transaction.cpp:
uint256 CTransaction::ComputeWitnessHash() const
{
if (!HasWitness()) {
return hash;
}
return SerializeHash(*this, SER_GETHASH, 0);
}
Also, you are forgetting to reverse endianess, and hash the witness reserved value 0000000000000000000000000000000000000000000000000000000000000000 (from the last 32 bytes of the coinbase input witness). So step by step:
$ reverse_endian 66beaceb4be99da1e9824448231ab4fd37bacaee912381e779b37cf0e1dadad7
d7dadae1f07cb379e7812391eecaba37fdb41a23484482e9a19de94bebacbe66
$ reverse_endian aecb37e25954e15489e25548eb663ffdfd8a1362cac757ad62e9614453d2a577
77a5d2534461e962ad57c7ca62138afdfd3f66eb4855e28954e15459e237cbae
$ reverse_endian 5b211bc589cbdf5ad86cab1e2fe91f01c8ab934d21536b35864d30a3ff778456
568477ffa3304d86356b53214d93abc8011fe92f1eab6cd85adfcb89c51b215b
$ hash256 0000000000000000000000000000000000000000000000000000000000000000d7dadae1f07cb379e7812391eecaba37fdb41a23484482e9a19de94bebacbe66
d822d7717f284b89ea6a97874af567e9887a26a9f7db449ce02377d8fae4643f
$ hash256 77a5d2534461e962ad57c7ca62138afdfd3f66eb4855e28954e15459e237cbae568477ffa3304d86356b53214d93abc8011fe92f1eab6cd85adfcb89c51b215b
c182a158773ea7fc7a252fa725fc726de2a171088b40528ca00de0569fe53afe
$ hash256 d822d7717f284b89ea6a97874af567e9887a26a9f7db449ce02377d8fae4643fc182a158773ea7fc7a252fa725fc726de2a171088b40528ca00de0569fe53afe
30d002641e0eb81b11c3d14f4b120e80b4c06bcb3d34d90a5a606ca85e90c841
$ hash256 30d002641e0eb81b11c3d14f4b120e80b4c06bcb3d34d90a5a606ca85e90c8410000000000000000000000000000000000000000000000000000000000000000
4a657fcaa2149342376247e2e283a55a6b92dcc35d4d89e4ac7b74488cb63be2
Which matches the op_return data in the second coinbase output: RETURN PUSHDATA(36)[<aa21a9ed> <4a657fcaa2149342376247e2e283a55a6b92dcc35d4d89e4ac7b74488cb63be2>]
Where does the (concatenated?) witness reserved value come from?
I alluded to this before, but it is in the witness field of the coinbase input:
the coinbase's input's witness must consist of a single 32-byte array
for the witness reserved value - BIP 141
|
[
"stackoverflow",
"0048515930.txt"
] | Q:
Excel using index & match instead of vlookup
My goal is to get student grades with INDEX & MATCH from G column to B column. I can do it with VLOOKUP function but could someone help me to get them with INDEX & MATCH?
My goal output:
A:
Please paste this in B2 and drag:
=INDICE($F$2:$G$5;CONFRONTA(A2;$F$2:$F$5;0);2)
Translation:
=INDEX($F$2:$G$5,MATCH(A2,$F$2:$F$5;0),2)
|
[
"stackoverflow",
"0032750871.txt"
] | Q:
my xpath is good, but i've got nothing with scrapy
I try to scrap one page with scrapy. I found the xpath with FireXpath (a firefox plugin), and it seem good. But with Scrapy, I've got no result.
My python program look like this:
#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
from scrapy.selector import Selector
from scrapy.contrib.spiders import CrawlSpider
from datetime import datetime
from scrapy.spider import BaseSpider
class robtex(BaseSpider):
# Crawling Start
CrawlSpider.started_on = datetime.now()
# CrawlSpider
name = 'robtex'
DOWNLOAD_DELAY = 3
start_urls = [ "https://www.whois.com/en/advisory/dns/com/stackoverflow/whois.html"]
def parse(self, response):
# Selector
sel = Selector(response)
print sel.xpath(".//*[@id='datawhois']/div[2]/table[3]/tbody/tr[3]/td[2]/a/text()").extract()
How to fixe it ?
Thanks in advance.
A:
You just need to remove tbody from the XPath expression:
.//*[@id='datawhois']/div[2]/table[3]/tr[3]/td[2]/a/text()
Demo:
$ scrapy shell https://www.robtex.com/en/advisory/dns/com/stackoverflow/whois.html
In [1]: response.xpath(".//*[@id='datawhois']/div[2]/table[3]/tbody/tr[3]/td[2]/a/text()").extract()
Out[1]: []
In [2]: response.xpath(".//*[@id='datawhois']/div[2]/table[3]/tr[3]/td[2]/a/text()").extract()
Out[2]: [u'STACKOVERFLOW.COM']
|
[
"stackoverflow",
"0010240167.txt"
] | Q:
python try-except
I have this code:
#! /usr/bin/python
import sys, string
def findAll(search, fh):
count = 0
for line in fh:
count += 1
if line.find(search) != -1:
print "%3d: %s"%(count, line.rstrip())
return count
search = raw_input("Enter string to be found: ")
filename = raw_input("Enter filename: ")
fh = open(filename, "rU")
findAll(search, fh)
My professor recommended I write this code and incorporate "improved usage".
I'm confused as to how but she recommended that
I modify the program by commenting out the raw_input() statements, then adding statements to check if the program is invoked with fewer than 2 arguments and if so to print 'Usage: findstring.py string filename. The code takes strings and locates them in a file.
I use the filename command line argument from sys.argv to open the file and prepare for an input/output error (IOError) to occur. Then to use a try-except block to encode what to do if opening the file works or not.
If the opening fails, I print 'Error: cannot open findstring.py where findstring.py is also the considered the text file.
To be honest... I was so busy writing down her suggestions that I had no idea how to do many of the things she recommended. Can someone help improve this code? I'm confused and I don't know how to do this. My prof did say that the code would run, but I don't know how to modify it.
A:
For improved usage, try using the argparse module. It makes taking command-line options easier.
http://docs.python.org/library/argparse.html#module-argparse
A code sample from the above link reads:
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print args.accumulate(args.integers)
Now think about how you might modify this sample for your assignment. You need to take strings (search term, filename) instead of integers.
For the try/except block, remember that the code to handle an error goes in the except portion of the block. That is, you might consider showing an error message in the except block.
|
[
"stackoverflow",
"0033785417.txt"
] | Q:
What the metrics names on dropwizard means
I integrated dropwizards on my machine.
I exposed them but I am looking for information what they means.
for example how can I get the number of requests per sec? any such information is available anywhere coz I couldnt find it on the official site.
thanks.
A:
It seems that vertx-dropwizard-metrics are using some customised meters. In their javadoc you can find the following:
/**
* A throughput metric, wraps a {@link Meter} object to provide a one second instant
* throughput value returned by {@link #getValue()}.
*
* @author <a href="mailto:[email protected]">Julien Viet</a>
*/
For more details see this commit.
So their documentation is little out-of-date.
|
[
"stackoverflow",
"0048324176.txt"
] | Q:
How to correctly inherit a class from sale module and change fields
I'm trying to inherit the "sale" module and work with my own product class. So I created this class:
class mymodule_product(models.Model):
_name = "mymodule.product"
_description = "mymodule Product Description"
name = fields.Char('Description', required= True)
code = fields.Integer('Code', required= True)
category_id = fields.Many2one('mymodule.category','Category')
And I created another class that has the field that I want to add it to the sales order lines:
class mymoduleSaleOrder(models.Model):
_name = 'mymodule.sale.order'
mymodule_product_id = fields.Many2one('mymodule.product', string='Products', required=True)
Then I created this xml code:
<record id="mymodule_sale_order_form_view" model="ir.ui.view">
<field name="name">mymodule.sale_order.form.view</field>
<field name="model">mymodule.sale.order</field>
<field name="inherit_id" ref="sale.view_order_form"/>
<field name="arch" type="xml">
<field name="product_id" position="replace">
<field name="mymodule_product_id" />
</field>
</field>
</record>
I added this code to manifest.py:
'depends': ['base', 'sale'],
When I upgrade my module I got this error:
File "..\odoo\addons\base\ir\ir_ui_view.py", line 380, in write
return super(View, self).write(self._compute_defaults(vals))
File "..\odoo\models.py", line 3557, in write
self._write(old_vals)
File "..\odoo\models.py", line 3708, in _write
self._validate_fields(vals)
File "..\odoo\models.py", line 1079, in _validate_fields
raise ValidationError("%s\n\n%s" % (_("Error while validating constraint"), tools.ustr(e)))
ParseError: "Error while validating constraint
Field `origin` does not exist
Error context:
View `mymodule.sale_order.form.view`
[view_id: 934, xml_id: n/a, model: mymodule.sale.order, parent_id: 539]
None" while parsing file:.../views/sale_order.xml:4, near
<record id="mymodule_sale_order_form_view" model="ir.ui.view">
<field name="name">mymodule.sale_order.form.view</field>
<field name="model">mymodule.sale.order</field>
<field name="inherit_id" ref="sale.view_order_form"/>
<field name="arch" type="xml">
<field name="product_id" position="replace">
<field name="mymodule_product_id"/>
</field>
</field>
</record>
When I try this python code instead :
class mymoduleSaleOrder(models.Model):
_name = 'mymodule.sale.order'
_inherit = 'sale.order'
mymodule_product_id = fields.Many2one('mymodule.product', string='Products', required=True)
I got this error:
ParseError: "Error while validating constraint
Field `randa_product_id` does not exist
Please Help.
Thanks.
A:
If I've understood you well you want to create a new customized class of products and replace the old one in sale order lines. So, you have your mymodule.product class well defined, but you don't have to create a new class for sale orders nor sale order lines, just inherit from the existing one:
class SaleOrderLine(models.Model):
_inherit = 'sale.order.line'
mymodule_product_id = fields.Many2one(
comodel_name='mymodule.product',
string='Products',
required=True
)
Then, your XML code must be like this one (I recommend you not to replace the original field product_id, just hide it. And I also recommend you to use xpath because there are several ocurrences of product_id field in the original view and if you don't, you're only going to modify the last one):
<record id="mymodule_sale_order_form_view" model="ir.ui.view">
<field name="name">mymodule.sale_order.form.view</field>
<field name="model">sale.order</field>
<field name="inherit_id" ref="sale.view_order_form"/>
<field name="arch" type="xml">
<xpath expr="//field[@name='order_line']/form//field[@name='product_id']" position="attributes">
<attribute name="invisible">1</attribute>
</xpath>
<xpath expr="//field[@name='order_line']/form//field[@name='product_id']" position="after">
<field name="mymodule_product_id" />
</xpath>
<xpath expr="//field[@name='order_line']/tree/field[@name='product_id']" position="attributes">
<attribute name="invisible">1</attribute>
</xpath>
<xpath expr="//field[@name='order_line']/tree/field[@name='product_id']" position="after">
<field name="mymodule_product_id" />
</xpath>
</field>
</record>
|
[
"stackoverflow",
"0043279070.txt"
] | Q:
JPA/EclipseLink Error in Creating Tables
I am trying to create a table using EclipseLink. The java class being used is :-
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Id;
@Entity
public class Submissions {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
private String XID;
private String Y;
@Temporal(TemporalType.DATE)
private Date uDate;
private String level;
private String state;
public Submissions() {
}
//All Relevant getter and setter functions
}
The relevant persistence xml in question is as follows:-
<persistence-unit name="SubmissionIds">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.obp.selenium.DataObjects.OriginationSubmissions</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:oracle:thin:@localhost:1521:orcl" />
<property name="javax.persistence.jdbc.user" value="------" />
<property name="javax.persistence.jdbc.password" value="------" />
<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode"
value="database" />
<!-- <property name="eclipselink.canonicalmodel.subpackage"
value="originationSubmissions" /> -->
</properties>
</persistence-unit>
We use the standard method is by implementing the EntityManagerFactory as :-
EntityManagerFactory factory = Persistence.createEntityManagerFactory("SubmissionIds");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
em.getTransaction().commit();
em.close();
However I keep getting the following errors :-
EL Warning]: 2017-04-07 14:04:53.768--ServerSession(1650327539)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.3.v20160428-59c81c5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: ORA-00904: : invalid identifier
Error Code: 904
Call: CREATE TABLE SUBMISSIONS (ID NUMBER(19) NOT NULL, XID VARCHAR2(255) NULL, Y VARCHAR2(255) NULL, LEVEL VARCHAR2(255) NULL, STATE VARCHAR2(255) NULL, UDATE DATE NULL, PRIMARY KEY (ID))
Query: DataModifyQuery(sql="CREATE TABLE SUBMISSIONS (ID NUMBER(19) NOT NULL, XID VARCHAR2(255) NULL, Y VARCHAR2(255) NULL, LEVEL VARCHAR2(255) NULL, STATE VARCHAR2(255) NULL, UDATE DATE NULL, PRIMARY KEY (ID))")
A:
Avtually Eclipse reported a bug that rises when there is a reserved word usage you can fine here :
https://bugs.eclipse.org/bugs/show_bug.cgi?id=260637.
the problem comes from using a reserved word I dont actually know your DBMS, if it is Mysql your attributs
XID and LEVEL
is a reserved word. you can find mysql reserved word here :
https://dev.mysql.com/doc/refman/5.7/en/keywords.html.
You can also se from the sql code used to build your tables that there is a column name update of type DATE
UDATE DATE NULL
So to my opinion, you also need watch your attribut name on uDate
|
[
"stackoverflow",
"0039848084.txt"
] | Q:
Memory error python computing permutations of list
I want to compute all possible ways of constructing a binary list of length n with the following line
combinations = map(list, itertools.product([0, 1], repeat=n))
This works fine with low n's but I want to compute this for big n's (i.e. values between 25-35). Is there a better and more efficient way of producing this list?
A:
Just create the list "lazily", so as to not store the entire thing in memory at once:
n = some-largish-value
for i in itertools.product([0, 1], repeat=n):
result = do_something_with(list(i))
|
[
"italian.stackexchange",
"0000005516.txt"
] | Q:
Solo vs soltanto vs solamente?
I was trying to find out how to translate the word "only" and found three separate words. Could someone help me understand when each of these is used and what the differences are between them? Examples would be amazing.
A:
There is no difference between the adverbs solo, solamente, and soltanto in terms of meaning and usage. The only difference I can think of comes down to a matter of style: if you have already used adverbs ending with -mente in your sentence, then it’s better to choose either solo or soltanto rather than solamente.
The Treccani dictionary says that solo “[s]i alterna a solamente e soltanto (rispetto ai quali è più fam.)” [trad.: “alternates with solamente and soltanto, compared to which is more familiar”] (sub voce “solo”). Actually, I would say that solo is slightly more common, but not limited to a specific register, as you can find it in every kind of texts.
Indeed, solo is more immediate and spontaneous than the other two synonyms:
Quest’auto mi è costata solo diecimila euro! [This car only set me
back € 10,000!]
You can also use soltanto and solamente, of course, but, given that it’s a colloquial sentence, solo turns out to be more spontaneous and direct, as it’s shorter.
A:
Hope the following extract may help:
Solo, soltanto and solamente are both adverbs and conjunctions and their use as such is interchangeable.
As an adverb their meaning would be equivalent to the English adverb "only" (as in solely, merely or exclusively). For example: Parlo solo/soltanto/solamente inglese. I speak only English
As a conjunction their meaning would be equivalent to the English conjunction "only" and convey an adverse meaning by describing a negative quality to something otherwise positive. For example: La pizza e buona, solo/soltanto/solamente un po' salata. (The pizza is good, only a little salty).
Solo, in addition to being an adverb and a conjunction is also an adjective and a noun:
as an adjective it means something similar to "alone" as in "without company". For example: Viaggio sempre solo. I travel always alone. Or this other one: Dopo la partenza della mia fidanzata sono rimasto solo nella stanza. After the departure of my fiancèe I remained alone in the room.
as a noun (male) it means sole, single, and its meaning is similar to that of the adjective "only" in English (as in "the one"; "the one person"; "the only person"; "the only one" - This is kind of interesting considering that in English "only" does not have a noun function but it uses a noun to approximate its meaning to the equivalent of the Italian noun solo). For example: Credo che tu non sia il solo ad avere questi dubbi. I think that you are not the only one to have these doubts. In music jargon its meaning would be "soloist or solo". For example: Questa e una composizione per solo. This is a composition for (a) soloist/solo.
Recap:
Solo/Soltanto/Solamente When used as an adverb or as a conjunction they can be interchanged. These three words translate to "only" (adverb and conjunction) in English.
Solo is also an adjective and a noun. When it functions as an adjective or as a noun its use cannot be interchanged with soltanto/solamente.
In all three cases (adjective, adverb and conjunction) solo can be translated as only using the corresponding adjective, adverb and conjunction function that the word only has in English. In the case of the noun function it can be translated as "the only one" because only does not have a noun function in the English language.
|
[
"stackoverflow",
"0008459282.txt"
] | Q:
turning off form assistant in mobile safari?
When running on a touchscreen device (iPhone, in my case, but I presume it does this on others), when the virtual keyboard pops up for a form field, there are added navigation buttons at the top of the keyboard: "previous", "next", "done". (And sometimes "autofill").
This is apparently the Mobile Safari "form assistant".
I find this redundant, superfluous, and confusing. iPhone users aren't used to this in native apps, and it's unnecessary. It's a touch device. You touch what you want to change. There's no need for navigation buttons!
I suppose users may be familiar with this, IF they use their device often to fill forms on websites. I've had an iPhone since the 3G, and never noticed this. I don't think I've ever filled a form on Mobile Safari! (I would use my desktop...)
The form assistant is there for navigating forms on websites, which might not be designed appropriately for a mobile device. So, in that context it serves a useful purpose.
But when using JQuery Mobile, you ARE designing an interface for use on a touchscreen mobile device. There shouldn't be a need for the form assistant. I find it particularly annoying in a local app (PhoneGap, Rhodes, etc.).
I've done some searches, and haven't come up with a solution.
Does anybody know how to turn this off?
A:
There is no solution for mobile Safari, but for PhoneGap there certainly is.
As of 2.6.0 there is an option in the config.xml
<preference name="HideKeyboardFormAccessoryBar" value="true" />
For versions before 2.6.0, or more sophisticated use, there is the KeyboardToolbarRemover, which even allows to dynamically show and hide the keyboardAcessoryView.
In your Javascript, include the module
var toolbar = cordova.require('cordova/plugin/keyboard_toolbar_remover');
To disable the toolbar
toolbar.hide()
To re-enable the toolbar
toolbar.show()
|
[
"stackoverflow",
"0031840120.txt"
] | Q:
wenzhixin bootstrap-table detailView (child row) not initializing
I am using the wenzhixin bootstrap table and I am trying to get another bootstrap table to initialize in the child row which is referred to in the code as 'detailView'.
I was using datatables but this, so far, seems simpler and more straight forward to work with.
I will be passing the key from the parent row to the child row. Right now I am just using a static table that I got to initialize outside of the child row, now I am simply moving it to the child row, trying to get it to initialize, and then I will make the content dynamic.
The data is passing, but it does not seem the table is initializing. I'm wondering if I need to hide a table somewhere that I can initialize behind the scenes and then pass the content to the row (seems messy, but I can't think of another way to pull this off).
my code to initalize the detailView in the main table;
detailView: true,
detailFormatter: 'compExtInfo',
here is what I am returning to the child row (detailView)
function compExtInfo(index, row) {
var pAPI = row.api;
var hOut = '<table data-toggle="table" data-url="./completion/getcompletionext.php?api=49-037-28606">'+
'<thead>'+
'<tr>'+
'<th data-field="api" data-visible=false>API</th>'+
'<th data-field="finalfieldreport">Last Fld Rp</th>'+
'<th data-field="onbase">OnBase</th>'+
'<th data-field="tbg">Tbg</th>'+
'<th data-field="active">Actv</th>'+
'</tr>'+
'</thead>'+
'</table>';
console.log(hOut);
return hOut;
}
here is the table / grid that will fully initialize if placed alone outside of a child table (same code as above, literally copied and pasted into the function).
<table data-toggle="table" data-url="./completion/getcompletionext.php?api=49-037-28606">
<thead>
<tr>
<th data-field="api" data-visible=false>API</th>
<th data-field="finalfieldreport">Last Fld Rp</th>
<th data-field="onbase">OnBase</th>
<th data-field="tbg">Tbg</th>
<th data-field="active">Actv</th>
</tr>
</thead>
</table>
A:
I found a solution for this finally, code is listed below.
Main table initializations for the child row listed below;
detailView: true,
onExpandRow: function (index, row, $detail) {
compExtInfo($detail, row);}
Function called from the main table; get row key and pass to table builder
function compExtInfo($detail, row) {
pAPI = row.api;
buildTable($detail.html('<table></table>').find('table'), pAPI);
}
Table builder function
function buildTable($ext, api) {
$ext.bootstrapTable({
url: './completion/getcompletionext.php?api='+api,
columns: [
{
field: 'api',
visible: false,
title: 'API'
},{
field: 'finalfieldreport',
title: 'Last Fld Rp'
...
]
});
}
|
[
"stackoverflow",
"0009250044.txt"
] | Q:
bind second ddl depending on the first ddl
I have a page where I have a LeagueDDL, a ClubDDL and then a list of players. What I want to achieve is that the user will choose the League, after that the Clubs are bound to the second DDL according to the ID of the League, and when the user also chooses the Club, a list of players are bound to the View depending on the ClubID.
So far I have the following :-
View :-
<script type="text/javascript">
function populateClubsDropdown() {
$("#ddlClubs").empty();
var typeID = getLeagueID();
$.getJSON('@Url.Action("GetClubsByLeague", "Footballer")?TypeID=' + typeID, function (result) {
$.each(result, function () {
$("<option>").attr("value", this.ClubID).text(this.Club).appendTo("#ddlClubs");
});
});
}
function getLeagueID() {
var leagueID = $("#ddlLeagues").val();
return leagueID;
}
</script>
@Html.DropDownListFor(model => model.League.LeagueID, Model.LeagueList,
new { id = "ddlLeagues", onChange = "$:populateClubsDropdown()" })
@Html.DropDownListFor(model => model.Club.ClubID, Model.ClubList, new { id = "ddlClubs" })
and in my controller I have :-
public ViewResult Index()
{
League league = new League();
string selected = "Please Select";
model.LeagueList = model.PopulateLeagueDDL(selected, league, null);
Club club = new Club();
model.ClubList = model.PopulateClubDDL(selected, league, club, null);
model.Footballers = db.Footballers.Include("Club").Include("Position").Include("Status").Include("Country");
return View(model);
}
public JsonResult GetClubsByLeague(int LeagueID)
{
var result = footballersDAL.GetClubsByLeagueId(LeagueID).Select(
c => new { ClubID = c.ClubID, Club = c.ClubName });
JsonResult jsonResult = new JsonResult { Data = result, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
return jsonResult;
}
When I launch the page the first time, both Dropdowns are correct, however when I change the LeagueDDL, I get an empty second DDL. And the Json breakpoint is not being hit.
I would appreciate some help on this, I can't quite figure out what I have wrong.
UPDATE TO VIEW
<script type="text/javascript">
function populateClubsDropdown() {
$("#ddlClubs").empty();
var typeID = getLeagueID();
$.getJSON('@Url.Action("GetClubsByLeague", "Footballer")?TypeID=' + typeID, function (result) {
$.each(result, function () {
$("<option>").attr("value", this.ClubID).text(this.Club).appendTo("#ddlClubs");
});
});
}
function getLeagueID() {
var leagueID = $("#ddlLeagues").val();
return leagueID;
$(function () {
$('#ddlLeagues').change(populateClubsDropdown);
});
}
@Html.DropDownListFor(model => model.League.LeagueID, Model.LeagueList,
new { id = "ddlLeagues" })
@Html.DropDownListFor(model => model.Club.ClubID, Model.ClubList, new { id = "ddlClubs" })
A:
It looks like the problem is here:
@Html.DropDownListFor(model => model.League.LeagueID, Model.LeagueList,
new { id = "ddlLeagues", onChange="$:populateClubsDropdown()" }) //What is"$:"?!
Change to:
@Html.DropDownListFor(model => model.League.LeagueID, Model.LeagueList,
new { id = "ddlLeagues", onChange = "populateClubsDropdown()" })
Usage of jQuery unobtrusive event listener is event better:
<script>
function populateClubsDropdown() {
$("#ddlClubs").empty();
var typeID = getLeagueID();
$.getJSON('@Url.Action("GetClubsByLeague", "Footballer")?TypeID=' + typeID, function (result) {
$.each(result, function () {
$("<option>").attr("value", this.ClubID).text(this.Club).appendTo("#ddlClubs");
});
});
}
$(function(){
$('#ddlLeagues').change(populateClubsDropdown);
});
</script>
@Html.DropDownListFor(model => model.League.LeagueID, Model.LeagueList,
new { id = "ddlLeagues"})
@Html.DropDownListFor(model => model.Club.ClubID, Model.ClubList,
new { id = "ddlClubs" })
Update:
It's looks like you send the wrong parameter to the action:
should be LeagueID but you send TypeId~
|
[
"stackoverflow",
"0056457551.txt"
] | Q:
c# return named tuple from linq join
i'am trying to perform a join between a revision entity from nhibernate envers and a list with user names. i want to return a list of named tuples.
this is my code
public IEnumerable<(Societa company, DateTime datetime, string userName)> CompanyHistory()
{
IAuditReader auditReader = this._session.Auditer();
var revison = auditReader.CreateQuery().ForHistoryOf<Societa, RevisionEntity>().Results();
IList<Persona> user = _session.QueryOver<Persona>().List();
var query = revison.Join(user,
rev => rev.RevisionEntity.IdUtente,
us => us.Id,
(rev, us) => new
{
Oggetto = rev.RevisionEntity,
DataModifica = rev.RevisionEntity.RevisionDate.ToLocalTime(),
NomeUtente = us.NomePersona
}).ToList();
}
but now i didn't find a way to return the tuple
cast didn't work
ToValueTuple is not avaible to fro my query object
i try also
(ele, p) => new (OutputGA Oggetto, DateTime DataModifica, string NomeUtente)
{
Oggetto = ele.RevisionEntity,
DataModifica = ele.RevisionEntity.RevisionDate.ToLocalTime(),
NomeUtente = p.NomePersona
}).ToList();
but i got new cannot be used with tuple type
than
(ele, p) => new Tuple<OutputGA, DateTime, string>
{
Oggetto = ele.RevisionEntity,
DataModifica = ele.RevisionEntity.RevisionDate.ToLocalTime(),
NomeUtente = p.NomePersona
}).ToList();
and got error about parameter not corresponding
A:
You can try this
var tuples = data.Select(x => (A: x.A, B: x.B));
|
[
"politics.stackexchange",
"0000050195.txt"
] | Q:
Why didn't Mike Mohring run in the Thüringen MP election?
While discussing the election of Thomas Kemmerich one question came up: Why didn't Mike Mohring run in the third iteration of the MP election? He is from the third largest faction. Did they think that Grüne and SPD would rather vote for a FDP candidate than for a CDU candidate? I understand that having both an CDU and FDP candidate would have divided the conservatives's votes and likely Bodo Ramelow would have gained the simple majority.
The best explanation I had is that Mike Mohring has alienated the SPD and Grüne so much that they would never vote for him instead of the Linke, and so they hoped that the FDP candidate would gain their sympathy?
Or was it really some trick played to get elected via the AfD without having to officially announce it beforehand? And Mike Mohring did not want to do it but Thomas Kemmerich did not mind?
A:
Mohring already rejected running back in November 2019 because the CDU only placed third in the election, which didn't give them a clear mandate to govern:
„Wir haben mit Platz drei keinen Regierungsauftrag“, betonte sein Vize Mario Voigt. Der Wählerauftrag laute Opposition.
On the other hand, some in his faction such as Michael Heym didn't rule out collaboration with the fascist AfD even back then.
The SPD and Grüne supporting Mohring was never an option. For one, because they prefer Ramelow, and for another, a coalition of CDU/SPD/Grüne only has 35%, well below the required 50% (even if we add the 5% of the FDP). They would be dependent on votes from the AfD or Linke. The Linke, having gained much more votes, would insist on their own MP, and if CDU/FDP cooperate with the AfD, they wouldn't need SPD/Grüne.
The official version of events by the CDU/FDP is that they were merely supporting the candidate of the so-called "middle" and not expecting to win, which may be another reason Mohring wasn't running (it may leave a bad impression if a relatively large party loses the election; the FDP on the other hand only gained 5% of the votes, so they loosing doesn't look as bad).
There is no public evidence for an official collusion between the fascist AfD and the CDU/FDP (yet), though many theorized about the possibility of the FDP candidate being elected with the help of the AfD beforehand. This knowledge didn't stop the CDU/FDP from proceeding as they seemingly didn't expect such a large backlash to cooperation with fascists.
|
[
"mathoverflow",
"0000189407.txt"
] | Q:
Finding maximum of a function with unfixed number of variables
Can anybody solve this:
For a constant positive integer $n\geq6$
find $k$ and positive integers $a_{1},a_{2},...,a_{k}$
that maximize the expression
$$\sum_{i=1}^{k}\left[-4a_{i}^{3}+\left(3n-3\right)a_{i}^{2}+\left(3n+1\right)a_{i}\right],$$
with $a_{1}+a_{2}+\dots+a_{k}=n$.
Some of my experimental results shows that the optimal solution is attained at $k=3$, with $a_{1},a_{2},a_{3}$ roughly equal to $\frac{n}{3}$.
A:
Allow the variables to be zero, and take $k=n$.
If $a_i,a_j$ are changed to $a_i-1,a_j+1$, the function changes by $6(a_j-a_i+1)(n-2a_i-2a_j-1)$. From this, everything follows.
If there are four non-zero values, the smallest two of them sum to at most $n/2$, so it is advantageous to move them apart until one of them is 0. Therefore, the optimum occurs with at most three non-zero values.
If one value is greater than n/2, and there are two other nonzero values, it is likewise advantageous to move the two small values apart until one is 0: you get two non-zero values which are best as equal as possible. If there are three values all less than $n/2$, it is advantageous to move them together.
So the best is either two values near n/2 or three values near n/3. Try them and you'll see the second is better.
|
[
"stackoverflow",
"0039621748.txt"
] | Q:
Using angular-multi-select I want to show selected options upon load
I'm using angular-multi-select (https://github.com/isteven/angular-multi-select) and loading a table based on inputs that are locally stored. I am successfully loading my table with the inputs but as far as my mutliselect showing which options are selected that is not reflected. My multiselect dropdown shows "None Selected" upon load because it seems as though it clears out selected or 'ticked' items upon load, although my table is reflecting the selected items I want to show. How can I show preselected items in the dropdown on load? Here is the code I'm using...
<div ng-hide="loadingCompanies"
isteven-multi-select
input-model="companies"
output-model="multiSelect.payorCompanies"
button-label="name"
item-label="name"
tick-property="ticked"
output-properties="id ticked"
max-labels="1"
>
</div>
and in my controller I have...
$scope.multiSelect = {};
$scope.multiSelect.payorCompanies = ReportService.getStoredReportFilter().payorCompanies;
$scope.multiSelect.payorCompanies is an array of payorCompanies with the 'ticked' attribute equaling true.
A:
I got it. I actually just had to set each item in $scope.companies to have a 'ticked' attribute that equals true :)
|
[
"stackoverflow",
"0018092938.txt"
] | Q:
Windows 8 CredentialPicker - Advice for a Win8 beginner
I've been doing .NET console, .NET Webforms, and light WPF work before, but this is my first foray into Windows 8 Metro development.
I'm developing an app that's dependent on a web service that requires an authentication token. The app is kind of useless without this token; they only need to provide this token and not a username or password. The token can be revoked by the service provider in the event the app needs to be de-authorized.
Since the token is basically required for any app functionality; it needs to be global, it needs to persist for the lifetime of the app; it would be great if the app remembered the credential in a secure way after the app terminates to be loaded on the next run. I tried sticking a CredentialPicker in the App.xaml.cs file, however I guess the credentialpicker needs to be on an actual page? What's the best way to make this global, and spawn the credentialpicker whenever the model class detects there's no credentials for whatever reason?
My logic I thought would be:
Boot App
Load App Start Page
Check Disk for Credential Hash
If Hash Not Exist, Launch CredentialPicker
Validate Credential/Key
If Credential/Key not valid,
Relaunch CredentialPicker
Else
Store Credentials To Disk
Else
Use Existing Credentials; Proceed
Store Credentials In PasswordVault for use during this app lifecycle
Apologize for the verbosity; I just want to know best practices using an application-wide set of credentials in Win8
A:
If you're authenticating with a web service, you want to use the Web Authentication Broker instead (Windows.Security.Authentication.Web.WebAuthenticationBroker, also see the sample on http://code.msdn.microsoft.com/windowsapps/Web-Authentication-d0485122). The collection of credentials stays in the broker, and you get the server response back that typically contains the key you need for subsequent calls.
Using the credential picker for this purpose isn't really what you want, as that UI is primarily intended for enterprise scenarios, and still requires that you manage the credentials directly in the app. The Web Auth Broker was designed so the credentials always exists on the service and all you get back is the key. There is also a topic in the docs Web authentication broker for online providers on creating a login page that will work great inside the broker.
Note that you can use the password vault for the key--just give it some dummy username in the credential object.
|
[
"stackoverflow",
"0009108130.txt"
] | Q:
Getting rid of tags in parsing XML
I'm parsing the XML from BART's website at http://www.bart.gov/dev/eta/bart_eta.xml
I want to parse a single station, lets say Millbrae:
<?php
$xml = simplexml_load_file('http://bart.gov/dev/eta/bart_eta.xml');
foreach($xml->station as $station){
if($station->name=="Millbrae"){
foreach($station->eta as $eta) {
echo $eta->destination;
echo "<br>";
echo $eta->estimate;
echo "<br>";
}}
}
?>
That outputs the correct data from Millbrae, but the output has a lot of tags-its as if it outputs the entire xml file until it gets to Millbrae, rather than just Millbrae.
Is there a way to get rid of all those tags? I am just learning php and html, so I am not even sure if I'm asking this question properly.
Thanks
A:
Look into PHP manual: strip_tags.
function strip_tags — Strip HTML and PHP tags from a string
You can do it like this:
<?php
$xml = simplexml_load_file('http://bart.gov/dev/eta/bart_eta.xml');
foreach($xml->station as $station) {
if($station->name=="Millbrae") {
foreach($station->eta as $eta) {
echo strip_tags ($eta->destination); //use strip_tags here
echo "<br>";
echo strip_tags ($eta->estimate); //use strip_tags here
echo "<br>";
}
}
}
?>
|
[
"stackoverflow",
"0003670570.txt"
] | Q:
Getting screen reader to read new content added with JavaScript
When a web page is loaded, screen readers (like the one that comes with OS X, or JAWS on Windows) will read the content of the whole page. But say your page is dynamic, and as users performing an action, new content gets added to the page. For the sake of simplicity, say you display a message somewhere in a <span>. How can you get the screen reader to read that new message?
A:
The WAI-ARIA specification defines several ways by which screen readers can "watch" a DOM element. The best supported method is the aria-live attribute. It has modes off, polite,assertive and rude. The higher the level of assertiveness, the more likely it is to interrupt what is currently being spoken by the screen reader.
The following has been tested with NVDA under Firefox 3 and Firefox 4.0b9:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-1.4.2.min.js"></script>
</head>
<body>
<button onclick="$('#statusbar').html(new Date().toString())">Update</button>
<div id="statusbar" aria-live="assertive"></div>
</body>
The same thing can be accomplished with WAI-ARIA roles role="status" and role="alert". I have had reports of incompatibility, but have not been able to reproduce them.
<div id="statusbar" role="status">...</div>
|
[
"stackoverflow",
"0057454841.txt"
] | Q:
how can I custom error message in AOP around annotations?
I want to custom error message in AOP around annotations.
I used to use @RestControllerAdvice before but It didn't work in AOP around method.
it outputs default error message.
I tried to input message in try ~ catch I know it's weird like //// 1 or //// 2
But I can't get to the point :(
TransactionAspect class
@Around("execution(* com.bono.server.controller..*(..))")
@Transactional
public Object caculatePerformanceTime(ProceedingJoinPoint proceedingJoinPoint) {
Object result = null;
try {
result = proceedingJoinPoint.proceed();
} catch (CustomeException e) { ////// 1
throw new ErrorMessage(CustomError.HTTP_400_MISTYPE);
}
catch (Throwable throwable) { /////// 2
return new ErrorMessage(CustomError.HTTP_400_MISTYPE);
}
return result;
}
ErrorMessage class
@Getter
@Setter
public class ErrorMessage {
private int errorCode;
private String errorMessage;
public ErrorMessage(CustomError customError) {
this.errorCode = customError.errorCode();
this.errorMessage = customError.errorMessage();
}
}
GroupExceptionAdvice class
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GroupExceptionAdvice extends ResponseEntityExceptionHandler {
//// 1
@ExceptionHandler(value = CustomeException.class)
public ResponseEntity<CustomErrorResponse> customhandleNotSatisfied(Exception ex, WebRequest request) {
CustomErrorResponse error = new CustomErrorResponse();
error.setTimestamp(LocalDateTime.now());
error.setError(ex.getMessage());
error.setStatus(HttpStatus.NOT_FOUND.value());
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
//// 2
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = CustomException.class)
public ErrorMessage handlerUnResolvedAddressException(MisTypingException e) {
return new ErrorMessage(CustomError.HTTP_400_MISTYPE);
}
}
{
"timestamp": "2019-08-12T01:14:16.467+0000",
"status": 500,
"error": "Internal Server Error",
"message": "class com.bono.server.config.exception.ErrorMessage cannot be cast to class org.springframework.http.ResponseEntity (com.bono.server.config.exception.ErrorMessage and org.springframework.http.ResponseEntity are in unnamed module of loader 'app')",
"path": "/bono/api/alarm"
}
I want to show like this
{
"code" : 102,
"message" : "got it !"
}
A:
Converting my previous comments into an answer because the OP said that they solved his problem.
Your ErrorMessage class does not extend any Exception or Throwable, so how can you throw it? The code should not even compile and yield a compile error like:
No exception of type ErrorMessage can be thrown;
an exception type must be a subclass of Throwable
I.e. in your sample class I you ought to write something like
public class ErrorMessage extends Exception {
// (...)
}
for a checked exception or
public class ErrorMessage extends RuntimeException {
// (...)
}
for a non-checked exception. But your class definition does not extend anything, i.e. implicitly it directly extends Object.
|
[
"stackoverflow",
"0036906658.txt"
] | Q:
How to set ID of a XML-View in a component environment?
I want to access a view's controller from a custom module with some utility functions. Basically you can do this that way:
var oController = sap.ui.getCore().byId("__xmlview1").getController();
The problem is that the above coding will not work in a real environment because __xmlview1is dynamically created by the framework. So I tried to find a possibility to set the ID of the view during instantiation. The problem is - I could not find one:
Trying to give the view an ID in the view.xml file does not work:
<mvc:View
controllerName="dividendgrowthtools.view.dividendcompare"
id="testID"
xmlns="sap.m"
...
Trying to set the ID in the router configuration of the component does not work either:
...
name: "Dividend Compare",
viewId: "test",
pattern: "Dividend-Compare",
target: "dividendcompare"
...
The problem is that I do not have direct control over the instantiation of the XML view - the component respectively the router does it.
So, is there a solution for that problem? Or at least a save way to get the view ID by providing the name of the view?
A:
You should have a look at the SAPUI5 EventBus.
I am pretty sure, you want to let the controller to do something with the dividentcompare view. With the SAPUI5 Eventbus, you can publish actions from one controller to another witout braking MVC patterns.
In your dividendcompare.controller.js:
onInit : function() {
var oEventBus = sap.ui.getCore().getEventBus();
oEventBus.subscribe("MyChannel", "doStuff", this.handleDoStuff, this);
[...]
},
handleDoStuff : function (oEvent) {
var oView = this.getView();
[...]
}
Now, in your anothercontroller.controller.js:
onTriggerDividendStuff : function (oEvent){
var oEventBus = sap.ui.getCore().getEventBus();
oEventBus.publish("MyChannel", "doStuff", { [optional Params] });
}
You are now able to get the view from the dividentcontroller in every case from every other controller of your app. You dont access the view directly, this would brake MVC patterns, but can pass options to its controller and do the handling there.
|
[
"stackoverflow",
"0002112272.txt"
] | Q:
How do I create a 'Most Recently Popular' bar for content in Ruby on Rails?
I'm a noob so please forgive if this is an easy question but I'm trying to create a 'Most Recently Popular' output for specific content on a rails project.
Right now the object I am pulling from has an attribute revision.background_title. I want to calculate popularity by finding the number of specific background_title's added over the past seven days then put them in order. For example if there are 4 background_title's named 'awesomecontent' then that would be above one that has 1 background_title named 'less awesome content'
This pulls all of them:
@revisions = Revision.find(:all, :order => "created_at desc")
Thanks.
A:
You can use the basic ActiveRecord find method to do this. The code would end up looking something like this:
@revisions = Revision.all(
:select => "background_title, count(*) count", # Return title and count
:group => 'background_title', # Group by the title
:order => '2 desc' # Order by the count descending
)
To see the output, you could then do something like this:
@revisions.each do |revision|
puts "Revision #{revision.background_title} appears #{revision.count} times"
end
giving
Revision z appears 10 times
Revision a appears 3 times
Revision b appears 2 times
Another option would be to take a look at ActiveRecord::Calculations:
http://api.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html
Calculations supports a count method that also supports the group option. However, going this route will give you back a hash containing the background_title as the key and the count as the value. Personally, find the first method more useful.
|
[
"stackoverflow",
"0037156065.txt"
] | Q:
Million value giving NaN with jquery CounterUp
I have a value that is formatted like 2.083.817. When using jquery script CounterUp it gives me a NaN - probably because of the two "." separators.
The value is being converted with this:
var nums = [];
var divisions = $settings.time / $settings.delay;
var num = $this.text();
var isComma = /[0-9]+,[0-9]+/.test(num);
num = num.replace(/,/g, '');
var isInt = /^[0-9]+$/.test(num);
var isFloat = /^[0-9]+\.[0-9]+$/.test(num);
var decimalPlaces = isFloat ? (num.split('.')[1] || []).length : 0;
I am not quite sure how I can get the script to handle the value with the two "." separators.
A:
The solution is for the most of the time so close, that you will have a hard time finding it..
for (var i = divisions; i >= 1; i--) {
// Preserve as int if input was int
var newNum = parseInt(num / divisions * i);
// Preserve float if input was float
if (isFloat) {
newNum = parseFloat(num / divisions * i).toFixed(decimalPlaces).replace(".", ",");
}
// Preserve commas if input had commas
if (isComma) {
while (/(\d+)(\d{3})/.test(newNum.toString())) {
newNum = newNum.toString().replace(/(\d+)(\d{3})/, '$1' + '.' + '$2');
}
}
nums.unshift(newNum);
}
I just reverse it so it will be 2,083,817 in the html and then replace "," with a "." to get the desired output. Probably not the most perfect solution, but it works.
|
[
"stackoverflow",
"0039891838.txt"
] | Q:
Read or retrieve value from spreadsheet using existing rangenames
I have an existing excel file and it has already defined cell name or cell range names.
I am able to get all cell range names using Openxml sdk. My sample code is given below:
var path = @"D:\test.xlsx";
using (var document = SpreadsheetDocument.Open(path, true))
{
var workbookPart = document.WorkbookPart;
var wb = workbookPart.Workbook;
var definedNames = wb.DefinedNames;
if (definedNames != null)
{
System.Console.WriteLine("Name\tText\tName.Value");
foreach (DefinedName dn in definedNames)
{
System.Console.WriteLine(dn.Name + "\t" + dn.Text + "\t" + dn.Name.Value);
}
}
}
Is there any way to retrieve or read cell value from defined name using this OpenXml or any other SDK in c#?
A:
Accessing Named Ranges
If you have one or more Named Ranges you can access them in different ways:
A specific range/cell in the named range
// worksheet scope
var range = worksheet.Range("NameOfTheRange");
var cell = worksheet.Cell("NameOfTheRange");
// workbook scope
var range = workbook.Range("NameOfTheRange");
var cell = workbook.Cell("NameOfTheRange");
All ranges/cells specified in the named range (yes a named range can point to many ranges/cells)
// worksheet scope
var ranges = worksheet.Ranges("NameOfTheRange");
var cells = worksheet.Cells("NameOfTheRange");
// workbook scope
var ranges = workbook.Ranges("NameOfTheRange");
var cells = workbook.Cells("NameOfTheRange");
Worksheet scope from the workbook
One handy way to access named ranges is to access worksheet's range from the workbook.
For example:
var range = workbook.Range("Sheet1!Result");
var cell = workbook.Cell("Sheet1!Result");
Scope:
If you ask for a named range in a worksheet then ClosedXML will look on the worksheet and then the workbook if it can't find it.
For example, after creating a named range with workbook scope you can access it from either the workbook or worksheet (as long as there isn't one on the worksheet already.
// Create a range with workbook scope (the default)
worksheet.RangeUsed().AddToNamed("Result");
// Access it from the workbook:
var range = workbook.Range("Result");
// Access it from the worksheet:
// What happens here is that it will try to get the named range
// on the worksheet, when it fails it then gets the named range
// on the workbook
var range = worksheet.Range("Result");
Can't find it?
A null is returned if the named range doesn't exist.
Reference: Accessing Named Ranges
|
[
"stackoverflow",
"0053012885.txt"
] | Q:
sockjs-node/info? 404 (Not Found)
I've done lost of search for couple of hours now and still can't find what I'm looking for. Basically I get this error in the console when running ng serve in my Angular 6 app:
GET http://local.mywebsitesecure.com/sockjs-node/info?t=1540568455931 404 (Not Found)
Based on my research the solution could be just updating
webpack.config.js
However, I can't find webpack.config.js in my project. They also say to do:
"ng eject"
to create a webpack, but it doesn't seem to work.
SOLUTION: I can get it to work by running this (It actually works!):
ng serve --public-host=http://localhost:4200
BUT I want to be able to set this up somewhere in my app so that I can only do
ng serve
Does anyone know how to fix this issue and gid rid of this error (sockjs-node/info). Thanks a lot in advance!
A:
You can edit your angular.json file and add the option for public-host. Mind you all options are camelCased not kebab-cased.
...
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "congiftest:build",
"publicHost":"http://localhost:4200"
},
},
...
This will allow you to just run ng serve and the public-host flag will be added.
|
[
"stackoverflow",
"0040262326.txt"
] | Q:
EdgeDriver is sending two letters via SendKeys
I am using Selenium WebDriver 3.0 to perform some automate tests. I have simple login page where I input login email, password and log in. When I am using EdgeDriver it sends two same letters instead of one to password field. I really dont know why, because other drivers dont have this problem (IE, FF, CH). This is part of code
edgedriver.FindElement(By.Id("IDEmail")).Clear();
edgedriver.FindElement(By.Id("IDEmail")).SendKeys("[email protected]");
edgedriver.FindElement(By.Id("IDPass")).Clear();
edgedriver.FindElement(By.Id("IDPass")).SendKeys("1");
edgedriver.FindElement(By.Id("IDLogin")).Click();
this will end up with 11 in password field and clicking on login fail because wrong password. Any clues why EdgeDriver is doing it?. Using version Microsoft EdgeHTML 14.14393
A:
It appears that Edge is form filling the password. If the username/password is saved for the test website, then even though you clear the field, Edge will form-fill the password (in this case the string "1") and then you will sendKeys("1"), resulting in "11".
An immediate workaround would be to either remove the saved login credentials or login and let form fill handle the user credentials for you.
|
[
"stackoverflow",
"0034510905.txt"
] | Q:
how to make website circular progress bar which which changes starting point?
Check This ImageI want to Make a Circular Progress Bar for my Website.Which Change Its Starting Point With Button Click. For Example, When Button 1 Clicked It Should Rotate From 270 Degrees, When Button 2 Clicked It Should Rotate From 0 degree,When Button 3 clicked It Should Rotate From 90 degrees and When Button 4 Clicked It Should Start from 180 degrees.....
Please Help Me
Thanks In Advance..
A:
Keep in mind first that this is not a clear answer, cause a right one would take me time of coding.
I recently used a open-source library from github. Here is the link.
https://github.com/kottenator/jquery-circle-progress
It is exactly what you want (with some modifications).
Here is the example. https://kottenator.github.io/jquery-circle-progress/
If you see the fourth progress circle, you see that you can set your own starting angle.
Let me here explain how can this achieve having Example four as my reference:
/*
* Example 4:
* - solid color fill
* - custom start angle
* - custom line cap
* - dynamic value set
*/
var c4 = $('.forth.circle');
c4.circleProgress({
startAngle: -Math.PI / 4 * 3,
value: 0.5,
lineCap: 'round',
fill: { color: '#ffa500' }
});
With StartAgle you can set the start value of the progress bar.
You can easy update your code to make the circle over and over again until the content you want load.
See the usage of the library here : https://github.com/kottenator/jquery-circle-progress#usage
See that answer too:
https://stackoverflow.com/a/13371976/4108694
|
[
"drupal.stackexchange",
"0000105499.txt"
] | Q:
Create product programmatically
I have a product with a custom field, according to this. I know I can create product with
$cp = commerce_product_new('product');
$cp->is_new = TRUE;
$cp->revision_id = NULL;
$cp->uid = 1;
$cp->status = 1;
$cp->created = $cp->changed = time();
$cp->sku = $product[sku];
$cp->title = $product[name];
$cp->language = LANGUAGE_NONE;
$cp->commerce_price = array(LANGUAGE_NONE => array( 0 => array(
'amount' => $product[sale_price] ? $product[sale_price] : $product[retail_price],
'currency_code' => 'USD',
)));$product[retail_price];
commerce_product_save($cp);
but I have some custom field.
How can I create a Drupal Commerce product programmatically with full custom fields?
Is $cp->myfield1='22'; sufficient?
A:
A commerce product is an entity like any other, so...
$cp->field_my_field[LANGUAGE_NONE][0]['value'] = '22';
A:
Just a tweak: the create method on the product controller already has some defaults so no need to add things like is_new or status.
public function create(array $values = array()) {
$values += array(
'product_id' => NULL,
'is_new' => TRUE,
'sku' => '',
'revision_id' => NULL,
'title' => '',
'uid' => '',
'status' => 1,
'created' => '',
'changed' => '',
);
return parent::create($values);
}
So I'd just do:
$cp = commerce_product_new('product');
$cp->uid = 1;
$cp->sku = $product[sku];
$cp->title = $product[name];
$cp->language = LANGUAGE_NONE;
$cp->commerce_price = array(LANGUAGE_NONE => array( 0 => array(
'amount' => $product[sale_price] ? $product[sale_price] : $product[retail_price],
'currency_code' => 'USD',
)));$product[retail_price];
$cp->my_field[LANGUAGE_NONE][0]['value'] = 22;
commerce_product_save($cp);
|
[
"stackoverflow",
"0011197812.txt"
] | Q:
How to use git format-patch on initial commit
I need to get patch file for inital commit (which is not empty) for our review process, but I'm confused as git format-patch command only makes it from branch that is on initial commit not including it.
Seems it must be some obvious move but I'm completely missing it.
A:
Try git format-patch --root $SHA (where $SHA is that first commit)
A:
for making patch for a single commit just use
git format-patch -1 HEAD # where "1" is a number, not "ell".
where "HEAD" could be changed to any other commit, or even hash code. This works even if HEAD is the first commit. I am not sure whether you are asking for this.
|
[
"stackoverflow",
"0034665404.txt"
] | Q:
What does & (single ampersand), and | (single pipe) operator do in comparison operation?
In a statement like:
if (valueA & valueB) != 99 {
print("they don't equal 99")
}
What does the & operator do? I thought it would mean if valueA and valueB both don't equal 99 execute the block.
And then what does the | do in this statement:
if valueA != (99 | 0) {
print("it doesn't equal 99")
}
I thought it would mean if valueA doesn't equal 99 OR 0 execute the block. However neither of my assumptions seem to be correct.
The correct way to write the above statement is:
if valueA != 99 && valueB != 99 {
print("it doesn't equal 99")
}
It seems logical that the first if-statement proposed would be a very succinct way to write that as it shortens the code written and is still, if not more, explicit.
A:
Those are both Bitwise Operators, which let you manipulate the actual data bits.
The information below was copied as-is from the official documentation:
Bitwise AND Operator
The bitwise AND operator (&) combines the bits of two numbers. It returns a new number whose bits are set to 1 only if the bits were equal to 1 in both input numbers:
Bitwise OR Operator
The bitwise OR operator (|) compares the bits of two numbers. The operator returns a new number whose bits are set to 1 if the bits are equal to 1 in either input number:
|
[
"stackoverflow",
"0063086262.txt"
] | Q:
BufferedInputStream.mark() method not working as expected
Code :
import java.io.*;
public class BufferedInputStreamDemo {
public static void main(String[] args) throws IOException {
String phrase = "Hello World #This_Is_Comment# #This is not comment#";
byte[] bytes = phrase.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
BufferedInputStream bin = new BufferedInputStream(in);
int character;
boolean com = false;
while ((character = bin.read()) != -1) {
switch(character) {
case '#' :
if (com) com = false;
else {
com = true;
bin.mark(1000);
}
break;
case ' ' :
if (com) {
com = false;
System.out.print('#');
bin.reset();
}
else {
System.out.print((char)character);
}
break;
default : if (!com) System.out.print((char)character);
}
}
in.close(); bin.close();
}
}
What does this code do?
This code reads the String and the bufferStream removes/hides comments. Here comments are denoted by #this_is_comment# and comments with ' ' (space) is not considered comment ex :
#This is not comment#.
Question:
Whenever ' ' (space) is encountered and com (boolean value, when true does not read the stream) is true it reverts the stream to the marked position, my doubt is that if it reverts, wouldn't the # be encountered again and com will be set to false hence considering it comment.
case '#' :
if (com) com = false;
else {
com = true;
bin.mark(1000);
}
but this is not the case the output is correct.
If possible please edit the question to make it more understandable.
A:
The behavior is expected. If you read the implementation of the methods .mark() and .read() of BufferedInputStream, you can see that:
The method .mark() sets markPos to pos:
public synchronized void mark(int readlimit) {
marklimit = readlimit;
markpos = pos;
}
The question is who is pos? Just go to its definition and will find this in JavaDoc (only reporting the relevant part):
/**
* The current position in the buffer. This is the index of the next
* character to be read from the <code>buf</code> array.
* <p>
* ... more JavaDoc
*/
protected int pos;
Hence, when you call .reset() you're doing this:
public synchronized void reset() throws IOException {
getBufIfOpen(); // Cause exception if closed
if (markpos < 0)
throw new IOException("Resetting to invalid mark");
pos = markpos;
}
Basically, you're restoring the last "next character" of your stream.
To make it simple
According to the official JavaDoc of BufferedInputStream, if you are in a String s = "Hello World" and you call .mark() while reading character W, when you do .reset() you will restart from the next character after W which is o.
This is why your code doesn't fall in the comment part again.
|
[
"math.stackexchange",
"0001279788.txt"
] | Q:
Finding angles of hyperbolic triangles
I am trying to learn about how to find the angles of hyperbolic triangles. Now below is a problem:
It has all the steps but I am not understanding the concept (the ones that are underlined in green and yellow)
If you notice, $\measuredangle BAC=\frac{\pi}{2}-\measuredangle OAP=\measuredangle OPA$ but I do not know why.
On the other hand, I understand the computation parts but it is meaningless if I dont get the concept.
Anyone can help out?
A:
Note that $\measuredangle BAC$ is the angle centered at $A$ (and not, e.g. $B$). The geodesic $AC$ is orthogonal to the geodesic $AP$ (why?), implying the first relation. The second is similar, you only have to reflect the angle $\measuredangle 0BQ$ about the tangent to $BC$ in $B$.
The last equation in your question ("if you notice") is true, cause $OPA$ is a Euclidean rightangled triangle in which the angles sum up to $180°$. (This is part of the technique, to find helper triangles in which Euclidean geometry applies..)
Edit: it is, of course, essential for this reasoning, that the upper half plane is a conformal model of Hyperbolic space, i.e. the Euclidean angles are equal to the Hyperbolic ones.
|
[
"stackoverflow",
"0001593305.txt"
] | Q:
Align= "center" effect on data shown gridview rows
I am facing a weird situation, I am developing an asp.net website, and I added a gridview control, it is placed inside td tag.
When I ran the website online, I noticed that the data shown on the rows are shifted to the left while their header tags are centered, so I gave the td an align="center" property, trying to make the data show centered in each column, and that worked perfectly when debugging the site offline.
However, when I ran the site online (after upload), the data still showed shifted (or aligned left).
Am I missing something here?
A:
Try this:
<RowStyle HorizontalAlign="Center" />
<AlternatingRowStyle HorizontalAlign="Center" />
A:
Set this property in the gridview: RowStyle-HorizontalAlign="Center"
|
[
"stackoverflow",
"0001686271.txt"
] | Q:
How do I set file.encoding for a junit test in ant?
I'm not quite done with file.encoding and ant. How do I set the file.encoding for junit tests in ant? The junit ant task doesn't support the encoding attribute like the javac task does.
I've tried running «ant -Dfile.encoding=UTF-8» and «ANT_OPTS="-Dfile.encoding=UTF-8" ant» without success. System.getProperty("file.encoding") within a test still returns MacRoman.
A:
JUnit supports a child element <jvmarg ...> which should do what you want.
<junit fork="yes">
<jvmarg value="-Dfile.encoding=UTF-8"/>
...
</junit>
I assume you were using the fork=yes attribute since this starts a new JVM for the test run, thus the parameters you send into ant at the command line ant -Dfoo=bar do not necessarily propagate to the JVM running the tests.
|
[
"stackoverflow",
"0005344336.txt"
] | Q:
Can I have a default method in a base class that's always called before child implementations?
C# here - is it possible to have an abstract base class define a method with default behavior, and have this default be called before a child class implementation? For example:
public abstract class Base
{
public virtual int GetX(int arg)
{
if (arg < 0) return 0;
// do something here like "child.GetX(arg)"
}
}
public class MyClass : Base
{
public override int GetX(int arg)
{
return arg * 2;
}
}
MyClass x = new MyClass();
Console.WriteLine(x.GetX(5)); // prints 10
Console.WriteLine(x.GetX(-3)); // prints 0
Basically I don't want to have to put the same boilerplate in every child implementation...
A:
Callable by who would be the question. The way that I've dealt with this issue in the past is to create 2 methods, a public one in the base class and a protected abstract one (perhaps virtual with no implementation) as well.
public abstract class Base
{
public int GetX(int arg)
{
// do boilerplate
// call protected implementation
var retVal = GetXImpl(arg);
// perhaps to more boilerplate
}
protected abstract int GetXImpl(int arg);
}
public class MyClass : Base
{
protected override int GetXImpl(int arg)
{
// do stuff
}
}
|
[
"android.stackexchange",
"0000019803.txt"
] | Q:
How do I find my contacts?
My contacts have dissapeared from my phone, over night, for no reason. (Galaxy S) Althoug nothing else in the phone has been affected. The messages still exist, the history is there, but only listed with phone numbers and not my contacts. I have pulled the battery, I have pulled the sim card and battery together and I have restarted the phone. Nothing seems to work. I beleive the contacts are in the phone because under my history some names appear but not all of them. How do I trace /data/data/com.android.providers.contacts/databases/contacts.db to see if my contacts exist at all. Where do I start?
A:
Maybe you just unchecked some/all contact sources from showing up in the contact list?
Open the contact list -> open the context menu -> hit 'more' -> choose view settings
|
[
"stackoverflow",
"0038293521.txt"
] | Q:
Link Android SDK tools to Visual Studio
I have been using the android standalone SDK. Now I want to use it with Visual Studio Community.
I installed VScommunity but it goes ahead to download the entire SDK again which I do not want.
Is there a way I can link to it so the emulator and adb tools can be used by visual studio.
-Thanks
A:
Is there a way I can link to it so the emulator and adb tools can be used by visual studio.
By default VS installs the third party dependencies for you to run the tool. You can clear the checkbox of any component that you don't want to install in the Common Tools and Software Development Kits group of the Visual Studio installer.
VS detects the third party configuration of your Android SDK. And you can check or override them under Tools Menu->Options->Tools for Apache Cordova->Environment Variables Overrides.
For details about installing third party dependencies manually, you can refer to this document.
|
[
"stats.stackexchange",
"0000142534.txt"
] | Q:
Contradictory input/output pairs when training neural network?
I think this question can probably be generalized away from neural networks, bu there goes: How should we handle possibly contradictory data? Suppose the neural networks maps n-bit strings to a bit. What if our training data contains something like
01101 -> 0
01101 -> 1
What is the effect of something like this? Should both instances be deleted as training samples?
or
How should we classify data that is not necessarily deterministic?
A:
The Neural Network will handle this on its own. Depending on the number of instances of the contradictory data the Neural Network will iterate over the values and the eta will change the weights in the direction represented in the data. The net effect will be the majority of instances of the data will have the heaviest impact on the Neural Networks neurons.
Just leave them in, and you will get the "most probable" solution.
|
[
"stackoverflow",
"0014548427.txt"
] | Q:
Android fragment XML layout issue
I'm trying to achieve what I though would be a reasonably straightforward fragment layout, but I'm having some problems. Can anyone suggest the XML solution, roughly, for the following layout (I'm aware that there is now support for nested fragments, but I'd like to avoid this if possible):
"============================="
| 111111111111111111 | 333333333 |
| 111111111111111111 | 333333333 |
| 111111111111111111 | 333333333 |
| 111111111111111111 | 333333333 |
| 111111111111111111 | 333333333 |
| 111111111111111111 | 333333333 |
| ================== | 333333333 |
| 222222222222222222 | 333333333 |
| 222222222222222222 | 333333333 |
"============================="
A:
That is indeed a simple layout.
Is this what you are looking for?
The code would be the following:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#ff0000" >
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="#00ff00" >
</FrameLayout>
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="#0000ff" >
</FrameLayout>
</LinearLayout>
|
[
"stackoverflow",
"0035220901.txt"
] | Q:
Download a file to Downloads folder of device using Cordova FileTransfer
I am using Cordova FileTransfer object to download a file from a url to device.
var fileTransfer = new FileTransfer();
var path = cordova.file.dataDirectory;
fileTransfer.download(
fileUrl,
path + "/sample.pdf",
function(theFile) {
console.log("download complete: " + theFile.toURI());
alert("File downloaded to "+cordova.file.dataDirectory);
},
function(error) {
console.log(JSON.stringify(error));
}
);
In this case the file is downloaded to data/data/com.fileDemo/files/
(I am not sure whether download is success as I can't access this folder. Getting success message as download complete: file:///data/data/com.fileDemo/files/sample.pdf).
How can I use the same method to download a file to "Downloads" folder of the android device?
A:
In Cordova, with FileTransfer, you can request TEMPORARY or PERSISTENT file system
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, gotFS, fail);
iOS
PERSISTENT will return the Documents directory,
TEMPORARY will return the Caches directory
Android
PERSISTENT will returns the root of the SD card/phone memory
TEMPORARY will return a folder inside the data folder.
Refer File API & FileTransfer for more info.
|
[
"stackoverflow",
"0004667461.txt"
] | Q:
Porting a Python program to C
I would like to port a program which is using urllib and json (Python 3) to C. My question is which libraries exist to replace urllib and json in C and which are the best (easier, documented, fast)? If there are not good libraries in C I also accept C++
Thank you all.
A:
For JSON, json.org has a list of implementations for a variety of languages, including C. Most of them should be fairly lightweight and fast.
To replace urllib, you probably want to look at libcURL.
|
[
"stackoverflow",
"0042797220.txt"
] | Q:
Custom Colormap using Matplotlib.image
I am using matplotlib.image.imsave('file.png',file,cmap=cmap) to save a .png of a 2d Numpy array where the array can only have values of 0, 1 or 10. I would like 0 to be white, 1 to be green and 10 to be red. I saw something similar at this question: Matplotlib: Custom colormap with three colors . The problem is that imsave does not take norm as an argument but using pyplot is too slow for my application. Any assistance would be appreciated!
A:
The input array consisting of values [0,1,10] is not really an image array. Image arrays would go from 0 to 255 or from 0. to 1..
a. using a LinearSegmentedColormap
An idea can be to normalize your array im to 1.: im = im/im.max(). It is then possible to create a colormap with the values
0 -> white, 0.1 -> green, 1 -> red using matplotlib.colors.LinearSegmentedColormap.from_list.
import matplotlib.image
import numpy as np
im = np.random.choice([0,1,10], size=(90, 90), p=[0.5,0.3,0.2])
im2 = im/10.
clist = [(0,"white"), (1./10.,"green"), (1, "red")]
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("name", clist)
matplotlib.image.imsave(__file__+'.png', im, cmap=cmap)
The corresponding pyplot plot
import matplotlib.pyplot as plt
plt.imshow(im, cmap=cmap)
plt.colorbar(ticks=[0,1,10])
plt.show()
would look like this
b. using a ListedColormap
A ListedColormap can be used to generate a colormap of the three colors white, green and red. In this colormap the colors are equally spaced, so one needs to map the image array to equally spaced values as well. This can be done using np.unique(im,return_inverse=True)[1].reshape(im.shape), which returns an array containing only the values [0,1,2]. We again need to normalize to 1.
im = np.random.choice([0,1,10], size=(90, 90), p=[0.5,0.3,0.2])
im2 = np.unique(im,return_inverse=True)[1].reshape(im.shape)
im3 = im2/float(im2.max())
clist = ["white", "green","red"]
cmap = matplotlib.colors.ListedColormap(clist)
matplotlib.image.imsave(__file__+'2.png',im3, cmap=cmap)
While the output image looks exactly the same as above, the corresponding matplotlib plot would have a different colorbar.
import matplotlib.pyplot as plt
plt.imshow(im2, cmap=cmap)
cb = plt.colorbar(ticks=[0,1,2])
cb.ax.set_yticklabels([0,1,10])
plt.show()
|
[
"stackoverflow",
"0009980682.txt"
] | Q:
Sqlite rejecting quoted value as ambiguous column name
I'm using Sqlite 3.7.11 with Windows x64 Visual Studio 2010. The example below can be run from the sqlite3.exe tool. I get the same failures from code.
Given this table:
PRAGMA foreign_keys=ON;
CREATE TABLE hashes( id INTEGER PRIMARY KEY, hash CHARACTER(4) NOT NULL UNIQUE );
CREATE TABLE sources( id INTEGER PRIMARY KEY, source VARCHAR(64) NOT NULL UNIQUE );
CREATE TABLE files( hash_id INTEGER, source_id INTEGER, filename VARCHAR(2048), extension VARCHAR(16),
FOREIGN KEY(hash_id) REFERENCES hashes(id)
FOREIGN KEY(source_id) REFERENCES sources(id)
UNIQUE( hash_id, source_id, filename ) );
And this initial data:
INSERT INTO hashes VALUES( ?, "abcd" );
INSERT INTO sources VALUES( ?, "mysource" );
I'm adding rows like this. The files tables is referencing the hash and source tables per the constraints above.
INSERT INTO files ( hash_id, source_id, filename, extension )
SELECT hashes.id, sources.id, "filename.ext", "ext"
FROM hashes, sources
WHERE hashes.hash = "abcd" AND sources.source = "mysource";
Everything works fine until 'id' shows up in either the filename or extension field. This doesn't make any sense -- it's quoted. Both of these inserts will fail:
INSERT INTO files ( hash_id, source_id, filename, extension )
SELECT hashes.id, sources.id, "id", ""
FROM hashes, sources
WHERE hashes.hash = "abcd" AND sources.source = "mysource";
INSERT INTO files ( hash_id, source_id, filename, extension )
SELECT hashes.id, sources.id, "filename.id", "id"
FROM hashes, sources
WHERE hashes.hash = "abcd" AND sources.source = "mysource";
Error: ambiguous column name: id
Do I need to further escape the quoted value somehow?
A:
Well ... that was a rookie mistake. This works once I used single quotes to indicate string literals:
INSERT INTO files ( hash_id, source_id, filename, extension )
SELECT hashes.id, sources.id, "id", ""
FROM hashes, sources
WHERE hashes.hash = "abcd" AND sources.source = "mysource";
INSERT INTO files ( hash_id, source_id, filename, extension )
SELECT hashes.id, sources.id, 'filename.id', 'id'
FROM hashes, sources
WHERE hashes.hash = "abcd" AND sources.source = "mysource";
|
[
"stackoverflow",
"0011769618.txt"
] | Q:
How to get original statusText with jQuery
I try to access the statusText on a post back to the server when an error occured. On the server side I'm setting the status text to an error message. StatusCode is 500 and statusText the error description.
Chrome console output inside the Headers section is:
Status Code:500 (big red dot) Error Message: Something went wrong.
But when I try to access the statusText now inside of the .error() function callback there is always the text "error":
.error(function (xhr, text) {
alert(xhr.statusText);
});
Is jQuery overwriting this field or how can I access the original values?
Thanks for help!
A:
I think you need to see the 3rd argument to the callback, it should be the HTTP status text. (according to the jQuery API documentation for the error callback)
function (xhr, ts, err) {
// ts => "error", "abort", etc (jQuery-specific)
// err => HTTP error from server
}
|
[
"mathematica.stackexchange",
"0000184919.txt"
] | Q:
Why does NSolve not solve my system of simultaneous equations?
I can not get my code to work.
I think my problem is rudimentary, but please tell me what I am doing wrong.
TH = 3;
S = 6;
μe = 30;
μg = 30;
λe = 300;
m = Array[Subscript[p, #1, #2] &, {S + 1, TH + 1}, {0, 0}]
NSolve[{
For[j = 0, j < TH, j++,
For[i = 0, i < S, i++,
If[j == 0 && i == TH, μe*Subscript[p, i, j] == λe*Subscript[p, i - 1, j]];
If[j == 0 && TH < i && i < S, (λe + μe)*Subscript[p, i, j] == μe*Subscript[p, i + 1, j] + μg*Subscript[p, i, j + 1]];
If[j == 0 && i == TH, (λe + μe)*Subscript[p, i, j] == μe*Subscript[p, i + 1, j] + μg*Subscript[p, i, j + 1] + λe*Subscript[p, i - 1, j]];
If[j == S - 1 && S - TH <= i && i < S, (μe + μg)*Subscript[p, i, j] == λe*Subscript[p, i - 1, j]];
If[j == TH - 1 && 0 < i && i < TH, (λe + μe)*Subscript[p, i, j] == μe*Subscript[p, i + 1, j - 1] + μe*Subscript[p, i + 1, j] + μg*Subscript[p, i, j + 1]];
If[j == TH && i == 0, λe*Subscript[p, i, j] == μe*Subscript[p, i + 1, j - 1] + μe*Subscript[p, i + 1, j]];
If[j == TH && 0 < i && i < S - TH, (λe + μe + μg)*Subscript[p, i, j] == μe* Subscript[p, i + 1, j] + λe*Subscript[p, i - 1, j], (λe + μe + μg)*Subscript[p, i, j] == μe*Subscript[p, i + 1, j] + λe*Subscript[p, i - 1, j] + μg*Subscript[p, i, j + 1]]
]
]
}, {m}]
A:
You have several syntax issues.
NSolve wants two arguments, the 1st being a simple list of equations and the 2nd being a simple list of variables.
Your NSolve expression essentially boils down to
NSolve[{Null}, {<4 x 7 array of variables>}]
because For always returns Null and because m is not a sequence of variables.
The fix lies in using Table to define the equations and applying Flatten to both the equation array and the variable array to get simple lists. I will also use Solve because there is no inexact quantities in the equations.
m = Array[Subscript[p, #1, #2] &, {S + 1, TH + 1}, {0, 0}] // Flatten;
eqns =
Table[
If[j == 0 && i == TH,
μe*Subscript[p, i, j] == λe*Subscript[p, i - 1, j]];
If[j == 0 && TH < i && i < S,
(λe + μe)*Subscript[p, i, j] == μe*Subscript[p, i + 1, j] + μg*Subscript[p, i, j + 1]];
If[j == 0 && i == TH,
(λe + μe)*Subscript[p, i, j] == μe*Subscript[p, i + 1, j] + μg*Subscript[p, i, j + 1] + λe*Subscript[p, i - 1, j]];
If[j == S - 1 && S - TH <= i && i < S,
(μe + μg)*Subscript[p, i, j] == λe*Subscript[p, i - 1, j]];
If[j == TH - 1 && 0 < i && i < TH, (λe + μe)*Subscript[p, i, j] == μe*Subscript[p, i + 1, j - 1] + μe*Subscript[p, i + 1, j] + μg*Subscript[p, i, j + 1]];
If[j == TH && i == 0,
λe*Subscript[p, i, j] == μe*Subscript[p, i + 1, j - 1] + μe*Subscript[p, i + 1, j]];
If[j == TH && 0 < i && i < S - TH,
(λe + μe + μg)*Subscript[p, i, j] == μe*Subscript[p, i + 1, j] + λe*Subscript[p, i - 1, j],
(λe + μe + μg)*Subscript[p, i, j] == μe*Subscript[p, i + 1, j] + λe*Subscript[p, i - 1, j] + μg*Subscript[p, i, j + 1]],
{j, 0, TH - 1}, {i, 0, S - 1}] // Flatten
Solve[eqns, m]
This gives
which shows your system is under determined, but which is an improvement over your attempt although it may not be what you expected.
|
[
"pm.meta.stackexchange",
"0000000721.txt"
] | Q:
Is there a lack of consensus amongst moderators about Product Management questions?
Today I posted my first PM.SE question, which was clearly tagged as 'Product-Management' (existing tag), and asked a question about licensing, which IMV is absolutely in the thick of Product-Management domain. It deals with positioning, pricing, go-to-market and licensing. However, it was flagged, and I conceded by deleting the question. However, on searching again the SE site, I hit upon the following Meta question, which seems to indicate that it was indeed on topic, or at least not absolutely off-topic.
Is there a misunderstanding on my part of what the linked meta Q&A says, or is there a lack of consensus amongst the mods here? It is not a rhetorical question.
Here are examples of somewhat popular questions (with well upvoted & accepted answers) that are tagged as 'Product-Management' questions, for whom I see no real relationship with Project Management.
What are Some Tools and Techniques for Communicating Product Updates to Existing Customers?
How and What to Learn - New to Product Management
Kindly note that while I'm new to PM.SE, I have spent a while on SE/SO, even if not a veteran. Not using that as an excuse for any special favours, but just to say that I'm aware of the SE general etiquette, and prior research.
A:
First, the question you should be asking is "Is there a consensus among the community", not moderators, as it is the community here who runs this site. Diamond moderators are here to handle exceptional circumstances. The 5 users who voted to close your post are all users of Project Management Stack Exchange who have contributed enough to gain the close/reopen privilege. Closing and reopening questions is part of the regular workflow for all users with at least 500 reputation, in order to help ensure we get the best content possible. This helps attract great project managers to our site and makes the Internet a better place.
Is the question a good fit for Stack Exchange?
Stack Exchange, all Stack Exchange sites, are Questions and Answers sites, meaning that questions are expected to be written in a way to where there is a finite answer or at least a handful of answers without there being infinite possibilities. The first part of your question is as follows:
Looking for ideas on as many licensing models as possible...
This is what Stack Exchange refers to as a polling question, and over the years we've learned these questions don't fit well with our Q&A model. First, it's difficult to evaluate which answers are more "correct", since every answer can be correct, and second, it creates a lot of noise making it harder for future visitors with a similar problem to quickly determine if the question or answers will help them. For idea generation, a traditional forum may be better than a Stack Exchange site.
Is product management on topic on Project Management Stack Exchange
The meta question you referenced was asked on day 2 of this site's private beta. We hadn't even gone public yet. A Stack Exchange beta site goes through a pain period where the community tries to figure out what the site is about, and in the early days, we weren't sure.
I thought there was a question brought up more recently about product management on this site, but I can't seem to locate it. However, it was discussed in-depth on Area 51, but the proposal for Product Management has since been deleted since the product management community has been unable to get enough committed users to launch a site. Thus, I am unable to reference any of the discussions.
I do recall that the product management community wasn't interested in merging with Project Management SE. The folks who posted insisted that project management and product management were completely separate domains.
We've not made it official, but it seems to me that product management would be off topic. If anyone from the community would like to weigh in, please do. Furthermore, those who think the two product management questions should be closed can use their close votes to put those posts on hold to help eliminate any future confusion about our site's scope. Hope this helps!
|
[
"security.stackexchange",
"0000151381.txt"
] | Q:
To whom do the PCI DSS password requirements apply?
The password requirements of PCI DSS, among everything else, state that you must enforce a very specific password policy:
You need to force the users to change their passwords every 90 days, their passwords cannot be shorter than 7 characters, etc.
As far as I know, large companies such as Google, Facebook, PayPal and many more don't enforce that policy.
For example, none of them freeze your account after a period of non-activity as PCI DSS requires and services such as Facebook allows your password to be 6 chars long (which is less than the 7 chars min stated in the PCI DSS requirements).
Those companies are PCI DSS Level 1 Service Providers and are listed in the PCI DSS Service Providers index.
How can those companies be PCI DSS compliant even though they don't enforce the PCI DSS password policy?
On whom does the policy apply? Does it apply on the simple user / customer or is it talking about the staff / moderators?
A:
The password requirements of PCI DSS, among everything else, state
that you must enforce a very specific password policy:
You need to force the users to change their passwords every 90 days,
their passwords cannot be shorter than 7 characters, etc.
...
On who does the policy apply? Does it apply on the simple user /
customer or is it talking about the staff / moderators?
To quote the DSS 3.2, intro text to Requirement 8 ("Identify and authenticate access to system components"):
Note: These requirements are applicable for all accounts, including
point-of-sale accounts, with administrative capabilities and all
accounts used to view or access cardholder data or to access systems
with cardholder data. This includes accounts used by vendors and
other third parties (for example, for support or maintenance). These
requirements do not apply to accounts used by consumers (e.g., cardholders).
As far as I know, large companies such as Google, Facebook, PayPal and
many more don't enforce that policy. For example, none of them freeze
your account after a period of non-activity as PCI DSS requires and
services such as Facebook allows your password to be 6 chars long
(which is less than the 7 chars min stated in the PCI DSS
requirements).
Those companies are PCI DSS Level 1 Service Providers and are listed
in the PCI DSS Service Providers index.
Google and PayPal are; I don't see Facebook on the Visa SP Listing. But as above, it's not your account - consumer account - that is governed by PCI DSS. And, especially with a company like Google, it's easy to have an account that never goes near touching a credit card or credit processing function. So it's not that surprising.
A:
It applies to passwords of users who have access to networks where card data is stored, who will normally be employees or contractors of the company. It doesn't apply to customer passwords, unless for some reason those passwords allow access to card data (not including the first six and last four digits of the card number, which don't have to be protected).
|
[
"stackoverflow",
"0029394632.txt"
] | Q:
JavaFX Circle object not registering mouse events properly
I want the user to be able to drag-move the circles around the pane. The circles dont seem to register (almost) no mouse events (as defined in the end). I have the same exact code for an empty pane it works just fine. Also if I change
circle1.setOnMouseDragged
to
paneForCircles.setOnMouseDragged
it works just fine but its not what I want because I need to manipulate both circles. Any ideas ? I would appreciate it if you could also tell me how to hide the part of the circle that overlaps with the adjacent elements if its center is too close to the pane border.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class Ex168 extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Circle circle1 = new Circle(30);
Circle circle2 = new Circle(35);
circle1.setCenterX(100);
circle1.setCenterY(100);
circle2.setCenterX(150);
circle2.setCenterY(120);
circle1.setStroke(Color.BLACK);
circle1.setFill(null);
circle2.setStroke(Color.BLACK);
circle2.setFill(null);
VBox vBoxForScene = new VBox(5);
vBoxForScene.setPadding(new Insets(5));
vBoxForScene.setAlignment(Pos.TOP_CENTER);
Pane paneForCircles = new Pane();
paneForCircles.setStyle("-fx-border-color: black");
vBoxForScene.heightProperty().addListener(ov -> paneForCircles.setPrefHeight(vBoxForScene.heightProperty().divide(1.2).doubleValue()));
paneForCircles.setPrefHeight(300);
HBox hBoxForFields = new HBox(5);
hBoxForFields.setAlignment(Pos.CENTER);
hBoxForFields.setSpacing(5);
// VBofForLeftFields
VBox vBoxForLeftFields = new VBox(5);
vBoxForLeftFields.setAlignment(Pos.CENTER_LEFT);
Label lblCircle1 = new Label("Enter Circle 1 info");
lblCircle1.setAlignment(Pos.TOP_LEFT);
TextField tfCircle1CenterX = new TextField();
tfCircle1CenterX.textProperty().bind(circle1.centerXProperty().asString());
TextField tfCircle1CenterY = new TextField();
tfCircle1CenterY.textProperty().bind(circle1.centerYProperty().asString());
TextField tfCircle1Radius = new TextField();
tfCircle1Radius.textProperty().bind(circle1.radiusProperty().asString());
tfCircle1CenterX.setPrefColumnCount(5);
tfCircle1Radius.setPrefColumnCount(5);
tfCircle1CenterY.setPrefColumnCount(5);
Label lblCenterX = new Label("Center x:", tfCircle1CenterX);
Label lblCenterY = new Label("Center x:", tfCircle1CenterY);
Label lblCircle1Radius= new Label("Radius: ", tfCircle1Radius);
lblCenterX.setContentDisplay(ContentDisplay.RIGHT);
lblCenterY.setContentDisplay(ContentDisplay.RIGHT);
lblCircle1Radius.setContentDisplay(ContentDisplay.RIGHT);
//VBoxForRightFields
VBox vBoxForRightFields = new VBox(5);
Label lblCircle2 = new Label("Enter Circle 2 info");
TextField tfCircle2CenterX = new TextField();
TextField tfCircle2CenterY = new TextField();
TextField tfCircle2Radius = new TextField();
tfCircle2CenterX.setPrefColumnCount(5);
tfCircle2CenterX.textProperty().bind(circle2.centerXProperty().asString());
tfCircle2Radius.setPrefColumnCount(5);
tfCircle2Radius.textProperty().bind(circle2.radiusProperty().asString());
tfCircle2CenterY.setPrefColumnCount(5);
tfCircle2CenterY.textProperty().bind(circle2.centerYProperty().asString());
Label lblCenter2X = new Label("Center x:", tfCircle2CenterX);
Label lblCenter2Y = new Label("Center x:", tfCircle2CenterY);
Label lblCircle2Radius= new Label("Radius: ", tfCircle2Radius);
lblCenter2X.setContentDisplay(ContentDisplay.RIGHT);
lblCenter2Y.setContentDisplay(ContentDisplay.RIGHT);
lblCircle2Radius.setContentDisplay(ContentDisplay.RIGHT);
vBoxForRightFields.getChildren().addAll(lblCircle2, lblCenter2X, lblCenter2Y, lblCircle2Radius);
vBoxForLeftFields.getChildren().addAll(lblCircle1, lblCenterX, lblCenterY, lblCircle1Radius);
hBoxForFields.getChildren().addAll(vBoxForLeftFields, vBoxForRightFields);
Label lblResult = new Label("Do the two circles intersect?");
Button btReDrawCircles = new Button("Redraw Circles");
vBoxForScene.getChildren().addAll(lblResult, paneForCircles, hBoxForFields, btReDrawCircles);
circle1.setOnMouseDragged(e -> {
System.out.println(e.getX());
circle1.setCenterX(e.getX());
circle1.setCenterY(e.getY());
});
circle2.setOnMouseDragged(e -> {
circle2.setCenterX(e.getX());
circle2.setCenterY(e.getY());
});
paneForCircles.getChildren().addAll(circle1, circle2);
Scene scene = new Scene(vBoxForScene);
primaryStage.setScene(scene);
primaryStage.setMinHeight(400);
primaryStage.setMinWidth(340);
primaryStage.setAlwaysOnTop(true);
primaryStage.show();
circle1.requestFocus();
}
}
This code on the other hand, which is supposed to do the same thing, works perfectly
public class CircleDraggingSample extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
final double RADIUS=10;
Pane pane = new Pane();
pane.setPrefHeight(300);
pane.setPrefWidth(300);
Circle circle1 = new Circle(RADIUS);
circle1.setCenterX(30);
circle1.setCenterY(30);
Circle circle2 = new Circle(RADIUS);
circle2.setCenterX(100);
circle2.setCenterY(100);
Line line = new Line();
line.endXProperty().bind(circle2.centerXProperty());
line.endYProperty().bind(circle2.centerYProperty());
line.startXProperty().bind(circle1.centerXProperty());
line.startYProperty().bind(circle1.centerYProperty());
pane.getChildren().addAll(circle1, circle2, line);
circle2.setOnMouseDragged(e -> {
circle2.setCenterX(e.getX());
circle2.setCenterY(e.getY());
});
circle1.setOnMouseDragged(e -> {
circle1.setCenterX(e.getX());
circle1.setCenterY(e.getY());
});
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
}
}
A:
Even though you have posted an example, I'd rather show you a way with mine how it is done in general. There are several ways, this is one that works:
public class DragNodes extends Application {
public static List<Circle> circles = new ArrayList<Circle>();
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
Group root = new Group();
Circle circle1 = new Circle( 100, 100, 50);
circle1.setStroke(Color.GREEN);
circle1.setFill(Color.GREEN.deriveColor(1, 1, 1, 0.3));
Circle circle2 = new Circle( 200, 200, 50);
circle2.setStroke(Color.BLUE);
circle2.setFill(Color.BLUE.deriveColor(1, 1, 1, 0.3));
Line line = new Line();
line.setStrokeWidth(20);
// binding
line.startXProperty().bind(circle1.centerXProperty());
line.startYProperty().bind(circle1.centerYProperty());
line.endXProperty().bind(circle2.centerXProperty());
line.endYProperty().bind(circle2.centerYProperty());
MouseGestures mg = new MouseGestures();
mg.makeDraggable( circle1);
mg.makeDraggable( circle2);
mg.makeDraggable( line);
root.getChildren().addAll(circle1, circle2, line);
primaryStage.setScene(new Scene(root, 1024, 768));
primaryStage.show();
}
public static class MouseGestures {
class DragContext {
double x;
double y;
}
DragContext dragContext = new DragContext();
public void makeDraggable( Node node) {
node.setOnMousePressed( onMousePressedEventHandler);
node.setOnMouseDragged( onMouseDraggedEventHandler);
node.setOnMouseReleased(onMouseReleasedEventHandler);
}
EventHandler<MouseEvent> onMousePressedEventHandler = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if( event.getSource() instanceof Circle) {
Circle circle = ((Circle) (event.getSource()));
dragContext.x = circle.getCenterX() - event.getSceneX();
dragContext.y = circle.getCenterY() - event.getSceneY();
} else {
Node node = ((Node) (event.getSource()));
dragContext.x = node.getTranslateX() - event.getSceneX();
dragContext.y = node.getTranslateY() - event.getSceneY();
}
}
};
EventHandler<MouseEvent> onMouseDraggedEventHandler = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if( event.getSource() instanceof Circle) {
Circle circle = ((Circle) (event.getSource()));
circle.setCenterX( dragContext.x + event.getSceneX());
circle.setCenterY( dragContext.y + event.getSceneY());
} else {
Node node = ((Node) (event.getSource()));
node.setTranslateX( dragContext.x + event.getSceneX());
node.setTranslateY( dragContext.y + event.getSceneY());
}
}
};
EventHandler<MouseEvent> onMouseReleasedEventHandler = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
}
};
}
}
It shows how to drag circles and bind another node (the line) so that it gets modified as well when you drag the circles. You can also drag the line separately which is a Node and handled differently.
In case you still got problems let me know.
As a general note, it's always advisable to add this to a node in order to understand which events happen:
node.addEventFilter(Event.ANY, e -> System.out.println( e));
and then check the console output while you do something on screen.
Regarding your main problem: You mustn't set Fill to null. In that case the click event won't get registered. You should use Color.TRANSPARENT instead. You can verify the event difference with the above mentioned method.
|
[
"networkengineering.stackexchange",
"0000008004.txt"
] | Q:
Troubleshoot SNMP - NPEG2 - Purpose of snmp mib community-map engineid command
we have several cisco 7225 vxr deployed on our network and we have an issue on SNMP access.
On last new deployment, we can't reach the last router implemented through SNMP. Comparing two router with similar config (change only IP address) rest it's the same, we can't reach on SNMP the last deployed Router.
From our monitoring server, we can ping both machine 10.30.0.12 and 10.30.0.40.
And we reach over SNMP 10.30.0.12
Output server :
MON # ping 10.30.0.12
PING 10.30.0.12 (10.30.0.12): 56 data bytes
64 bytes from 10.30.0.12: icmp_seq=0 ttl=254 time=1.288 ms
64 bytes from 10.30.0.12: icmp_seq=1 ttl=254 time=1.270 ms
^C
--- 10.30.0.12 ping statistics ---
2 packets transmitted, 2 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 1.270/1.279/1.288/0.009 ms
MON # snmpwalk -v 2c -c comm3 10.30.0.12
^C
MON # snmpwalk -v 2c -c comm3 10.30.0.12
SNMPv2-MIB::sysDescr.0 = STRING: Cisco IOS Software, 7200 Software (UBR7200P-JK9SU2-M), Version 12.2(33)SCG6, RELEASE SOFTWARE (fc1)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2013 by Cisco Systems, Inc.
Compiled Thu 31-Oct-13 13:45 by prod_rel_team
SNMPv2-MIB::sysObjectID.0 = OID: CISCO-DOCS-EXT-MIB::cisco.1.827
MON # ping 10.30.0.40
PING 10.30.0.40 (10.30.0.40): 56 data bytes
64 bytes from 10.30.0.40: icmp_seq=0 ttl=254 time=1.034 ms
64 bytes from 10.30.0.40: icmp_seq=1 ttl=254 time=0.945 ms
^C
--- 10.30.0.40 ping statistics ---
2 packets transmitted, 2 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.945/0.990/1.034/0.044 ms
MON # snmpwalk -v 2c -c comm3 10.30.0.40
Timeout: No Response from 10.30.0.40
SNMP configuration (output from show run all) same on both router :
snmp-server group ADM v3 auth match exact read v1default write CFGCOPY access 8
snmp-server view *ilmi system included
snmp-server view *ilmi atmForumUni included
snmp-server view CFGCOPY ccCopyTable.* included
snmp-server view v1default iso included
snmp-server view v1default internet included
snmp-server view v1default snmpMPDMIB excluded
snmp-server view v1default snmpTargetMIB excluded
snmp-server view v1default snmpNotificationMIB excluded
snmp-server view v1default snmpUsmMIB excluded
snmp-server view v1default snmpVacmMIB excluded
snmp-server view v1default snmpCommunityMIB excluded
snmp-server view v1default ciscoIpTapMIB excluded
snmp-server view v1default cisco802TapMIB excluded
snmp-server view v1default ciscoTap2MIB excluded
snmp-server view v1default ciscoUserConnectionTapMIB excluded
snmp-server view *tv.00000000.00000010.00000080.000000007F iso.2.840.10036 included
snmp-server view *tv.00000000.00000010.00000080.000000007F internet included
snmp-server view *tv.FFFFFFFF.FFFFFFFF.FFFFFFFF.FFFFFFFF7F iso.2.840.10036 included
snmp-server view *tv.FFFFFFFF.FFFFFFFF.FFFFFFFF.FFFFFFFF7F internet included
snmp-server community comm1default RO 1
snmp-server community comm2default RO 2
snmp-server community comm3default RW 3
snmp-server community comm4default RO 51
snmp-server priority normal
no snmp-server trap link ietf
no snmp-server trap link switchover
snmp-server trap authentication vrf
snmp-server trap authentication acl-failure
snmp-server trap retry 3
snmp-server trap-source Loopback1
snmp-server packetsize 1500
snmp-server trap timeout 30
snmp-server queue-length 10
snmp-server location Hub
snmp-server contact 0461523
snmp-server chassis-id SN
snmp-server enable traps snmp authentication linkdown linkup coldstart warmstart
snmp-server enable traps tty
snmp-server enable traps config
snmp-server enable traps entity
snmp-server enable traps envmon fan shutdown supply temperature
snmp-server enable traps cable
snmp-server enable traps rtr
snmp-server host 10.10.254.10 traps version 1 comm1 udp-port 162
snmp-server host 10.10.10.253 traps version 1 comm1 udp-port 162
snmp-server host 10.11.161.11 traps version 1 comm1 udp-port 162
snmp-server host 10.11.168.240 traps version 1 comm1 udp-port 162
snmp-server host 10.11.126.96 traps version 2c comm1 udp-port 162
snmp-server host 10.11.167.5 traps version 1 public udp-port 162 comm1 docsis-cmts
snmp-server manager session-timeout 600
snmp-server manager
snmp-server inform retries 3 timeout 15 pending 25
snmp ifmib ifindex persist
snmp mib notification-log globalsize 500
snmp mib notification-log globalageout 15
snmp mib community-map comm1 engineid 800000090300A44C11809A1B
snmp mib community-map comm2 engineid 800000090300A44C11809A1B
snmp mib community-map comm3 engineid 800000090300A44C11809A1B
snmp mib community-map comm4 engineid 800000090300A44C11809A1B
snmp mib community-map comm5 engineid 80000009030024E9B301AC1B
snmp mib community-map comm6 engineid 800000090300A44C11809A1B
Edit1:
Solution :
- Removing the snmp mib community-map command solve the issue and I get access to router through SNMP.
What is the purpose of such command ? Why on this router isn't working and on the others it is.
A:
snmp mib community-map
To associate a Simple Network Management Protocol (SNMP) community
with an SNMP context, engine ID, or security name, use the snmp mib
community-map command in global configuration mode. To change an SNMP
community mapping to its default mapping, use the no form of this
command.
Cisco IOS Network Management Command Reference
This fails when copying configs between routers because each will have a unique engineid. On the clone router, you've associated all your communities with a non-existent engineid. I'm not sure there's a way to force IOS to use the same (user supplied) engineid.
[UPDATE]
So you can... snmp-server engineID local 800000090300A44C11809A1B (I don't recommend doing that, 'tho)
|
[
"stackoverflow",
"0026123480.txt"
] | Q:
Weka Decision tree Java to lists
I want to make a decision tree and break it to lists (name , sign , val).
I made the tree with this code :
//Get File
BufferedReader reader = new BufferedReader(new FileReader(PATH + "TempArffFile.arff"));
//Get the data
Instances data = new Instances(reader);
reader.close();
//Setting class attribute
data.setClassIndex(data.numAttributes() - 1);
//Make tree
J48 tree = new J48();
String[] options = new String[1];
options[0] = "-U";
tree.setOptions(options);
tree.buildClassifier(data);
//Print tree
System.out.println(tree);
now I need to break it to arrays how can i do that ?
Example :
i get this tree :
title <= 1: bad (4.0)
title > 1
| positionMatch <= 1
| | countryCode <= 1: good (3.0/1.0)
| | countryCode > 1: bad (8.0/3.0)
| positionMatch > 1: good (4.0/1.0)
so i want to get 4 lists from that tree:
title(<= 1) -> bad
title(> 1) -> position(<= 1) -> countryCode(<= 1) -> good
title(> 1) -> position(<= 1) -> countryCode(> 1) -> bad
title(> 1) -> position(> 1) -> good
How can i do that ?
A:
Not that nice but maybe better then nothing...
Maybe it will give u an idea.
public static void split(String tree){
String[] lines = tree.split("\n");
List<List<String>> lists = new ArrayList<List<String>>();
for(String line : lines){
List<String> temp = new ArrayList<String>();
while(line.indexOf("|") != -1){
temp.add("|");
line = line.replaceFirst("\\|", "");
}
temp.add(line.trim());
lists.add(temp);
}
for(int i = 0; i < 3; i++){
lists.remove(0);
}
for(int i = 0; i < 4; i++){
lists.remove(lists.size()-1);
}
List<String> substitutes = new ArrayList<String>();
for(List<String> list : lists){
for(int i = 0; i < list.size(); i++){
if(!list.get(i).contains(":") && !list.get(i).equals("|") && !substitutes.contains(list.get(i))){
substitutes.add(list.get(i));
}
}
}
for(List<String> list : lists){
for(int i = 0; i < list.size(); i++){
if(list.get(i).equals("|")){
list.set(i, substitutes.get(i));
}
}
}
StringBuilder sb = new StringBuilder();
for(List<String> list : lists){
String line = "";
for(String s : list){
line = line+" "+s;
}
if(line.endsWith(")")){
sb.append(line+"\n");
}
}
System.out.println(sb.toString());
}
Input
J48 unpruned tree
petalwidth <= 0.6: Iris-setosa (50.0)
petalwidth > 0.6
| petalwidth <= 1.7
| | petallength <= 4.9: Iris-versicolor (48.0/1.0)
| | petallength > 4.9
| | | petalwidth <= 1.5: Iris-virginica (3.0)
| | | petalwidth > 1.5: Iris-versicolor (3.0/1.0)
| petalwidth > 1.7: Iris-virginica (46.0/1.0)
Number of Leaves : 5
Size of the tree : 9
Output:
petalwidth <= 0.6: Iris-setosa (50.0)
petalwidth > 0.6 petalwidth <= 1.7 petallength <= 4.9: Iris-versicolor (48.0/1.0)
petalwidth > 0.6 petalwidth <= 1.7 petallength > 4.9 petalwidth <= 1.5: Iris-virginica (3.0)
petalwidth > 0.6 petalwidth <= 1.7 petallength > 4.9 petalwidth > 1.5: Iris-versicolor (3.0/1.0)
petalwidth > 0.6 petalwidth > 1.7: Iris-virginica (46.0/1.0)
|
[
"stackoverflow",
"0015103890.txt"
] | Q:
Submit today's date as a hidden form input value
I need to send the current date in this format yyyymmdd via a hidden form input field.
I have the date formatted as I want with this javascript
function getDate()
{
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} today = yyyy+mm+dd;
}
And this is my form input field
<input type="hidden" name="startdate" onload="this.value = getDate();"/>
I've tried several ways to assign the date above to my var startdate and send it to the server, without any success.
Can you show me how to pass the date to my hidden input field when the page loads?
And I'm wondering if this posses any problems with regards to security and hackers?
Thanks for your help
A:
<input type="hidden" name="startdate" id="todayDate"/>
<script type="text/javascript">
function getDate()
{
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm}
today = yyyy+""+mm+""+dd;
document.getElementById("todayDate").value = today;
}
//call getDate() when loading the page
getDate();
</script>
A:
If you are using the date for some kind of validation then for security you would be much better off using server side scripting; that way the client can't spoof dates.
Furthermore, you shouldn't use an <input>, even if you used the server side to generate the date, because you could still spoof the time using Firebug or many other web developer tools. The HTTP POST (or whatever) submitted could contain spoofed data. In the end nothing is 100% secure though.
|
[
"stackoverflow",
"0057147348.txt"
] | Q:
Why does my interrupt get called, but won't enter the handler?
I'm trying to recieve communication from an USART in interrupt mode. The debugger shows me that the interrupt is getting called on a keypress, but the execution gets stuck in the vector table definition.
I initialize my usart with the following.
static void MX_USART2_UART_Init(void)
{
huart2.Instance = USART2;
huart2.Init.BaudRate = 19200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE END USART2_Init 2 */
LED_Initialize();
USART2->CR1=USART_CR1_RE|USART_CR1_TE|USART_CR1_UE|USART_CR1_RXNEIE; // Enable interrupt
NVIC_SetPriority(USART2_IRQn, 2); // set priority level
NVIC_EnableIRQ(USART2_IRQn); // Enable in NVIC
}
void USART2_IRQHandler(void)
{
blink_led();
}
If I run the application in debug mode, hit a key, stop and step through the code, I find it's looping on the branch instruction here, inside of the included startup_stm32f446xx.s.
USART2_IRQHandler
B USART2_IRQHandler
PUBWEAK USART3_IRQHandler
SECTION .text:CODE:REORDER:NOROOT(1)
So I know the interrupt is getting generated, but it can't seem to find my handler. Even not in debug mode, my LED doesn't blink, which is a function I've tested seperateky.
I'm not sure if this issue is from from the HAL library. I've read through their documentation and variations with their NVIC enable instructions to the same result. The usart works fine in polling, but I need interrupts for my functionality.
A:
Your question has "c++" tag, so I assume you compile your project with a C++ compiler. C++ compilers name-mangle function names, which prevents the branch instruction to find its target, because its real name isn't USART2_IRQHandler anymore.
You need prefix your ISR with extern "C" to tell C++ not to name-mangle it.
extern "C" void USART2_IRQHandler(void) {
blink_led();
}
|
[
"stackoverflow",
"0004750963.txt"
] | Q:
TeamCity - how to get currently running builds via REST API?
Does anyone know how to use the TeamCity REST API to find out which builds are currently running, and how far through they are (elapsed time vs estimated time)?
Ta
Matt
A:
The URL returns what you are asking for, including percentage complete.
http://teamcityserver/httpAuth/app/rest/builds?locator=running:true
<builds count="1">
<build id="10" number="8" running="true" percentageComplete="24" status="SUCCESS" buildTypeId="bt3" startDate="20110714T210916+1200" href="/httpAuth/app/rest/builds/id:10" webUrl="http://phillipn02:29000/viewLog.html?buildId=10&buildTypeId=bt3"/>
</builds>
Source: http://devnet.jetbrains.net/message/5291132#5291132.
The relevant line on the REST API documentation is the one that reads "http://teamcity:8111/httpAuth/app/rest/builds/?locator= - to get builds by "build locator"." in the "Usage" section.
This works with TeamCity version 6.5; I haven't tried it on earlier versions, but I suspect it will work back to version 5.
A:
You can use "running:true/false/any" as one of the build dimensions for the build locator. (EDIT: added in TeamCity 6.0)
http://confluence.jetbrains.net/display/TW/REST+API+Plugin
The TeamCity REST API documentation will give you some examples of some of the ways you can construct the URL. The Build Locator section on that page will list the different options you have for refining your results (one of which is running).
However, I don't know of a way to get information about the running builds elapsed/estimated time using the REST API. I'm not sure if this would be possible. If you did find a way to do this, I would be be very interested to read how!
Good luck!
|
[
"stackoverflow",
"0010387320.txt"
] | Q:
Concise Explanation of Core.logic
I want to use Clojure's Core.logic. However, I want to also understand how it works. Is there a concise explanation of it somewhere? (Like implementing a metacircular evaluator?)
Thanks!
A:
core.logic is an implementation of miniKanren - originally written and designed in Scheme by Dan Friedman, William Byrd, Oleg Kiselyov and others. It is an attempt to embed Prolog-style relational programming within Lisp.
If you want to understand how it works you'll need to read the first three chapters of William Byrd's dissertation: https://scholarworks.iu.edu/dspace/bitstream/handle/2022/8777/Byrd_indiana_0093A_10344.pdf?sequence=1
The Reasoned Schemer also covers the unifier in detail. However the much more subtle goal portion of miniKanren isn't given a comprehensive treatment - you'll need to look at Byrd's dissertation for that.
Even then, as with meta-circular interpreters - many insights cannot be gained without trying to implement the system yourself in a variety of programming languages.
|
[
"stackoverflow",
"0050871884.txt"
] | Q:
How to convert numbers into vector of integers?
I want my program to ask the user to input any number and then store it into a std::vector where every single digit is allocated to a separate vector index:
input: 142
output vector: [1, 4, 2]
I tried this:
int main()
{
std::vector<int> v;
int number;
cin >> number;
for(unsigned int i = 100; i > 0; i/=10)
{
v.push_back(number/i);
number -= (number/i)*i;
}
for(size_t i = 0; i < v.size(); ++i)
{
std::cout<<v[i]<<std::endl;
}
}
It works. But what should I do when the input-length is unknown?
A:
Use simply std::string and for each char(which is actually integers) of string convert to integer as follows: SEE LIVE HERE
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<int> v;
std::string number = "123456789987654321";
for(auto& Integer: number)
v.emplace_back(static_cast<int>(Integer - '0'));
for(const auto& it: v) std::cout << it << " ";
}
Output:
1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1
In case of entering unwanted characters/ user inputs(for example some negative numbers or even this: +-1234567), you can go for something with try-catch. try to convert the char to int, otherwise skip in the catch block as follows. SEE LIVE HERE
#include <iostream>
#include <vector>
#include <string>
#include <exception>
int main()
{
std::vector<int> v;
std::string number = "+-1234567";
for(auto& Integer: number)
{
std::string Char(1, Integer); // convert to string
try { v.emplace_back(std::stoi(Char)); }
catch(...) { continue; } // any case of exceptions
/* or using much simpler std::isdigit from <cctype>
by which conversion to std::string and try-catch can be avoided.
if(std::isdigit(Integer))
v.emplace_back(static_cast<int>(Integer - '0'));
*/
}
for(const auto& it: v) std::cout << it << " ";
}
Output:
1 2 3 4 5 6 7
Edte: As per @Aconcagua suggested, included the solution with std::isdigit
|
[
"stackoverflow",
"0007125443.txt"
] | Q:
Use dependency injection for Properties.Settings.Default?
Should you consider the use of Properties.Settings.Default within a class as a dependency, and therefore inject it?
e.g.:
public class Foo
{
private _settings;
private bool _myBool;
public Foo(Settings settings)
{
this._settings = settings;
this._myBool = this._settings.MyBool;
}
}
.
.
or would you consider the use of Settings as an application wide global as good practice?
e.g.:
public class Foo
{
private bool _myBool;
public Foo()
{
this._myBool = Properties.Settings.Default.MyBool;
}
}
A:
I would choose "none of the above" and inject the boolean value directly:
public class Foo
{
private readonly bool _myBool;
public Foo(bool myBool)
{
_myBool = myBool;
}
}
This decouples Foo from knowledge of any infrastructure that supports the retrieval of the boolean value. Foo has no reason to introduce complexity by depending on a settings object, especially if it contains other unrelated values.
A:
You may want to encapsulate Settings in a class and have an interface for them. This way, where your settings are coming from can be changed for things like unit testing. If you're also using an IoC container, then by all means register the settings with the container.
I do this for the ConfigurationManager and WebConfigurationManager so that I can inject settings for tests. Nathan Gloyn has wrapped the adapters and interface up already in a project that you can use if you also want to do this.
|
[
"stackoverflow",
"0041236414.txt"
] | Q:
How should I link specific rows to columns in a Qtablewidget
I have a Qtablewidget with 3 columns. The first column contain user names, the second and third are columns are check boxes. I would like these check boxes to be attributes for the row of users. For example If you look at the image below, User: bruno is marked(has attributes) delete and delete home. I would like to have an output like: User Bruno marked for delete, marked for delete home. To do that, I would need to link the users to both these columns which I haven't the slightest idea. How should I approach this problem. Below is the code that I already came up with. It populates the users column from a file.
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self, rows, columns):
QtGui.QWidget.__init__(self)
self.table = QtGui.QTableWidget(rows, columns, self)
self.table.setHorizontalHeaderItem(0, QtGui.QTableWidgetItem("Users"))
self.table.setHorizontalHeaderItem(1, QtGui.QTableWidgetItem("Delete User"))
self.table.setHorizontalHeaderItem(2, QtGui.QTableWidgetItem("Delete User and Home"))
self.table.verticalHeader().hide()
header = self.table.horizontalHeader()
header.setStretchLastSection(True)
rowf = 0
with open("/home/test1/data/users") as in_file:
if in_file is not None:
users = in_file.readlines()
for line in users:
users = QtGui.QTableWidgetItem()
self.table.setItem(rowf, 0, users)
users.setText(line)
rowf+=1
in_file.close()
for column in range(columns):
for row in range(rows):
if column % 3:
item = QtGui.QTableWidgetItem(column)
item.setFlags(QtCore.Qt.ItemIsUserCheckable |
QtCore.Qt.ItemIsEnabled)
item.setCheckState(QtCore.Qt.Unchecked)
self.table.setItem(row, column, item)
self.table.itemClicked.connect(self.cell_was_clicked)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.table)
self._list = []
def cell_was_clicked(self, item):
#row = self.table.currentItem().row()
#col = self.table.currentItem().column()
#print "item:", item
#print "row=", row
if item.checkState() == QtCore.Qt.Checked:
print('"%s" Checked' % item.text())
#self._list.append(item.row())
else:
#print "(", row , ",", col, ")"
print('%s' % item.text())
print (item.row(),item.column())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window(200, 3)
window.resize(400, 400)
window.show()
sys.exit(app.exec_())
A:
fixed it like this:
def cell_was_clicked(self, item):
if item.checkState() == QtCore.Qt.Checked:
user = self.table
delete = user.horizontalHeaderItem(item.column()).text()
print ('%s' % user.item(item.row(), 0).text())
print ('is marked for %s' % delete)
print('%s Checked' % item.text())
#self._list.append(item.row())
else:
print('%s' % item.text())
print (item.row(),item.column())
|
[
"stackoverflow",
"0028301329.txt"
] | Q:
Using MongoDB API in a Web application
I'd need to use the MongoClient and DB objects repeatedly in a Web application:
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB( "test" );
Is it safe to cache and re-use these objects among different clients accessing our application?
Thanks
A:
You should create this once and inject it via CDI/Guice, if you can. If you can't do that, you could use a static factory method to return the one instance of your MongoClient. MongoClient maintains a connection pool and is safe to use between different threads. If you create a new MongoClient with each request, not only is it going to be a performance hit to set up that pool and open a new connection, but you'll likely leave dangling connections unless you properly close that MongoClient at the end of the request.
|
[
"stackoverflow",
"0061560361.txt"
] | Q:
("vector subscript out of range") for Binary search problem
I am trying to implement binary search function in C++, in this function I have sorted vector of integers, then I enter vector of integers to check the index of the value I am searching for, If value is not found -1 should be returned
The problem is I receive message _DEBUG_ERROR("vector subscript out of range"); while debugging.
Here is the code
#include <iostream>
#include <cassert>
#include <vector>
using std::vector;
int binary_search(const vector<int> &a, int x, int left, int right) {
left = 0;
right = (int)a.size();
if (left > right) return -1;
int mid = (left + ((left - right) / 2));
if (a[mid] == x)
{
return mid;
}
else if (x > mid)
{
return binary_search(a, x, mid + 1, right);
}
else if (x < mid)
return binary_search(a, x, left, mid - 1);
}
int linear_search(const vector<int> &a, int x) {
for (size_t i = 0; i < a.size(); ++i) {
if (a[i] == x) return i;
}
return -1;
}
int main() {
int n;
std::cin >> n;
vector<int> a(n);
for (size_t i = 0; i < a.size(); i++) {
std::cin >> a[i];
}
int m;
std::cin >> m;
vector<int> b(m);
int left =0;
int right= (int)a.size() - 1 ;
for (int i = 0; i < m; ++i) {
std::cin >> b[i];
}
for (int i = 0; i < m-1; ++i) {
std::cout << binary_search(a, b[i], left, right) << ' ';
}
}
A:
There are 2 problems with this code:
In the binary search function, you start with assigning your parameters with new values, which will lead to infinite recursion. Just remove this assignment.
Your mid is assigned like this int mid = (left + ((left - right) / 2)); but should be this: int mid = (left + ((right - left) / 2)); (your current mid is always less or equal to left, and your error comes up here, since you try to use negative index)
|
[
"stackoverflow",
"0045047323.txt"
] | Q:
How to animate an element so it loops inside its parent in HTML5 and CSS3?
I'm trying to achieve an animation similar to the animation present in the "scroll down icon" at this page.
Here's my attempt at it:
body {
background-color: black;
}
@keyframes anim {
0% { top: 18% }
30% { top: 18% }
50% { top: 100% }
51% { top: -50% }
70% { top: 18% }
100% { top: 18% }
}
#scroll-down-icon {
position: absolute;
left: 32px;
top: 32px;
border: 2.3px solid white;
width: 128px;
height: 128px;
border-radius: 64px;
}
h1 {
width: 100%;
height: 100%;
position: relative;
color: white;
font-size: 32px;
left: 0;
top: 18%;
text-align: center;
animation-name: anim;
animation-duration: 1.75s;
animation-delay: 1s;
animation-iteration-count: infinite;
}
<div id="scroll-down-icon"><h1>╲╱</h1></div>
However the code above doesn't make the the h1 really "loop" inside the #scroll-down-icon div.
How would I address this issue and create an effect similar to the one present in the page using CSS & HTML?
A:
div {
overflow:hidden;
cursor: pointer;
}
body {
background-color: black;
}
@keyframes anim {
0% { top: 18% }
30% { top: 18% }
50% { top: 100% }
51% { top: -50% }
70% { top: 18% }
100% { top: 18% }
}
#scroll-down-icon {
position: absolute;
left: 32px;
top: 32px;
border: 2.3px solid white;
width: 128px;
height: 128px;
border-radius: 64px;
}
h1 {
width: 100%;
height: 100%;
position: relative;
color: white;
font-size: 32px;
left: 0;
top: 18%;
text-align: center;
animation-name: anim;
animation-duration: 1.75s;
animation-delay: 1s;
animation-iteration-count: infinite;
}
div {
overflow:hidden;
cursor: pointer;
}
<div id="scroll-down-icon"><h1>╲╱</h1></div>
|
[
"serverfault",
"0000372991.txt"
] | Q:
IIS URL Rewrite Module Query String Parameters
Is it possible to use URL Rewrite to provide more complex query string functionality than the "Append query string" checkbox that it has? Specifically, is it possible to specify the keys for certain query string parameters and have it only append those name value pairs.
For example, for the input:
http://www.example.org/test?alpha=1&beta=2&gamma=3
and the list of query string parameter keys: beta gamma
it should output:
http://www.example.org/redirect?beta=2&gamma=3
(Note that the query string parameters in the input appear in arbitrary order.)
A:
My solution would be use conditions for that. By matching the conditions against the {QUERY_STRING} you can use back references to use them in the redirect URL.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Redirect" stopProcessing="true">
<match url="(.*)" />
<conditions trackAllCaptures="true">
<add input="{QUERY_STRING}" pattern="&?(beta=[^&]+)&?" />
<add input="{QUERY_STRING}" pattern="&?(gamma=[^&]+)&?" />
<add input="{REQUEST_URI}" pattern="^/redirect" negate="true" />
</conditions>
<action type="Redirect" url="/redirect?{C:1}&{C:2}" appendQueryString="false" redirectType="Found" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
The only possible problem with this solution might be (depending on what you want) is that the redirect will only happen if both the beta and gamma query string variables are present in the query string. If they are not, the redirect will not happen.
The redirect rule matches against any URL ((.*)). If needed, you can change that. I've also added an extra condition to not have the rule match against the redirect URL itself which would otherwise cause the redirect URL to be redirected itself.
|
[
"stackoverflow",
"0008419731.txt"
] | Q:
Split a string with JavaScript
the following code works for me, but seems to be quite long-winded. Can i shorten it?
var str = "some title of an event here, weekday 17:00 – 18:00 o’clock, with name of a person";
var date = str.split(', ');
var time = date[1].split(' ');
var timeItems = time[1].split('–');
var startTime = timeItems[0].trim();
var endtime = timeItems[1].trim();
alert("event lasts from "startTime + " to " + endtime);
Thanks
A:
Is all you want the startTime and endTime? If so, you could just do split() on the colon character:
times = str.split(':');
startTime = times[0].slice(-2) + ':' + times[1].slice(0,2);
endTime = times[1].slice(-2) + ':' + times[2].slice(0,2);
alert("event lasts from " + startTime + " to " + endTime);
|
[
"stackoverflow",
"0029162680.txt"
] | Q:
Xcode - unidentified symbols for architecture archs in libpjmedia-codec-arm-apple-darwin9.a(opencore.o)
I really having a hard time to figure out the problem.
i'm using PJSIP and also opencore-amr.
successfully compiled opencore-amr to arm64 (lipo -info told me)
successfully integrate opencore-amr (arm64) with PJSIP
(arm64),configure it, make dep, make clean and make without any
error.
when i try to compile it with XCode. it says
Undefined symbols for architecture arm64:
"_Decoder_Interface_Decode", referenced from:
_amr_codec_decode in libpjmedia-codec-arm-apple-darwin9.a(opencore_amr.o)
I did ar-t libpjmedia-codec-arm-apple-darwin9.a and the opencore.o inside the library is arm64.
I really have no clue to solve this.
please help me, thanks
FYI : I've tried open core with pjsip for android, and no issue at all.
A:
This is the linker error, you probably forgot to link some library. Go to Project settings -> Build phases -> Link Binary with Libraries section and review it. Try to google which framework contains the classes mentioned in error log and then add it to frameworks list.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.