id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23534300
|
Maybe i'm missing out on something or straight up doing something wrong?
$(document).ready(function(){
var addOpdracht = $('<a/>', {
'class': 'btn btn-primary'
}).on('click', function(){
$('.jumbotron').append(getExerciseBlock(i));
}).html('<i class="fa fa-plus"></i>');
$('.jumbotron').append(addOpdracht);
for(var i = 0; i< 0; i++){
$('.jumbotron').append(getExerciseBlock(i));
}
})
function getAddBtn(target, i){
var addBtn = $('<a/>', {
'class': 'btn btn-primary'
}).on('click', function(){
$(target).append(getWordPartInput(i));
}).html('<i class="fa fa-plus"></i>');
console.log(target);
return addBtn;
}
function getExerciseBlock(i){
var eBlock = $('<div/>',{
'id': i,
'class': 'col-md-12'
});
$(eBlock).append(getAudioBtn(i), getWordInput(i),
getWordPartInput(i),getAddBtn(eBlock, i));
return eBlock;
}
function getAddBtn(target, i){
var addBtn = $('<a/>', {
'class': 'btn btn-primary'
}).on('click', function(){
$(target).append(getWordPartInput(i));
}).html('<i class="fa fa-plus"></i>');
console.log(target);
return addBtn;
}
function getAudioBtn(id, cValue){
cValue = cValue || '';
var audioBtn = $('<a/>', {
'class': 'btn btn-primary'
}).html('<i class="fa fa-volume-up"></i>');
return audioBtn;
}
function getWordInput(id, cValue){
cValue = cValue || '';
var wInput = $('<input/>', {
'class': 'form-group form-control',
'type': 'text',
'name': 'question_takeAudio_exerciseWord[]',
'placeholder': 'Exercises'
})
return wInput;
}
function getWordPartInput(id, cValue){
cValue = cValue || '';
var wpInput = $('<input/>', {
'class': 'form-group form-control',
'type': 'text',
'value': cValue,
'placeholder': 'Syllables'
});
return wpInput;
}
So, what the idea should be:
*
*I click on var addOpdracht and it adds a whole extra field (it's basically cloning), but I need the clone to get an ID.
*The first field starts with ID 0, but when I click to clone it gives the second field an ID of 0 as well.
*I want it to get ID = 1 so I can send it to a JSON file and later on
pull it back based off its ID.
So what is it that i'm either doing wrong or not seeing ?
Please clarify this for me as well.
SECOND EDIT: my HTML code below.
THRID EDIT: I found out that the i I set to 0 defines the ID, but if I were to set i = 0; i< 10; i++ it will give me 10 input blocks to start off with, but I want one block to start with and whenever I click on it to reproduce the block again, but I want that one to have an ID of +1.
I'm sorry for all the EDITS. I am just trying to keep up to date on the stuff I have been trying.
<!doctype html>
<html lang="en">
<head>
<title>Exercise CMS</title>
<meta charset="UTF-8">
<script type="text/javascript" src="../../assets/vendor/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="../../assets/vendor/jquery-ui/jquery-ui.min.js"></script>
<script type="text/javascript" src="../../assets/vendor/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../../assets/vendor/bootstrap-select/dist/js/bootstrap-select.min.js"></script>
<script type="text/javascript" src="js/exercise_CMS.js"></script>
<link rel="icon" href="http://dk.fcsprint2.nl/favicon.ico?v=2">
<link rel="stylesheet" type="text/css" href="../../assets/vendor/jquery-ui/themes/base/jquery-ui.min.css">
<link rel="stylesheet" type="text/css" href="../../assets/vendor/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="../../assets/vendor/font-awesome/css/font-awesome.css">
<link rel="stylesheet" type="text/css" href="../../assets/vendor/bootstrap-select/dist/css/bootstrap-select.min.css">
<link rel="stylesheet" type="text/css" href="../../css/fonts.css">
<!--<link rel="stylesheet" type="text/css" href="style.css">-->
<!-- <script src="cms.js"></script>-->
</head>
<body>
<div class="container">
<div class="panel-group">
<div class="panel panel-default">
<div class="panel panel-primary">
<div class="panel-heading">
<div class="row">
<h2 id="exerciseTitle" class="col-md-8 col-sm-7 col-xs-6">CMS</h2>
<div class="col-md-offset-2 col-md-2">
<h2>
<select class="languageSelector form-control required" id="languageSelector" ></select>
</h2>
</div>
</div>
</div> <!-- end of panel-heading -->
<div class="panel-body">
<div class="jumbotron" id="mainList">
<form class="container-fluid" method="POST">
</form>
</div>
</div> <!-- end of panel-body -->
</div> <!-- end panel-primary -->
</div> <!--end panel-group -->
</div> <!-- end of container-->
A: Chage your:
$(document).ready(function(){
var addOpdracht = $('<a/>', {
'class': 'btn btn-primary'
}).on('click', function(){
$('.jumbotron').append(getExerciseBlock(i));
}).html('<i class="fa fa-plus"></i>');
$('.jumbotron').append(addOpdracht);
for(var i = 0; i< 0; i++){
$('.jumbotron').append(getExerciseBlock(i));
}
})
with that and will work:
$(document).ready(function(){
var id = 0;
var addOpdracht = $('<a/>', {
'class': 'btn btn-primary'
}).on('click', function(){
$('.jumbotron').append(getExerciseBlock(id));
id++;
}).html('<i class="fa fa-plus"></i>');
$('.jumbotron').append(addOpdracht);
})
And one tip: Please always keep your code formatted this will help you in many ways and safe you a lot of time!
| |
doc_23534301
|
In example, I have tables named as accounts and currencies.
Here are the accounts columns: id, label, currency
And Currencies columns: id, label
I have created migrations on both of them like that:
public function up()
{
Schema::create('accounts', function (Blueprint $table) {
$table->id();
$table->string('label', 255);
$table->integer('currency');
});
}
Here is the currencies:
public function up()
{
Schema::create('currencies', function (Blueprint $table) {
$table->id();
$table->string('label', 255);
});
}
I want to assign account's currency column to currency's id.
I have tried this:
public function up()
{
Schema::table('accounts', function (Blueprint $table) {
$table->foreign('currency')
->references('id')
->on('currencies')
->onUpdate('cascade');
});
}
But it throws this error:
SQLSTATE[HY000]: General error: 1005 Can't create table `test`.`accounts` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `accounts` add constraint `accounts_currency_foreign` foreign key (`currency`) references `currencies` (`id`) on update cascade)
How can I write the migration?
A: the id column in currency is from type: unsignedBigInteger
you have to update currency to this type first to be able to be a foreign key.
public function up()
{
Schema::table('accounts', function (Blueprint $table) {
$table->unsignedBigInteger('currency')->change();
$table->foreign('currency')
->references('id')
->on('currencies')
->onUpdate('cascade');
});
}
or you can modify the first migration if possible.
| |
doc_23534302
|
In those anchors, there are some unwanted anchor like . I don't only choose all anchors, but some of them.
The html of anchor looks like this:
<a xmlns="" href="exp3dbasics-c-ExpDesktop-ActionBar.htm#exp3dbasics-c-ExpDesktop-ActionBar">Action Bar</a>
The c# code should be:
protected string[] GetHref(string html)
{
Regex regex = new Regex("<anchor>([^<]+)</anchor>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
Match match = regex.Match(html);
if (match.Success)
{
............
}
return ...;
}
| |
doc_23534303
|
private final List<PhoneNumber> receivers = new ArrayList<>();
It signifies an error underneath the first < after 'new ArrayList'. ^
I'm running Eclipse and Windows 8 - 32-bit, could this be an encoding problem?
A: Try this: You have to parametarize the type of object at both sides.
private final List<PhoneNumber> receivers = new ArrayList<PhoneNumber>();
A: The Diamond Operator, used to reduce the verbosity when using generics was added in JDK 1.7. The fact you're getting a syntax error probably means you're using an older version to compile this piece of code.
Either use JDK 1.7 to compile the code, or change to:
new ArrayList<PhoneNumber>();
A: This was the solution for me:
*
*Window -> Preferences -> Java -> Compiler -> Compiler Compliance Level: 1.7
this was 1.6 at first.
Had to download Eclipse Indigo RS2 for this one.
| |
doc_23534304
|
These movie files are accessed across a network by various users and that's where I'm running into a problem.
When the script runs and tries to move the files it throws a resource busy error because the files are open by various users. Is there a way in Python to force close these files before I attempt to move them?
Further clarification:
JMax is correct when he mentions it is server level problem. I can access our windows server through Administrative Tools > Computer Management > Shared Folders > Open Files and manually close the files there, but I am wondering whether there is a Python equivalent which will achieve the same result.
something like this:
try:
shutil.move(src, dst)
except OSError:
# Close src file on all machines that are currently accessing it and try again.
A: This question has nothing to do with Python, and everything to do with the particular operating system and file system you're using. Could you please provide these details?
At least in Windows you can use Sysinternals Handle to force a particular handle to a file to be closed. Especially as this file is opened by another user over a network this operation is extremely destabilising and will probably render the network connection subsequently useless. You're looking for the "-c" command-line argument, where the documentation reads:
Closes the specified handle (interpreted as a hexadecimal number). You
must specify the process by its PID.
WARNING: Closing handles can cause application or system instability.
And if you're force-closing a file mounted over Samba in Linux, speaking from experience this is an excruciating experience in futility. However, others have tried with mixed success; see Force a Samba process to close a file.
A: As far as I know you have to end the processes which access the file. At least on Windows
A: The .close() method doesn't work on your object file?
See dive into Python for more information on file objects
[EDIT] I've re-read your question. Your problem is that users do open the same file from the network and you want them to close the file? But can you access to their OS?
[EDIT2] The problem is more on a server level to disconnect the user that access the file. See this example for Windows servers.
| |
doc_23534305
|
/interpreter?node(around:10, 40.7127, 74.0059)[maxspeed];out;
I haven't implemented this into my code yet, testing it on Firefox.
Why is the XML file empty, and are there any other free online resources which can be used to get the speed limit of a road at coordinates x,y?
Note: I would prefer if it supported speed limits in the UK
A: Two reasons your query returns an empty result:
*
*You are querying in a very sparsely mapped region
*You are querying for nodes instead of ways
Try this query instead:
way
(around:70, 51.0483, 13.7495)
[maxspeed];
(._;>;);
out;
See the result on overpass turbo.
| |
doc_23534306
|
var app = angular.module('cpu-usage', []);
app.controller('GaugeController', ['$scope', '$http',
function($scope, $http) {
var viewAll = this;
viewAll.gauge = [];
$http.get('dom/json/cpuUsage.json').success(function(data){
viewAll.gauge = data;
});
$scope.value = viewAll.gauge[0].value;
However, I am having a hard time taking out the value from my variable array viewAll.gauge. I'm having an error in:
Error: viewAll.gauge[0] is undefined
@http://localhost:8080/js/directives/cpusagegauge.js:11:2
e@http://localhost:8080/js/angular.min.js:35:343
h/<.instantiate@http://localhost:8080/js/angular.min.js:35:474
ce/this.$get</<@http://localhost:8080/js/angular.min.js:68:140
x/<@http://localhost:8080/js/angular.min.js:54:226
q@http://localhost:8080/js/angular.min.js:7:384
x@http://localhost:8080/js/angular.min.js:54:89
g@http://localhost:8080/js/angular.min.js:48:28
g@http://localhost:8080/js/angular.min.js:48:1
g@http://localhost:8080/js/angular.min.js:48:1
x@http://localhost:8080/js/angular.min.js:55:10
g@http://localhost:8080/js/angular.min.js:48:28
x@http://localhost:8080/js/angular.min.js:55:10
z/<@http://localhost:8080/js/angular.min.js:61:261
l/k.success/<@http://localhost:8080/js/angular.min.js:73:32
Re/e/m.promise.then/L@http://localhost:8080/js/angular.min.js:99:147
Re/e/m.promise.then/L@http://localhost:8080/js/angular.min.js:99:147
Re/f/<.then/<@http://localhost:8080/js/angular.min.js:100:321
me/this.$get</g.prototype.$eval@http://localhost:8080/js/angular.min.js:111:1
me/this.$get</g.prototype.$digest@http://localhost:8080/js/angular.min.js:108:458
me/this.$get</g.prototype.$apply@http://localhost:8080/js/angular.min.js:112:323
g@http://localhost:8080/js/angular.min.js:73:285
x@http://localhost:8080/js/angular.min.js:77:322
Ne/</y.onreadystatechange@http://localhost:8080/js/angular.min.js:78:358
http://localhost:8080/js/angular.min.js
Line 93
BTW, my JSON file is pretty small.
[{
"value": "80"
}]
A: The problem is that the callback of $http.get() is called asynchronously. In your case viewAll.gauge = data;is called after $scope.value = viewAll.gauge[0].value;
The following should work:
var app = angular.module('cpu-usage', []);
app.controller('GaugeController', ['$scope', '$http',
function($scope, $http) {
var viewAll = this;
viewAll.gauge = [];
$http.get('dom/json/cpuUsage.json').success(function(data){
$scope.value = data.gauge[0].value;
});
})
Additionally if you want to update scope variables in async callbacks you have to wrap it in $scope.$apply(function() { //your code goes here });. Here is the full example:
var app = angular.module('cpu-usage', []);
app.controller('GaugeController', ['$scope', '$http',
function($scope, $http) {
var viewAll = this;
viewAll.gauge = [];
$http.get('dom/json/cpuUsage.json').success(function(data){
$scope.apply(function() {
$scope.value = data.gauge[0].value;
});
});
})
| |
doc_23534307
|
I'm doing this in Java, if that matters, and will be doing the transformation in a TemplateMethodModelEx.exec method.
A: With ElementModel.getNode() you can get the org.w3c.dom.Node, and after that it's the usual (FreeMarker-independent) business. When the new DOM is ready, you can get the current ObjectWrapper from the freemarker.core.Environment and return objectWrapper.wrap(newNode) to the template (and here I assume you are using the default object wrapper, which knows about Node-s).
| |
doc_23534308
|
EDIT:working solution
[[UITabBarItem appearance] setTitleTextAttributes:
[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor blackColor], UITextAttributeTextColor,
[UIColor whiteColor], UITextAttributeTextShadowColor,
[NSValue valueWithUIOffset:UIOffsetMake(0, 1)], UITextAttributeTextShadowOffset,
[UIFont fontWithName:@"Rok" size:0.0], UITextAttributeFont,
nil]
forState:UIControlStateNormal];
A: Specifically for iOS 7, try using NSForegroundColorAttributeName instead of UITextAttributeTextColor
A: Do you mean this one? Keep in mind, this only works for iOS5.0 or later.
if ([self.tabBarItem respondsToSelector:@selector(setTitleTextAttributes:)]) {
NSLog(@"*** Support method(iOS 5): setTitleTextAttributes:");
[self.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:@"AmericanTypewriter" size:20.0f], UITextAttributeFont,
[UIColor blackColor], UITextAttributeTextColor,
[UIColor grayColor], UITextAttributeTextShadowColor,
[NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)], UITextAttributeTextShadowOffset,
nil]];
}
Apple's documentation on customizing appearance:
In iOS v5.0 and later, you can customize the appearance of tab bars by setting item label text attributes using appearance selectors declared by UIBarItem. You can also use the methods listed in “Customizing Appearance.” You can customize the appearance of all segmented controls using the appearance proxy (for example, [UITabBarItem appearance]), or just of a single tab bar. You can also provide finished selected and unselected images using the methods listed in “Managing the Finished Selected Image”; these methods, though, do not participate in the UIAppearance proxy API (see UIAppearance). UIKit does now provide any automatic treatment to finished images. For good results, you must provide finished selected and unselected images in matching pairs using setFinishedSelectedImage:withFinishedUnselectedImage:.
Edit:
Here is another example using the UIAppearance system and the NSDictionary literal syntax:
[[UITabBarItem appearance] setTitleTextAttributes:@{
UITextAttributeFont : [UIFont fontWithName:@"AmericanTypewriter" size:20.0f],
UITextAttributeTextColor : [UIColor blackColor],
UITextAttributeTextShadowColor : [UIColor grayColor],
UITextAttributeTextShadowOffset : [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)]}];
Edit (by @JeremyWiebe):
As of iOS 6, the dictionary keys have been changed to be the same as OS X uses:
NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowColor = [UIColor grayColor];
shadow.shadowOffset = CGSizeMake(0, 1.0);
[[UITabBarItem appearance] setTitleTextAttributes:@{
NSFontAttributeName : [UIFont fontWithName:@"AmericanTypewriter" size:20.0f],
NSForegroundColorAttributeName : [UIColor blackColor],
NSShadowAttributeName : shadow }];
A: [[UITabBarItem appearance] setTitleTextAttributes:@{
UITextAttributeFont : [UIFont fontWithName:@"HelveticaNeue-Bold" size:10.0f],
UITextAttributeTextColor : [UIColor colorWithRed:0/255.0 green:48/255.0 blue:92/255.0 alpha:1.0],}
forState:UIControlStateNormal];
[[UITabBarItem appearance] setTitleTextAttributes:@{
UITextAttributeFont : [UIFont fontWithName:@"HelveticaNeue-Bold" size:10.0f],
UITextAttributeTextColor : [UIColor colorWithRed:0/255.0 green:138/255.0 blue:196/255.0 alpha:1.0],}
forState:UIControlStateSelected];
A: UITextAttributeFont, UITextAttributeTextColor etc. are deprecated in iOS 7.0.
You have to use:
NSFontAttributeName, NSParagraphStyleAttributeName, NSForegroundColorAttributeName, NSBackgroundColorAttributeName, NSLigatureAttributeName, NSKernAttributeName, NSStrikethroughStyleAttributeName, NSUnderlineStyleAttributeName, NSStrokeColorAttributeName, NSStrokeWidthAttributeName, NSShadowAttributeName and NSVerticalGlyphFormAttributeName
A: I do not have enough reputation points to add a comment so I will add another answer here.
I have had the same problem and searched for the past hour and finally realized that my issue is because I didn't put the code into method viewWillAppear. Not sure if this is common sense as I just started with objective-c but thought this should be another piece of important information to the answer as the same code didn't work inside viewDidLoad.
According to this post, this code only works if put in the method viewWillAppear.
A: Working solution for iOS 7.0+:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor redColor], NSForegroundColorAttributeName,
nil] forState:UIControlStateNormal];
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor whiteColor], NSForegroundColorAttributeName,
nil] forState:UIControlStateSelected];
}
| |
doc_23534309
|
<a class="filterbutton" ng-click="filters.grade = '7'">7 Grade</a>
<a class="filterbutton" ng-click="filters.grade = '6'">6 Grade</a>
<a class="filterbutton" ng-click="filters.grade = ''">X Clear Filters</a>
<ul>
<li ng-repeat="name in names | filter:filters">{{name.student}}, {{name.grade}} grade</li>
</ul>
And the controller:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.filters = { };
$scope.names = [{
"student": "Jimmy", "grade":7
}, {
"student": "Johny", "grade":7
}, {
"student": "Little Joe", "grade":6
}];
});
This works as expected. But what I wanted to do is to be able to check one of the filters and jump to another page with the same controller, so that when loaded the second page would be already filtered. So for example, if I click "filter by 7 grade in another page", it would jump to anotherpage.html and the output there would be already filtered.
I have made a plunkr here to illustrate what I mean. Thanks in advance!
A: Also you can try this simple solution:
HTML (add filter parameter to href attribute):
<a class="filterbutton" href="anotherpage.html?filter=7">Filter by 7 Grade in Another Page</a>
<a class="filterbutton" href="anotherpage.html?filter=6">Filter by 6 Grade in Another Page</a>
Javascript (get them from url and apply it)
app.controller('myCtrl', function($scope) {
$scope.filters = { grade : window.location.search.replace('?filter=','') };
$scope.names = [{
"student": "Jimmy", "grade":7
}, {
"student": "Johny", "grade":7
}, {
"student": "Little Joe", "grade":6
}];
});
| |
doc_23534310
|
chrome.storage.local.get(['valueInput'], (result) => {
if (typeof result.valueInput !== 'undefined') {
let selectorInput = document.querySelectorAll('input');
result.valueInput.forEach((item, index) => selectorInput[index].value = item);
}
});
And i splice this code to independent function
function getFromeStorage(value) {
let arr = [];
chrome.storage.local.get(value, (result) => {
if (typeof result.valueInput !== 'undefined') {
result.valueInput.forEach((item, i) => arr[i] = item);
}
});
return arr;
\\ Array(18)[0: "3" 1: "1" 2: "1" 3: "1" 4: "1" 5: "1" 6: "1" 7: "1" 8: "1" 9: "1" 10: "1" 11: "1" 12: "1" 13: "1" 14: "1" 15: "1" 16: "1" 17: "1"]
}
But when i splice this function this function wont work
let selectorInput = document.querySelectorAll('input');
let valueInput = getFromeStorage("valueInput");
valueInput.forEach((item, index) => selectorInput[index].value = item);
HTML
<tr>
<td class="center-align">Administrowanie systemami operacyjnymi</td>
<td class="center-align row">
<input type="number" class="input-default-weight" min="1" max="20" value="1">
<i id="hint-default-weight" class="material-icons md-dark center-vertically tooltipped hint" data-position="top" data-delay="250" data-tooltip="Ilość lekcji w tygodniu" data-tooltip-id="1b1400b4-3270-0b0c-da17-8540ce6f2408">info_outline</i></td>
<td class="center-align">5</td>
<td class="center-align yearPresent">86%</td>
</tr>
This is the same code but i only splice my main code to function and i call this in my code. How can i fix this?
A: It looks like you're returning the arr variable before the callback has been called so it's always returning an empty array.
function getFromeStorage(value) {
let arr = [];
chrome.storage.local.get(value, (result) => {
// This function won't fill 'arr' until later
if (typeof result.valueInput !== 'undefined') {
result.valueInput.forEach((item, i) => arr[i] = item);
}
});
// This empty 'arr' gets returned too early
return arr;
Since chrome.storage.local.get is asynchronous your function accessing it must deal with that. One way is to add a callback or Promise to your function. To keep it simple here's how it would look with a callback:
function getFromeStorage(value, callback) {
chrome.storage.local.get(value, (result) => {
const arr = [];
if (typeof result.valueInput !== 'undefined') {
result.valueInput.forEach((item, i) => arr[i] = item);
}
callback(arr);
});
}
You would then have to change how you use the function to wait for the callback to be called like this:
let selectorInput = document.querySelectorAll('input');
let valueInput = getFromeStorage("valueInput", (valueInput) =>{
valueInput.forEach((item, index) => selectorInput[index].value = item);
});
| |
doc_23534311
|
int PlaySong()
{
ifstream File("\Text.txt");
if (File.is_open() == false)
return -1;
int F = 0;
int D = 0;
while (File.eof() == false)
{
File >> F >> D;
Beep(F, D);
}
return 0;
}
A: No it wouldn't damage the sound card if you are using the frequency of the sound, in hertz. in the range 37 through 32,767 (0x25 through 0x7FFF).
A: I do not think you can damage any hardware with that, even if the function was not written for the purpose your audio card will have a wide frequency range. Although there is a possibility to damage attached speakers by playing a very low frequency often :).
A: Short answer - no. If the sound is not correct, it is probably down to the sound card driver or perhaps out-of-range parameters.
You have not revealed your input data, but very short time periods with rapidly changing frequencies is likely to be less than musical, and generate uncontrolled harmonics from incomplete cycles of the tone. This is especially true when the period is less than 1/F, but any abrupt frequency switch will introduce a discontinuity that will produce harmonics, and doing this rapidly will be clearly audible.
It seems that Beep() is clearly well defined to work with sound-cards since Windows 7 at least; prior to that it will have either not been supported, or will have driven the speaker directly from the timer chip.
From MSDN Beep documentation:
A long time ago, all PC computers shared a common 8254 programmable interval timer chip for the generation of primitive sounds. The Beep function was written specifically to emit a beep on that piece of hardware.
On these older systems, muting and volume controls have no effect on Beep; you would still hear the tone. To silence the tone, you used the following commands:
net stop beep
sc config beep start= disabled
Since then, sound cards have become standard equipment on almost all PC computers. As sound cards became more common, manufacturers began to remove the old timer chip from computers. The chips were also excluded from the design of server computers. The result is that Beep did not work on all computers without the chip. This was okay because most developers had moved on to calling the MessageBeep function that uses whatever is the default sound device instead of the 8254 chip.
Eventually because of the lack of hardware to communicate with, support for Beep was dropped in Windows Vista and Windows XP 64-Bit Edition.
In Windows 7, Beep was rewritten to pass the beep to the default sound device for the session. This is normally the sound card, except when run under Terminal Services, in which case the beep is rendered on the client.
| |
doc_23534312
|
The activities are listening to ddbb changes so the views can be updated when data changes. Problem is data can change while activities are in background, so I am not sure when and how i should listen for changes. I can think of two approaches:
*
*Listen for changes during the whole Activity lifecycle (onCreate - onDestroy) and just update the views when the data changes. This will update views from background activities.
*Listen for changes only when the Activity is being active or displayed (between onStart/onStop or onResume/onPause) and force a view update every time the activity comes to the foreground (since changes might have happened while activity wasn't listening).
*Mixed approaches; keep the listeners the whole lifecycle but only update views when activity comes to foreground.
Im not sure which is the correct way to handle data observing while in background.
Option 2 sounds more reasonable, but having to update the views when the activity comes to foreground may lead to UI lag right when the user starts interacting with the activity.
Option 1 will cause a lot of updates every time data is updated.
Thoughts on this?
A: You can choose any of the three options that suits your particular use case. Though I will say that the conventional use is with start/stop. onStart says that the activity is visible to the user in some way (either fully or partially) and onStop says that the activity is definitely not visible. So if you don't care to update the UI while the activity is not showing at all, use these lifecycle states.
You just may need to be prepared to capture data that you may have missed while the activity was stopped before it gets started again (for example, if the user pressed the home button, then came back to the activity via the task switcher. So performing your query again and rebuilding the contents of views from scratch may be necessary.
| |
doc_23534313
|
This helped avoid replacing existing UITableViewController(s) with a view controller + table (or hacking the combined component to display a view that does not scroll with the table on top of the table).
This was working fine until I tried adding didSelectRow on the Table object. Although the (pop up) view controller works ok, when dismissed, the following issues started (all associated with the navigation controller):
*
*toolbar - I have a tool bar on screen (always shown). On dismissing the (pop up) view controller, the toolbar changes status to 'hidden' (setting 'hidden' to false brought it back).
*on screen (floating) buttons (owned by the nav controller) - if these were displayed, they now 'disappear'. Checking the x, y coordinates, showed that their position has not changed but it looks as if they've been pushed backward from a view layering perspective).
Any ideas? Has anyone encountered this behaviour?
tested on the following devices: 4s, 5, 6/6p, 6s/6sp.
All devices showed the same issue except iPhone 6 (1st gen).
Tested with ios versions 9.2, 9.2.1, 9.3, 9.3.1.
A: The issues were caused as a result of displaying the view using the 'current'/presenting VC as oppose to presenting via the navigation controller. Once changed, it all worked as expected.
| |
doc_23534314
|
(it works when I execute the commands manually)
Step 8 : RUN dotnet restore
---> Running in 3ef8b4c1d107
Dockerfile:
FROM microsoft/dotnet
VOLUME /Documents/Docker/dnc
EXPOSE 80
ENV "ASPNETCORE_URLS=http://+:80"
RUN mkdir app
RUN cd app
RUN dotnet new -t web
RUN dotnet restore
RUN dotnet run
A: With the help of another SO post I found out I was missing a WORKDIR.
The correct code is:
FROM microsoft/dotnet
VOLUME /Documents/Docker/dnc
EXPOSE 80
ENV "ASPNETCORE_URLS=http://+:80"
RUN mkdir app
# RUN cd app <- turned out was not necessary.
WORKDIR /app
RUN dotnet new -t web
RUN dotnet restore
RUN dotnet run
| |
doc_23534315
|
public final class Employee{
private final int id;
private Address address;
public Employee(int id, Address address)
{
this.id = id;
this.address=address;
}
public int getId(){
return id;
}
public Address getAddress(){
return address;
}
}
public class Address{
private String street;
public String getStreet(){
return street;
}
public void setStreet(String street){
this.street = street;
}
}
A: If you want to encapsulate a mutable object into an immutable one, then you need to:
*
*Create a copy of the mutable object (i.e. via copy constructor, cloning, serialization/deserialization, etc.);
never store the reference to the original mutable object.
*Never return the mutable object. If you must to, then return a copy of the object.
*Avoid methods which can change the mutable object.
public Employee(int id, Address address){
this.id = id;
this.address=new Address();
this.address.setStreet( address.getStreet() );
}
public Address getAddress() {
Address nuAdd = new Address(); // must copy here too
nuAdd.setStreet( address.getStreet() );
return nuAdd;
}
A: In Employee class, return the deep clone copy of the address instance in the getAddress() method instead of returning original instance. So that if anybody changed the address instance, it can not reflect the original instance. But one condition, Address class must implements Cloneable interface.
public final class Employee{
private final int id;
private Address address;
public Employee(int id, Address address) {
this.id = id;
this.address=address;
}
public int getId(){
return id;
}
public Address getAddress() throws CloneNotSupportedException{
return (Address) address.clone();
}
}
Reference :-Immutable Class in java
A: Well, the concept is reading the JLS and understanding it. Chapter 17 of the JLS "Threads and Locks" describes memory visibility and synchronization. Section 17.5 "Final Field Semantics" describes the memory visibility semantics for final fields. That section says in part:
final fields also allow programmers to implement thread-safe immutable objects without synchronization. A thread-safe immutable object is seen as immutable by all threads, even if a data race is used to pass references to the immutable object between threads. This can provide safety guarantees against misuse of an immutable class by incorrect or malicious code. final fields must be used correctly to provide a guarantee of immutability.
The usage model for final fields is a simple one: Set the final fields for an object in that object's constructor; and do not write a reference to the object being constructed in a place where another thread can see it before the object's constructor is finished. If this is followed, then when the object is seen by another thread, that thread will always see the correctly constructed version of that object's final fields. It will also see versions of any object or array referenced by those final fields that are at least as up-to-date as the final fields are.
So you need to:
*
*Make address both final and private.
*For any mutable object, you must prevent the reference to that object from being seen externally.
In this case, #2 probably means you can't return a reference to Address like you have with getAddress(). And you have to make a defensive copy in the constructor. I.e., make a copy of any mutable parameter, and store the copy in Employee. If you can't make a defensive copy, there's really no way to make Employee immutable.
public final class Employee{
private final int id;
private final Address address;
public Employee(int id, Address address)
{
this.id = id;
this.address=new Address(); // defensive copy
this.address.setStreet( address.getStreet() );
}
public int getId(){
return id;
}
public Address getAddress() {
Address nuAdd = new Address(); // must copy here too
nuAdd.setStreet( address.getStreet() );
return nuAdd;
}
Implementing clone() or something similar (a copy ctor) would make creating defensive objects easier for complicated classes. However, the best recommendation I think would be to make Address immutable. Once you do that you can freely pass around its reference without any thread-safety issues.
In this example, notice I do NOT have to copy the value of street. Street is a String, and strings are immutable. If street consisted of mutable fields (integer street number for example) then I would have to make a copy of street also, and so on ad infinitum. This is why immutable objects are so valuable, they break the "infinite copy" chain.
Since this question is getting popular, I should also add a mention of Brian Goetz's book, Java Concurrency in Practice, which is how I learned about these techniques, and I'm basically paraphrasing that book above.
A: Well there is steps provided by Java docs
A Strategy for Defining Immutable Objects
The following rules define a simple strategy for creating immutable
objects. Not all classes documented as "immutable" follow these rules.
This does not necessarily mean the creators of these classes were
sloppy — they may have good reason for believing that instances of
their classes never change after construction. However, such
strategies require sophisticated analysis and are not for beginners.
*
*Don't provide "setter" methods — methods that modify fields or objects
referred to by fields.
*Make all fields final and private.
*Don't allow
subclasses to override methods. The simplest way to do this is to
declare the class as final. A more sophisticated approach is to make
the constructor private and construct instances in factory methods.
*If
the instance fields include references to mutable objects, don't allow
those objects to be changed:
*
*Don't provide methods that modify the
mutable objects.
*Don't share references to the mutable objects. Never
store references to external, mutable objects passed to the
constructor; if necessary, create copies, and store references to the
copies. Similarly, create copies of your internal mutable objects when
necessary to avoid returning the originals in your methods.
Address class is mutable because you can modify it with the setStreet method.
So other class can modify this class.
We can defend against this by taking a copy of the of the Address instance when it is passed in rather than trusting the reference to the instance we are given.
Making Address object final
private final Address address;
Secondly,
this.address = new Address(address.getStreet());
Create constructor in Address class that sets Street.Remove setter method for street.
And finally instead of
public Address getAddress(){
return address;
}
Use
public Address getAddress(){
return new Address(address.getStreet());
}
A: So in your example Employee class is immutable, because once it is created, you can't change its state, because it has only getter methods.
Address class is mutable because you can modify it with the setStreet method.
So if you have other class which uses Address object, you are sure that that class can't modify the objects state.
A: You can also use shallow copy using cloning
public final class Employee{
private final int id;
private Address address;
public Employee(int id, Address address)
{
this.id = id;
this.address=address.clone();
}
public int getId(){
return id;
}
public Address getAddress(){
return address.clone();
}
}
Using this will create a separate object of Address in Employee class so in this case any changes made to the Address object passed as argument in Employee constructor will not change the member variable Address object of Employee class.
The getAddress() method is also returning a clone object so any changes made to the object fetched by this method do not effect the address object of Employee class.
Note:
To use this make Address class Cloneable.
A: What is difference between the creating the object of employee calling the clonne method.
1) Creating employee object inside constructor and getter method and setting the required Value by creating the object of employee inside constructor and setting the required field of employee into it as below.
Example :
public final class Employee{
private final int id;
private final Address address;
public Employee(int id, Address address)
{
this.id = id;
this.address=new Address(); // defensive copy
this.address.setStreet( address.getStreet() );
}
public int getId(){
return id;
}
public Address getAddress() {
Address nuAdd = new Address(); // must copy here too
nuAdd.setStreet( address.getStreet() );
return nuAdd;
}
2) cloning the employee object inside constructor and getter method as below.
Example :
public final class Employee{
private final int id;
private Address address;
public Employee(int id, Address address)
{
this.id = id;
this.address=address.clone();
}
public int getId(){
return id;
}
public Address getAddress(){
return address.clone();
}
}
| |
doc_23534316
|
My strategy has been to plot the first set of bars, create space between them and try to plot the second in those spaces with whether par(new=TRUE) or add = TRUE argument in barplot. However, the second set of bars always overlap the first. Barplot documentation suggests that the offset argument should be useful, but I can't seem to find any examples using it and my own experimentation never seems to come out as expected.
Here is an example of code I've tried so far:
data1 = cbind(c(1,1.25),c(1.2,1.5),c(.75,1.2))
data2 = cbind(c(1.3,1.5),c(1,1.25),c(1.25,.75))
barplot(data1,
space = 3,
col = c(2,3))
barplot(data2,
space = 3,
col = c(4,5),
add = TRUE)
Any suggestions or resources would be greatly appreciated.
A: You can adjust the space parameter of the second plot. In this case, the space before the first bar needs to be larger than for the first plot. The spaces between bars, however, need to be the same. You can use the argument space = c(4, 3, 3) for the second plot.
barplot(data1,
space = 3,
col = c(2, 3))
barplot(data2,
space = c(4, 3, 3),
col = c(4, 5),
add = TRUE)
| |
doc_23534317
|
type User {
id: ID!
name: String!
}
type UserConnection {
totalCount: Int
pageInfo: PageInfo
edges: [UserEdge]
}
type UserEdge {
cursor: String
node: User
}
type PageInfo {
lastCursor: Int
hasNextPage: Boolean
}
type Query {
users(first: Int, after: String): UserConnection
}
Consider the following router on within SPA front-end:
/users - once the user hit this page, I'm fetching first 10 records right up from the top of the list and further I'm able to paginate by reusing a cursor that I've retrieved from the first response.
/user/52 - here I'd like to show up 10 records that should go right from the position of user52.
Problem What are the possible ways to retrieve a particular subset of records on the very first request? On this moment I don't have any cursor to construct something similar to
query GetTenUsersAfter52 {
users(first: 10, after: "????") { # struggling to pass anything as a cursor...
edges {
node {
name
}
}
}
}
What I've already tried(a possible solution) is that I know that on a back-end the cursor is encoded value of an _id of the record in the DB. So, being on /users/52 I can make an individual request for that particular user, grab the value of id, then on the front-end I can compute a cursor and pass it to the back-end in the query above.
But in this case personally, I found a couple of disadvantages:
*
*I'm exposing the way of how my cursor is computed to the front-end, which is bad since if I needed to change that procedure I need to change it on front-end and back-end...
*I don't want to make another query field for an individual user simply because I need its id to pass to the users query field.
*I don't want to make 2 API calls for that as well...
A: This is a good example of how Relay-style pagination can be limiting. You'll hit a similar scenario with create mutations, where manually adding a created object into the cache ends up screwing up your pagination because you won't have a cursor for the created object.
As long as you're not actually using Relay client-side, one solution is to just abandon using cursors altogether. You can keep your before and after fields, but instead simply accept the id (or _id or whatever PK) value instead of a cursor. This is what I ended up doing on a recent project and it simplified things significantly.
| |
doc_23534318
|
def lambda_handler(event, context):
return_value = {} #creates empty dictionary#
return_value['missingtagkeys'] = [] #within return values dictionary, create a missing tag key list#
return_value['missingtagvalues'] = [] #within return values dictionart, creates a missing tag values key list#
return_value['incorrecttagkeys'] = [] #within return values dictionary, create a incorrect tag key list#
return_value['incorrecttagvalues'] = [] #within return values dictionary, create a incorrect tag value list#
return_value['unknowntagvalues'] = [] #within return values dictionary, create a unknown tag value list#
# THE BELOW IS A SAMPLE OF WHAT THE DICTIONARY STRUCTURE WILL END UP AS #
# instance_tag_issues = {}
# instance_tag_issues{'instance_ids'} = {}
# instance_tag_issues{'instance_ids'}{'tags'} = {}
buildertag = [{
"Key": "builder",
"Value": "unknown"
}]
instance_ids = []
reservations = ec.describe_instances().get('Reservations', [])
for reservation in reservations:
tags = {}
for instance in reservation['Instances']:
try:
for tag in instance['Tags']:
tags[tag['Key']] = tag['Value']
if tag['Key'] == 'Name':
# print(tag['Value'])
instance_nametag = tag['Value']
except:
pass
#section almost works but has error
try:
if tag['Key'] == 'contact':
instance_contacttag = tag['Value']
print(instance_contacttag)
# We receive the following error when uncommenting the below print statement. Need to figure out why instance_nametag is unassigned?
# "errorMessage": "local variable 'instance_nametag' referenced before assignment",
print(instance_nametag + " (" + instance['InstanceId'] + ")" + " has a contact tag of '" + instance_contacttag + "'.")
except:
print("CONTACT TAG MISSING")
# Checks if builder tag exist and adds if it doesn't #
if not 'builder' in tags:
tagissue = (instance_nametag + " (" + instance['InstanceId'] + " does not have builder tag. Adding 'builder' tag with value of 'unknown'.")
print(instance_nametag + " (" + instance['InstanceId'] + ")" + " does not have builder tag. Adding 'builder' tag with value of 'unknown'.")
ec.create_tags(Resources=[instance["InstanceId"]], Tags=buildertag)
return_value['missingtagkeys'].append(tagissue)
instance_ids['missingtagkeys'].append(tagissue)
# print(instance_ids['instance_ids']['missingtagkeys'])
# print(instance_ids['instance_ids']['missingtagkeys'])
# print(instance_ids['instance_ids']['missingtagkeys'])
# print(instance_ids['instance_ids']['missingtagkeys'])
# print(instance_ids['instance_ids']['missingtagkeys'])
# print(instance_tag_issues['i-xyz123454596']['missingtagkeys'])
# Checks for null tag value and print output #
elif tags['builder'] in ['']:
print(instance_nametag + " (" + instance['InstanceId'] + ")" + " has no value for builder tag.")
tagissue = (instance_nametag + " (" + instance['InstanceId'] + ")" + " has no value for builder tag.")
ec.create_tags(Resources=[instance["InstanceId"]], Tags=buildertag)
return_value['missingtagvalues'].append(tagissue)
# instance_ids['instance_ids']['missingtagvalues'].append(tagissue)
print(instance_ids['instance_ids']['missingtagvalues'])
# Checks for unknown tag value and print output #
elif tags['builder'] in ['Unknown', 'unknown']:
print(instance_nametag + " (" + instance['InstanceId'] + ")" + " has unknown for it's builder tag value.")
tagissue = (instance_nametag + " (" + instance['InstanceId'] + ")" + " has unknown for it's builder tag value.")
return_value['unknowntagvalues'].append(tagissue)
# instance_ids['instance_ids']['unknowntagvalues'].append(tagissue)
# print(instance_ids['instance_ids']['unknowntagvalues'])
# print(instance_ids['instance_ids']['unknowntagvalues'])
# print(instance_ids['instance_ids']['unknowntagvalues'])
# print(instance_ids['instance_ids']['unknowntagvalues'])
# print(instance_ids['instance_ids']['unknowntagvalues'])
# Checks for builder tags equal to approved values and print output #
elif tags['builder'] in ['r', 'k', 'c', 'a', 'm']:
print(instance_nametag + " (" + instance['InstanceId'] + ")" + " has an approved builder tag value.")
tagissue = (instance_nametag + " (" + instance['InstanceId'] + ")" + " has an approved builder tag value.")
# return_value['unknowntagvalues'].append(tagissue) ###resources with approved tag values doesn't need reporting
# Checks for builder tags equal to unapproved values and print output #
elif tags['builder'] not in ['r', 'k', 'c', 'a', 'm']:
print(instance_nametag + " (" + instance['InstanceId'] + ")" + " has a incorrect builder tag value.")
tagissue = (instance_nametag + " (" + instance['InstanceId'] + ")" + " has a incorrect builder tag value.")
return_value['incorrecttagvalues'].append(tagissue)
# Sets variables for sns formatting
instanceids = instance_ids
incorrect_keys = '\n'.join(return_value['incorrecttagkeys'])
incorrect_values = '\n'.join(return_value['incorrecttagvalues'])
missing_keys = '\n'.join(return_value['missingtagkeys'])
missing_values = '\n'.join(return_value['missingtagvalues'])
unknown_values = '\n'.join(return_value['unknowntagvalues'])
# instance_tagissues = (instance_tag_issues['i-abc12354568']['tags']['contact'])
# contact_tag = '\n'.join(str(instance_contacttag))
# approvedtags_approvedvalues = print(approvedtagsapprovedvalues)
email_body = """
Here is a list of EC2 tags that need review.
Please correct the tags using the approved values list located below
<insert site here>.
------------------------------------------------------------------------------------
Summary of incorrect tags keys and/or values:
------------------------------------------------------------------------------------
Incorrect Tag Keys : {incorrect_keys}
Incorrect Tag Values : {incorrect_values}
------------------------------------------------------------------------------------
Summary of missing tags keys and/or values:
------------------------------------------------------------------------------------
Missing Tag Keys : {missing_keys}
Missing Tag Values : {missing_values}
------------------------------------------------------------------------------------
Summary of unknown values:
------------------------------------------------------------------------------------
Unknown Tag Values:
{unknown_values}
------------------------------------------------------------------------------------
Below is a list of approved tag keys/values:
{instanceids}
<insert approved tags/values dic here>
""".format(incorrect_keys = incorrect_keys,
incorrect_values = incorrect_values,
missing_keys = missing_keys,
missing_values = missing_values,
unknown_values = unknown_values,
instanceids = instanceids
# instance_tagissues = instance_tagissues
# contact_tag = contact_tag
# approvedtags_approvedvalues = approvedtags_approvedvalues
)
sns_client.publish(
TopicArn = 'arn',
Subject = 'Incorrect Tags Detected',
Message = str(email_body) + str(return_value),
)
return return_value
Alright, so there is really no error and this is the output:
Test Event Name Testingtaggingautomation
>
> Response { "missingtagkeys": [
> "Testing-lambda-tagging-script-missingtags (i-06958aa5b does not have builder tag. Adding 'builder' tag with value of 'unknown'." ],
> "missingtagvalues": [
> "Testing-lambda-tagging-script-nullvaluetags (i-0097b990b) has no value for builder tag." ], "incorrecttagkeys": [],
> "incorrecttagvalues": [
> "Testing-lambda-tagging-script-badtags (i-00cd48f3c) has a incorrect builder tag value." ], "unknowntagvalues": [
> "Testing-lambda-tagging-script-unknownvalue (i-04c9468d) has unknown for it's builder tag value." ] }
>
> Function Logs START RequestId: 81b926c0-07c6-4311-b76f-fc77a1ef9ecf
> Version: $LATEST i-0e2d43b046 is the instance id within the
> instance_ids dictionary Testing-lambda-tagging-script-goodtags
> (i-0e2d43b04) has an approved builder tag value. i-00cd48f36 is the
> instance id within the instance_ids dictionary
> Testing-lambda-tagging-script-badtags (i-00cd48f3c02178736) has a
> incorrect builder tag value. i-0097b990b is the instance id within the
> instance_ids dictionary Testing-lambda-tagging-script-nullvaluetags
> (i-0097b990b) has no value for builder tag. i-06958aa5b is the
> instance id within the instance_ids dictionary
> Testing-lambda-tagging-script-missingtags (i-06958aa5b) does not have
> builder tag. Adding 'builder' tag with value of 'unknown'.
> i-04c9468ddbc1b996e is the instance id within the instance_ids
> dictionary Testing-lambda-tagging-script-unknownvalue (i-04c9468dd)
> has unknown for it's builder tag value. END RequestId:
> 81b926c0-07c6-4311-b76f-fc77a1ef9ecf REPORT RequestId:
> 81b926c0-07c6-4311-b76f-fc77a1ef9ecf Duration: 1295.80 ms Billed
> Duration: 1296 ms Memory Size: 128 MB Max Memory Used: 80 MB Init
> Duration: 490.50 ms
The output that I want is to get the value of "contact" in each instance and throw all the "incorrect, missing, unknown" list in there, so that we can email that person of the issue. I don't have anything in the code to email a specific person but I'm assuming it would look something like:
Contact1 = {john@doe.com,
Missingtagkeys,
Missingtagvalues,
incorrecttagkeys,
incorrecttagvalues,
unknowntagvalues}
Contact2 = {jane@doe.com,
Missingtagkeys,
Missingtagvalues,
incorrecttagkeys,
incorrecttagvalues,
unknowntagvalues}
Basically, go through and iterate through each dictionary and send an email to each contact with their tag issue.
I'm sorry if this is not what you requested, but please let me know if you need anything else. I seriously don't think I have the logic right here to accomplish what I want.
A: The hard part is that the program is collecting information by looping through instances, but you then want to send emails based on contact.
It will need to create a dictionary of contacts, which contains a dictionary of categories (missing tag key, missing tag values, incorrect tag keys, etc), which contains a list with the details, eg:
{
'jane@doe.com`: {
'Missingtagkeys': ['important-key1', 'important-key2'],
'Missingtagvalues': ['finance', 'HR']
},
'john@doe.com': {
'Missingtagkeys': ['important-key1', 'important-key5'],
'Missingtagvalues': ['IT'],
'incorrecttagkeys': ['dpartment']
}
}
Your code would need to intelligently add or update the 'contact dictionary' entries, and then the categories within it. For example:
everything_dict = {}
contact = 'john@doe.com'
# Add contact to dictionary if not already there
if contact not in everything_dict:
everything_dict[contact] = {
'Missingtagkeys' : [],
'Missingtagvalues' : [],
'incorrecttagkeys' : [],
'incorrecttagvalues' : [],
'unknowntagvalues' : []
}
# Store values
everything_dict[contact]['incorrecttagkeys'].append('foo-key')
...
# Retrieve contacts and values for emailing
for email, data in everything_dict.items():
print(email) # Recipient email address
print(data['incorrecttagkeys']) # Access data like this
| |
doc_23534319
|
<!doctype html>
<html>
<head>
<script src="index1.js"></script>
<title>Drinking Game</title>
</head>
<body>
<button id="creategame" >Create game</button>
<p id="demo">Hello</p>
<script>
$(document).ready(function(){
$('#creategame').click(function(){
$("#demo").append("Test");
});
});
</script>
</body>
</html>
A: My guess is you don't load jQuery file, and the console has
$ is not defined
error. Simply, add
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
to <head> tag
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="index1.js"></script>
<title>Drinking Game</title>
</head>
A: You are missing the jQuery file. Add this code <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> to your file above the <script src="index1.js"></script>. Make sure it's above it because if it's not then you can't call the jQuery functions in the your index1.js file.
A: try using the .html() function:
$("#demo").html("Test");
A: The following worked for me.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id='createGame' class="btn btn-default">Click</button>
<p id="demo">Hello</p>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script>
$(document).ready(function() {
$("#createGame").click(function(){
$("#demo").append("Test");
});
});
</script>
</body>
</html>
You need to reference jQuery in a <script> tag somewhere.
| |
doc_23534320
|
Now I wish to deploy the GitHub project on a VPS. I got the reverse proxy to work in the guide but for my use-case I cant seem to figure it out. What can I do differently?
nmap screenshot
Link to the reverse proxy guide I used.
The code for the proxy container:
server {
server_name ca.domain.come;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://futura-ca.lxd:4000; # container name
}
real_ip_header proxy_protocol;
set_real_ip_from 127.0.0.1;
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/ca.katunka.me/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/ca.katunka.me/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = ca.domain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80 proxy_protocol;
listen [::]:80 proxy_protocol;
server_name ca.domain.com;
return 404; # managed by Certbot
}
Thank you!
A: Within containers, you can use domains names like proxy.lxd and futura-ca.lxd. The website on futura-ca.lxd can be a plain Website on port 80 and there is no HTTPS on that specific website. The reason is that the proxy container acts as a TLS Termination Proxy, which means that HTTPS is handled from the visitor's browser up to (and including) the proxy server in the container.
If port 4000 is the default port of a specific Web application, then you can still use that port. But if not, then it is simpler to stick to port 80.
You run certbot from withing the TLS termination proxy (the proxy container), and it takes care of obtaining for you a Let's Encrypt certificate. And installing it.
| |
doc_23534321
|
A: Are you looking for something like this?
def css_class(record)
today_ten_am = Time.now.at_beginning_of_day.advance(hours: 10)
if record.created_at > today_ten_am
'danger'
end
end
For the future: please post more inputs, what you tried, your existing code and everything.
| |
doc_23534322
|
reactScrollTo(nextPos){
let elem = document.getElementById('ref-'+nextPos);
let amount = elem.offsetTop+530
window.scrollTo(0, amount);
}
A: If you're already using React, I would suggest doing your scrolling in a declarative way, instead of manipulating the DOM yourself.
Check out something like react-scroll.
It allows you to do stuff like:
scroll.scrollMore(100)
Just pop that in whatever lifecycle event you want.
A: if you want to do window scroll to some specific position then maybe consider use url anchor.
check here how to use url anchor
if you try to have "transition" effect while scrolling, then consider use "transform" instead of scrolling.(this is more suitable for scroll inside an element, not window itself)
| |
doc_23534323
|
I run the command below to find log destination and got stderr as the location.
show log_destination ;
How can I reach that file on DB app? FYI, I want all logs, not the logs that are from DBeaver.
A: https://tableplus.com/blog/2018/10/how-to-show-queries-log-in-postgresql.html#:~:text=The%20location%20of%20the%20log,pgsql%2Fdata%2Fpg_log%2F%20.
In Ubuntu is under /var/log/postgresql
A: You can run pg_lsclusters.
> pg_lsclusters
Ver Cluster Port Status Owner Data directory Log file
11 main 5432 online postgres /var/lib/postgresql/11/main /var/log/postgresql/postgresql-11-main.log
A: On recent PostgreSQL versions, that is simple:
SELECT pg_current_logfile();
For old versions, proceed as follows:
*
*Verify that the logging collector is started:
SHOW logging_collector;
*
*If not, the location of the log depends on how PostgreSQL was started.
*If yes, the log will be in log_directory:
SHOW log_directory;
If that is a relative path, it is relative to the PostgreSQL data directory.
Since the log file is on the database server, you probably won't be able to access it with a client tool.
| |
doc_23534324
|
I have updated the code as below
public Tridion.ContentDelivery.Web.Linking.ComponentLink ComponentLink
{
get
{
if (this._componentLink == null)
{
this._componentLink = new Tridion.ContentDelivery.Web.Linking.ComponentLink(261);
}
return this._componentLink;
}
}
but when I am browsing the website it gives me following error
Java.Lang.Throwable: com.tridion.linking.Linking.getLogger()Lcom/tridion/logging/Logger;
Detail Error
[Throwable: com.tridion.linking.Linking.getLogger()Lcom/tridion/logging/Logger;]
Codemesh.JuggerNET.NTypeValue.Throw(Int64 inst) +373
Codemesh.JuggerNET.JavaClass.ThrowTypedException(Int64 inst) +1365
Codemesh.JuggerNET.JavaMethod.CallObject(JavaProxy jpo, JavaMethodArguments args) +524
Com.Tridion.Linking.ComponentLink..ctor(Int32 publicationId) +127
Tridion.ContentDelivery.Web.Linking.ComponentLink..ctor(Int32 publicationId) +28
Project.Web.UI.TridionBasePage.get_ComponentLink() +88
ASP.en_includes_controls_rss_items_ascx.get_componentLink() in d:\Websites\Project\en\Includes\controls\rss-items.ascx:7
ASP.en_includes_controls_rss_items_ascx.Header_PreRender(Object sender, EventArgs e) in d:\Websites\Project\en\Includes\controls\rss-items.ascx:20
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.Control.OnPreRender(EventArgs e) +8996626
System.Web.UI.Control.PreRenderRecursiveInternal() +103
System.Web.UI.Control.PreRenderRecursiveInternal() +175
System.Web.UI.Control.PreRenderRecursiveInternal() +175
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2496
A: Did you install the 64-bit version of Tridion 2011 CD ?
I think all previous .jar files(such as cd_link.jar etc) are not removed from the lib directory.
Could you please recheck it.
A: When I have seen this error after an upgrade, it is usually because the now deprecated cd_broker_conf.xml is still in place. You can rename it to something like deprecated_cd_broker_conf.xml, restart your services and check again.
Other common causes for that kind of error is:
*
*You don't have the correct jars on your Web application Check Here
| |
doc_23534325
|
A: There is no built in function to delete from a array. So, the only way is to "pull" each value down by one, and then re-dim to lop off the last value.
Arrays hark back to old days of FORTAN and early GWBASIC languages that were popular on personal computers in the late 1970's, and early 80's. Most new languages (including VBA)) have a lot better choices. Because this is a "painful" approach, then I would build a function that deletes the row for you.
This code will show how deleting works:
Private Sub Command104_Click()
Dim MyData() As Integer
Dim i As Integer
ReDim MyData(1 To 5)
For i = 1 To 5
MyData(i) = i * 100
Next i
Call MyDisplay(MyData)
' delete 3rd row
Call MyDelete(MyData, 3)
Call MyDisplay(MyData)
End Sub
Public Sub MyDelete(v() As Integer, intPos As Integer)
Dim numRows As Integer
Dim i As Integer
numRows = UBound(v)
' move every row down one
For i = intPos To numRows - 1
v(i) = v(i + 1)
Next i
' get rid of last row
ReDim Preserve v(1 To numRows - 1)
End Sub
Public Sub MyDisplay(v() As Integer)
Dim i As Integer
For i = 1 To UBound(v)
Debug.Print i, "--->", v(i)
Next i
End Sub
Output:
1 ---> 100
2 ---> 200
3 ---> 300
4 ---> 400
5 ---> 500
1 ---> 100
2 ---> 200
3 ---> 400
4 ---> 500
| |
doc_23534326
|
For example, we have Person object like below:
public class Person {
@NotNull
private String firstName;
@NotNull
private String lastName;
// getter and setter
}
When I use the javax.validation.Validator to validate this object, we need to make sure that the firstName always be validated first and then lastName. Is there any way for hibernate validator archive that requirement?
A: You want to use group sequences. In particular you probably want to redefine the default group for your entity. See also Redefining the Default group for a class as defined by the Bean Validation specification .
| |
doc_23534327
| ||
doc_23534328
|
We have a (fairly typical?) arrangement for a multilingual Symfony CMF website, where resource paths are prefixed by the desired locale—for example:
*
*http://www.example.com/en/path/to/english-resource.html; and
*http://www.example.com/fr/voie/à/ressource-française.html.
We are using RoutingAutoBundle to store such routes in the content repository, and DynamicRouter to utilise them: simple and easy.
If a GET request arrives without a locale prefix, we would like to:
*
*determine the most appropriate locale for the user; and then
*redirect1 the user to the same path but with locale prefix added.
Current Approach
The first part is an obvious candidate for LuneticsLocaleBundle, with router higher in its guessing order than our desired fallback methods: again, simple and easy.
However, how best to implement the second part is a little less obvious. Currently we have configured Symfony's default/static router to have a lower priority in the routing chain than DynamicRouter, and have therein configured a controller as follows:
/**
* @Route("/{path}", requirements={"path" = "^(?!(en|fr)(/.*)?$)"})
* @Method({"GET"})
*/
public function localeNotInUriAction()
{
$request = this->getRequest();
$this->redirect(
'/'
. $request->getLocale() // set by Lunetics
. $request->getRequestUri()
);
}
But this feels rather hacky and I'm on the search for something "cleaner".
A better way?
Initially I thought to modify LuneticsLocaleBundle so that it would fire an event whenever a guesser determines the locale, thinking that if it was not the RouterLocaleGuesser then we could infer that the requested URI did not contain a locale. However this clearly isn't the case, since the RouterLocaleGuesser will only determine the locale if there was a route in the first place—so I'd not have made any progress.
I'm now a bit stuck for any other ideas. Perhaps I'm already doing the right thing after all? If so, then all I need to do is find some way to inject the permitted locales (from the config) into the requirement regex…
*
*External redirection, i.e. via a response with HTTP 302 status.
A: we use a custom 404 handler and lunetics:
exception_listener:
class: AppBundle\EventListener\ExceptionListener
arguments:
container: "@service_container"
tags:
- { name:"kernel.event_listener", event:kernel.exception, handler:onKernelException }
and the php class
class ExceptionListener
{
/**
* @var ContainerInterface
*/
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
if ($this->container->getParameter('kernel.debug')) {
// do not interfere with error handling while debugging
return;
}
$exception = $event->getException();
if ($exception instanceof NotFoundHttpException) {
$this->handle404($event);
return;
}
// ...
}
public function handle404(GetResponseForExceptionEvent $event)
{
$request = $event->getRequest();
if (preg_match('#^\/(de|fr|en)\/#', $request->getPathInfo())) {
// a real 404, these are nicely handled by Twig
return;
}
// i *think* that the locale is not set on the request, as lunetics comes after routing, and the routing will raise the 404
$bestLang = $this->container->get('lunetics_locale.guesser_manager')->runLocaleGuessing($request);
if (! $bestLang) {
$bestLang = 'de';
}
$qs = $request->getQueryString();
if (null !== $qs) {
$qs = '?'.$qs;
}
$url = $request->getSchemeAndHttpHost() . $request->getBaseUrl() . '/' . $bestLang . $request->getPathInfo() . $qs;
$this->redirect($event, $url);
}
it would be nicer to also check if the target path actually exists - as is, we will redirect /foobar to /de/foobar and display a 404 for that one, which is not that elegant.
| |
doc_23534329
|
I just wanted to add that if anybody encounter a need for filtering HTML, I would propose using a MutationObserver (That was my final choice ..)
A: Read a bit more on DOM manipulation, it will help. Yes, using content scripts here is the right way to go. You'll want to have your script run at "document_start" which is run before Chrome begins parsing the DOM (that way you'll get a head start, essentially) You could do this filtering a few ways actually;
*
*Just use the DOM as one big string, and remove the words you want. However, this is a messy way of eoing things, if something important was named after your word (like a class, tag name, or whatnot), you'd break the DOM.
*Loop over the text nodes (strings) in a DOM as soon as the DOM is ready, and replace and edit those text nodes.
There's tutorials detailing this kind of thing you can find online easily, along the lines of DOM manipulation and text node replacement. This article details it much more intimately and better than I have here: Replacing text in the DOM...solved?
And here is a JS library (from the same guy who wrote that article) which practically does all the hard work for you: https://github.com/padolsey/findAndReplaceDOMText
A: The way I would approach this is through a jQuery/other framework plugin. I would suggest you take a look at some highlight plugins that are available in pretty much every framework around. See here for some examples of doing highlighting.
Essentially what you'll need to do is select heading tags p tags and spans and loop over each replacing bad words.
| |
doc_23534330
|
/*library code*/
struct UserDataForFooCallback; /* opaque user datatype */
typedef void CallbackFn(int i, struct UserDataForFooCallback* user);
void foo(CallbackFn* callback, struct UserDataForFooCallback* user)
{
callback(42, user);
}
/*application code*/
#include <stdio.h>
#include "foo.h"
struct UserDataForFooCallback
{
int a;
};
static void fooCallback(int i, struct UserDataForFooCallback* user)
{
printf(user->a == i ? "ok\n" : "fail\n");
}
int main()
{
struct UserDataForFooCallback cbd = {42};
foo(fooCallback, &cbd);
return 0;
}
Advantages:
*
*Type safe callbacks
*no struct MyFoo* data=arg pointer assignments in the callback code
Drawbacks:
*
*AFAIK there must not be more than one definition of a user defined datatype (or am I mixing this with the one definition rule of C++?), which makes them problematic if there are more than uses of the back-calling function (say foo in the example is used by different program parts)
*The need to define a new type for every callback/group of callbacks (maybe it's not so important, since the many callback functions does use one already)
The main thing I want to know if this is really a good idea, or if thie is only a good-looking-but-Armageddon-like-impact idea.
A: If there are two libraries using your library, that both defined UserDataForFooCallback as a different structure, it is One Definition Rule violation. Just stick with void*.
A: If you don't care about type of the user data, you can always use void*. Then people can send whatever data they want.
Note that it's a C-way of implementing that. If you're using C++, you can create a base class and derive from it. Of course, your callback's argument should be the base class.
| |
doc_23534331
|
public class Country
{
public string ISOAlpha3Code { get; set; }
public string NameUS { get; set; }
public string NameES { get; set; }
public string NameFR { get; set; }
public List<Province> Provinces { get; set; }
}
public class Province
{
public string Code { get; set; }
public string NameUS { get; set; }
public string NameES { get; set; }
public string NameFR { get; set; }
}
The database view that has to be used to populate these models returns a flat list, like this:
I was hoping to configure the entity, for the DbContext, to split out provinces for the countries.
I could create a domain model that matches the database results, though I would really like to separate the domain model from how its represented in this particular database - especially if the DB changes.
Is something like this possible? And If so, how would it be implemented?
public class CountryConfiguration : IEntityTypeConfiguration<Country>
{
public void Configure(EntityTypeBuilder<Country> builder)
{
builder.ToTable("v_WS_CountriesAndProvinces");
builder.Property(p => p.NameUS).HasColumnName("CountryNameUS");
builder.Property(p => p.NameES).HasColumnName("CountryNameES");
builder.Property(p => p.NameFR).HasColumnName("CountryNameFR");
// something to split out the provinces?
builder.Property(p => p.Provinces).HasConversion(
v => ToDB(v), // to DB
v => FromDB(v) // from DB
);
}
private List<Province> FromDB(object v)
{
throw new NotImplementedException();
}
private object ToDB(List<Province> v)
{
throw new NotImplementedException();
}
}
A: Could adjust your model slightly to accommodate the repeating group.
public class Country {
public string ISOAlpha3Code { get; set; }
public virtual ICollection<Name> Names { get; set; }
public virtual ICollection<Province> Provinces { get; set; }
}
public class Province {
public string Code { get; set; }
public string ISOAlpha3Code { get; set; } // FK to Country
public virtual ICollection<Name> Names { get; set; }
}
public class Name {
public string ISOAlpha3Code { get; set; } // FK to Country
public string Code { get; set; } // FK to Province, null for country names
public string Language { get; set; } // US-EN, etc.
public string NameField { get; set; }
}
Of course, this all assumes the data is immutable once entered, otherwise add & maintain relationships using surrogate PK/FKs if key data may change (ISOAlpha3Code, Code). And I would make sure that a NVARCHAR was generated for NameField since you will want to store Unicode strings.
| |
doc_23534332
|
Cannot use instance member 'BasicInfoViewModel' within property initializer; property initializers run before 'self' is available
struct BasicInfoViewModel {
let infos = PublishSubject<InfoResult>()
let selectedImage: Observable<UIImage>
let fullname: Observable<String>
let phoneNumber: Observable<String>
let email: Observable<String>
let placeOfBirth: Observable<String>
let dateOfBirth: Observable<String>
let religion: Observable<String>
var isValid: Observable<Bool> {
return Observable.combineLatest(fullname.asObservable(), phoneNumber.asObservable(), email.asObservable(), placeOfBirth.asObservable(), dateOfBirth.asObservable(), religion.asObservable()).map { $0.0.count > 0 }
}
}
class BasicInfoViewController: UITableViewController {
var viewModel = BasicInfoViewModel()
}
A: You need to construct your BasicInfoViewModel inside the view did load method and pass the inputs in from the views.
| |
doc_23534333
|
*
*We have developed a .Net MVC application.
*It is used inside a local network.
*We have workstations that view the MVC website (presentation tier)
*We have an application server hosting the site (Logic tier)
*We have a database server storing the data (SQL 2008 R2) (Data tier)
So I thought that due to the tiers, it is a three tier architecture.
However, because we have used MVC, does this mean that our layers are more directly (albeit loosely-coupled) connected, thus making our architecture a less linear (three tier) and more triangular (MVC)?
How do you think I should describe this architecture?
A: I think the term "3-tier architecture" is ill-defined and outdated because it highlights not the way your code is structured nor does it offer any benefit or drawback from a user perspective. The problem is that it refers to the physical deployment, something that in times of virtualization and distributed computing is hardly meaningful.
"Tier" refers to machines, and since you can typically run and debug your website only using your local dev machine, it can usually be deployed 1-tier. The more relevant question, perhaps, is "what is the maximum number of (logical) machines I can split my application up in?" That number is independent of the actual deployment, and is dictated by the code's structure instead - by the layering. Of course, machines that duplicate another machine (multiple web servers for load balancing) don't count.
The information is still hardly relevant. It suggests that your code separates concerns and might be more scalable than code which does not allow splitting to separate tiers. Another idea is strong decoupling: you can replace one layer w/o touching another one. In practice, that is hardly ever working (e.g. switch from Oracle to MySQL), and solves some outdated problems: "a change of operating system in the presentation tier would only affect the user interface code." (Wikipedia)
All this becomes more ill-defined when you add external SaaS/PaaS products, or third party tools like SolR (a search engine). Is SolR part of the data tier or part of the logic tier? Does your architecture become 4-tier by adding a caching layer? What if your database tier is not one machine, but a cluster of 10 machines?
MVC, on the other hand, refers to the way your code is structured. It's not only a presentation-layer pattern, however: The model does not know the controller, nor the view. MVC separates data, presentation and logic into different layers. Most MVC implementations use Two-Step-View as a presentation-layer pattern, and PageController as a controller pattern. A FrontController usually exists as well and handles all requests before delegating to the respective PageController - but the key is that the model does not know all this.
I'd suggest to drop the notion of "n-tier architecture" altogether.
A: I would describe it as a 3 tier application and would put the MVC aspect into the presentation-tier.
Since your basic structure is a three tier based one and uses MVC for Displaying data to the user. (Maybe you can put the box with MVC overlaying presentation-tier and application-tier - to illustrate the actual interaction between these two).
| |
doc_23534334
|
Are there any good groovy tutorials out there besides what is on http://groovy.codehaus.org/?
class Greet {
def name
Greet(who) { name = who[0].toUpperCase() +
who[1..-1] }
def salute() { println "Hello $name!" }
}
g = new Greet('world') // create object
g.salute() // Output "Hello World!"
A: You're right -- a negative number in a range basically refers to the end of the list, rather than the beginning. -x is equivalent to who.length()-x.
What you're dealing with is known as slices in Python. (I mention the terminology because searching for something like "groovy slices" may help you find more information, although I don't know if they're actually called "slices" in reference to Groovy.) You can find more information on this particular syntax feature here.
As for other resources, I found the book Groovy in Action to be quite handy for learning Groovy.
A: For several languages, PLEAC is a great resource.
| |
doc_23534335
|
Here is the relevant code:
@IBOutlet weak var Stadt: UITextField!
@IBOutlet weak var Strasse: UITextField!
@IBOutlet weak var Platzart: UITextField!
@IBOutlet weak var Groesse: UITextField!
@IBOutlet weak var AnzToreKoerbe: UITextField!
@IBOutlet weak var Untergrund: UITextField!
// Variable für die Firebase Database
override func viewDidLoad() {
super.viewDidLoad()
Stadt.delegate = self
Untergrund.delegate = self
Groesse.delegate = self
AnzToreKoerbe.delegate = self
Platzart.delegate = self
Picker.delegate = self
}
@IBOutlet weak var Picker: UIPickerView!
var currentData = [""]
let UntergrundArray = ["Asphalt", "Kunstrasen Sand", "Kunstrasen Granulat", "Rasen", "Tartan", " "]
let StadtArray = ["Norderstedt", "Hamburg", "Berlin", "München"]
let GroesseArray = [ "2 vs 2", "3 vs 3", "4 vs 4", "5 vs 5"]
let AnzTorKoerbe = ["1", "2", "3", "4"]
let Art = ["Fußball", "Basketball"]
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{
if textField.tag == 1{
currentData = StadtArray
}else if textField.tag == 2{
currentData = UntergrundArray
}else if textField.tag == 3 {
currentData = GroesseArray
}else if textField.tag == 4 {
currentData = AnzTorKoerbe
}else if textField.tag == 5 {
currentData = Art
}
Picker.reloadAllComponents()
return false;
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return currentData.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return currentData[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let itemSelected = currentData[row]
print(itemSelected)
if (itemSelected == StadtArray[row]) {
Stadt.text = StadtArray[row]
}else if (itemSelected == UntergrundArray[row]) {
Untergrund.text = UntergrundArray[row]
}else if (itemSelected == GroesseArray[row]) {
Groesse.text = GroesseArray[row]
}else if (itemSelected == AnzTorKoerbe[row]) {
AnzToreKoerbe.text = AnzTorKoerbe[row]
}else {
Platzart.text = Art[row]
}
}
A: currentData can be any one of the other arrays. And row can be for an index larger than some of the arrays. This is the cause of the crash.
The proper solution is to fix how you determine which label to update.
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let itemSelected = currentData[row]
if currentData === StadtArray {
Stadt.text = itemSelected
} else if currentData === UntergrundArray {
Untergrund.text = itemSelected
} else ... and the others as needed
}
Though a better option might be to add another property to track the current text field.
var currentField: UITextField?
Then update textFieldShouldBeginEditing:
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{
currentField = textField
if textField.tag == 1 {
currentData = StadtArray
} else if textField.tag == 2 {
currentData = UntergrundArray
} else if textField.tag == 3 {
currentData = GroesseArray
} else if textField.tag == 4 {
currentData = AnzTorKoerbe
} else if textField.tag == 5 {
currentData = Art
}
Picker.reloadAllComponents()
return false;
}
Then update didSelectRow:
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let itemSelected = currentData[row]
if let currentField = currentField {
currentField.text = itemSelected
}
}
A: The problem is that this test is being executed:
if (itemSelected == StadtArray[row]) {
...but, as you rightly say, the data actually being displayed in the picker view is not from StadtArray but from UntergrundArray. Thus, you select the fifth row and row is 4, but StadtArray has only four entries so index 4 is out of bounds; there is no such thing as StadtArray[4]. And so you crash.
You could fix this by arranging the tests in ascending order of array size, or by adding a size test on the array before speaking of [row], but as rmaddy rightly says, the real problem is that your test for which source the currentData comes from is just a badly designed test.
What I personally would do is this. I would eliminate currentData and the five model arrays, and maintain my model data as a single array of arrays:
let model = [["Asphalt", "Kunstrasen Sand", "Kunstrasen Granulat", "Rasen", "Tartan", " "], ["Norderstedt", "Hamburg", "Berlin", "München"], [ "2 vs 2", "3 vs 3", "4 vs 4", "5 vs 5"], ["1", "2", "3", "4"], ["Fußball", "Basketball"]]
Now I would maintain a single number representing the index into model of the current array:
var currentModel : Int = 0
This makes things incredibly easy and direct! The number of components would be model[currentModel].count, and titleForRow would be model[currentModel][row] — and we could eliminate the if/else in didSelect, because model[currentModel] takes us directly into the correct model and so model[currentModel][row] works there too.
(Though actually, the title for the row is the data, so you could alternative just call titleForRow inside didSelect, couldn't you? And again there would be no danger of error.)
| |
doc_23534336
|
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data.SqlClient;
namespace SolutionCW
{
/// <summary>
/// Interaction logic for addCustomer.xaml
/// </summary>
public partial class addCustomer : Window
{
public addCustomer()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e) // add customer button
{
string inputName = nameinput.Text;
string inputLastname = secondnameinput.Text;
string Number = phonenumber.Text;
string address = addressinput.Text;
string Pcode = postcode.Text;
string cmdstring = "INSERT INTO Customer (FirstName, LastName, PhoneNumber, Address, Postcode) VALUES (@Name, @LastName, @Phone, @Addinput, @Pcode)";
string connString = MainWindow.DBconnection;
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = cmdstring;
comm.Parameters.AddWithValue("@Name", nameinput.Text);
comm.Parameters.AddWithValue("@LastName", secondnameinput.Text);
comm.Parameters.AddWithValue("@Phone", phonenumber.Text);
comm.Parameters.AddWithValue("@Addinput", addressinput.Text);
comm.Parameters.AddWithValue("@Pcode", postcode.Text);
try
{
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
Customer basic = new Customer();
basic.updateTable();
}
catch(SqlException)
{
}
this.Close();
}
}
}
}
I have shown my code for adding a customer record from the form to my database, but when I press the add button, it does not show the newly entered data when it opens up the database. It only shows the newly entered record when I exit the database/refresh and go back in? any help appreciated, thanks
A: I'm not sure how you're displaying your data. However, the issue is your button event executes, then sends the data to the database, but the control that displays your data hasn't been re-rendered. Depending on the type of control, will vary on the command to refresh.
// Form:
var form = new ApplicationForm();
form.Refresh();
// Update Panel:
updatePanelSample.Update();
Without more information on how you're displaying the data, we won't be able to help you update or redraw the rendered application to display the update.
| |
doc_23534337
|
IPython allows writing user-defined cell magics. My plan is creating a plotting function which can plot one or multiple arbitrary Python expressions (expressions based on Pandas Series objects), whereby each line in the cell string is a separate graph in the chart.
This is the code of the cell magic:
def p(line, cell):
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame()
line_list = cell.split('\n')
counter = 0
for line in line_list:
df['series' + str(counter)] = eval(line)
counter += 1
plt.figure(figsize = [20,6])
ax = plt.subplot(111)
df.plot(ax = ax)
def load_ipython_extension(ipython):
ipython.register_magic_function(p, 'cell')
The function receives the entire cell contents as a string. This string is then split by line breaks and evaluated using eval(). The result is added to a Pandas DataFrame. Finally the DataFrame is plotted using matplotlib.
Usage example: First define the Pandas Series object in IPython notebook.
import pandas as pd
ts = pd.Series([1,2,3])
Then call the magic in IPython notebook (whereby the whole code below is one cell):
%%p
ts * 3
ts + 1
This code fails with the following error:
NameError: name 'ts' is not defined
I suspect the problem is that the p function only receives ts * 3\n ts + 1 as a string and that it does not have access to the ts variable defined in the namespace of IPython notebook (because the p function is defined in a separate .py file).
How does my code have to be changed so the cell magic has access to the ts variable defined in the IPython notebook (and therefore does not fail with the NameError)?
A: Use the @needs_local_scope decorator decorator. Documentation is a bit missing, but you can see how it is used, and contributing to docs would be welcome.
A: You could also use shell.user_ns from Magics. For example something like:
from IPython.core.magic import Magics
class MyClass(Magics):
def myfunc(self):
print(self.shell.user_ns)
See how it's used in code examples: here and here.
| |
doc_23534338
|
[Errno 13] Permission denied: '/static'
This is my settings.py STATIC_ROOT and STATIC_URL line:
STATIC_URL = /static/
#STATIC_ROOT = home/alexholst/excelsite/static
STATIC_ROOT = os.path.join(BASE_DIR, "..", "static")
#STATIFILES_DIR = [
# os.path.join(BASE_DIR, "static")
#]
Ive serched online for the past 2 hours to no avail. What could this be?
A: well your user does not have permission for to write in the static folder.
Add your server user to have access to all of the project folders (recursively)
sudo chown -R my_user:my_user /path/to/my/project
| |
doc_23534339
|
Now, however, there is a new problem. Occasionally (meaning every 20-30 switches) when switching the endpoint device, the sound on the far end gets "fuzzy" or distorted. Switching the endpoint again (and restarting the devices) seems to get rid of the problem, but I still don't know the root issue here. I've also noticed that when the far end audio is distorted, the near end playback is perfect, which lead me to believe that timing is not an issue.
Have people encountered similar problems when switching audio endpoints, or could there be something else going on?
A: Microsoft has told me this is a reported bug on WinRT and they are looking into it now.
| |
doc_23534340
|
Here my code.
On PrepareOptionMenu (Menu menu){
If (favClicked){
menu.finditem (R.id.id_favorite).setvisible (false);
menu.finditem (R.id.id_favorite 2). setvisible (true);
}
else if (! favClicked){
menu.finditem ( R.id.id_favorite).setvisible (true);
menu.finditem (R.id.id_favorite 2).setvisible (false);
}
return super . onPrepareOptionMenu (menu);
}
@Override
protected void onRestoreInstanceState (Bundle saveInstanceState){
super.onRestoreInstanceState (saveInstanceState);
favClicked=saveInstanceState. getBoolean ("favClicked")
}
AND THEN I USE THE RESTOREINSTACESTATE METHOD SAME LIKE THE SAVEINSTANCE STATE...BUT IT DOSENT WORK FOR ME.
A: You need to store somewhere (database or your method of choice) what you have already favorite.
Once that procedure is created, on your onStart() and when you show another item, check if the current item is favorited or not and set your menuItem accordingly.
I don't think saving the instance state has any use in this scenario.
| |
doc_23534341
|
1) browser sends a request
2) The server sends response and Angular's JS bundle (main.js).
Assuming that I have understood the working mechanism correctly, is there a way I can get the cookies which are in the http response which delivered the Angular JS bundle?
My server on receiving the request, inserts two cookies and then send a response to the client. The response also includes my Angular application. Is there a way I can get access to the Cookies in my app.component.ts?
A: I had the same issue with Angular 8, after a lot of research, I've found that Cookies are saved on the browser automatically, if you want to retreive them you can use ngx-cookie-service and get them like if you get an item from your localstorage.
| |
doc_23534342
|
How can i find out my current id?
$qry = mysql_query("SELECT performerid,pic0 FROM ".$table." WHERE id > $currentid ORDER BY id ASC LIMIT 1");
A: Select it?
$qry = mysql_query("SELECT id,performerid,pic0 FROM ".$table." WHERE id > $currentid ORDER BY id ASC LIMIT 1");
A: MySQL doesn't work with any concept of current ID. If you're looking for the last inserted ID then it can be done via mysql_inserted_id function.
| |
doc_23534343
|
I had created phone auth for my android app using flutter-firebase. When the Android Device verification from cloud console is off, it redirects to a captcha screen and automatically captcha gets verified and after entering the otp received, app login functionality works properly.
But when Android Device verification is on ,for not showing the captcha screen,it shows this error on entering the otp :
Ignoring header X-Firebase-Locale because its value was null. I/flutter (27447): [firebase_auth/session-expired] The sms code has expired. Please re-send the verification code to try again.
My Flutter,Firebase Auth version is updated, and sha1 and sha256 are already added in firebase project setting.
Cant find a solution ,please guide.
A: Try to pass an empty function to verificationCompleted as param in the verifyPhoneNumber function.
final FirebaseAuth auth = FirebaseAuth.instance;
await auth.verifyPhoneNumber(
phoneNumber: this.widget.phoneNumber,
timeout: const Duration(seconds: 5),
verificationCompleted: (PhoneAuthCredential phoneAuthCredential){},
verificationFailed: verificationFailed,
codeSent: codeSent,
codeAutoRetrievalTimeout: codeAutoRetrievalTimeout,
forceResendingToken: _forceResendToken)
| |
doc_23534344
|
@extends('layout/master')
@section('content2')
<h1>
{{date('d m y')}} <br>
@{{date('d m y')}} <br>
{{ isset($data) ? $data : 'Not' }}
{{ $data or 'Default' }}
</h1>
@stop
A: What you want to use in that case is null coalescing operator, which was introduced in PHP7.
The expression (expr1) ?? (expr2) evaluates to expr2 if expr1 is NULL, and expr1 otherwise.
In particular, this operator does not emit a notice if the left-hand side value does not exist, just like isset(). This is especially useful on array keys.
Therefore you can use it like this:
{{ $data ?? 'Default' }}
| |
doc_23534345
|
Right now I'm trying to use this one: https://github.com/boostorg/graph_parallel/blob/master/example/dijkstra_shortest_paths.cpp
The problems start on distributed graph creation:
Graph g(reader.begin(), reader.end(), reader.weight_begin(),
reader.num_vertices());
If I remove it and the following code, everything compiles just fine. If I add this string - a lot of errors, like
boost::enable_if<boost::mpi::is_mpi_datatype<unsigned long>, void>::type boost::graph::distributed::send_oob<unsigned long>(boost::graph::distributed::mpi_process_group const&, int, int, unsigned long const&, int) in cc6AGjMu.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
just overwhelm me. The full list of errors I provide here: https://pastebin.com/post.php <- errors there
I have latest boost release 1.65.1 (I also tried 1_64, 1_55, and some others with the same result). I also tried using it on 2 different systems: my mac os laptop, and my university supercomputer (where everything, for example MPI, is set up correctly).
I use the following command to compile the example file:
mpic++ -fopenmp -O3 -std=c++11 -fpermissive -I boost_1_65_1/ PBGL_test.cpp -o PBGL_test -lboost_mpi -lboost_serialization -lboost_system
Where PBGL_test.cpp is the example file I linked above.
I understand that, most probably, I forgot to link some important library, but I have no idea which one exactly, and I can't find the solution or similar problems in the web.
If anyone have any ideas what else I need to link, or have a working example of PBGL distributed graphs usage (with makefile or just instructions how to compile them) - please, link them here.
Thank you in advance!
| |
doc_23534346
|
if (Config.DEBUG) {
// do something
} else {
// do something
}
I realized that Config.DEBUG is deprecated in API 14. What is the alternative if it?
A: You could use:
if(BuildConfig.DEBUG){
// do something
}else{
// do something
}
It's not really documented anywhere but seems to work in both eclipse and Android Studio (latest versions respectively).
Returns true if the current build is a debug build and false if it's an release. Since it's not documented anywhere be wary of using it in production code since it may be stripped at any time (and there are reports of incorrectly attributing releases to debug builds).
| |
doc_23534347
|
I want the server side login code to create the connection and store the jid, sid, and rid in a cookie. Then on subsequent page requests, its just a simple matter of reading the cookie and passing the jid, sid, and rid to the Strophe attach() function.
Sounds easy right? However libstrophe in C does not provide the sid or rid after you establish a connection? I found out how to get the sid by issuing a certain "session authorization" stanza, but have no idea how to get the rid?
I realize this is kind of obscure. Any help anyone?
A: What you're looking for is pre-binding; see http://metajack.im/2009/12/14/fastest-xmpp-sessions-with-http-prebinding/.
| |
doc_23534348
|
Is it possible to downgrade a backup of a higher JIRA version to be able to import it?
A: It's not possible!
Solution: upgrade Jira version
| |
doc_23534349
|
I have illustrated the situation graphically:
Inside the container, there are TWO siblings (RED <div>and BLUE <div>). Both have position: absolute;
RED has z-index:1;
BLUE has z-index:2;
RED's child (GREEN) has position:relative; and z-index:99;
I want to make GREEN to be upper than BLUE
Thank you!
UPDATE 1. Here is the fiddle
http://jsfiddle.net/yn9z7/
A: The key to solve that is in the article linked by sudhAnsu63 :
New stacking contexts can be formed on an element in one of three ways:
When an element is the root element of a document (the element)
When an element has a position value other than static and a z-index value other than auto
When an element has an opacity value less than 1
But the interpretation is just the opposite. To set the blue element between the red and the green, the red one can not generate a stacking context. It is generating an stacking context because of the second rule; it has position absolute an z-index different from auto.
So, the solution is:
#red{
z-index:auto;
}
demo
A: This won't work since Red's z-index is lower than blue. z-index only works with elements with a common root element.
Check out the Stacking Contexts part in this article
A: Here the Blue div and the Red div is the direct child of container div. z-Index will not work exactly.
try changing the opacity of blue div to 0.99;
.bluediv {
opacity: .99;
}
http://philipwalton.com/articles/what-no-one-told-you-about-z-index/
http://coding.smashingmagazine.com/2009/09/15/the-z-index-css-property-a-comprehensive-look/
A: yeah, this is not possible because child elements inherit the z-index of the parent. so it does not make sense to give the green div a z-index of 99 because it's z-index is only valid inside the parent (red div).
So if you give a container a certain z-index lets say 20, the z-indexing inside this container starts again from 0. this is a good thing because otherwise we had to give all children a z-index of minimal 21 or they won't be visible.
the first container on a web page is the body tag, you can stack all its children with the z-index property starting from layer 0 (z-index 0). just like the body tag every child has its own z-index "system" unrelated to higher elements in the DOM. so the z-indexing starts over from 0 inside a parent container with its own defined z-index.
| |
doc_23534350
|
I currently have:
^(?:[^ ]*\ ){2}([^ ]*)
Any help wouild be aprreciated.
Thanks!
A: You can capture the second and the third "word" as in 1 or more non whitespace characters:
^\S+ (\S+ \S+)
Regex demo
Or if supported with a lookbehind:
(?<=^\S+ )\S+ \S+
Regex demo
A: I think this is the regex you're looking for:
(?<=\s)([^ ]*)
Link to example: https://regex101.com/r/wSdzLe/1
| |
doc_23534351
|
I get my domain class name from a gsp to access an object instance (of a particular id) of this domain class. I am trying the following code. Is this correct?
String id = params['id']
String className = params['className']
def instance = className.get(id);
Is there any other way to this?
A: first of all you have to inject the grailsApplication bean in your controller.
def grailsApplication
after that you can use getClassForName method to retrieve the desired class by name.
grailsApplication.getClassForName(className).
you have to use the full qualified class name, e.g. my.test.MyClass
A: def id = params.id
def className = params.'className'
def domainClazz = grailsApplication.classLoader.loadClass(className)
def instance = id ? domainClazz.get(id as Long) : null
You may:
grailsApplication.classLoader.loadClass("Book")
or
grailsApplication.classLoader.loadClass("com.yourapp.Book")
| |
doc_23534352
|
I converted the project to Maven
When i run this java -jar My-Test-0.0.1-SNAPSHOT.jar
It says:
no main manifest attribute, in My-Test-0.0.1-SNAPSHOT.jar
What is wrong with me pom file?
The pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.blogspot.test</groupId>
<artifactId>My-Test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>My-Test</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.44.0</version>
</dependency>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<shadedClassifierName>all</shadedClassifierName>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</dependencies>
</project>
A: Is your project a web project?? Because as I know, Selenium only works with web projects. And there you have your project packaged as a jar (not as a war)
| |
doc_23534353
|
I have a service that is initialized with delegate/lambda expression that can return value from any place. In this context this lambda expression argument should return value from session once called.
Here is example code:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IMyService>(serviceProvider =>
{
return new MyService(() => {
var session = serviceProvider.GetServices<Microsoft.AspNetCore.Session.DistributedSession>().First();
return session.GetString("CompanyID");
}
);
}
);
// Add framework services.
services.AddMvc();
services.AddDistributedMemoryCache();
services.AddSession();
}
My session is configured fine (I can get/set values in controllers). However, I cannot fetch the service from IServiceProvider. I cannot find what type should be provided to GetServices method to get a service that will find session.
A: Microsoft.AspNetCore.Session.DistributedSession implements ISession, but ISession isn't registered with the DI system so you can't resolve it directly.
But as you can see here, the ISession is created during the execution of the Session middleware and put into the list of features (a list where a middleware can put data that can be consumed later on during the request). The HttpContext.Session property is populated from the ISessionFeature set during the session middleware call. So you can access it from HttpContext.
You'll need to register the IHttpContextAccessor with
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
and resolve this, then access it's HttpContext.Session property. You have to do the registration, because the IHttpContextAccessor isn't registered by default anymore since RC2, as mentioned in this announcement here on the GitHub issue tracker.
| |
doc_23534354
|
/* */
right after last line of text. What can cause such a weird behavior? Here is my setup:
$tcpdf = new TcPdf;
$tcpdf->setPrintHeader(false);
$tcpdf->setPrintFooter(false);
$tcpdf ->setFontSubsetting(true);
$tcpdf->AddPage();
$tcpdf ->SetFont('freesans', '', 11);
$tcpdf->writeHTML($input,false);
// ^ I thought removing the new line would fix it but didn't
$tcpdf->Output($output, 'I');
| |
doc_23534355
|
So far, I've been able to successfully save the data using boost text archive, and now switched to boost binary archive. It appears to work when saving the data, but when I try to load the data I get this error:
"Exception Unhandled - Unhandled exception at [memory address] in VileEngine.exe Microsoft C++ exception: boost::archive::archive_exception at memory location [different mem address]"
I can skip past this error multiple times but when the program runs and loads, the data of the loaded character is way off so I know it has to be either in the way I'm saving it, or more likely in the way I'm loading it. I've tried reading through the boost docs but couldn't find a way to fix it. I also tried searching through other posts but couldn't find an answer, or maybe I just don't understand the answers. Any help is greatly appreciated.
Relevant code posted below. I can post all the code if needed but it's quite a bit for all the classes.
in Character.hpp
private:
friend class boost::serialization::access; //allows serialization saving
//creates the template class used by boost to serialize the classes data
//serialize is call whenever this class is attempting to be saved
template<class Archive>
void serialize(Archive& ar, const unsigned int version) {
ar << name;
ar << *charStats;
ar << inventory;
}
/*********************************
* Data Members
***********************************/
std::string name;
Stats* charStats;
std::vector<std::string> inventory;
public:
Character();
void loadCharacter(std::string &charName); //saves all character details
void saveCharacter(); //loads all character details
in Character.cpp
/*********************************************
Functions to save and load character details
**********************************************/
void Character::saveCharacter() {
//save all details of character to charactername.dat file
//create filename of format "CharacterName.dat"
std::string fileName = name + ".dat";
std::ofstream saveFile(fileName);
//create serialized archive and save this characters data
boost::archive::binary_oarchive outputArchive(saveFile);
outputArchive << this;
saveFile.close();
}
void Character::loadCharacter(std::string &charName) {
//load details of .dat file into character using the characters name
std::string fileName = charName + ".dat";
std::ifstream loadFile(fileName);
boost::archive::binary_iarchive inputArchive(loadFile);
inputArchive >> name;
Stats* temp = new Stats;
inputArchive >> temp;
charStats = temp;
inputArchive >> inventory;
loadFile.close();
}
in Stats.hpp
private:
friend class boost::serialization::access; //allows serialization saving
//creates the template class used by boost to serialize the classes data
//serialize is call whenever this class is attempting to be saved
template<class Archive>
void serialize(Archive& ar, const unsigned int version) {
ar & skillSet;
ar & subSkillMap;
ar & level;
ar & proficiencyBonus;
}
A: When you save, you ONLY write this (by pointer, which is an error, see below):
boost::archive::binary_oarchive outputArchive(saveFile);
outputArchive << this;
Whe you load, you somehow read three separate things. Why? They should obviously match. And 100%. So:
void Character::saveCharacter() {
std::ofstream saveFile(name + ".dat");
boost::archive::binary_oarchive outputArchive(saveFile);
outputArchive << *this;
}
You save *this (by reference) because you do not want the deserialization to allocate a new instance of Character on the heap. If you do, you cannot make it a member function.
Regardless, your serialize function uses operator<< where it MUST use operator& because otherwise it will only work for save, not load. Your compiler would have told you, so clearly, your code is different from what you posted.
See it live: Live On Coliru
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/set.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/string.hpp>
#include <fstream>
struct Stats{
private:
std::set<int> skillSet{1, 2, 3};
std::map<int, std::string> subSkillMap{
{1, "one"},
{2, "two"},
{3, "three"},
};
int level = 13;
double proficiencyBonus = 0;
friend class boost::serialization::access; //allows serialization saving
template <class Archive> void serialize(Archive& ar, unsigned)
{
ar & skillSet;
ar & subSkillMap;
ar & level;
ar & proficiencyBonus;
}
};
struct Character {
private:
friend class boost::serialization::access; // allows serialization saving
template <class Archive>
void serialize(Archive& ar, const unsigned int version)
{
ar & name;
ar & *charStats;
ar & inventory;
}
/*********************************
* Data Members
*********************************/
std::string name;
Stats* charStats = new Stats{};
std::vector<std::string> inventory;
public:
Character(std::string name = "unnamed") : name(std::move(name)){}
~Character() { delete charStats; }
// rule of three (suggest to use no raw pointers!)
Character(Character const&) = delete;
Character& operator=(Character const&) = delete;
void loadCharacter(std::string const& charName);
void saveCharacter();
};
/*********************************************
Functions to save and load character details
**********************************************/
void Character::saveCharacter() {
std::ofstream saveFile(name + ".dat");
boost::archive::binary_oarchive outputArchive(saveFile);
outputArchive << *this;
}
void Character::loadCharacter(std::string const &charName) {
std::ifstream loadFile(charName + ".dat");
boost::archive::binary_iarchive inputArchive(loadFile);
inputArchive >> *this;
loadFile.close();
}
int main() {
{
Character charlie { "Charlie" }, bokimov { "Bokimov" };
charlie.saveCharacter();
bokimov.saveCharacter();
}
{
Character someone, someone_else;
someone.loadCharacter("Charlie");
someone_else.loadCharacter("Bokimov");
}
}
Saves two files and loads them back:
==== Bokimov.dat ====
00000000: 1600 0000 0000 0000 7365 7269 616c 697a ........serializ
00000010: 6174 696f 6e3a 3a61 7263 6869 7665 1300 ation::archive..
00000020: 0408 0408 0100 0000 0000 0000 0007 0000 ................
00000030: 0000 0000 0042 6f6b 696d 6f76 0000 0000 .....Bokimov....
00000040: 0003 0000 0000 0000 0000 0000 0001 0000 ................
00000050: 0002 0000 0003 0000 0000 0000 0000 0300 ................
00000060: 0000 0000 0000 0000 0000 0000 0000 0001 ................
00000070: 0000 0003 0000 0000 0000 006f 6e65 0200 ...........one..
00000080: 0000 0300 0000 0000 0000 7477 6f03 0000 ..........two...
00000090: 0005 0000 0000 0000 0074 6872 6565 0d00 .........three..
000000a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000000b0: 0000 0000 0000 0000 0000 00 ...........
==== Charlie.dat ====
00000000: 1600 0000 0000 0000 7365 7269 616c 697a ........serializ
00000010: 6174 696f 6e3a 3a61 7263 6869 7665 1300 ation::archive..
00000020: 0408 0408 0100 0000 0000 0000 0007 0000 ................
00000030: 0000 0000 0043 6861 726c 6965 0000 0000 .....Charlie....
00000040: 0003 0000 0000 0000 0000 0000 0001 0000 ................
00000050: 0002 0000 0003 0000 0000 0000 0000 0300 ................
00000060: 0000 0000 0000 0000 0000 0000 0000 0001 ................
00000070: 0000 0003 0000 0000 0000 006f 6e65 0200 ...........one..
00000080: 0000 0300 0000 0000 0000 7477 6f03 0000 ..........two...
00000090: 0005 0000 0000 0000 0074 6872 6565 0d00 .........three..
000000a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000000b0: 0000 0000 0000 0000 0000 00 ...........
| |
doc_23534356
|
private void Suggestion_Box_SelectedIndexChanged(object sender, EventArgs e)
{
List<ComboBox> boxes = new List<ComboBox>()
{
Suggestion_Box1,
Suggestion_Box2,
Suggestion_Box3,
Suggestion_Box4
};
var i = 0;
foreach (ComboBox cb in boxes)
{
if (cb.SelectedIndex != -1)
{
cb.BackColor = Color.FromName(All_Colors[cb.SelectedIndex]);
Suggestion_Panel1.BackColor = Suggestion_Box1.BackColor;
Suggestion_Panel2.BackColor = Suggestion_Box2.BackColor;
Suggestion_Panel3.BackColor = Suggestion_Box3.BackColor;
Suggestion_Panel4.BackColor = Suggestion_Box4.BackColor;
}
}
}
The "All_Colors" array is a string array with different colors in it.
The Suggestion Boxes are Combo Boxes
and the Suggestion Panel are Panels.
A: My opinion, no need to update all the panels' back color when only 1 should be changed. You can bind each panel's BackColor property to corresponding ComboBox's BackColor property.
My code:
public partial class Form1 : Form
{
List<string> colors = new List<string> { "red", "blue", "green", "yellow" };
public Form1()
{
InitializeComponent();
// binding here
this.panel1.DataBindings.Add("BackColor", this.comboBox1, "BackColor");
this.panel2.DataBindings.Add("BackColor", this.comboBox2, "BackColor");
this.panel3.DataBindings.Add("BackColor", this.comboBox3, "BackColor");
this.panel4.DataBindings.Add("BackColor", this.comboBox4, "BackColor");
}
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
var comboBox = sender as ComboBox;
if(comboBox.SelectedIndex < 0)
return;
comboBox.BackColor = Color.FromName(colors[comboBox.SelectedIndex]);
}
}
A: I did it myself, i do not know if its the best thing to do, but i did it like this.
private void Suggestion_Box_SelectedIndexChanged(object sender, EventArgs e)
{
Dictionary<ComboBox, Panel> CoLi = new Dictionary<ComboBox, Panel>
{
{ Suggestion_Box1, Suggestion_Panel1 },
{ Suggestion_Box2, Suggestion_Panel2 },
{ Suggestion_Box3, Suggestion_Panel3 },
{ Suggestion_Box4, Suggestion_Panel4 }
};
foreach (var i in CoLi)
{
if (i.Key.SelectedIndex != -1)
{
i.Key.BackColor = Color.FromName(Used_Colors[i.Key.SelectedIndex]);
i.Value.BackColor = Color.FromName(Used_Colors[i.Key.SelectedIndex]);
}
}
}
| |
doc_23534357
|
However, now I'm trying to setup triggered builds through the GitHub plugin's web hook at https://user:pass@myci.example.com/github-webhook, but it looks like I'm running into issues since my jobs are configured with repositories such as github-my-project:zacharydanger/my-project.git and the plugin's not recognizing them because it's trying to match it as git@github.com:zacharydanger/my-project.git.
Is there a workaround for this?
A: Alright. Looks like there's no workaround, but this GitHub support page about managing deploy keys says that you can just create a user account for deploying. So I've added Jenkins' default public key to an account and given it pull access to the private repos it needs to build.
| |
doc_23534358
|
<MenuItem
value={one.supplier_Name}
key={one.supplier_Name}
data-id={one.supplier_ID}
>
{one.supplier_Name}
</MenuItem>
from MenuItem when Select onChange event is called. I've tried
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={newValues.supplier}
onChange={(e) => {
console.log(e.target.dataset.id);
}}
...MenuItem here
</Select>
but I think because of there is no data attributes on select, it's logging Cannot read property 'id' of undefined
Is there another way to get selected data attributes when onChange is triggered in Select ?
A: The event parameter in your onChange handler function contains two attributes:
*
*target which references the element receiving the event,
*currentTarget which references the element on which the handler was attached
Source: MDN documentation
In your case, it is counter-intuitive, but you should use currentTarget, because of the way Material-UI builds the DOM elements for your select:
onChange={(e) => {
console.log(e.currentTarget.dataset.id);
}}
| |
doc_23534359
|
A: Just in case anyone is interested, I figured it out. It's
set_target_properties(<your-target> PROPERTIES
XCODE_GENERATE_SCHEME TRUE
XCODE_SCHEME_WORKING_DIRECTORY <desired-directory>)
| |
doc_23534360
|
I already test the several in my Firefox(3.6.13).That's not working only on firefox.
Thanks
A: Ok, when alert message appears if you do not close it and open a new tab or somehow switch to different (because alert is modal), Firefox freezes.
My FF also got frozen after several times.
http://pokit.etf.ba/get/5e4bb9d6b9c3bc6b1bd1128c1342eb74.png
plugin-container.exe has encountered a problem and needs to close. We are sorry for the inconvenience.
| |
doc_23534361
|
I have this function that I'm playing around with. The idea is to initiate a list with a self executing function and then recall that self executing function within the self executing function.
var arr = [(function(){
//when first entering here arr is currently undefined
//here I call an asynchronous function that will start in 1 second
setTimeout(function(){
//1 second has passed so arr has been initiated.
//Notice that arr[Ø] is undefined and arr[1] isn't
//Why?
console.log('Why is this: ' + arr[0] + ' and ' + arr[1] + ' isnt ');
}, 1000);
})(), 2];
So in the end I'm trying to create a loop.
Question:
Within the self executing funciton I create a setTimeout and wait 1 second for my arr to finish initiating itself. Why is arr[0] undefined and arr[1] isn't? Is it even possible creating a loop this way?
DEMO
Final working demo: Thanks NoDownVotesPlz
A: arr[0] is undefined because the function doesn't return anything in your function,
If you want to show some value you, you should return it from the function after setTimeout: DEMO
var arr = [(function() {
setTimeout(function() {
document.write('Why is this: ' + arr[0] + ' and ' + arr[1] + ' isnt ');
}, 1000);
return 1 // return here
})(), 2];
| |
doc_23534362
|
I wish to have the top and bottom divs fill the remaining space.
Something like this
<div class="container">
<div class="top">
</div>
<div class="middle">
Content
</div>
<div class="bottom">
</div>
</div>
If possible I would like the set a min height for the top and bottom containers.
A: With flexbox you can do that
html, body {
margin: 0;
}
body {
display: flex; /* IE fix */
}
.container {
display: flex;
flex-direction: column;
min-height: 100vh;
width: 100%; /* IE fix */
}
.top, .bottom {
flex: 1; /* fill remaining space */
background: lightblue;
}
.middle {
background: lightgreen;
}
<div class="container">
<div class="top">
</div>
<div class="middle">
Content
</div>
<div class="bottom">
</div>
</div>
And if you need, you can also add a min-height to the top/bottom elements
html, body {
margin: 0;
}
body {
display: flex; /* IE fix */
}
.container {
display: flex;
flex-direction: column;
min-height: 100vh;
width: 100%; /* IE fix */
}
.top, .bottom {
flex: 1; /* fill remaining space */
background: lightblue;
min-height: 200px; /* set a min-height */
}
.middle {
background: lightgreen;
}
<div class="container">
<div class="top">
</div>
<div class="middle">
Content
</div>
<div class="bottom">
</div>
</div>
A:
.top{
min-height:100px;
}
.bottom{
min-height:100px;
}
or you can use different meseurment - like vh - for view height and so on
Forgot to add - it will go into your css file
A: Here is a table solution for all you purists.
html, body {
margin: 0;
height:100%;
}
.container {
display: table;
height: 100%;
width: 100%;
}
.container > div {
display: table-row;
}
.table-cell {
display: table-cell;
}
.top, .bottom {
background: #ADD8E6;
}
.middle {
background: #90EE90;
height:1px;
}
<div class="container">
<div class="top">
<div class="table-cell">
</div>
</div>
<div class="middle">
<div class="table-cell">
Content
</div>
</div>
<div class="bottom">
<div class="table-cell">
</div>
</div>
</div>
| |
doc_23534363
|
People
Group ID
Albert
1
Bernard
1
Charles
2
Daniel
2
Elizabeth
3
Francis
3
And what I would like to have is this:
People 1
People 2
Group ID
Albert
Bernard
1
Charles
Daniel
2
Elizabeth
Francis
3
I tried to pivot and unpivot here and there mindlessly to no avail, any ideas?
A: In powerquery,
Right-click the GroupID column and Group By...
Allow the default options and hit ok
Change the last part of the formula in the formula bar (or in home...advanced editor...) from
= Table.Group(Source, {"Group ID"}, {{"Count", each Table.RowCount(_), type number}})
to
= Table.Group(Source, {"Group ID"}, {{"Count", each Text.Combine(List.Transform([People], Text.From), ","), type text}})
that combines the People column into one column separated by commas
Then right click that column and split column by delimiter, for each occurrence of a comma
Full sample code:
let Source = Excel.CurrentWorkbook(){[Name="Table5"]}[Content],
#"Grouped Rows" = Table.Group(Source, {"Group ID"}, {{"Count", each Text.Combine(List.Transform([People], Text.From), ","), type text}}),
#"Split Column by Delimiter" = Table.SplitColumn(#"Grouped Rows", "Count", Splitter.SplitTextByDelimiter(",", QuoteStyle.Csv), {"Count.1", "Count.2"})
in #"Split Column by Delimiter"
//fancy version that includes Column titles and auto adjusts for dynamic number of columns
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Grouped Rows" = Table.Group(Source, {"Group ID"}, {{"Count", each Text.Combine(List.Transform([People], Text.From), ","), type text}}),
DynamicColumnList = List.Transform({1..List.Max(Table.AddColumn(#"Grouped Rows", "Custom", each List.Count(Text.PositionOfAny([Count], {","}, Occurrence.All)))[Custom])+1}, each "Person." & Text.From(_)),
#"Split Column by Delimiter" = Table.SplitColumn(#"Grouped Rows","Count",Splitter.SplitTextByDelimiter(",", QuoteStyle.Csv),DynamicColumnList )
in #"Split Column by Delimiter"
Another way ....
Right-click the GroupID column and Group By...
Allow the default options and hit ok
Change the last part of the formula in the formula bar (or in home...advanced editor...) from
= Table.Group(Source, {"Group ID"}, {{"Count", each Table.RowCount(_), type number}})
to
= Table.Group(Source, {"Group ID"}, {{"count", each Table.AddIndexColumn(_, "Index", 1, 1), type table}})
Use arrows atop new column and expand [x] People and [x] Index
Click select index column, transform pivot, choose People as value, advanced options, don't aggregate
full sample code
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
Group = Table.Group(Source, {"Group ID"}, {{"count", each Table.AddIndexColumn(_, "Index", 1, 1), type table}}),
#"Expanded count" = Table.ExpandTableColumn(Group, "count", {"People", "Index"}, {"People", "Index"}),
#"Pivoted Column" = Table.Pivot(Table.TransformColumnTypes(#"Expanded count", {{"Index", type text}}, "en-US"), List.Distinct(Table.TransformColumnTypes(#"Expanded count", {{"Index", type text}}, "en-US")[Index]), "Index", "People")
in #"Pivoted Column"
| |
doc_23534364
|
<span class='blue_mark'> text selected </span>
How can I accomplish this within the following code:
var selection = document.getSelection();
var range = selection.getRangeAt(0);
var contents = range.extractContents();
var node = document.createElement('span');
node.style.backgroundColor = "yellow";
node.appendChild(contents);
range.insertNode(node);
selection.removeAllRanges(); //Clear the selection, showing highlight
A: If you just want a class instead of a style attribute, use this by replacing node.style. backgroundColor = "yellow"; with node.classList.add('blue_mark'); or node.className += ' blue_mark';.
| |
doc_23534365
|
I will repeat it below:
Given an array of n distinct elements, find the minimum number of swaps required to sort the array.
Examples:
Input : {4, 3, 2, 1}
Output : 2
Explanation : Swap index 0 with 3 and 1 with 2 to
form the sorted array {1, 2, 3, 4}.
Input : {1, 5, 4, 3, 2}
Output : 2
I have solved the problem by doing the following.
*
*Sorting the array (n log(n)) time
*Making a hash to keep track of the swaps required as I compare both the sorted array and the original array. This should be another O(n) time
Total Time Complexity should be: O(n + (n log n)) = O(n log(n))
Below is the code I have written for the same and it works for the test cases provided.
def solution(array)
sorted = array.sort
puts array.inspect
puts sorted.inspect
counter_parts_that_have_been_seen = {}
number_of_swaps_required = 0
array.each_with_index do | val, idx |
if counter_parts_that_have_been_seen[val] == true
next
end
array_val = val
sorted_val = sorted[idx]
if array_val != sorted_val
puts "A swap will be required: array val is #{array_val} and sorted_array_val is #{sorted_val}"
number_of_swaps_required += 1
counter_parts_that_have_been_seen[sorted_val] = true
end
end
puts "Number of swaps required are: #{number_of_swaps_required}"
end
Now, my question is, how does one verify the CORRECTNESS? I have no sense of weather this approach is correct.
Can anybody shed some light on this?
A: If there is a element that is not in the correct position, then there must also be another element that is also not in it's correct position (the first element need to be placed in some other position that is occupied by another element). If this is represented in the form of a graph, the positions that don't have correct elements will have one edge towards it and on edge from it. This will end up forming one or more cycles. Now, the positions of the elements in the cycle are all within that cycle. So, we now need to prove that if there are 'n' elements in a cycle, minimum 'n-1' swaps are needed to sort them.
We can prove this be induction.
Base: n=1
Only one element, so already sorted (trivial). This means 0 swaps, ie, n-1 => 1-1 = 0
Assume if there are k elements in a cycle, it takes min k-1 swaps
k+1 elements
A element in a cycle is has an edge towards the position that it need to be. This position has another edge towards some other position. Now, if we swap the former element, we are removing the former edge and the latter element goes to the swapped position. Now we are left with a cycle of size (k+1)-1 = k. By induction, k cycle requires k-1 swaps. So, k+1 will require (k-1)+1 = k swaps.
A: Starting at the first element in the unsorted array, check if it is in the correct place, if not swap the correct value into that position. The test can either be done as you did by comparing to a sorted version of the collection, or the selected element can be compared to each element that follows it.
As you go along you may encounter elements that are in the correct position - either because they started in the correct place or they were swapped there when placing an earlier element (the last element must be by the time all other ones have been placed). Just leave those in place and move to the next element.
With this method every swap places at least one element correctly, some swaps will correctly place both.
An element in a correct place can be discounted from the problem - there is never a need to move it from its correct place to sort any other elements.
Also a pair of elements that in each others places (e.g. 3 and 1 in {3,2,1} ) never need to be swapped with any of the other elements. They form their own independent set of elements.
Once you have a method, as above, for obtaining the correct answer, it can obviously be used to evaluate any alternative method.
A: Index : 0 1 2 3 4 5 6 7 8 9
------+-----+---+---+---+---+---+---+---+---+--
Array : 1 22 32 42 12 83 64 93 73 53
------+-----+---+---+---+---+---+---+---+---+--
A BBBBBBBBBBBBBB CC DD CCCCCCCCCC
Target: 0 2 3 4 1 8 6 9 7 5
Diffs : 0 1 1 1 -3 3 0 2 -1 -4
Source: 0 4 1 2 3 9 6 8 5 7
In this example, the array[] needs to be sorted.
*
*Target is the index where this position should go after the sort
*source is the position where this index shoul get its value from
*diffs is the relative movement that the item at this index does during the sort
You can see four (cyclic) groups:
*
*A : 1 member 1
*B : 4 members {22,32,42,12}
*C : 4 members: {83,93,73,53}
*D : 1 member: 64
The groups with 1 member are already sorted: zero swaps needed.
The groups with 4 members can be sorted with 4 swaps each. (the final swap puts two elements to their final place)
So the number of swaps needed is 0+3+3+0
Now you only need to prove that you can sort an N-cycle in N-1 swaps...
| |
doc_23534366
|
name col_2
Manish 352-103
Manish 342-123
ganesh 362-111
ganesh 789-232
abcd 456-231
abcd 047-234
now i want it as:
name col-2
Manish 352-103, 342-123
ganesh 362-111, 789-232
abcd 456-231, 047-234
(I need distinct values of name and col-2 values must appended for the each distinct value of name)
Both column values are of type text
A: This solved the requirement in MySQL
select name, group_concat(col-2) from dbo.sample group by name
A: Try this :
select name, string_agg(concat(col-2, ', '))
from dbo.Sample
group by name
| |
doc_23534367
|
I don't want to change my data (it will be difficult and very problematic due to fact that I want to copy this shape 4 times on page) but I want to set local coordinate system in some place and then start drawing. Any ideas? Maybe another PDF C# library?
A: The problem was resolved by code:
PdfTemplate tp = cb.CreateTemplate(width, height);
tp.MoveTo(oStartPoly.dStartX, oStartPoly.dStartY);
etc...
than you do like so:
cb.AddTemplate(tp, fScaleFactor, 0, 0, fScaleFactor, fX, doc.PageSize.Height / 3);
Within this method you can scale and set absolute location.
The only problem is that line width is scaled too.
| |
doc_23534368
|
My current level in python is quite low (I'm a healthcare professional trying to do basic stuff) and it's basically adding together some code found online here and there but I still understand simple functions such as buttons and windows.
I have uploaded a picture to show more accurately what I'm aiming for: My goal in tkinter
Here is my current and my attempts so far:
from tkinter import *
import tkinter
import tkinter.ttk as ttk
from tkinter import Frame
import csv
root = tkinter.Tk()
root.title("Python - Healthcare continuity")
width = 500
height = 400
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)
root.geometry("%dx%d+%d+%d" % (width, height, x, y))
root.resizable(0, 0)
TableMargin = ttk.Frame(root)
TableMargin.grid(column=0, row=0, sticky=(N, W, E, S))
scrollbarx = Scrollbar(TableMargin, orient=HORIZONTAL)
scrollbary = Scrollbar(TableMargin, orient=VERTICAL)
# open file
with open("open(first.csv,'r+',encoding='utf-8')", newline = "") as file:
reader = csv.reader(file)
# r and c tell us where to grid the labels
r = 0
for col in reader:
c = 0
for row in col:
# i've added some styling
label = tkinter.Label(root, width = 10, height = 2, \
text = row, relief = tkinter.RIDGE)
label.grid(row = r, column = c)
c += 1
r += 1
with open("second.csv", newline = "") as file:
reader = csv.reader(file)
# r and c tell us where to grid the labels
r = 0
for col in reader:
c = 0
for row in col:
# i've added some styling
label = tkinter.Label(root, width = 10, height = 2, \
text = row, relief = tkinter.RIDGE)
label.grid(row = r, column = c)
c += 1
r += 1
with open("third.csv", newline = "") as file:
reader = csv.reader(file)
# r and c tell us where to grid the labels
r = 0
for col in reader:
c = 0
for row in col:
# i've added some styling
label = tkinter.Label(root, width = 10, height = 2, \
text = row, relief = tkinter.RIDGE)
label.grid(row = r, column = c)
c += 1
r += 1
root.mainloop()
Thank you for your help.
| |
doc_23534369
|
Using MSDN's article on the COM elevation moniker, I’ve configured the server class following the specified requirements. The server was successfully registered in the HKLM hive.
The code sample:
procedure CoCreateInstanceAsAdmin(const Handle: HWND;
const ClassID, IID: TGuid; PInterface: PPointer);
var
rBindOpts: TBindOpts3;
sMonikerName: WideString;
iRes: HRESULT;
begin
ZeroMemory(@rBindOpts, Sizeof(TBindOpts3));
rBindOpts.cbStruct := Sizeof(TBindOpts3);
rBindOpts.hwnd := Handle;
rBindOpts.dwClassContext := CLSCTX_LOCAL_SERVER;
sMonikerName := 'Elevation:Administrator!new:' + GUIDToString(ClassID);
iRes := CoGetObject(PWideChar(sMonikerName), @rBindOpts, IID, PInterface);
OleCheck(iRes);
end;
class function CoIMyServer.Create: IMyServer;
begin
CoCreateInstanceAsAdmin(HInstance, CLASS_IMyServer, IMyServer, @Result);
end;
When it comes to CoGetObject(PWideChar(sMonikerName), @rBindOpts, IID, PInterface) I get the UAC screen and confirm running the server as admin. However, OleCheck(iRes) returns: "The requested operation requires elevation" error.
From that article I’ve read about "Over-The-Shoulder (OTS) Elevation".
Is this the only way to get my server instance available for the non-elevated process? If so, when should CoInitializeSecurity be called on the server?
Complete registration details
HKLM\SOFTWARE\Wow6432Node\Classes\CLSID
{MyServer CLSID}
(Default) = IMyServer Object
LocalizedString = @C:\Program Files (x86)\MyServer\MyServer.exe,-15500
Elevation
Enabled = 0x000001 (1)
LocalServer32
(Default) = C:\PROGRA~2\MyServer\MYSERVER.EXE
ProgID
(Default) = uMyServer.IMyServer
TypeLib
(Default) = {TypeLib GUID}
Version
(Default) = 1.0
HKLM\SOFTWARE\Wow6432Node\Classes\Interface
{GUID of IID_IMyServer}
(Default) = IMyServer
ProxyStubClsid32
(Default) = {Some GUID}
TypeLib
(Default) = {TypeLib GUID}
Version = 1.0
Above are the only entries that exist in my registry after registering the server.
Additional details
Tried without success calling CoInitializeSecurity() implicitly + setting lunch permissions as advised using the following code:
function GetSecurityDescriptor(const lpszSDDL: LPWSTR; out pSD: PSecurityDescriptor): Boolean;
begin
Result := ConvertStringSecurityDescriptorToSecurityDescriptorW(lpszSDDL, SDDL_REVISION_1,
pSD, nil);
end;
function GetLaunchActPermissionsWithIL(out pSD: PSecurityDescriptor): Boolean;
var
lpszSDDL: LPWSTR;
begin
// Allow World Local Launch/Activation permissions. Label the SD for LOW IL Execute UP
lpszSDDL := 'O:BAG:BAD:(A;;0xb;;;WD)S:(ML;;NX;;;LW)';
Result := GetSecurityDescriptor(lpszSDDL, pSD);
end;
function GetAccessPermissionsForLUAServer(out pSD: PSecurityDescriptor): Boolean;
var
lpszSDDL: LPWSTR;
begin
// Local call permissions to IU, SY
lpszSDDL := 'O:BAG:BAD:(A;;0x3;;;IU)(A;;0x3;;;SY)';
Result := GetSecurityDescriptor(lpszSDDL, pSD);
end;
function SetAccessPermissions(hAppKey: HKEY; pSD: PSECURITY_DESCRIPTOR): Boolean;
var
dwLen: DWORD;
iRes: LONG;
begin
dwLen := GetSecurityDescriptorLength(pSD);
iRes := RegSetValueExA(hAppKey, 'AccessPermission', 0, REG_BINARY, pSD, dwLen);
Result := iRes = ERROR_SUCCESS;
end;
function SetLaunchActPermissions(hAppKey: HKEY; pSD: PSECURITY_DESCRIPTOR): Boolean;
var
dwLen: DWORD;
iRes: LONG;
begin
dwLen := GetSecurityDescriptorLength(pSD);
iRes := RegSetValueExA(hAppKey, 'LaunchPermission', 0, REG_BINARY, pSD, dwLen);
Result := iRes = ERROR_SUCCESS;
end;
procedure Initialize;
var
pSD: PSecurityDescriptor;
sSubKey: WideString;
hAppKey: HKEY;
begin
sSubKey := 'AppID\{GUID}';
RegOpenKeyW(HKEY_CLASSES_ROOT, PWideChar(sSubKey), hAppKey);
if GetAccessPermissionsForLUAServer(pSD) then
if not SetAccessPermissions(hAppKey, pSD) then
raise Exception.Create(Format('Access permissions aren''t set. System error: %d',
[GetLastError()]));
pSD := nil;
if GetLaunchActPermissionsWithIL(pSD) then
if not SetLaunchActPermissions(hAppKey, pSD) then
raise Exception.Create(Format('Launch permissions aren''t set. System error: %d',
[GetLastError()]));
end;
initialization
TAutoObjectFactory.Create(ComServer, TMyServer, Class_IMyServer,
ciMultiInstance, tmApartment);
Initialize;
As a AppID GUID I tried to use both the same CLSID GUID of my server interface and a new generated GUID: result was the same.
AccessPermission and LaunchPermission values appeared at the specified place after server registering.
Also tried:
*
*Specifying ROTFlags = 1 in the AppId key
*Building the server as 64-bit application
Additional registry keys/values I created manually:
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\AppID\MyServer.exe]
@="MyServer"
"AppID"="{My GUID}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\AppID\{My GUID}]
@="MyServer"
"ROTFlags"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{My GUID}]
@="MyServer Object"
"AppID"="{My GUID}"
A: One mistake you are making is you are passing the RTL's global HInstance variable where CoGetObject() expects an HWND instead. An HINSTANCE handle is not a valid HWND handle. You need to use an actual HWND such as the Handle property of a TForm, or else specify 0 to let the Elevation Moniker choose a suitable window for you.
As for the ERROR_ELEVATION_REQUIRED return value, all I can say is that your COM registration is likely incomplete somewhere. Please show the complete registration details that are actually being stored in the Registry (not what your code thinks it is storing - what the Registry is actually storing).
CoInitializeSecurity() should be called when the server process begins running.
| |
doc_23534370
|
.multilineTextAlignment(.center)
.multilineTextAlignment(.trailing)
.multilineTextAlignment(.leading)
But there is no justified attribute, is there a fastest way than use a UILabel and UIViewRepresentable ?
thanks
| |
doc_23534371
|
#define _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
#include <fstream>
using namespace std;
wstring utf8_to_uft16(string str)
{
wstring_convert<std::codecvt_utf8_utf16<int16_t>, int16_t> convert;
auto p = reinterpret_cast<const wchar_t *>(convert.from_bytes(str).data());
return wstring(p);
}
int main()
{
string u8 = u8"hello";
wstring u16 = utf8_to_uft16(u8);
wcout << u16;
cin.ignore(1);
}
the produced string by the function is empty and nothing is printed.
A: wstring_convert::from_bytes returns a std::basic_string. This string will be destroyed at the end of the line and the pointer returned from data() will no longer be valid.
Is there a reason you don't just convert directly to wchar_t?
wstring utf8_to_uft16( string str )
{
wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> convert;
return convert.from_bytes( str );
}
| |
doc_23534372
|
Goal: on a wiki page link to a specific object in one of the GIT repositories within the same project (e.g., a word document).
Is there any way to do this?
A: You could try to use the following format in Wiki:
URL: [text to display](RepoURL)
For example:
[link](https://{ServerName}/{CollectionName}/_git/{ProjectName}?path=%2FREADME.md)
This format applies to all repos.
If the target file is under the repo of the wiki, you can use the file path to set the link. The method here has limitations.
Absolute path in Git: [text to display](/folder/target.md)
For example:
Files
link
[link](/aspnet/Views/Shared/1.md)
In this case, the link file needs to be a text that can be displayed on the wiki(e.g. .md file).
Note: If the file is in another repo, the absolute path cannot be used.
Here is a doc about Wiki MarkDown.
| |
doc_23534373
|
we can see the background events overlap in a way making then difficult to distinguish, while the normal events are nicely cascaded. Is there a way to have the background events the same?
I could just style normal events as transparent, but I want to have another 'layer' on top where I can put events that aren't affected by the background ones overlap.
A: I solved this by setting a custom isBG attribute, and checking for it/adjusting the width in the eventAfterRender callback.
Code here: http://jsbin.com/kisiquxojo/1/edit?js,output
| |
doc_23534374
|
<PRE>
form action="#" method="post"
input type="hidden" name="cmd" value="_cart"
input type="hidden" name="add" value="1"
input type="hidden" name="w3ls_item" value="Asus Laptop"
input type="hidden" name="amount" value="880.00"
button type="submit" class="w3ls-cart"> Add to cart /button
/form
</PRE>
Here is my Javascript for FORM
<pre>
w3ls.render();
w3ls.cart.on('w3sb_checkout', function (evt) {
var items, len, i;
if (this.subtotal() > 0) {
items = this.items();
for (i = 0, len = items.length; i < len; i++) {
}
}
});
</pre>
and my APP.JS code for UI-ROUTER
<pre>
routerApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/pages/home');
$stateProvider
.state('home', {
url: '/pages/home',
templateUrl: 'pages/home.html'
})
</pre>
When i click on "Add to cart" button its taking me to default page how can i make it to point to the javascript function?
Thanks in advance!
| |
doc_23534375
|
So on my messages.rb model I am using:
def to_param
"#{id}-#{message.gsub(/\W/, '-').downcase}"
end
to make it so the url wills show up like so:
http://myapp.com/messages/1-this-is-a-message
The problem with this is, when the message is really long, and on live, it causes the app to crash.
How can I change this to_params function to limit the number of characters that will show up in the url to the first 25 or so.
Thanks!
A: Use the String object's slice method or [] notation: ([] is just an alias to slice)
def to_param
"#{id}-#{message[0..25].gsub(/\W/, '-').downcase}"
end
A: def to_param
"#{id}-#{truncate(message, :length => 40).gsub(/\W/, '-').downcase}"
end
You can use Rails's truncate helper:
truncate(message, :length => 40)
message is your message of course and you can specify your length
| |
doc_23534376
|
Notice: Undefined variable: form in ...templates/template.php on line 49
Fatal error: Call to a member function open() on a non-object in.../templates/template.php on line 49
this is my function in class.php:
public function executeProduct(sfWebRequest $request)
{
$this->renderPartial('integrate/Product');
$form = new ProductForm();
if ($request->isMethod('post') && $request->hasParameter($form->getName()))
{
$form->bindRequest($request);
if ($form->isValid())
{
$form->save();
return $this->redirectBack();
}
$this->forms['product'] = $form;
}
else
{
foreach ($form->getGlobalErrors() as $nom=>$error)
{
echo $nom.':'.$error;
}
}
}
what can I do as solution for that?
A: No, unfortunately this method is wrong, I must put if ($request->isMethod('post'))
I modified my template:
<form action="<?php echo url_for('integrate/Product') ?>" method="POST">
<ul>
<ul> <li> <?php echo $form['name']->label()?> </li>
<?php echo $form['name']->field()?>
</ul>
all blocks in :
if ($request->isMethod('post') && $request->hasParameter($form->getName()))
if I delete that, it works but I must put it, so after this changes ; I have this error :
Notice: Undefined variable: form in ...templates/template.php on line 49
Fatal error: Call to a member function label() on a non-object in.../templates/template.php on line 49
A: When you render a partial, you have to provide the variables manually. try
$this->renderPartial('integrate/Product', array('form' => $form));
and moving the call at the end of the action.
| |
doc_23534377
|
A: try commons-io function IOUtils.toString(InputStream, String)
public static String toString(InputStream input, String encoding)
the tool iconv also could help to do this.
A: Try with this:
System.setProperty("file.encoding", "UTF-8");
public static String getDefaultCharEncoding(){
byte [] bArray = {'w'};
InputStream is = new ByteArrayInputStream(bArray);
InputStreamReader reader = new InputStreamReader(is);
String defaultCharacterEncoding = reader.getEncoding();
return defaultCharacterEncoding;
}
Read more: http://javarevisited.blogspot.com/2012/01/get-set-default-character-encoding.html#ixzz4gYeXFUxn
| |
doc_23534378
|
.link {
padding:50px;
border: 1px solid black;
}
.link:hover {
background:red;
}
<div class="container">
<div class="link">
<a href="example.com">This is the link</a>
</div>
</div>
Currently it applys the hover as soon as I enter the link div. Is there a way to only apply the hover when I am over the text but still apply the background hover color to the whole div?
A: Some pointer-events trick can do it
.link {
padding: 50px;
border: 1px solid black;
pointer-events: none; /* disable on the div */
}
.link a {
pointer-events: initial; /* re-enable for only the link */
}
.link:hover {
background: red;
}
<div class="container">
<div class="link">
<a href="example.com">This is the link</a>
</div>
</div>
A: One of the methods to achieve this effect is by using javascript (with jquery for convinience)
$(document).on('mouseover', '.link a', function() {
$(this).parent().addClass('active');
}
$(document).on('mouseout', '.link a', function() {
$(this).parent().removeClass('active');
}
A: There is no parent selector in CSS. In order to do this, you've to use JavaScript. I have provided jQuery solution whenever you hover on the anchor, the div changes to red, and when you move out it will change to white.
$('.link a').on('mouseover',function(){
$('.link').css('background-color','red');
});
$('.link a').on('mouseleave', function(){
$('.link').css('background-color','white');
});
.link {
padding:50px;
border: 1px solid black;
}
/*You can remove this :hover effect
.link:hover a {
background:red;
}
*/
<div class="container">
<div class="link">
<a href="example.com">This is the link</a>
</div>
</div>
| |
doc_23534379
|
A: You need to add a permission in the manifest.json for all domains you will be XHR'ing to. If you don't know beforehand which domains, you can add a permission for any url:
"permissions": ["<all_urls>"],
| |
doc_23534380
|
For digits, we have performed our testing on MNIST data set.
However for the English alphabets we have not been able to find any openly available (i.e. available for free), standard data set. All we have been able to find is NIST and CEDAR handwritten data sets, available on their respective official sites, but they come at a substantial cost.
Is there any other, openly available standard data set of English alphabets which can be used for testing the Handwritten Character Recognition system.
A: Did you check the UCI Machine Learning repository?
http://archive.ics.uci.edu/ml/datasets.html
What about this one?
http://archive.ics.uci.edu/ml/datasets/UJI+Pen+Characters
This is what you may be looking for:
https://www.nist.gov/itl/iad/image-group/emnist-dataset
| |
doc_23534381
|
All the functionality works fine except that i cannot get the styles to be loaded
when starting the dev server.
Mt index.html
<head>
<title>CMS</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="Angular2 File Upload">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="../node_modules/primeng/resources/themes/aristo/theme.css" />
<link rel="stylesheet" type="text/css" href="../node_modules/font-awesome/css/font-awesome.min.css" />
<link rel="stylesheet" type="text/css" href="../node_modules/primeng/resources/primeng.min.css" />
</head>
<body>
<upload-component>Loading...</upload-component>
</body>
</html>
My webpack.config.js
var path = require('path');
var webpack = require('webpack');
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
var HtmlPlugin = require('html-webpack-plugin')
const ENV = process.env.NODE_ENV = 'development';
const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 8080;
const metadata = {
env: ENV,
host: HOST,
port: PORT
};
module.exports = {
devServer: {
contentBase: path.join(__dirname, '../webapp/app'),
stats: "errors-only",
historyApiFallback: true
},
stats: "errors-only",
devtool: 'source-map',
entry: {
'@angular': [
'rxjs',
'reflect-metadata',
'zone.js'
],
'common': ['es6-shim'],
'app': './app/src/main.ts'
},
output: {
path: path.join(__dirname, '../webapp/app'),
filename: '[name].js',
sourceMapFilename: '[name].js.map',
chunkFilename: '[id].chunk.js'
},
module: {
loaders: [{
test: /\.ts$/,
loaders: ['ts-loader', 'angular2-template-loader'],
exclude: [/node_modules/, /releases/]
}, {
test: /\.json$/,
loader: 'json'
}, {
test: /\.css$/,
loader: 'raw'
}, {
test: /\.html$/,
loader: 'raw'
}, {
test: /\.(png|jpg)$/,
loader: 'url?limit=10000'
}]
},
plugins: [
new CommonsChunkPlugin({
names: ['@angular', 'common'],
minChunks: Infinity
}),
new HtmlPlugin({
template : path.join(__dirname, 'index.html')
})
],
resolve: {
extensions: ['.ts', '.js', '.json', '.css', '.html']
},
};
Any suggestions?
A: I got around the problem by importing the .css files to diraclty form main main.ts file.
This solved my problem:
https://stackoverflow.com/a/40464229/2960896
| |
doc_23534382
|
Thank you.
public delegate int FibPointer(int x); // FibbonaciSequence() pointer
class Program
{
static void Main(string[] args)
{
// fibonacci Length
int fibLength = 8;
// point delegate to method
FibPointer fb = new FibPointer(FibonacciSequence);
IAsyncResult iftAR = fb.BeginInvoke(
fibLen, new AsyncCallback(FibCompleted), null);
Console.WriteLine("Fibonacci process now running on thread {0}\n",
Thread.CurrentThread.ManagedThreadId);
int count = 0;
while (!iftAR.IsCompleted) // completion occurs when userIN length is reached
{
// run fib sequence.
Console.WriteLine("{0}", FibonacciSequence(count));
count++;
}
Console.ReadKey();
}
static int FibonacciSequence(int num)
{
int num1 = 0, num2 = 1, res = 0;
if (num == 0) return 0;
if (num == 1) return 1;
for (int i = 0; i < num; i++)
{
res = num1 + num2;
num1 = num2;
num2 = res;
Thread.Sleep(300);
// track background thread from pool
Console.WriteLine("Working on thread: {0}",
Thread.CurrentThread.ManagedThreadId);
}
return res;
}
static void FibCompleted(IAsyncResult ar)
{
Console.WriteLine("\nFib Sequence Completed.");
// retrieve result
AsyncResult res = (AsyncResult)ar;
//FibPointer fp = ar.AsyncState as FibPointer;
FibPointer fp = res.AsyncDelegate as FibPointer;
// call EndInvoke to grab results
string returnVal = fp.EndInvoke(ar).ToString();
Console.WriteLine("\nreturn val is: {0}", returnVal);
}
}
A: If you must use pure APM. Here is an example of it in action.
void Main()
{
// fibonacci Length
int fibLength = 8;
// point delegate to method
Func<int, int> fb = FibonacciSequence;
var completedEvent = new System.Threading.AutoResetEvent(false);
var iftAR = fb.BeginInvoke(fibLength, FibCompleted, completedEvent);
completedEvent.WaitOne();
var result = fb.EndInvoke(iftAR);
Console.WriteLine("Fibonacci process now running on thread {0}\n", Thread.CurrentThread.ManagedThreadId);
Console.WriteLine(result);
}
static int FibonacciSequence(int num)
{
int num1 = 0, num2 = 1, res = 0;
if (num == 0) return 0;
if (num == 1) return 1;
for (int i = 0; i < num; i++)
{
res = num1 + num2;
num1 = num2;
num2 = res;
Thread.Sleep(300);
// track background thread from pool
Console.WriteLine("Working on thread: {0}",
Thread.CurrentThread.ManagedThreadId);
}
return res;
}
static void FibCompleted(IAsyncResult ar)
{
var completedEvent = (AutoResetEvent)ar.AsyncState;
completedEvent.Set();
}
However. Nobody uses pure APM any more. APM was superceeded by EAP, which was in turn superceeded by TAP.
I would advise you learn TAP instead. It is much simplier. To adapt APM code to TAP you can use the TaskFactory helper function.
async Task Main()
{
// fibonacci Length
int fibLength = 8;
// point delegate to method
Func<int, int> fb = FibonacciSequence;
var result = await Task.Factory.FromAsync (fb.BeginInvoke, fb.EndInvoke, fibLength, null);
Console.WriteLine("Fibonacci process now running on thread {0}\n", Thread.CurrentThread.ManagedThreadId);
Console.WriteLine(result);
}
static int FibonacciSequence(int num)
{
int num1 = 0, num2 = 1, res = 0;
if (num == 0) return 0;
if (num == 1) return 1;
for (int i = 0; i < num; i++)
{
res = num1 + num2;
num1 = num2;
num2 = res;
Thread.Sleep(300);
// track background thread from pool
Console.WriteLine("Working on thread: {0}",
Thread.CurrentThread.ManagedThreadId);
}
return res;
}
However, most people would just work in TAP. Which would look like this.
async Task Main()
{
// fibonacci Length
int fibLength = 8;
var result = await FibonacciSequence(fibLength);
Console.WriteLine("Fibonacci process now running on thread {0}\n", Thread.CurrentThread.ManagedThreadId);
Console.WriteLine(result);
}
static Task<int> FibonacciSequence(int num)
{
// Run computationally intensive work on thread pool.
return Task.Run(() =>
{
int num1 = 0, num2 = 1, res = 0;
if (num == 0) return 0;
if (num == 1) return 1;
for (int i = 0; i < num; i++)
{
res = num1 + num2;
num1 = num2;
num2 = res;
Thread.Sleep(300);
// track background thread from pool
Console.WriteLine("Working on thread: {0}",
Thread.CurrentThread.ManagedThreadId);
}
return res;
});
}
| |
doc_23534383
|
So far I've tried several different approaches none of which seem satisfactory:
1) Monitoring and catching WM_QueryEndSession call
Drawbacks: basically, this call is commonly used to notify running apps and interactive users of the system shutdown. However, this call might not work with a non-responding app or service. Or the actual shutdown might be delayed till the unresponsive services are terminated and apps are closed by the system, even though the call exited with the correct status.
2) Windows Event Log
It could be possible to develop a program to read Windows event log. The program would require some time to scan through the event log and verify if the the relevant message was logged or not. But it looks like that would take some time and probably wouldn't complete before the system initiates Event logging service closure and further shutdown. Moreover, running a program during system shutdown doesn't seem reliable.
3) Simply pinging the computer to make sure the network adapter was disconnected from the network.
That is not the first action taken in the shutdown process and might be significantly delayed by non-responding processes and other reasons.
Is there any reliable way to catch a shutdown call to the system before the system gets powered off?
A: To be honest, my brain is screaming NO. The whole idea seems flawed. It sounds like a desperate attempt to address a symptom of an entirely different problem. Furthermore, testing beyond certain boundaries is generally ill-advised, and with good reason: it over-complicates things to the point where it really is not worth the effort. For example, in this situation where you're testing shutdown:
*
*Do you really want to shutdown in the test?
*What about other application that don't want you to shutdown now?
*If you do actually shutdown, your app testing the shutdown will go down with the rest of the system.
*After shutting down, do you automatically restart?
*If you use the shutdown option to automatically restart - is this going to be the same as a production scenario?
*Maybe you need a proper power-off and wake-on-LAN to perform a remote restart for a more realistic test?
*Or perhaps you want to test the shutdown command without actually shutting down?
*
*The problem is as soon as you send the shutdown command (successfully), Windows starts shutting down.
*You could abort the shutdown, but by that time other applications may have been closed in response to the request (not very friendly behaviour).
This is a situation where it is usually more appropriate to mock the interface to the problematic boundary. Then you simply test that the interactions with the mock are correct.
However that said, I still worry that you're trying to address symptoms of a different problem.
You said: "There was a discrepancy with some Windows deployments (not all, though)".
Did you identify the root cause of the discrepancy? If you have an application that's supposed to automatically issue a shutdown command, there are a number of reasons it could fail:
*
*The application might not have been running.
*There might be a bug that prevented it from making the necessary call.
*It might have made the call, but Windows may have rejected it (Hopefully you ARE checking the return value of the API call?) for some reason (permission, remote sessions, OS in the middle of something else - who knows?).
*Now, even if the call returns a success result, the shutdown can still be stopped. (BTW, you said you needed to know the initiation time. This is it! This is when shutdown started. Write the current time to a file, in the registry - whatever you like.
*Even given all of the above, any application can abort the shutdown process. So even if your code that shuts down the system has been thoroughly tested, and works perfectly - some other entirely unrelated app can turn around and say: "ix-nay on the shutdown hey!" - and the system continues running....
Getting back to "symptom of a different problem"... Some things you've said (checking event log, concerned about the time, saying: "catch if the shutdown call was issued to the system") suggest you're trying to find out after-the-fact "was the shutdown command issued"?
This doesn't sound like a testing issue - this sounds like a logging issue.
Perhaps you want to test that this very important logging is happening correctly?
And this brings me straight back to: rather mock the Windows API calls, and test that your interactions with the documented API are correct.
If I haven't dissuaded you from taunting the gods of madness...
You mentioned a drawback to monitoring WM_QueryEndSession of apps/services not responding. However, you don't really care about other apps. You only need one app, your app. A tiny simple stand-alone monitoring utility if necessary. When it gets the message - log it along with the reason. (There's still no guarantee shutdown will complete of course.)
You can go a step further, your monitoring app can use the SetProcessShutdownParameters function to be one of the first processes notified of the shutdown. Of course if shutdown is aborted, your monitoring utility will no longer be running, and will need to be restarted. (Did I mention madness and insanity?)
Alternatively, set it to be one of the last shutdown allowing you to take some action at a time closer to actual shutdown (if it does in fact shutdown).
Your concerns with reading the Event Log were because it might be too slow to finish while the system is shutting down. Why would you even want to read it during shutdown? (Or has the madness taken hold already?) The data is unlikely to run off while the disks are parking off doing nothing. Read it on restart if you have to. But first read about the Shutdown Event Tracker.
Finally, instead of (or in addition to) listening for WM_QueryEndSession, listen for WM_EndSession. There are some situations where the former won't be sent. But as far as I can tell, the latter should always be sent.
Did I mention madness? ... Maybe it was insanity. ... I know I mentioned the loony-bin. ... What who why when how? ... They're inside my head!
The madness ends.
| |
doc_23534384
|
class Note(models.Model):
sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='sender_note', on_delete=models.CASCADE)
receiver = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
related_name='reciever_note', on_delete=models.CASCADE)
status = models.BooleanField(blank=True, null=True)
action = models.CharField(choices=NOTE_CHOICES, max_length=5, blank=True, null=True)
There are situation, when the reciever an the sender are the same user, but in the majority of cases are different users.
I created a custom queryset, where I use a RawQueryset:
qs_str = 'SELECT N.id, N.status,N.action, U.email AS email FROM notes_note AS N LEFT JOIN users_user AS U on N.sender_id=U.id WHERE action IN %s AND status IS NOT TRUE AND U.is_staff=%s'
qs = Note.objects.raw(qs_str, [action, user_is_staff])
I need to get:
*
*both receiver and sender (to get attributes from them especially email)
*check if sender is staff or not
A: There is no reason to use a raw query for such a simple case..
Note.objects.filter(sender__is_staff = True, action__in = action)
if you really want to optimize to prefetch sender/receiver you can use select_related('sender', 'receiver').
| |
doc_23534385
|
function SubmitQuery(Org_UID) {
var ddlProduct_No = $("#Org_UID");
$.ajax({
type: 'POST',
url: '@Url.Action("ShowNewProfessionalWindow", "UpdateOrganizationUID")',
dataType: "html",
data: {
countryno: $("#Org_UID").val() }
My Controller
[HttpPost]
public ActionResult ShowNewProfessionalWindow(string countryno)
{
UpdateOrganizationUIDViewModel model = new UpdateOrganizationUIDViewModel();
//model.Org_UID = OrgUID;
model.org_name_long = "test";
model.org_name_short = "test";
return RedirectToAction("Index", model);
}
How can I return value of model to view using jquery?
A: Use JsonResult
Change your code and return JsonResult, So use
return Json(model);
instead of
return RedirectToAction("Index", model);
If you want to return View use
First you can create a method as, which will accept ViewName and Model it will return HTML string
public static string RenderRazorViewToString(ControllerContext controllerContext, string viewName, object model)
{
controllerContext.Controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
var viewContext = new ViewContext(controllerContext, viewResult.View,
controllerContext.Controller.ViewData, controllerContext.Controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
Usage also you have to return JsonResult instead of PartialViewResult
public JsonResult yourpartialviewresult()
{
return Json(new
{
data = RenderRazorViewToString(this.ControllerContext, "partialview", model)
});
}
| |
doc_23534386
|
what i have done to configure my service is given below.
try
{
Uri baseAddress = new Uri("http://localhost:8080/Easicreate/SearchService");
BasicHttpBinding binding = new BasicHttpBinding();
this.host = new ServiceHost(typeof(SearchServiceContract));
this.host.AddServiceEndpoint(typeof(ISearchServiceContract), binding, "http://localhost:8080/Easicreate/SearchService");
//// Enable metadata publishing.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.HttpGetUrl = baseAddress;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
this.host.Description.Behaviors.Add(smb);
this.host.Open();
}
catch (Exception ex)
{
this.host = null;
}
I am little bit confused ?
A: i am not sure but try removing
smb.HttpGetUrl = baseAddress;
and check as you are passing same baseAddress in endpoint and in behaviour, either dont pass url in endpoint
| |
doc_23534387
|
Y is an element which states the number of tweets which have been received, ( checks length of an array) and X is another which has it's text content incremented by 1 every second.
*
*I just put some random values for the time for it to take, I would use a more logical scale ( every 60 secs or something).
I wanted to log this information every minute, to make a graph but i've made an infinite loop somehow and i'm not quite sure how.
Here's the code:
function saveinfo(){
var x = document.getElementsByClassName('timer')[0].textContent;
var y = document.getElementsByClassName('counter')[0].textContent;
while (x != "510"){
if(x = "5"){
console.log(y);
}
else if (x = "200") {
console.log(y);
}
else if (x = "300"){
console.log(y);
}
else if (x = "400"){
console.log(y);
}
else if (x = "500"){
console.log(y);
x = "510"
}
}
};
A: When your if statements are evaluated, you're setting x:
if(x = "5"){
This means that x will never equal "510", and your loop will go on forever.
To fix this, you should do something like if(x === '5')
A: Three main reasons:
*
*x is a local variable, not a reference to the content in the element. When the content changes, the value in x stays the same.
*= is the assignment operator, not the comparison operator. You need to use == (or better, ===) for comparison. Since x = "5" evaluates to true, you will never get past the first if.
*Your loop prevents the UI from updating anyway, because JavaScript is by default single-threaded. Even if you did read the value in the timer all the time rather than reading the local, it would still never change.
A: Your if/else statements aren't working. You put in if(x = "200") instead of if( x == "200"). In if/else statements, if(x=1)doesn't work. if(x==1) or if(x=="1") always work. if(x==="1") works only if x is a string that says "1". if(x===1) only works if x is a number.
All you need to do is change the if(x="number") into if(x=="number")
| |
doc_23534388
|
Draggable.create(this, {
trigger: $(this).find(".a4")
});
Draggable.create(this, {
type: 'rotation',
trigger: $(this).find(".a0, .a2, .a6, .a8"),
cursor: 'alias'
});
});
If I create 2 draggables, only the last one sticks. Any way to have multiple triggers on the same object?
https://jsfiddle.net/w91nfmdg/
| |
doc_23534389
|
Can someone please help me with this?
A: Using VBA. ReverseSort by date and then by Column C and then do a remove duplicates. Remove duplicates moves everything after the first instance. If you sort correctly first then that's exactly what you want.
| |
doc_23534390
|
Below is a snippet of the code that runs the quizz
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class serv3p extends HttpServlet
{
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String qKey = req.getParameter("sQuestionID");
int iQuestionID = Integer.parseInt(qKey);
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String sourceURL = new String("jdbc:odbc:MyQuiz");//DSN name
Connection databaseConnection = DriverManager.getConnection(sourceURL);
if (databaseConnection != null)
out.println("<P>Connection made<BR>");
if (iQuestionID < 11) out.println("QuestionID is: " + qKey);
Statement myStatement = databaseConnection.createStatement();
ResultSet results = myStatement.executeQuery ("SELECT TOP 10 QuestionBank.QuestionText, QuestionBank.Choice1, QuestionBank.Choice2,"
+"QuestionBank.Choice3, QuestionBank.Choice4,QuestionBank.Answer FROM QuestionBank ORDER BY RND(QuestionID)");
//ResultSet results = myStatement.executeQuery ("SELECT * FROM QuestionBank WHERE QuestionID = '"+qKey+"'");
if (results.next())
{
String r1, r2, r3, r4, r5;
r1 = results.getString(1);
r2 = results.getString(2);
r3 = results.getString(3);
r4 = results.getString(4);
r5 = results.getString(5);
//r6 = results.getString(6);
out.println("<BODY BGCOLOR='lightblue'></BODY>" +
"<FORM method = \"post\" action = \"http://localhost:8080/servlet/Relay\">" +
"<TABLE BORDER = 2 CELLPADDING = 4 CELLSPACING = 2>" +
"<TR><TD COLSPAN = 6 ALIGN = CENTER><H2><B>Quick Quizz : Sports</B></H2></TD></TR>");
out.println("<TR><TD>" + r1 + "</TD></TR>");
out.println("<TR><TD><input type = \"radio\" name = \"answer\" value = \"1\">" + r2 + "</TD></TR><BR>");
out.println("<TR><TD><input type = \"radio\" name = \"answer\" value = \"2\">" + r3 + "</TD></TR><BR>");
out.println("<TR><TD><input type = \"radio\" name = \"answer\" value = \"3\">" + r4 + "</TD></TR><BR>");
out.println("<TR><TD><input type = \"radio\" name = \"answer\" value = \"4\">" + r5 + "</TD></TR><BR>");
out.println("</TABLE>");
results.close();
iQuestionID++; qKey = "" + iQuestionID;
out.println("<BR>End of Database Records<BR>");
if (iQuestionID < 11)
{
out.println("<BR><BR><INPUT type = \"submit\" value = \"Press for Next Question\">" +
"<INPUT type = \"hidden\" name = \"sQuestionID\" value = '" + qKey + "'><p>" +
"<INPUT type = \"hidden\" name = \"choice\" value = \"Play\"></FORM></BODY></HTML>");
}
else
{out.println("<BR><BR><INPUT type = \"submit\" value = \"Press to Exit\">" +
"<INPUT type = \"hidden\" name = \"sQuestionID\" value = '" + qKey + "'><p>" +
"<INPUT type = \"hidden\" name = \"choice\" value = \"serv43a\"></FORM></BODY></HTML>");
}
out.close();
}
}
catch(ClassNotFoundException cnfe)
{System.out.println(cnfe);}
catch(SQLException sqle)
{System.out.println("Error is: " + sqle);}
}
}
A: Why not use the database to store the calculated score, and then display it on the results page? If you don't need to keep the scores for any length of time (e.g. longer than an hour or so), you can always check for, and delete old records as often as necessary.
A: Well the question you should ask yourself is, do i want to keep the scores for an amount of time ( for an example: a poll ), or do you just want to use it as a Test like software wich returns the exact score after the test, but than just destroys that value together with the end of the software,
if you do want to keep it for a longer amount of time, you could write all values in an access database, or even an SQL server,
if you think the values you want to keep aren't that mutch, than i'd sugest you write it down in a txt based file, since it is easy to store and doesn't take as much time as a database connection to write it away,
to get at your score you will need to hardcode the right answers, with swich cases or if/else, just hardcode the place of your string with te correct answer, and add the score to a private int (or float/double)
displaying it is not that hard, if you want to display the stuff from plenty op participants, just use an enhanced for loop, with a println wich displays the name of the participant and the numbers, or even put it in a JFrame. thats up to you,
my advise
( a lot of data you want to keep ) => SQL / (access) databases
( a bit of data you want to keep ) => txt File and if you know the exact number of participants ( XML )
( just diplay ) print your score,
you will need to hardcode this score, and that depends on how you chose the values.
final tip: Dont open too many db connections it will only slow your progress down, and stuff like the right answer are easy to hard code since they are not variable, and you only have like 10 questions
Question 1: (edit)
no problem, you only want like 10 Questions right, cause i discussed the problem with a friend of mine last night, and if you do want to keep the scores for a longer amount of time, you might want to have the possibility to add more questions if not,
just use the if else way for each question
if(Question1.equals("Question1"))
{
no problem, you only want like 10 Questions right, cause i discussed the problem with a friend of mine last night, and if you do want to keep the scores for a longer amount of time, you might want to have the possibility to add more questions if not,
just use the if else way for each question
if(Question1.equals("Question1"))
{
Switch(answer)
case 1: points++; break;
case 2: break;
case 3: break;
default: break;
}
}
else
{
if(Question2.equals("Question2"))
{
Switch(answer)
case 1: break;
case 2: points++; break;
case 3: break;
default: break;
}
else
{
}
}
and so on, fill in the Questions like this,
String Question = "Question1";
if ( Question.equals("Question1"))
{
...
}
if you do wish to do it with a database, you can as well put the answer in an extra attribute, and than you could do it like this
int[] answerOnTheQuestions = the answers from the test ( put them in an Int array )
int[] answers = ( your db link to the right table and column here )
int score = 0;
for ( int counter = 0; counter < questions.length; counter ++)
{
if( answersOnTheQuestions[counter] == answers[counter] )
{
score++;
}
}
Write score to your table together with like a participants name that you can get in the GUI or consle.
I hope this helped :)
| |
doc_23534391
|
Ideally the cookies doesn't hold any significance for the static request except overloading the request.
So, I tried giving the below configuration in the Apache's HTTPD.Conf file:
*
*Uncommenting (It was commented prior to my change),
LoadModule setenvif_module modules/mod_setenvif.so &
LoadModule headers_module modules/mod_headers.so
*Added below 2 lines,
SetEnvIf Mime image/.* unset-cookie
Header unset Set-Cookie
Post this change, if I intercept the HTTP request using tamper data, I still see the png / jpeg request carrying the cookies with it.
Can somebody help me if I am missing anything else?
A: The domain name of static image URL should be different than the URL that serve dynamic webpage
| |
doc_23534392
|
I want to achieve this functionality using python code instead, but I can't figure out how to send a message until the device is up without throwing exceptions (since the device is not connected).
This is what I have tried, but it does not work (with pyserial):
def send_w(serial_port, baud_rate):
msgw = "w_"
ans = ""
ser = serial.Serial(port=serial_port, baudrate=baud_rate,timeout = 10)
ser.write(msgw)
ans = ser.read(24)
ser.close()
print(ans)
return ans
def set_firmware_version(serial_port, baud_rate):
s = ""
try:
with serial.Serial(serial_port,baud_rate,timeout=1) as ser:
msgr = "%reset "+sk+"_"
ser.write(msgr)
ser.close()
print("reset")
except (IOError) as e:
print("Error in: set_firmware_version")
print(e)
return s
time.sleep(1)
send_w(serial_port, baud_rate)
set_firmware_version(sp,br)
This gives the following error:
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)
I also tried sending the messages in a loop with a short timeout, but had the same problem. Is there any way to send a message continuously and disregard exceptions if the device is not found?
Any help will be greatly appreciated.
Full Traceback:
Traceback (most recent call last):
File "mc_config.py", line 69, in <module>
set_firmware_version(sp,br)
File "mc_config.py", line 64, in set_firmware_version
send_w(serial_port, baud_rate)
File "mc_config.py", line 46, in send_w
ans = ser.read(24)
File "/home/avidbots/.local/lib/python2.7/site-packages/serial/serialposix.py", line 501, in read
'device reports readiness to read but returned no data '
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)
(I am using ubuntu 16.04 and python 3)
A: What if you put the excepting code into a try and then catch the exception with an except serial.serialutil.SerialException {...} block?
Clearly there's a significant window of time to submit the w ( otherwise the "press w" method wouldn't often work.) Your requirement, then, would be to retry only the part of the code that's absolutely necessary to send the w, so that you send it quickly enough to "catch" the system in its bootup state. Since the backtrace shows that the exceptions occurs in send_w, then you can add try/except blocks and a while loop around what is now one line at the end of set_firmware_version.
Instead of just this:
send_w(serial_port, baud_rate)
Something like this might solve the problem:
while True:
try:
send_w(serial_port, baud_rate)
break
except serial.serialutil.SerialException:
pass # retry
You may need to change your imports to expose that exception, fyi. And you may need to consider whether you're catching too many possible exceptions - it's possible that exception might also represent other errors that shouldn't be retried. You might also need to add a small sleep time there - this is essentially a busy wait loop (https://en.wikipedia.org/wiki/Busy_waiting).
| |
doc_23534393
|
HTML:
<div id="ytapiplayer2" style="display:none;">
<object width="600" height="375">
<param name="movie" value="http://www.youtube.com/v/WSulgIt-Q_c?fs=1&hl=en_US&rel=0&autoplay=1"></param>
<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube.com/v/WSulgIt-Q_c?fs=1&hl=en_US&rel=0&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="600" height="375"></embed>
</object>
</div>
<img src="image.jpg" id="imageID" />
<img src="button_image.jpg" id="stop_replace" />
JavaScript/Jquery:
$('#imageID').click(function() {
$('#ytapiplayer2').show();
$('#imageID').hide();
});
The code on jsfiddle: http://jsfiddle.net/AdUvY/6/. I know this also could be done using iframe but I need it implemented in this way. Could you help me please. Thanks.
A: I created a sample Demo for you.
Please check this and let me know if it gives a solution to your problem.
Demo : http://jsfiddle.net/codebombs/Rpgkk/2/
Here I am using jQuery SWFObject Plugin from http://jquery.thewikies.com/swfobject/. This allows us to write simple code to embed SWF Objects.
Also, in IE Browsers if you jus Hide the SWF object, then there is a chance of playing in the background. So, best thing will be remove the complete player from the div, if you don't need that any more.
So, I removed the SWF object from player div when I don't want that.
This automatically allows us to start the player from starting when we need.
Please let me know if it need any modifications.
| |
doc_23534394
|
The backend is sending the S3 Storage configuration to my project so I have to configurate Amplify with the data received.
I tried to configurate the storage following this test but It's failing with the following error:
PluginError: Unable to decode configuration
Recovery suggestion: Make sure the plugin configuration is JSONValue
▿ pluginConfigurationError : 3 elements
- .0 : "Unable to decode configuration"
- .1 : "Make sure the plugin configuration is JSONValue"
- .2 : nil
This is my code:
func amplifyConfigure() {
do {
Amplify.Logging.logLevel = .verbose
try Amplify.add(plugin: AWSCognitoAuthPlugin())
try Amplify.add(plugin: AWSS3StoragePlugin())
let storageConfiguration = StorageCategoryConfiguration(
plugins: [
"awsS3StoragePlugin": [
"bucket": "bucket",
"region": "us-west-2",
"defaultAccessLevel": "protected"
]
]
)
let amplifyConfiguration = AmplifyConfiguration(storage: storageConfiguration)
try Amplify.configure(amplifyConfiguration)
// LOG success.
} catch {
// LOG Error.
}
}
Can someone help me with this custom configuration?
Thanks!
A: It seems that config cannot be declared directly in one go for some reason, possibly type-related. For me it works if I declare it in multiple steps. Try replacing this:
let storageConfiguration = StorageCategoryConfiguration(
plugins: [
"awsS3StoragePlugin": [
"bucket": "bucket",
"region": "us-west-2",
"defaultAccessLevel": "protected"
]
]
)
with this:
var storageConfigurationJson : [String:JSONValue] = [ "awsS3StoragePlugin" : [] ]
storageConfigurationJson["awsS3StoragePlugin"] = ["bucket": "bucket",
"region": "us-west-2",
"defaultAccessLevel": "protected"]
let storageConfiguration = StorageCategoryConfiguration(plugins: storageConfigurationJson)
I've only used Amplify config with AuthCategoryConfiguration, so in case StorageCategoryConfiguration has a different syntax you may need to adjust my suggested code accordingly.
| |
doc_23534395
|
In a new requirement, i have to scrape emails from multiple email folders and use some of these Service - Spring Data components to store the information extracted through scraping.
The email scraping has to be scheduled (or run as a job) in a Spring context. This program might be horizontally scaled over multiple AWS instances running REST server described above.
Question:
I have following options to run the email reading, scraping job.
1. Develop a REST endpoint that is intended to do this operation and a CRON Job that runs a script which makes this REST call periodically.
2. Check the feasibility of using Spring Batch that initiate the job which directly invoke the Service - Spring Data components to persist data.
Please suggest if Spring Batch makes a good architectural choice here considering scalability required for this component.
Thanks for your time! In case you have a parallel option, please suggest that too. :)
| |
doc_23534396
|
I know there are lots of questions and answers about intervals in StackOverflow, but none of them use a Type to implement a timer, and I cannot find a solution for my problem. Could anyone explain what's the reason my timer doesn't keep tick-ing.
var TIMER;
var Timer = function (ms, interval, $timer) {
this.ms = ms;
this.interval = interval;
this.$timer = $timer;
this.counter = null;
this.start = function () {
this.counter = window.setInterval(this.tick(), this.interval);
};
this.tick = function () {
this.ms -= this.interval;
console.log(this.ms);
this.trigger('tick');
console.log("ticking...");
if (this.ms < 0) {
this.ms = 0;
}
if (this.ms == 0) {
window.clearInterval(this.counter);
}
};
this.hold = function () {
};
this.expire = function () {
};
this.trigger = function (event) {
if (typeof event === 'string') {
var e = jQuery.Event(event);
this.trigger(e);
} else {
this.$timer.trigger(event);
}
}
};
var initTimerPlugin = function () {
var $timer = $('<div class="timer">');
TIMER = new Timer(30000, 100, $timer);
$timer.on('tick', function () {
console.log('hello world');
});
TIMER.start();
};
$(document).ready(initTimerPlugin);
FYI: the JQuery version I use is 3.2.1.
| |
doc_23534397
|
I'm now trying to create an expandable search that looks like the one in the pic below
and this is what i've got so far
<style name="AppSearchView" parent="Widget.AppCompat.Light.SearchView">
<item name="searchIcon">@drawable/ic_search</item>
<item name="queryBackground">@null</item>
<item name="searchHintIcon">@null</item>
<item name="queryHint">@string/search_hint</item>
</style>
is that possible to do it?
Thanks
A: Make sure that you have the following attributes in your search menu item if not add it
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
| |
doc_23534398
|
enum MyError: ErrorType {
// .. cases
}
extension SignalType where Error: MyError {
// my exetensions her
}
But I keep getting error like this
Type 'Error' constrained to non-protocol type 'MyError'
This is really odd, if you look at ErrorType definition
public protocol ErrorType {
}
As it's a protocol, then why the compiler complaining it's a non-protocol type, any idea?
A: You're right, but MyError is not a protocol, which is what the error says.
When you use this syntax:
extension SignalType where Error: MyError
You're saying: extension for any SignalType whose Error conforms to MyError. But that's impossible. What you need is:
extension SignalType where Error == MyError
Which reads: extension for any SignalType whose Error is MyError.
| |
doc_23534399
|
Eg: TestMethod1 is as below:
I am having a registration form in that I am having a username field.
I am passing username: "Test123" with sendkeys() ----->(this is coming from excel)
now if I rerun the script I got an error as "Username already exist please enter unique username"
for this problem, I created a function for appending a random string to the username. so the new username will be "Test123SomeRandomstring" ----> This is stored in the string variable in TestMethod1
Now I am having an issue with my next test method which is as below (TestMethod2) which is login TestMethod:
Now When I am trying to Login with the help of the username I need that string variable from TestMethod1 to be used for login in TestMethod2.
Can Anyone Help with this?
Thanks in Advance.
Note: I have to create the above code in C# only
[TestMethod]
public virtual void TestRegristration()
{
try
{
LoginPage ObjLoginPage = LoginPage.GetInstance(this);
var generator = new GenerateRandomString();
var randomString = generator.RandomString();
ObjLoginPage.enterUserName(1, ObjExcelHelper, Driver, "UserName",randomString);//Enter Usernamewith some random string
ObjLoginPage.enterPassword(1, ObjExcelHelper, Driver, "Password");//Enter Password, Confirm Password and Click Register Button
}
catch (Exception ex)
{
ex.ToString();
}
}
[TestMethod]
public virtual void TestLoginWithValidCredential()
{
try
{
LoginPage ObjLoginPage = LoginPage.GetInstance(this);
ObjLoginPage.enterUserName(1, ObjExcelHelper, Driver, "UserName");//need to pass randomString here with username from TestMethod1
//ObjLoginPage.enterPassword(1, ObjExcelHelper, Driver, "Password");
}
catch (Exception ex)
{
ex.ToString();
}
}
public class GenerateRandomString
{
public string RandomString()
{
int length = 5;
// creating a StringBuilder object()
StringBuilder str_build = new StringBuilder();
Random random = new Random();
char letter;
for (int i = 0; i < length; i++)
{
double flt = random.NextDouble();
int shift = Convert.ToInt32(Math.Floor(25 * flt));
letter = Convert.ToChar(shift + 65);
str_build.Append(letter);
}
//System.Console.WriteLine(str_build.ToString());
return str_build.ToString();
}
}
A: Ideally individual tests should be self contained and you should not rely on the test order.
The next best thing is the constructor. In MS Test the constructor is called once.
The also is ClassInitializeAttribute Class or event AssemblyInitialize attribute (but they are static which I find limiting). Here are the official Examples:
[TestClass()]
public sealed class DivideClassTest
{
[AssemblyInitialize()]
public static void AssemblyInit(TestContext context)
{
MessageBox.Show("AssemblyInit " + context.TestName);
}
[ClassInitialize()]
public static void ClassInit(TestContext context)
{
MessageBox.Show("ClassInit " + context.TestName);
}
However for your scenario maybe a string, possibly static readonly is enough.
private static readonly Test UserId = ...
A helper method could create the user if it doesn't exist or gets the id if it already exists.
Update
[TestClass()]
public class MyTestClass
{
private string TestId {get; set;}
public MyTestClass()
{
var generator = new GenerateRandomString();
TestId = generator.RandomString();
[TestMethod]
public void TestRegristration()
{
...
ObjLoginPage.enterUserName(1, ObjExcelHelper, Driver, "UserName",TestId );
or
[TestClass()]
public class MyTestClass
{
private static string TestId {get; set;}
[ClassInitialize()]
public static void ClassInit(TestContext context)
{
var generator = new GenerateRandomString();
TestId = generator.RandomString();
}
[TestMethod]
public void TestRegristration()
{
...
ObjLoginPage.enterUserName(1, ObjExcelHelper, Driver, "UserName",TestId );
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.