_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d19301 | test | The string "hostednetwork" will never be the same as the string "started"
Also, you have a syntax error with your elsestatement. Nevertheless, you don't need it:
netsh wlan show hostednetwork|find "Status"|find "started">nul && goto stop || goto start
A: For anyone who would like to use this method, here is the complete working code
@ECHO OFF
netsh wlan show hostednetwork|find "Status"|find "Started">nul && goto stop || goto start
:start
netsh wlan start hostednetwork
goto end
:stop
netsh wlan stop hostednetwork
goto end
:end
PAUSE
Thanks to those who put into the creation of this method | unknown | |
d19302 | test | Only set the cycle on one of the slideshows; then use the after callback to transition the other one to the corresponding slide:
after: function(currSlideElement, nextSlideElement, options, forwardFlag) {
// your code here
} | unknown | |
d19303 | test | You can use ToByteArray() function and then the Guid constructor.
byte[] buffer = Guid.NewGuid().ToByteArray();
buffer[0] = 0;
buffer[1] = 0;
buffer[2] = 0;
buffer[3] = 0;
Guid guid = new Guid(buffer);
A: Since the Guid struct has a constructor that takes a byte array and can return its current bytes, it's actually quite easy:
//Create a random, new guid
Guid guid = Guid.NewGuid();
Console.WriteLine(guid);
//The original bytes
byte[] guidBytes = guid.ToByteArray();
//Your custom bytes
byte[] first4Bytes = BitConverter.GetBytes((UInt32) 0815);
//Overwrite the first 4 Bytes
Array.Copy(first4Bytes, guidBytes, 4);
//Create new guid based on current values
Guid guid2 = new Guid(guidBytes);
Console.WriteLine(guid2);
Fiddle
Keep in mind however, that the order of bytes returned from BitConverter depends on your processor architecture (BitConverter.IsLittleEndian) and that your Guid's entropy decreases by 232 if you use the same number every time (which, depending on your application might not be as bad as it sounds, since you have 2128 to begin with).
A: The question is about replacing bits, but if someone wants to replace first characters of guid directly, this can be done by converting it to string, replacing characters in string and converting back. Note that replaced characters should be valid in hex, i.e. numbers 0 - 9 or letters a - f.
var uniqueGuid = Guid.NewGuid();
var uniqueGuidStr = "1234" + uniqueGuid.ToString().Substring(4);
var modifiedUniqueGuid = Guid.Parse(uniqueGuidStr); | unknown | |
d19304 | test | Avoid shell=True, it leads to security issues. And it is also at the root of your problem, as the $1 is interpreted.
Do this instead:
subprocess.check_output(["stat", filename]) | unknown | |
d19305 | test | You can simply limit the queryset for those fields by overriding the init method in the PersonAdminForm class:
class PersonAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PersonAdminForm, self).__init__(*args, **kwargs)
self.fields['fathers'].queryset = Person.objects.filter(sex='m')
self.fields['mothers'].queryset = Person.objects.filter(sex='f') | unknown | |
d19306 | test | try this
int actionBarBackground = getResources().getColor(R.color.actionBarBackground);
and you set actionBarBackground in the method setColorFilter thats all
A: Answer marked as "right" use getColor() method which is deprecated.
That's why here is up-to-date answer:
int color = ResourcesCompat.getColor(getResources(), R.color.my_color, null);
A: please add PorterDuff.Mode.MULTIPLY See below example
viewHolder.Icon.getDrawable().setColorFilter(getResources().getColor(R.color.blue), PorterDuff.Mode.MULTIPLY ); | unknown | |
d19307 | test | Usually component routing doesn't reload because angular works as SPA(single page application) - but you can make your components to load in order to reduce the browser size if that is the only case
Use href and your path name insted of routerLink on your sidebar anchor link - this will make your component to reload everytime when you click - everytime it will load all your js from server - if you are using lazy load this process is not the right way - this will only helps you to reduce the browser RAM usage on every click and doesn't maintain any previous data but routing will work as the same
So href will be the word for your question - but make sure that you really want to load your components
Hope it helps - Happy Coding:)
A: If you want to reload the entire page, just use
window.location.reload(); | unknown | |
d19308 | test | [myTextField becomeFirstResponder] will probably do what you want.
A: That would be a little tricky to do. The controls in iPhone use the concept of "first responders" Any events will be handled by the first responder in the controller. Now, when an alert view is displayed, it becomes the first responder so it can respond to button clicks. When a text field is selected by the user, the keyboard gets the control. So I guess what you want to achieve can be done by making the text field the first responder after showing the alert ([txtField becomeFirstResponder])
But I have no idea how the alert view's responses will be handled then. You won't be able to click the OK button on the alert view till the keyboard is dismissed and you resign the first responder of the text field. ([txtField resignFirstResponder]) (This is just a guess, you will have to check the final behavior)
A: [myTextField becomeFirstResponder] works -- I tested it. | unknown | |
d19309 | test | You cannot do this on a stock device. Your best bet is to create a launcher that only allows launching your app. The user needs to agree to run it however, and it can always be changed and/or disabled in Settings. | unknown | |
d19310 | test | after long research, we found out, that this behavior sources in the smart screen filter.
if smartscreen is disabled, then it just won't work (with no error and no message). as soon as smartscreen is enabled, everything works as designed.
according to microsoft, this is by design and won't be changed (as large companies would ever allow smartscreen -.-) | unknown | |
d19311 | test | I'd try Apache POI, the Java API for Microsoft documents. Its based on Java and I've seen it used in Android before.
I haven't used it myself though, so I can't accredit to how well it works.
A: Check out the source code of APV - it's a PDF viewer based on MuPdf library - both are free. You can probably assemble something quickly. | unknown | |
d19312 | test | Technically you are violating the Rules of Hooks. You should move out useToast from the function's body called toastTest into the root of your function component.
See my suggested solution below:
const App = () => {
const toast = useToast(); // useToast moved here from the function
const { register, handleSubmit, watch, errors } = useForm();
const onSubmit = data => {
console.log('data', data);
}
const toastTest = () =>
// please notice useToast is removed from here
// ... rest of the function's body
}
return <> { /* your return */ }</>
} | unknown | |
d19313 | test | I think you could search more on topic about asynchronous in javascript.
in general if you wish to wait for 2 or more action to complete before running another method. You could use Promise.all(), or nest the callback into callback hell or use async.series() library. Back to redux, you could make sure that all your queue has finished running before rendering( dispatch() )
Also my recommendation is to learn Promise instead of async library.
example case:
fetch().then( res => dispatch({type: "I_GET_THE_DATA", payload: res.data}))
you could even chain fetch if you want.
fetch(mealURL).then( res1 =>{
fetch(ingredientsURL).then(res2 => {
var meal_and_ingredients = {
meal: res1,
ingredients: res2
}
dispatch({type: "GET_TWO_DATA", payload: meal_and_ingredients})
})
}) | unknown | |
d19314 | test | If you are expecting to create an insert query where you don't want to provide an id and the database should generate it automatically based on table defination then you need to create insert query where you have to mention columns names.
Example
INSERT INTO <TABLENAME>(COLUMN1, COLUMN2, COLUMN3, COLUMN4)
VALUES
(VALUE1,VALUE2, VALUE 3,VALUE 4);
So in ur case it should be
INSERT INTO PATIENT(FirstName,MiddleName,LastName,E_mail)
values
('myname','mymiddlename','mylastname','myemailid');
Sequence of column names and their values are very important. They should match exactly. If you don't provide a value for one of column and if its is auto increment, then DB will add an value to it else it will add null value. | unknown | |
d19315 | test | Google Translate says he said:
"Matus know the těchhle point I stopped, I'm a beginner and do not know what I stand on it all night"
Sounds like you need to read up on some JavaScript and jQuery tutorials. I began with something like this: jQuery for Absolute Beginners: The Complete Series
Really hope this helps.
A: You have a number of problems you need to solve.
Break them down into smaller chunks and tackle it from there.
Only numbers
You could watch the field (check out .on) for a change and then delete any character that's not part of the set [\d] or [0-9], but that could get messy.
A better idea might be to watch for a keydown event and only allow the keys that represent numbers.
The Dot
Trying to dynamically stop the user from deleting the dot is messy, so let's just focus on adding it back in when the field is blurred.
That's pretty easy, right? Just check for a . and if there isn't one, append ".00" to the end of the field.
Decimal Places
This is really the same problem as above. You can use .indexOf('.') to determine if the dot is present, and if it is, see if there are digits after it. If not, append "00" if so, make sure there's 2 digits, and append a "0" if there's only 1.
String Pattern
This could really be solved any number of ways, but you can reuse your search for the decimal place from above to split the string into "Full Dollar" and "Decimal" parts.
Then you can use simple counting on the "Full Dollar" part to add spaces. Check out the Javascript split and splice functions to insert characters at various string indexes.
Good luck! | unknown | |
d19316 | test | tried reconstructing it and it seems to work, clicking on the link opens a new tab with the new url.
https://plnkr.co/edit/gy4eIKn02uF0S8dLGNx2?p=preview
<a target="_blank" ng-href="{{someService.someProperty.href}}" ng-click="someService.someMethod()">
Hello!
<br/>
{{someService.someProperty.href}}
</a>
A: You can do it as like the below code
;(function(angular) {
angular.module('myApp.directives')
.directive('myExample', myExample);
myExample.$inject = ['$timeout'];
function myExample($timeout) {
return {
restrict: 'A',
scope: {
myExample: '&',
ngHref: '='
},
link: function(scope, element, attrs) {
element.on('click', function(event) {
event.preventDefault();
$timeout(function() {
scope.myExample();
scope.$apply();
var target = attrs.target || '_blank';
var url = scope.ngHref;
angular.element('<a href="' + url + '" target="' + target + '"></a>')[0].click();
});
});
}
};
}
})(angular);
In Controller
;(function(angular) {
'use strict';
angular.module('myApp.controllers').controller('HomeController', HomeController);
HomeController.$inject = ['$scope'];
function HomeController($scope) {
$scope.url = 'http://yahoo.com';
$scope.someFunction = function() {
$scope.url = 'http://google.com';
};
}
})(angular);
In HTML You can use like
<div ng-controller="HomeController">
<a ng-href="url" my-example="someFunction()" target="_blank">Click me to redirect</a>
</div>
Here instead of ng-click I have used custom directive which simulates the ng-click but not as exactly as ng-click
If the parent scope function is async you change your directive and someFunction in controller as like below
@Directive
;(function(angular) {
angular.module('myApp.directives')
.directive('myExample', myExample);
myExample.$inject = ['$timeout'];
function myExample($timeout) {
return {
restrict: 'A',
scope: {
myExample: '&',
ngHref: '='
},
link: function(scope, element, attrs) {
element.on('click', function(event) {
event.preventDefault();
scope.myExample().then(function() {
$timeout(function() {
scope.$apply();
var target = attrs.target || '_blank';
var url = scope.ngHref;
angular.element('<a href="' + url + '" target="' + target + '"></a>')[0].click();
});
});
});
}
};
}
})(angular);
@Controller
;(function(angular) {
'use strict';
angular.module('myApp.controllers').controller('HomeController', HomeController);
HomeController.$inject = ['$scope', '$q'];
function HomeController($scope, $q) {
$scope.url = 'http://yahoo.com';
$scope.someFunction = function() {
var deferred = $q.defer();
$scope.url = 'http://google.com';
deferred.resolve('');
return deferred.promise;
};
}
})(angular);
Here I just simulated the async, it may be your http call too
A: make sure the value in href tag is updated after you click on it. Try debugging the ng-click function. According to the official documentation:
Using AngularJS markup like {{hash}} in an href attribute will make the link go to the wrong URL if the user clicks it before AngularJS has a chance to replace the {{hash}} markup with its value. Until AngularJS replaces the markup the link will be broken and will most likely return a 404 error. The ngHref directive solves this problem.
In your case, i think the old link is not getting updated with the new values of the model. Hence, redirecting to old link.
A: Try calling a function on ui-sref or ng-href which will return the state name that you want to redirect. Something like this
html:
<a ui-href="{{GetUpdatedHref()}}" >Hello!</a>
controller.js
$scope.GetUpdatedHref = function(){
//perform your http call while it's being processed show a loader then finally return the desired state (page location)
return "main.home"
}
If this doesn't work for you use ng-click instead of ui-sref and then $state.go("main.home") inside function.
Hope this may resolve your problem. | unknown | |
d19317 | test | You need to do some special encoding with the names. The following is an example.
Let's suppose the length of all names are less than 100 characters. For each name, do the following steps to encode it:
*
*record the indices of upper case letters with 2 digits: for BeNd, the indices are 00 and 02.
*convert upper case letters of the name into lower cases to get a lower case name: from BeNd to bend
*append the indices to the lower case name to get the encoded name: from bend to bend0002
*add the encoded name into the sorted set: zadd key 0 bend0002
In this way, BeNd and bend should be ordered side by side.
When you want to do the search, use the same encoding method to encode the given name, do the search, and decode the results. Since the encoded name records the indices of upper case letters, you can decode it easily. | unknown | |
d19318 | test | You need to setup your environment:
*
*First, install Command Line Tools for Xcode (I'm not 100% sure that you can install without XCode, if not then install XCode from App Store).
*Then install MacPorts
To complete macports setup run this command in Terminal.app:
% sudo port selfupdate
If you done, then you can install scapry from macports:
% sudo port install py27-scrapy
Afther this you should be able to use scrapy command in Terminal.app. | unknown | |
d19319 | test | not sure about the specific error, as it should have the same issue for vanilla and anaconda spark, however, a couple of things you can check:
Make sure the same python version is installed on both your drivers and workers. Different versions can cause issues with serialization.
IPYTHON_OPTS is generally deprecated. Instead I define the following environment variables:
# tells pyspark to use notebook
export PYSPARK_DRIVER_PYTHON_OPS="notebook"
# tells pyspark to use the jupyter executable instead of python. In your case you might want this to be ipython instead
export PYSPARK_DRIVER_PYTHON=/opt/anaconda2/bin/jupyter
# tells pyspark where the python executable is on the executors. It MUST be the same version of python (preferably with the same packages if you are using them in a UDF or similar
export PYSPARK_PYTHON=/opt/anaconda2/bin/python
Of course I see you are not adding a master to the command line so this would run spark locally if you haven't changed you spark defaults (i.e. no workers). | unknown | |
d19320 | test | *
*you can use animations to split into frames
*have sliced numpy array to create frames
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
xg = np.random.rand(100, 22400)
# xg = np.random.rand(10, 1200)
base = px.imshow(xg, aspect="auto", color_continuous_scale="gray")
frameSize = 400
frames = [
go.Frame(
data=px.imshow(
xg[:, x : x + frameSize], aspect="auto", color_continuous_scale="gray"
).data,
name=x,
)
for x in range(0, xg.shape[1], frameSize)
]
go.Figure(data=frames[0].data, frames=frames, layout=base.layout).update_layout(
updatemenus=[{
"buttons": [{"args": [None, {"frame": {"duration": 500, "redraw": True}}],
"label": "▶",
"method": "animate",
},],
"type": "buttons",
}],
sliders=[{
"steps": [{"args": [[d],
{"frame": {"duration": 0, "redraw": True},
"mode": "immediate",},],
"label": d,
"method": "animate",
}
for d in range(0, xg.shape[1], frameSize)
],
}],
) | unknown | |
d19321 | test | One ruleset:
table.table.stats {display:inline-table}
display: inline-table behavior is simply a table that will sit inline with elements instead of the default behavior of occupying the whole width and pushing everything at its left and right -- up and down.
you might have a more complicated environment with your real code so you can
Chain the classes to get higher specificity which may be overkill but with Bootstrap it is common necessity.
table.table.stats.table.stats {display:inline-table}
Demo
table.table.stats {
display: inline-table
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="row">
<div class="col-xs-6">
<h2>Specifications</h2>
<table class="table stats">
<tbody>
<tr>
<th>Price :</th>
<td class=" text-right">
100 </td>
</tr>
<tr>
<th>Manufacturer:</th>
<td class=" text-right">
Gigabyte </td>
</tr>
<tr>
<th>Wattage:</th>
<td class=" text-right">
150 </td>
</tr>
<tr>
<th>Product:</th>
<td class=" text-right">
Product 1 </td>
</tr>
</tbody>
</table>
</div>
<div class="col-xs-6">
<h2>Earning</h2>
<table class="table stats">
<tbody>
</tbody>
<thead>
<tr>
<th>Period</th>
<th class="text-right">Rev</th>
<th class="text-right">Cost</th>
<th class="text-right">Profit</th>
</tr>
</thead>
<tbody>
<tr>
<td>Hour</td>
<td class="text-right text-info">$
<span id="rev-hour">
0.022 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-hour">
0.006 </span>
</td>
<td class="text-right text-success">$
<span id="earning-hour">
0.016 </span>
</td>
</tr>
<tr>
<td>Day</td>
<td class="text-right text-info">$
<span id="rev-day">
1.34 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-day">
0.36 </span>
</td>
<td class="text-right text-success">$
<span id="earning-day">
0.98 </span>
</td>
</tr>
<tr>
<td>Week</td>
<td class="text-right text-info">$
<span id="rev-week">
9.37 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-week">
2.52 </span>
</td>
<td class="text-right text-success">$
<span id="earning-week">
6.85 </span>
</td>
</tr>
<tr>
<td>Month</td>
<td class="text-right text-info">$
<span id="rev-month">
37.48 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-month">
10.08 </span>
</td>
<td class="text-right text-success">$
<span id="earning-month">
27.40 </span>
</td>
</tr>
<tr>
<td>Year</td>
<td class="text-right text-info">$
<span id="rev-year">
449.77 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-year">
120.96 </span>
</td>
<td class="text-right text-success">$
<span id="earning-year">
328.81 </span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
A: Add the container-fluid class div around the row.
There is no such class as col-xs-6 instead use col-6
Added another div in col-6 and add padding to it for making some space between them.
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container-fluid">
<div class="row">
<div class="col-6">
<div class="pr-1">
<h2>Specifications</h2>
<table class="table stats">
<tbody>
<tr>
<th>Price :</th>
<td class=" text-right">
100 </td>
</tr>
<tr>
<th>Manufacturer:</th>
<td class=" text-right">
Gigabyte </td>
</tr>
<tr>
<th>Wattage:</th>
<td class=" text-right">
150 </td>
</tr>
<tr>
<th>Product:</th>
<td class=" text-right">
Product 1 </td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-6">
<div class="pr-1">
<h2>Earning</h2>
<table class="table stats">
<tbody>
</tbody>
<thead>
<tr>
<th>Period</th>
<th class="text-right">Rev</th>
<th class="text-right">Cost</th>
<th class="text-right">Profit</th>
</tr>
</thead>
<tbody>
<tr>
<td>Hour</td>
<td class="text-right text-info">$
<span id="rev-hour">
0.022 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-hour">
0.006 </span>
</td>
<td class="text-right text-success">$
<span id="earning-hour">
0.016 </span>
</td>
</tr>
<tr>
<td>Day</td>
<td class="text-right text-info">$
<span id="rev-day">
1.34 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-day">
0.36 </span>
</td>
<td class="text-right text-success">$
<span id="earning-day">
0.98 </span>
</td>
</tr>
<tr>
<td>Week</td>
<td class="text-right text-info">$
<span id="rev-week">
9.37 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-week">
2.52 </span>
</td>
<td class="text-right text-success">$
<span id="earning-week">
6.85 </span>
</td>
</tr>
<tr>
<td>Month</td>
<td class="text-right text-info">$
<span id="rev-month">
37.48 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-month">
10.08 </span>
</td>
<td class="text-right text-success">$
<span id="earning-month">
27.40 </span>
</td>
</tr>
<tr>
<td>Year</td>
<td class="text-right text-info">$
<span id="rev-year">
449.77 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-year">
120.96 </span>
</td>
<td class="text-right text-success">$
<span id="earning-year">
328.81 </span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div> | unknown | |
d19322 | test | Use find(sub_str) function.
new_list = [item[item.find("eww"):] for item in List]
print(new_list)
Output:
['eww/d/df/rr/e.jpg', 'eww/ees/err/err.jpg', 'eww/err/dd.jpg']
A: new_list2=[item[item.find('eww'):item.rfind('/')+1] for item in List]
print(new_list2)
output= ['eww/d/df/rr/', 'eww/ees/err/', 'eww/err/']
A: Here are the steps I would do:
*
*split the string after eww
assuming that each string contains 'eww' you can split the string like this: split = 'eww'+string.split('eww')[1]
*Now, you have to loop over each character in the remaining string and save the index of the last /
*Remove everything after the last / with the index from step 3: split = split[:splitIndex]
*Now, you just have to put everything in a loop that iterates over the list and execute each of the steps above on each element of the list and save the modified string to the ModiefiedList list.
A: You can use a regex in a list comprehension.
A perfect use case for the new walrus operator (python ≥3.8):
List=['a/c/d/eww/d/df/rr/e.jpg',
'ss/dds/ert/eww/ees/err/err.jpg',
'fds/aaa/eww/err/dd.jpg']
import re
out = [m.group() if (m:=re.search('eww/(.*)/', s)) else s
for s in List]
output:
['eww/d/df/rr/', 'eww/ees/err/', 'eww/err/']
NB. this keeps the original string in case of no match, if you rather want to drop it:
out = [m.group() for s in List if (m:=re.search('eww/(.*)/', s))] | unknown | |
d19323 | test | The reason is you don't add a spy on _performLogic method.
You can use jest.spyOn(object, methodName) method to spy on the _performLogic method.
E.g.
index.js:
function Thing() {}
Thing.prototype.getStuff = function() {
return new Promise((resolve, reject) => {
this.getOtherStuff().then(data => {
this._performLogic();
const goodstuff = data;
resolve({ newdata: goodstuff });
});
});
};
Thing.prototype.getOtherStuff = function() {
console.log("real get other stuff");
};
Thing.prototype._performLogic = function() {
console.log("real perform logic");
};
module.exports = Thing;
index.spec.js:
const Thing = require(".");
describe("Thing", () => {
describe("#getStuff", () => {
afterEach(() => {
jest.restoreAllMocks();
});
it("should pass", async () => {
// make a stub
jest
.spyOn(Thing.prototype, "getOtherStuff")
.mockImplementationOnce(() => Promise.resolve({ data: "value" }));
// add a spy
jest.spyOn(Thing.prototype, "_performLogic");
let instance = new Thing();
await instance.getStuff();
expect(Thing.prototype._performLogic).toHaveBeenCalled();
expect(Thing.prototype.getOtherStuff).toBeCalledTimes(1);
});
});
});
Unit test result with coverage report:
PASS src/stackoverflow/59148901/index.spec.js (7.573s)
Thing
#getStuff
✓ should pass (12ms)
console.log src/stackoverflow/59148901/index.js:375
real perform logic
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 91.67 | 100 | 83.33 | 90.91 | |
index.js | 91.67 | 100 | 83.33 | 90.91 | 14 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.013s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59148901 | unknown | |
d19324 | test | You need to add Woodstox to the classpath, see the accepted answer here: https://stackoverflow.com/a/24603135/3745288 | unknown | |
d19325 | test | Using Object#keys:
const getPropertyNames = (arr = []) => arr.length > 0 ? Object.keys(arr[0]) : [];
const data = [ { "name": "Tiger Nixon", "position": "System Architect", "salary": "320800", "start_date": "2011\/04\/25", "office": "Edinburgh", "rating": "5421" }, { "name": "Garrett Winters", "position": "Accountant", "salary": "170750", "start_date": "2011\/07\/25", "office": "Tokyo", "rating": "8422" }, { "name": "Ashton Cox", "position": "Junior Technical Author", "salary": "86000", "start_date": "2009\/01\/12", "office": "San Francisco", "rating": "1562" }, { "name": "Cedric Kelly", "position": "Senior Javascript Developer", "salary": "433060", "start_date": "2012\/03\/29", "office": "Edinburgh", "rating": "6224" } ];
console.log( getPropertyNames(data) ); | unknown | |
d19326 | test | Not long ago, all Doctrine bundles moved to the Doctrine organizaton. This causes some confusion based on which repository and branch you are using.
If you're using Symfony 2.0.x, then your deps should look something like this:
[DoctrineFixturesBundle]
git=http://github.com/doctrine/DoctrineFixturesBundle.git
target=bundles/Symfony/Bundle/DoctrineFixturesBundle
version=origin/2.0
Notice the target/namespace is actually Symfony\Bundle\DoctrineFixturesBundle.
However, you shouldn't have any problems using the latest DoctrineFixturesBundle with Symfony 2.0.x - as long as you upgrade the rest of the Doctrine dependencies also. You can use this in your deps instead:
[doctrine-common]
git=http://github.com/doctrine/common.git
version=2.2.0
[doctrine-dbal]
git=http://github.com/doctrine/dbal.git
version=2.2.1
[doctrine]
git=http://github.com/doctrine/doctrine2.git
version=2.2.0
[doctrine-fixtures]
git=http://github.com/doctrine/data-fixtures.git
[DoctrineFixturesBundle]
git=http://github.com/doctrine/DoctrineFixturesBundle.git
target=bundles/Doctrine/Bundle/FixturesBundle | unknown | |
d19327 | test | Short Answer : There are no such mapping.
Some rules might rely on those metrics (for instance an issue can be raised if coverage is <= X% (even though it is better to rely on quality gate for this)) but those metrics are distinct from rules. | unknown | |
d19328 | test | I hope it helps, And not too late.
TAG POS=1 TYPE=INPUT:HIDDEN ATTR=NAME:_RequestVerificationToken* EXTRACT=TXT | unknown | |
d19329 | test | System.out.println(new BigDecimal("58.15"));
To construct a BigDecimal from a hard-coded constant, you must always use one of constants in the class (ZERO, ONE, or TEN) or one of the string constructors. The reason is that one you put the value in a double, you've already lost precision that can never be regained.
EDIT: polygenelubricants is right. Specifically, you're using Double.toString or equivalent. To quote from there:
How many digits must be printed for
the fractional part of m or a? There
must be at least one digit to
represent the fractional part, and
beyond that as many, but only as many,
more digits as are needed to uniquely
distinguish the argument value from
adjacent values of type double. That
is, suppose that x is the exact
mathematical value represented by the
decimal representation produced by
this method for a finite nonzero
argument d. Then d must be the double
value nearest to x; or if two double
values are equally close to x, then d
must be one of them and the least
significant bit of the significand of
d must be 0.
A: Yes, println (or more precisely, Double.toString) rounds. For proof, System.out.println(.1D); prints 0.1, which is impossible to represent in binary.
Also, when using BigDecimal, don't use the double constructor, because that would attempt to precisely represent an imprecise value. Use the String constructor instead.
A: out.println and Double.toString() use the format specified in Double.toString(double).
BigDecimal uses more precision by default, as described in the javadoc, and when you call toString() it outputs all of the characters up to the precision level available to a primitive double since .15 does not have an exact binary representation. | unknown | |
d19330 | test | If you are currently using Request("ParameterName") to retrieve parameters then you should change to Request.Form("ParameterName") which will only get the parameter if it was POSTed.
Alternatively you can lookup the method used to access the page from the Request.ServerVariables collection and end the script if it is not POST. Here's an example:
If Request.ServerVariables("REQUEST_METHOD") <> "POST" Then Response.End
I noticed that you also said that you want to accept posts only from your server. The above changes will still allow another webpage to be set up to POST to your page. If you want to ensure that only your web page can post then you will need to add some more protection. Here's one way of doing it.
1) When you render your form create a random numbers and create a session variable named by the random number with a value to check for later.
Randomize
strVarName = Int((999999 - 100000 + 1) * Rnd() + 100000)
Session(strVarName) = "Authorised"
2) In your form add a hidden field with the value of the random number.
<input type="hidden" name="varname" value="<%= strVarName %>" />
3) In the script that processes the posted form get the value of the hidden field.
strVarName = Request.Form("varname")
4) Check that the session variable is set and has a value of True.
If Session(strVarName) <> "Authorised" Then
'Failed! Either show the user an error message or stop processing
Response.End
End If
5) Remove the session variable so that the same form cannot be resubmitted.
Session.Items.Remove(strVarName)
You don't need the random number but using it means that the same user can have multiple forms open in different windows/tabs and each one will work. | unknown | |
d19331 | test | you can import the ecore metamodel and thus its datatypes using import "http://www.eclipse.org/emf/2002/Ecore" as ecore. Then you can use them as return value in a terminal or datatype rule LONG returns ecore::ELong: INT ("L"|"l");. Finally you have to implement a ValueConverter that does the Convertion from String to Long and Vice Versa
public class MyDslValueConverters extends DefaultTerminalConverters {
IValueConverter<Long> longValueConverter = new IValueConverter<Long>() {
@Override
public Long toValue(String string, INode node) throws ValueConverterException {
// TODO make this more robust
return Long.parseLong(string.substring(0, string.length()-1));
}
@Override
public String toString(Long value) throws ValueConverterException {
// TODO make this more robust
return Long.toString(value)+"L";
}
};
@ValueConverter(rule = "LONG")
public IValueConverter<Long> LONG() {
return longValueConverter;
}
}
And dont forget the binding
class MyDslRuntimeModule extends AbstractMyDslRuntimeModule {
override bindIValueConverterService() {
return MyDslValueConverters
}
} | unknown | |
d19332 | test | It's possible, yes. You'd need to setup two advertised.listeners and listeners on the brokers with a protocol of and SSL for one set and SASL_SSL / SASL_PLAINTEXT for the other.
It's kubernetes network policies that control how cluster access happens, not only Kafka, but also, you'll need a NodePort or Ingress for any external app to reach services within the cluster. The Strimzi operator covers both, by the way | unknown | |
d19333 | test | You should add dev and prod variables to your settings.json file, and load them locally with meteor --settings settings.json. The settings.json file would look something like this:
{
"dev": {
"public": {
"facebook": {
"appId": "abc123"
}
},
"private": {
"facebook": {
"secret": "456def789"
}
}
},
"prod": {
"public": {
"facebook": {
"appId": "def234"
}
},
"private": {
"facebook": {
"secret": "789ghi101112"
}
}
}
You could then access them just as you were before: Meteor.settings.dev.public.facebook.appId.
The public/private may be overkill for your project (and I may have messed up the brackets), but this should convey the general concept. For more info, check out this oft-cited post. | unknown | |
d19334 | test | My suggestion for you is to catch on DbUpdateConcurrencyException and use entry.GetDatabaseValues(); and entry.OriginalValues.SetValues(databaseValues); into your retry logic. No need to lock the DB.
Here is the sample on EF Core documentation page:
using (var context = new PersonContext())
{
// Fetch a person from database and change phone number
var person = context.People.Single(p => p.PersonId == 1);
person.PhoneNumber = "555-555-5555";
// Change the person's name in the database to simulate a concurrency conflict
context.Database.ExecuteSqlCommand(
"UPDATE dbo.People SET FirstName = 'Jane' WHERE PersonId = 1");
var saved = false;
while (!saved)
{
try
{
// Attempt to save changes to the database
context.SaveChanges();
saved = true;
}
catch (DbUpdateConcurrencyException ex)
{
foreach (var entry in ex.Entries)
{
if (entry.Entity is Person)
{
var proposedValues = entry.CurrentValues;
var databaseValues = entry.GetDatabaseValues();
foreach (var property in proposedValues.Properties)
{
var proposedValue = proposedValues[property];
var databaseValue = databaseValues[property];
// TODO: decide which value should be written to database
// proposedValues[property] = <value to be saved>;
}
// Refresh original values to bypass next concurrency check
entry.OriginalValues.SetValues(databaseValues);
}
else
{
throw new NotSupportedException(
"Don't know how to handle concurrency conflicts for "
+ entry.Metadata.Name);
}
}
}
}
}
A: Why don't you handle the concurrency problem in the code, why it needs to be in the DB layer?
You can have a method that updates the value of given wallet with given value and you can use simple lock there. Like this:
private readonly object walletLock = new object();
public void UpdateWalletAmount(int userId, int amount)
{
lock (balanceLock)
{
Wallet w = _context.Wallets.Where(ww => ww.UserId == userId).FirstOrDefault();
w.Amount = w.Amount + amount;
w.Inserts++;
_context.Wallets.Update(w);
_context.SaveChanges();
}
}
So your methods will look like this:
[HttpGet]
[Route("request1")]
public async Task<string> request1()
{
try
{
UpdateWalletAmount(1, 10);
}
catch (Exception ex)
{
// log error
}
return "request 1 executed";
}
[HttpGet]
[Route("request2")]
public async Task<string> request2()
{
try
{
UpdateWalletAmount(1, 20);
}
catch (Exception ex)
{
// log error
}
return "request 2 executed";
}
You don't even need to use a transaction in this context.
A: You can use distributed lock mechanism with redis for example.
Also, you can lock by userId, it will not lock method for others. | unknown | |
d19335 | test | I was able to fix the issue by setting "equals" to "In a List".
here is the steps
In DataSets -> Query Designer -> Filter -> Any of section click on equals then select In a List | unknown | |
d19336 | test | Try the GROUP_CONCAT function supported by HSQLDB version 2.3.x and later. The HSQLDB syntax is different and documented here.
http://hsqldb.org/doc/2.0/guide/dataaccess-chapt.html#dac_aggregate_funcs
The example given in the Guide shows how you specify the grouping and ordering of the results;
SELECT LASTNAME, GROUP_CONCAT(DISTINCT FIRSTNAME ORDER BY FIRSTNAME DESC SEPARATOR ' * ') FROM Customer GROUP BY LASTNAME | unknown | |
d19337 | test | Most likely, you also need the mono runtime and all the support libraries that are needed.
Run your app once from the debugger (or at least deploy from within Visual Studio/Xamarin Studio), and you will
a) get a notice (in deploy output) about all the libraries/frameworks being installed before the app launches, this can actually take a minute before first launch
b) you have those supports installed for the future, so as long as you target the same framework version, you can simply directly install the .apks
Normally, you don't use .apks directly, since most often your first shot is not perfect anyway, so the debugging helps a lot. :) | unknown | |
d19338 | test | You cannot substract strings.
You should use a.prototype.localeCompare(b)
It will return 1 if a > b; -1 if b > a; and otherwise 0
In your example you should do following:
return source.sort((a, b) => {
if (a.orderBy && b.orderBy) {
return sortOrder === "asc" ? a.orderBy - b.orderBy : b.orderBy - a.orderBy;
}
return sortOrder === "asc" ? a.localeCompare(b) : b.localeCompare(a);
}); | unknown | |
d19339 | test | ASP.NET Scaffolding is expecting Entity Framework based Data Model classes in order to help you creating views/controllers . But you are using View Model ,view model doesn't been persist in a database and also it doesn't have any primary key field, hence it cannot be scaffolded. And also when using scaffold wizard you always need to choose data context . But a view model has no relationship with your data context.
You should use your actual data model instead of a viewmodel to perform scaffolding , then modify the codes to use view model to transfer data between views and controllers
Inside your controller action that you could map the view model back to your data model that will be persisted using EF. You could use AutoMapper to map between your view models and data models. | unknown | |
d19340 | test | I hope I understood your qusition. In this example I calculated the histogramm of one particle object. But if you wan't to do this for all 1e6 groups (1e4*1e4*1e6=1e14) comparisons, this would still take a few days.
In this example I used Numba to accomplish the task.
Code
import numpy as np
import numba as nb
import time
#From Numba source
#Copyright (c) 2012, Anaconda, Inc.
#All rights reserved.
@nb.njit(fastmath=True)
def digitize(x, bins, right=False):
# bins are monotonically-increasing
n = len(bins)
lo = 0
hi = n
if right:
if np.isnan(x):
# Find the first nan (i.e. the last from the end of bins,
# since there shouldn't be many of them in practice)
for i in range(n, 0, -1):
if not np.isnan(bins[i - 1]):
return i
return 0
while hi > lo:
mid = (lo + hi) >> 1
if bins[mid] < x:
# mid is too low => narrow to upper bins
lo = mid + 1
else:
# mid is too high, or is a NaN => narrow to lower bins
hi = mid
else:
if np.isnan(x):
# NaNs end up in the last bin
return n
while hi > lo:
mid = (lo + hi) >> 1
if bins[mid] <= x:
# mid is too low => narrow to upper bins
lo = mid + 1
else:
# mid is too high, or is a NaN => narrow to lower bins
hi = mid
return lo
#Variant_1
@nb.njit(fastmath=True,parallel=True)
def bincount_comb_1(pvel,pcoords,bins):
vlos_binned=np.zeros(bins.shape[0]+1,dtype=np.uint64)
for i in nb.prange(pvel.shape[0]):
for j in range(pvel.shape[0]):
if( (pcoords[i] - pcoords[j]) < 0.):
vlos = 0.
else:
vlos = (pvel[i] - pvel[j])
dig_vlos=digitize(vlos, bins, right=False)
vlos_binned[dig_vlos]+=1
return vlos_binned
#Variant_2
#Is this also working?
@nb.njit(fastmath=True,parallel=True)
def bincount_comb_2(pvel,pcoords,bins):
vlos_binned=np.zeros(bins.shape[0]+1,dtype=np.uint64)
for i in nb.prange(pvel.shape[0]):
for j in range(pvel.shape[0]):
#only particles which fulfill this condition are counted?
if( (pcoords[i] - pcoords[j]) < 0.):
vlos = (pvel[i] - pvel[j])
dig_vlos=digitize(vlos, bins, right=False)
vlos_binned[dig_vlos]+=1
return vlos_binned
#Variant_3
#Only counting once
@nb.njit(fastmath=True,parallel=True)
def bincount_comb_3(pvel,pcoords,bins):
vlos_binned=np.zeros(bins.shape[0]+1,dtype=np.uint64)
for i in nb.prange(pvel.shape[0]):
for j in range(i,pvel.shape[0]):
#only particles, where this condition is met are counted?
if( (pcoords[i] - pcoords[j]) < 0.):
vlos = (pvel[i] - pvel[j])
dig_vlos=digitize(vlos, bins, right=False)
vlos_binned[dig_vlos]+=1
return vlos_binned
#Create some data to test
bins=np.arange(2,32)
pvel=np.random.rand(10_000)*35
pcoords=np.random.rand(10_000)*35
#first call has compilation overhead, we don't measure this
res_1=bincount_comb_1(pvel,pcoords,bins)
res_2=bincount_comb_2(pvel,pcoords,bins)
t1=time.time()
res=bincount_comb_1(pvel,pcoords,bins)
print(time.time()-t1)
t1=time.time()
res=bincount_comb_2(pvel,pcoords,bins)
print(time.time()-t1)
t1=time.time()
res=bincount_comb_3(pvel,pcoords,bins)
print(time.time()-t1)
Performance
#Variant_1: 0.5s 5.78d for 1e6 groups of points
#Variant_2: 0.3s 3.25d for 1e6 groups of points
#Variant_3: 0.22s 2.54d for 1e6 groups of points | unknown | |
d19341 | test | Looks like the problem is that the server response is an object, but not an array.
// try to replace
this.httpClient.get<Employee[]>(...);
// by
this.httpClient.get<{ response: Employee[] }>(...).pipe(
map(response => response.response)
); | unknown | |
d19342 | test | Your unit tests shouldn’t include the Function App entry point, just like they shouldn’t include Asp.Net controllers, or the Main method of a Console app. | unknown | |
d19343 | test | Like <include> the only attributes that ViewStub lets you override are the layout attributes and which id the child view will have after inflation. | unknown | |
d19344 | test | The receiver for the invocation of doSomething() within run() is Outer.this. The synchronized will therefore lock the monitor on the object referenced by that expression.
On computing the target reference in a method invocation expression, the JLS says
Otherwise, let T be the enclosing type declaration of which the
method is a member, and let n be an integer such that T is the n'th
lexically enclosing type declaration of the class whose declaration
immediately contains the method invocation. The target reference is
the n'th lexically enclosing instance of this.
T here is Outer, since that's the class that declares it. n is 1, as Outer is the immediately enclosing type declaration of Inner. The target reference is therefore the 1'th lexically enclosing instance of this, ie. Outer.this.
Concerning synchronized methods, the JLS says
For an instance method, the monitor associated with this (the object
for which the method was invoked) is used. | unknown | |
d19345 | test | Path only contains information about where a file (or other thing) is located, it does not provide any information on how to process it. As you know the Path is a file then you can use the File class to process it, in this case to open a stream on it.
In language terms Path does not have a newOutputStream method so it will fail to compile.
From Oracle documentation on Path
Paths may be used with the Files class to operate on files, directories, and other types of files. | unknown | |
d19346 | test | This worked for me
Editor JS Links
Simply add as follows under tools:
embed: {
class: Embed,
config: {
services: {
instagram: true,
},
},
}, | unknown | |
d19347 | test | git reset --hard will bring you back to the last commit, and git reset --hard origin/master will bring you back to origin/master.
A: You can revert the change
Read more:
http://book.git-scm.com/4_undoing_in_git_-_reset,_checkout_and_revert.html
A: Another option is just to discard all your changes
git checkout .
And then
git pull | unknown | |
d19348 | test | The easiest way I found was to simply include the missing characters into the font and the re-use cufon. For this task I used the Glyph App - Demo version works perfectly for 30 days and you can export fonts without restriction. | unknown | |
d19349 | test | It seems that a lot of your widgets actually do not have constraints. Remove the tools:ignore="MissingConstraints" attribute to see the missing ones. Every widget needs to be constrained at least with two constraints (one for the vertical axis, one for the horizontal axis).
Things display correctly in the layout editor simply because it's much nicer to keep the widgets where you put them while you are designing things, even if they don't have constraints. But on device, those fixed positions are not used. | unknown | |
d19350 | test | I just finished wrestling with this for about three hours.
Okay, short answer (which marken, above, deserves credit for): Just right-click the dimmed out python3 executable, then click "Quick Look", then hit the space bar to exit the quick-look, and notice the executable is now selected, and just hit enter, or click "Choose".
I have the following explanation to offer. The reason for our ability to see--but not to select--the python3 executable is that Homebrew uses a file alias, /usr/local/bin/python3, which brew's installation is given restricted permissions that Xcode is unable to pre-select, for reasons I am unsure of. (You might notice you can tediously select the executable at each and every runtime.) The alias points, in my case, to the Homebrew "Cellar"; for your reference, using the Terminal app to execute,ls -al /usr/local/bin/python3 reveals that my it's aliased to the true Homebrew python3 executable located at /usr/local/Cellar/python3/3.5.2_3/bin/(python3).
A: In the file selection window right-click on python3.5 and select quick look. Close the quick look window and python3.5 will become selectable.
(images attached show workflow referencing the newer python3.6 - it is the same for all python releases).
Right click on python executable
Pop up window will be shown
Select quicklook
Python executable has been selectable and "choose" button is clickable
A: Just right click and Quick Look option works. File becomes selectable, and then you can choose to specify it as an executable in your Xcode project.
A: If you are using Anaconda, you can install the python.app package:
conda install python.app
Then, in Xcode, select </path/to/anaconda-environment>/python.app/Contents/MacOS/python.
(Note: Do not select the python.app in the bin directory (</path/to/anaconda-environment>/bin/python.app), which will result in some error regarding the Mach-O header.) | unknown | |
d19351 | test | How about using:
$args = func_get_args();
call_user_func_array('mysql_safe_query', $args);
A: N.B. In PHP 5.6 you can now do this:
function mysql_row_exists(...$args) {
$result = mysql_safe_query(...$args);
return mysql_num_rows($result) > 0;
}
Also, for future readers, mysql_* is deprecated -- don't use those functions.
A: Depending on the situation, following might also work for you and might be a little faster.
function mysql_safe_query($format) {
$args = func_get_args();
$args = is_array($args[0]) ? $args[0] : $args; // remove extra container, if needed
// ...
Which now allows for both types of calling, but might be problematic if your first value is supposed to be an actual array, because it would be unpacked either way.
You could additionally check on the length of your root-array, so it might not be unpacked if if there are other elements, but as mentioned: It is not really that "clean" in general, but might be helpful and fast :-) | unknown | |
d19352 | test | You could make a simple function:
bounds = (prop, min, max) ->
val = position[prop];
if (val < min)
dot.css prop, min
if (var > max)
dot.css prop, max
bounds 'left', dot_radius, display_width - dot_radius
bounds 'top', dot_radius, display_height - dot_radius
You even might put the dot_radius inside the function, though it gets less reusable then. | unknown | |
d19353 | test | I strongly suggest using the Boost C++ regex library. If you are developing serious C++, Boost is definitely something you must take into account.
The library supports both Perl and POSIX regular expression syntax. I personally prefer Perl regular expressions since I believe they are more intuitive and easier to get right.
http://www.boost.org/doc/libs/1_46_0/libs/regex/doc/html/boost_regex/syntax.html
But if you don't have any knowledge of this fine library, I suggest you start here:
http://www.boost.org/doc/libs/1_46_0/libs/regex/doc/html/index.html
A: I found the answer here:
#include <regex.h>
#include <stdio.h>
int main()
{
int r;
regex_t reg;
if (r = regcomp(®, "\\b[A-Z]\\w*\\b", REG_NOSUB | REG_EXTENDED))
{
char errbuf[1024];
regerror(r, ®, errbuf, sizeof(errbuf));
printf("error: %s\n", errbuf);
return 1;
}
char* argv[] = { "Moo", "foo", "OlOlo", "ZaooZA~!" };
for (int i = 0; i < sizeof(argv) / sizeof(char*); i++)
{
if (regexec(®, argv[i], 0, NULL, 0) == REG_NOMATCH)
continue;
printf("matched: %s\n", argv[i]);
}
return 0;
}
The code above will provide us with
matched: Moo
matched: OlOlo
matched: ZaooZA~!
A: Manuals should be easy enough to find: POSIX regular expression functions. If you don't understand that, I would really recommend trying to brush up on your C and C++ skills.
Note that actually replacing a substring once you have a match is a completely different problem, one that the regex functions won't help you with. | unknown | |
d19354 | test | There is a mesh to vtk converter which I used a while ago. | unknown | |
d19355 | test | you said: "But each object within those arrays does not contain information nested any further".
So there are not folder inside first-level folder. Did I understand correctly?
If so, why not to read the whole storage with chrome.storage.sync.get,
delete the substructure you want (i.e delete storage.folder_id or delete storage.file_id")
and finally save the trimmed object with chrome.storage.sync.set ?
Note that elements within chrome.storage are stored as a key + value pair, and it is not possible to delete a subtree directly with the remove method.
EDIT
I may have misunderstood one thing.
If you call await chrome.storage.sync.get(null) you get only one item called "storage" or you get one root item with several folders and files items?
If the right answer is one then my previous answer is still valid (you have to cut\trim the object and then save it at the end of the work in the chrome.storage).
If the right answer is two then the thing is simpler because you can directly delete any item using remove method and the object id without bothering recursion and other things. | unknown | |
d19356 | test | You can't do that without reflection, because the type T is erased at runtime (meaning it will be reduced to its lower bound, which is Base).
Since you do have access to a Class<T> you can do it with reflection, however:
return (String) clazz.getMethod("getStaticName").invoke(null);
Note that I'd consider such code to be code smell and that it is pretty fragile. Could you tell us why you need that?
A: If it is OK for you to pass an object instance rather than Class in your static accessor, then, there is a simple and elegant solution:
public class Test {
static class Base {
public static String getStaticName() { return "Base"; }
public String myOverridable() { return Base.getStaticName(); };
}
static class Child extends Base {
public static String getStaticName() { return "Child"; }
@Override
public String myOverridable() { return Child.getStaticName(); };
}
static class StaticAccessor {
public static <T extends Base>String getName(T instance) {
return instance.myOverridable();
}
}
public static void main(String[] args) {
Base b = new Base();
Child c = new Child();
System.out.println(StaticAccessor.getName(b));
System.out.println(StaticAccessor.getName(c));
}
}
The output is:
Base
Child
A: I don't believe you can do this without reflection.
It appears you should be doing is not using static methods. You are using inheritance but static methods do not follow inheritance rules. | unknown | |
d19357 | test | You can extract your data this way:
1> Message = [[<<>>],
1> [<<"10">>,<<"171">>],
1> [<<"112">>,<<"Gen20267">>],
1> [<<"52">>,<<"20100812-06:32:30.687">>]] .
[[<<>>],
[<<"10">>,<<"171">>],
[<<"112">>,<<"Gen20267">>],
[<<"52">>,<<"20100812-06:32:30.687">>]]
2> [Data] = [X || [<<"112">>, X] <- Message ].
[<<"Gen20267">>]
3> Data.
<<"Gen20267">>
Another way:
4> [_, Data] = hd(lists:dropwhile(fun([<<"112">>|_]) -> false; (_)->true end, Message)).
[<<"112">>,<<"Gen20267">>]
5> Data.
<<"Gen20267">>
And another one as function in module (probably fastest):
% take_data(Message) -> Data | not_found
take_data([]) -> not_found;
take_data([[<<"112">>, Data]|_]) -> Data;
take_data([_|T]) -> take_data(T). | unknown | |
d19358 | test | you can donwload a converter https://developers.google.com/speed/webp/download for the images, also you can use some online converter like https://cloudconvert.com/webp-converte
for me it doesn't make sense if you want to convert on your angular app the images(tecnically angular doesnt serve images it creates a small server cos angular is a front end framework), cos the computer cost of the convertion it's even heavier than serve heavy images, so the solution is =>
First, convert your images, and then use them on your angular project, from a cdn or serve it static replacing your static images... | unknown | |
d19359 | test | When installing Bootstrap from their GitHub repository, you get a large amount of files that are only required for debugging, testing, compiling from source, etc. It includes many operations that are only needed if you are trying to contribute to Bootstrap.
The NPM version is just a packaged, production-ready version of Bootstrap. Even after running npm install, you don't get all of the GitHub files, as they are unnecessary for a production environment. You cannot therefore build the NPM version, except by adding basically everything from the GitHub version. | unknown | |
d19360 | test | Running kill -QUIT $(cat /run/php/php7.4-fpm.pid) does take the process_control_timeout config in account. It will cause the PHP-FPM process to stop as soon as all the scripts have finished their execution. At that point the PID will be removed. So, in order to make it work:
*
*run $(kill -QUIT $(cat /run/php/php7.4-fpm.pid))
*in a loop, check if /run/php/php7.4-fpm.pid still exists, if not, break the loop. | unknown | |
d19361 | test | Nice catch.
To me, it sounds like a compiler bug more or less. There is an option in VC to select to "Force Conformance In For Loop Scope" so that the for loop variable goes out of scope outside for loop.
However, that doesn't fix the issue you mentioned in the debugger. Regardless of which option you select, both variables are there in the debugger, which appears to be confusing.
The only way to distinguish between them is that out-of-scope i should have value 0xcccccccc in debug mode. This should be compiler specific, and WinDbg handles it in a different way, as mentioned in the following article.
What I tried: VC2008, VC2012
There is a good article well experimenting this issue.
A: MSVC has a special compiler flag that can affect the scoping of int i in your examples: /Zc:forScope.
It's on by default, but the debugger is probably set up to accommodate for it to be turned off with /Zc:forScope- which would make the following code valid (even though it's not standards-compliant):
{
for (int i=0; i < 10; ++i)
{
// Do something
}
for(i=0; i < 10; ++i)
{
// Do something else
}
}
Alternatively, if you've accidentally turned it off, your code is not working as you (and the C++ standard) expect, but then you'd probably get a warning on redeclaring i.
A: There is an option in Visual Studio that controls whether the scope of variables defined in a for loop are visible beyond the for loop. It's called /Zc:forScope. When you use /Zc:forScope-, you get the behavior you described. To change the behavior to conform to C++ stanards, you have to use /Zc:forScope
More information can be found at MSDN Website: /Zc:forScope (Force Conformance in for Loop Scope). | unknown | |
d19362 | test | I've seen it late, but anyways, here goes:
*
*What you describe matches exactly the implementation of an intrusive hash table of MyClass elements, where
*
*anInt1 is the hash (the bucket identifier) for an element
*the bucket lists are implemented as linked lists
*equality is defined as equality of (anInt1, Name)
So really, your program could just be:
Live On Coliru
std::unordered_set<MyClass> values {
{ "John", 0 }, { "Mike", 1 }, { "Dagobart", 2 },
{ "John", 3 }, { "Mike", 4 }, { "Dagobart", 5 },
{ "John", 6 }, { "Mike", 7 }, { "Dagobart", 8 },
{ "John", 9 }, { "Mike", 10 },
};
for(int i = 0; i<=3; ++i) {
if(2 == i) {
for(auto& e: values) std::cout << e.name << " "; std::cout << "\n";
for(auto& e: values) e.bIsMarkedToDelete |= ("Mike" == e.name);
for(auto it=begin(values); it!=end(values);) {
if (it->bIsMarkedToDelete) it = values.erase(it);
else ++it;
}
}
std::cout << "i=" << i << ", values.size(): " << values.size() << "\n";
}
values.clear();
std::cout << "Done\n";
*if you really wanted contiguous storage, I can only assume you wanted this for performance
*
*you do not want to use pointers instead of objects, since that simply negates the memory layout ("AllThingsBunchedTogether") benefits and you'd be better of with the unordered_set or unodered_map as above
*you do not want to use auto_unlink mode, since it cripples performance (by doing uncontrolled deletion triggers, by inhibiting constant-time size() and by creating thread safety issues)
*instead, you should employ the above stratagy, but with boost::intrusive::unordered_set instead see http://www.boost.org/doc/libs/1_57_0/doc/html/intrusive/unordered_set_unordered_multiset.html
Here, again, is a proof-of-concept:
Live On Coliru
#include <vector>
#include <iostream>
#include <boost/intrusive/unordered_set.hpp>
#include <vector>
//#include <functional>
//#include <algorithm>
namespace bic = boost::intrusive;
struct MyClass : bic::unordered_set_base_hook<bic::link_mode<bic::auto_unlink>>
{
std::string name;
int anInt1;
mutable bool bIsMarkedToDelete;
MyClass(std::string name, int i) : name(name), anInt1(i), bIsMarkedToDelete(false) {}
bool operator==(MyClass const& o) const { return anInt1 == o.anInt1 && name == o.name; }
struct hasher { size_t operator()(MyClass const& o) const { return o.anInt1; } };
};
typedef bic::unordered_set<MyClass, bic::hash<MyClass::hasher>, bic::constant_time_size<false> > HashTable;
int main() {
std::vector<MyClass> values {
MyClass { "John", 0 }, MyClass { "Mike", 1 }, MyClass { "Dagobart", 2 },
MyClass { "John", 3 }, MyClass { "Mike", 4 }, MyClass { "Dagobart", 5 },
MyClass { "John", 6 }, MyClass { "Mike", 7 }, MyClass { "Dagobart", 8 },
MyClass { "John", 9 }, MyClass { "Mike", 10 },
};
HashTable::bucket_type buckets[100];
HashTable hashtable(values.begin(), values.end(), HashTable::bucket_traits(buckets, 100));
for(int i = 0; i<=3; ++i) {
if(2 == i) {
for(auto& e: values) std::cout << e.name << " "; std::cout << "\n";
for(auto& e: values) e.bIsMarkedToDelete |= ("Mike" == e.name);
values.erase(std::remove_if(begin(values), end(values), std::mem_fn(&MyClass::bIsMarkedToDelete)));
}
std::cout << "i=" << i << ", values.size(): " << values.size() << "\n";
std::cout << "i=" << i << ", hashtable.size(): " << hashtable.size() << "\n";
}
values.clear();
std::cout << "Done\n";
}
A: Here's the error message, which you omitted:
Assertion `node_algorithms::inited(to_insert)' failed.
From this we can understand that an element is being inserted twice. This isn't valid with intrusive containers in general.
When you have your lists inside the loop, they are destroyed and recreated each time. But when they are outside, you never clear them, and you also never clear values, so this sequence occurs:
*
*Add 11 elements to values.
*Add all values to the lists.
*Add 11 elements to values; it still has the previous 11 so now 22 elements.
*Add all values to the lists. Crash on the first one, because it is already in a list.
One solution is to add values.clear() at the top of the while(!done) loop. | unknown | |
d19363 | test | I'M find
The
Shell.FlyoutBehavior="Flyout"
must be added to the TabBar
I share the code below :
<TabBar Title="Tab bar FlyoutItem" Shell.FlyoutBehavior="Flyout" FlyoutDisplayOptions="AsSingleItem" >
<Tab Title="T1" Icon="T1.png" >
<ShellContent ContentTemplate="{DataTemplate views:T1}" />
</Tab>
<Tab Title="T2" Icon="T2.png" >
<ShellContent ContentTemplate="{DataTemplate views:T2}"/>
</Tab>
<Tab Title="T3" Icon="T3.png" >
<ShellContent ContentTemplate="{DataTemplate views:T3}"/>
</Tab>
<Tab Title="T4" Icon="T4.png" >
<ShellContent ContentTemplate="{DataTemplate views:T4}"/>
</Tab>
<Tab Title="T5" Icon="Home.png" >
<ShellContent ContentTemplate="{DataTemplate views:HomePage}"/>
</Tab>
</TabBar>
<FlyoutItem FlyoutDisplayOptions="AsMultipleItems" Shell.TabBarIsVisible="True">
<Tab Title="T6" Icon="email.png" >
<ShellContent ContentTemplate="{DataTemplate views:T6}" />
</Tab>
<Tab Title="T7" Icon="email.png" >
<ShellContent ContentTemplate="{DataTemplate views:T7}"/>
</Tab>
<Tab Title="T8" Icon="email.png" >
<ShellContent ContentTemplate="{DataTemplate views:T8}"/>
</Tab>
<Tab Title="T9" Icon="email.png" >
<ShellContent ContentTemplate="{DataTemplate views:T9}"/>
</Tab>
</FlyoutItem> | unknown | |
d19364 | test | Most probably it's the problem identified by BLUEPIXY. This is wrong:
char n1;
scanf("%s", &n1);
One possible solution:
char n1;
scanf(" %c", &n1);
Another possible solution, which allows any whitespace (not only a single space) between words:
char n1;
char tmp[128];
if (scanf("%s", tmp) != 1) abort();
if (strlen(tmp) != 1) abort();
n1 = tmp[0];
A: You are trying to input a string into a char variable. Even if you enter one character, the next memory position is overwritten with \0. This may access read-only memory and results in the abrupt termination.
Instead do:
scanf(" %c", &n1); | unknown | |
d19365 | test | You can not get identifier by value, but you can make your identifier name look like a value and get it by string name,
So what I suggest,
use your String resource name something like, resource_150
<string name="resource_150">150</string>
Now here resource_ is common for your string entries in string.xml file, so
in your code,
String value = "150";
int resourceId = this.getResources().
getIdentifier("resource_"+value, "string", this.getPackageName());
Now resourceId value is as equivalent to R.string.resource_150
Just make sure here this represent your application context. In your case MainActivity.this will work.
A: EDIT
You can't search for a resource Id by the string value. You could make your own Map of the values and resourceIds and use that as a look up table, but I believe just choosing an intelligent naming convention like in the accepted answer is the best solution.
A: I have found some tips here: Android, getting resource ID from string?
Below an example how to get strings and their values defined in strings.xml. The only thing you have to do is making a loop and test which string is holding your value. If you need to repeat this many times it might be better to build an array.
//---------
String strField = "";
int resourceId = -1;
String sClassName = getPackageName() + ".R$string";
try {
Class classToInvestigate = Class.forName(sClassName);
Field fields[] = classToInvestigate.getDeclaredFields();
strField = fields[0].getName();
resourceId = getResourceId(strField,"string",getPackageName());
String test = getResources().getString(resourceId);
Toast.makeText(this,
"Field: " + strField + " value: " + test ,
Toast.LENGTH_SHORT).show();
} catch (ClassNotFoundException e) {
Toast.makeText(this,
"Class not found" ,
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this,
"Error: " + e.getMessage() ,
Toast.LENGTH_SHORT).show();
}
}
public int getResourceId(String pVariableName, String pResourcename, String pPackageName)
{
try {
return getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
A: In addition to user370305, you could make an extension and use it the same was as with int ids.
import android.app.Activity
fun Activity.getString(id: String): String {
val resourceId = this.resources.getIdentifier(id, "string", this.packageName)
return getString(resourceId)
} | unknown | |
d19366 | test | While using code in jsfiddle you can also look for external sources towards your left.
<script src="https://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://knockoutjs.com/downloads/knockout-2.0.0.js"></script> | unknown | |
d19367 | test | If price_nodes is correctly fill
i.e. price_nodes =
<span id="SkuNumber" itemprop="identifier" content="sku:473768" data-nodeid="176579" class="product-code col-lg-4 col-md-4">ΚΩΔ. 473768</span>
You just have to do this:
datanode = price_nodes.get('data-nodeid')
Full code should be:
from bs4 import BeautifulSoup as soup
html = '<div><span id="SkuNumber" itemprop="identifier" content="sku:473768" data-nodeid="176579" class="product-code col-lg-4 col-md-4">ΚΩΔ. 473768</span></div>'
page = soup(html, 'html.parser')
price_nodes = page.find('span', {'id': 'SkuNumber'})
datanode = price_nodes.get('data-nodeid')
A: from bs4 import BeautifulSoup
html = '<span id="SkuNumber" itemprop="identifier" content="sku:473768" data-nodeid="176579" class="product-code col-lg-4 col-md-4">ΚΩΔ. 473768</span></div>'
soup = BeautifulSoup(html)
price_nodes = soup.find('span', attrs={'id': 'SkuNumber'})
print(price_nodes['data-nodeid']) | unknown | |
d19368 | test | Thank you Mark & Arioch for contributing.
After hours of failed experimenting with the included fbtrace.exe included in Firebird 2.5 installation i've decided to use "FB TraceManager" Trial version.
Found here: https://www.upscene.com/downloads/fbtm | unknown | |
d19369 | test | In the ".Net" SDK, each of the models has a "Validate()" method. I have not yet found anything similar in the Powershell commands.
In my experience, the (GUI) validation is not foolproof. Some things are only tested at runtime.
A: I know it has been a while and you said you didn't want the validation to work in an year - but after a couple of years we finally have both the Validate all and Export ARM template features from the Data Factory user experience via a publicly available npm package @microsoft/azure-data-factory-utilities. The full guidance can be found on this documentation. | unknown | |
d19370 | test | Ok, I'll explain what you probably could find out by debugging, or by simply reading a textbook on Pascal as well:
The line:
c := (a+b)*(a-b);
does the following:
a + b is the union of the two sets, i.e. all elements that are
in a or in b or in both, so here, that is [2, 3];
a - b is the difference of the two sets, i.e. it is a minus the
elements of a that happen to be in b too. In this case, no
common elements to be removed, so the result is the same as a,
i.e. [3]
x * y is the intersection of the two sets, i.e. elements that are in
x as well as in y (i.e. a set with the elements both have in common).
Say, x := a + b; y := a - b;, then it can be disected as:
x := a + b; // [3] + [2] --> [2, 3]
y := a - b; // [3] - [2] --> [3]
c := x * y; // [2, 3] * [3] --> [3] | unknown | |
d19371 | test | Since the locking mechanism isn't specified I'd assume it uses a normal mutex in which case the obvious problem is this:
A a;
a[0] = a[1];
Put differently, it is very easy to dead-lock the program. This problem is avoided with recursive mutexes.
The other obvious problem is that the code depends on copy-elision which is not guaranteed to always happen. If the copy is not elided upon return the temporary will release the lock and the copy will release it again which normally is undefined behavior. In addition, access to the member is unguarded and will potentially introduce data races. To avoid this problem you should define a move constructor and make sure that the moved from state doesn't try to release the mutex, e.g.:
A::Proxy::Proxy(Proxy&& other)
: val(other.val)
, parent(other.parent) {
other.parent = 0;
}
A::Proxy::~Proxy() {
if (parent){
parent->unlock();
}
}
The not so obvious issue is that it is unlikely to result in an efficient implementation. | unknown | |
d19372 | test | gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)
This sets the default direction for widgets that don't call set_direction. | unknown | |
d19373 | test | Your XML document is a valid instance of the schema below. I have changed the following:
*
*added an xs:element declaration for the outermost element, dictionaryResponse. It is not enough to declare a type of that name, you also have to use this type in an element declaration.
*Added elementFormDefault="qualified" to your schema, because the target namespace should apply to all elements in your document instances. Without it, your schema expects elements that are in no namespace.
*Made http://dictionaries.persistence.com the default namespace of the schema document
*Changed type of entry element to entryType: Do not use the same name for the element name and the name of the type, this can cause a lot of confusion.
XML Schema
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" targetNamespace="http://dictionaries.persistence.com" xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified" xmlns="http://dictionaries.persistence.com">
<xs:element name="dictionaryResponse" type="dictionaryResponseType"/>
<xs:complexType name="dictionaryRequest">
<xs:sequence>
<xs:element name="dictionaryCode" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="dictionaryResponseType">
<xs:sequence>
<xs:element name="entry" type="entryType" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="entryType">
<xs:sequence>
<xs:element name="dictionaryCode" type="xs:string"/>
<xs:element name="id" type="xs:string"/>
<xs:element name="code" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
There is no dictionaryRequest element in your sample document - are you sure you need a type definition for it? | unknown | |
d19374 | test | Well .. I found the answer. Basically, the upload component SAFileUp, uses the "Temp" directory where the uploaded file is cached to set the permissions of the uploaded file. In my case this directory was C:\Windows\temp. All I did was give the account IIS_IUSRS READ access to the C:\Windows\temp directory and I was able to access the uploaded file without issue.
Here is an article on SoftArtisans's website that clued me in and helped me find the directory the uploaded file was cached to.
http://support.softartisans.com/kbview_776.aspx | unknown | |
d19375 | test | As per the source code of iniparser (https://github.com/ndevilla/iniparser/blob/deb85ad4936d4ca32cc2260ce43323d47936410d/src/iniparser.c#L312):
in iniparser_dumpsection_ini function, there is this line:
fprintf(f,
"%-30s = %s\n",
d->key[j]+seclen+1,
d->val[j] ? d->val[j] : "");
As you can see, key is printed with format specifier %-30s which is probably causing this issue.
So, you can clone the repo source code and make the changes. Example, replace format specifier with %s, like:
fprintf(f,
"%s = %s\n", // CHANGE HERE
d->key[j]+seclen+1,
d->val[j] ? d->val[j] : ""); | unknown | |
d19376 | test | SELECT `Date`, COUNT(`Date`) as `Count`
FROM stats_clicks
GROUP BY `Date`
Result
Date Count
1331713370000 2
1337156570000 1
1337761370000 3
1338366170000 1
A: Go with this query. You will get corect count with no repetition.
SELECT date,count(*) FROM stats_clicks GROUP BY date; | unknown | |
d19377 | test | You just write a second loop to join the threads
totalPoints = []
def workThread(i):
global totalPoints
totalPoints += i
threads = []
for i in range(NUMBER_OF_THREADS):
t = threading.Thread(target=workThread, args=(i,))
t.start()
threads.append(t)
for t in threads:
t.join()
Your code will fail at totalPoints += i because totalPoints is a list. You don't handle exceptions in your threads so you may fail silently and not know what happened. Also, you need to be careful how you access a shared resource such as totalPoints to be thread safe.
A: does this help: ?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import threading
import time
import random
NUMBER_OF_THREADS=20
totalPoints = []
def workThread(i):
global totalPoints
time.sleep(random.randint(0, 5))
totalPoints.append((i, random.randint(0, 255)))
threads = []
for i in range(NUMBER_OF_THREADS):
t = threading.Thread(target=workThread, args=(i,))
t.start()
threads.append(t)
for t in threads:
t.join()
print totalPoints
It always prints something like this:
[(1, 126), (10, 169), (11, 154), (0, 214), (9, 243), (12, 13), (15, 152), (6, 24), (17, 238), (13, 28), (19, 78), (16, 130), (2, 110), (3, 186), (8, 55), (14, 70), (5, 35), (4, 39), (7, 11), (18, 14)]
or this
[(2, 132), (3, 53), (4, 15), (6, 84), (8, 223), (12, 39), (14, 220), (0, 128), (9, 244), (13, 80), (19, 99), (7, 184), (11, 232), (17, 191), (18, 207), (1, 177), (5, 186), (16, 63), (15, 179), (10, 143)] | unknown | |
d19378 | test | You could use a cursor to do loops, but that is a poorly performaning option compared to a set based operation.
Using not exists() to return all clients in programs that ended in May, that have not re-enrolled:
select
ClientULink
, ProgramULink
, StartDate
, EndDate
from Client_Program cp
where cp.EndDate >= '20170501'
and cp.EndDate < '20170601'
and not exists (
select 1
from Client_Program i
where i.ClientULink = cp.ClientULink
and i.ProgramULink = cp.ProgramULink
and i.StartDate >= cp.EndDate
)
Notes:
*
*Bad habits to kick : mis-handling date / range queries - Aaron Bertrand
*What do between and the devil have in common? - Aaron Bertrand
*Should I use not in(), outer apply(), left outer join, except, or not exists()? - Aaron Bertrand
*The only truly safe formats for date/time literals in SQL Server, at least for datetime and smalldatetime, are: YYYYMMDD and YYYY-MM-DDThh:mm:ss[.nnn] - Bad habits to kick : mis-handling date / range queries - Aaron Bertrand
test setup:
create table Client_Program (ClientULink uniqueidentifier, ProgramULink uniqueidentifier, StartDate datetime, EndDate datetime)
insert into Client_Program values
('00000000-0000-0000-0000-000000000000','00000000-0000-0000-0000-000000000000','2017-02-02T06:00:00','2017-05-02T06:00:00')
,('11111111-1111-1111-1111-111111111111','11111111-1111-1111-1111-111111111111','2017-02-02T06:00:00','2017-05-02T06:00:00')
,('11111111-1111-1111-1111-111111111111','11111111-1111-1111-1111-111111111111','2017-05-02T06:00:00','2017-08-02T06:00:00')
select
ClientULink
, ProgramULink
, StartDate = convert(char(10),StartDate,120)
, EndDate = convert(char(10),EndDate,120)
from Client_Program cp
where cp.EndDate >= '20170501'
and cp.EndDate < '20170601'
and not exists (
select 1
from Client_Program i
where i.ClientULink = cp.ClientULink
and i.ProgramULink = cp.ProgramULink
and i.StartDate >= cp.EndDate
)
rextester demo: http://rextester.com/LYE54567
returns:
+--------------------------------------+--------------------------------------+------------+------------+
| ClientULink | ProgramULink | StartDate | EndDate |
+--------------------------------------+--------------------------------------+------------+------------+
| 00000000-0000-0000-0000-000000000000 | 00000000-0000-0000-0000-000000000000 | 2017-02-02 | 2017-05-02 |
+--------------------------------------+--------------------------------------+------------+------------+
You could also use aggregation and filter in the having clause where max(EndDate) is between some date range (If they re-enrolled, then their max(EndDate) would not be in the date range):
select
ClientULink
, ProgramULink
from Client_Program cp
group by
ClientULink
, ProgramULink
having max(EndDate)>= '20170501'
and max(EndDate) < '20170601'
returns:
+--------------------------------------+--------------------------------------+
| ClientULink | ProgramULink |
+--------------------------------------+--------------------------------------+
| 00000000-0000-0000-0000-000000000000 | 00000000-0000-0000-0000-000000000000 |
+--------------------------------------+--------------------------------------+
A: In general, if you are looping in SQL, you're probably doing it wrong. You can use EXCEPT to achieve this.
SELECT ClientULink
FROM Client_Program
WHERE CAST(EndDate as date) BETWEEN '2017-05-01' AND '2017-05-30'
EXCEPT
SELECT ClientULink
FROM Client_Program
WHERE CAST(StartDate as date) > '2017-05-01'
Edit: If a client Starts and Ends within the DateRange they will be wrongly excluded from the result.
A: Are you certain you are not over-thinking this? Not re-enrolled appears to be the set of IDs (client, program) that have a count of 1. E.g.,
select cp.ClientULink, cp.ProgramULink from dbo.Client_Program as cp
group by cp.ClientULink, cp.ProgramULink
having count(*) = 1
order by cp.ClientULink, cp.ProgramULink ;
What else do you need?
A: If you need the date filter, try something like this:
select ClientULink, ProgramULink, StartDate, EndDate
from Client_Program cp
inner join
(
select ClientULink, ProgramULink, count(*) as Count
from Client_Program cp2
group by ClientULink, ProgramULink
having count(*) = 1
) cp2
on cp.ClientULink = cp2.ClientULink
and cp.ProgramULink = cp2.ProgramULink
where cast(cp.EndDate as date) between '2017-05-01' and '2017-05-30' | unknown | |
d19379 | test | C++11 has introduced noexcept, throw is somewhat deprecated (and according to this less efficient)
noexcept is an improved version of throw(), which is deprecated in C++11. Unlike throw(), noexcept will not call std::unexpected and may or may not unwind the stack, which potentially allows the compiler to implement noexcept without the runtime overhead of throw().
When an empty throw specification is violated, your program is terminated; this means you should only declare your functions as non throwing, only when they have a no throw exception guarantee.
Finally you need a move constructor to be non throwing (specified with noexcept) to be able to use the r-value ref version of std::vector<T>::push_back (see a better explanation here)
A: The standard throw() doesn't enhance optimizability.
If a method is marked as throw() then the compiler is forced to check if an exception is thrown from the method and unwind the stack - just like if the function is not marked as throw(). The only real difference is that for a function marked throw() the global unexpected_handler will be called (which generally calls terminate()) when the exception leaves the function, unwinding the stack to that level, instead of the behavior for functions without an exception specification which will handle the exception normally.
For pre-C++11 code, Sutter & Alexandrescu in "C++ Coding Standards" suggested:
Avoid exception specifications.
Take exception to these specifications: Don’t write exception
specifications on your functions unless you’re forced to (because
other code you can’t change has already introduced them; see
Exceptions).
...
A common but nevertheless incorrect belief is that exception
specifications statically guarantee that functions will throw only
listed exceptions (possibly none), and enable compiler optimizations
based on that knowledge
In fact, exception specifications actually do something slightly but
fundamentally different: They cause the compiler to inject additional
run-time overhead in the form of implicit try/catch blocks around the
function body to enforce via run-time checking that the function does
in fact emit only listed exceptions (possibly none), unless the
compiler can statically prove that the exception specification can
never be violated in which case it is free to optimize the checking
away. And exception specifications can both enable and prevent further
compiler optimizations (besides the inherent overhead already
described); for example, some compilers refuse to inline functions
that have exception specifications.
Note that in some versions of Microsoft's compilers (I'm not sure if this behavior has changed in more recent versions, but I don't think so), throw() is treated in a non-standard way. throw() is equivalent to __declspec(nothrow) which does allow the compiler to assume that the function will not have an exception thrown and undefined behavior will result if one is.
C++11 deprecates the C++98 style exception specification and introduced the noexcept keyword. Bjarne Stroustup's C++11 FAQ says this about it:
If a function declared noexcept throws (so that the exception tries to
escape, the noexcept function) the program is terminated (by a call to
terminate()). The call of terminate() cannot rely on objects being in
well-defined states (i.e. there is no guarantees that destructors have
been invoked, no guaranteed stack unwinding, and no possibility for
resuming the program as if no problem had been encountered). This is
deliberate and makes noexcept a simple, crude, and very efficient
mechanism (much more efficient than the old dynamic throw()
mechanism).
In C++11 if an exception is thrown from a function marked as noexcept the compiler is not obligated to unwind the stack at all. This affords some optimization possibilities. Scott Meyers discusses the new noexcept in his forthcoming book "Effective Modern C++". | unknown | |
d19380 | test | As far as I can see it appears that you shouldn't use an automatic return service bus binding. Instead, you should manually connect to the return topic/queue and handle the message logistics manually. | unknown | |
d19381 | test | You should use ngFor instead of ng-repeat
<ol>
<li *ngFor="let item of testarr">{{item}}ITEM Found!</li>
</ol> | unknown | |
d19382 | test | As long as all of the batch parameters are supposed to be passed to your program, then you can simply call your batch with the parameters as you have specified them, and use the following within your batch script.
program.exe %*
The problem becomes much more complicated if you only want to pass some of the batch parameters to the called program.
Unfortunately there is no method to escape quotes within a quoted string. It is also impossible to escape parameter delimiters. So it is impossible to simultaneously embed both spaces and quotes within a single batch parameter.
The SHIFT command can strip off leading parameters, but %* always expands to the original parameter list; it ignores prior SHIFT operations.
The FOR /F does not ignore quoted delimiters, so it doesn't help.
The simple FOR can properly parse quoted parameter lists, but it expands * and ? characters using the file system. That can be a problem.
The only thing left to do is to use a GOTO loop combined with SHIFT to build a string containing your desired parameters.
Suppose the first 3 parameters are strictly for the batch file, and the remaining parameters are to be passed to the called program.
@echo off
setlocal
set "args="
:buildProgramArgs
if [%4]==[] goto :argsComplete
set args=%args% %4
shift /4
goto :buildProgramArgs
:argsComplete
program.exe %args%
::args %1 %2 and %3 are still available for batch use | unknown | |
d19383 | test | If your images are in mydomain.com/images and you are linking to them using relative links on the page mydomain.com/sub/folder/ the browser is going to try to attempt to access the image via mydomain.com/sub/folder/images/i.gif. But if you change your links to absolute links, the browser will correctly attempt to load mydomain.com/images/i.gif. However, the RewriteRule will change it to: mydomain.com/index/php?Controller=images&View=i.gif. To avoid this you need to add a few RewriteConds:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9-_]+)\/?$ index.php?Controller=$1
RewriteRule ^([a-zA-Z0-9-_]+)/([a-zA-Z0-9-_]+)\/? index.php?Controller=$1&View=$2
So that when attempting at access an existing file/directory, don't rewrite to index.php. | unknown | |
d19384 | test | No, because the shell does the wild card expansion.
It finds files in the directory that match the expression, so for instance you can use "echo *.c" to discover what the shell would match. Then it lists out, every filename matching *.c on the exec call or if none *.c which is likely to result in an error message about file not found.
It is more powerful that the shell does the expansion, the same file wildcarding is immediately available for all programs, like cat, echo, ls, cc. | unknown | |
d19385 | test | This error happen because the registry value DefaultData and DefaultLog (which correspond to default data directory) are either empty or does not exists.
See documentation for more information.
Most of the time, these registry values does not exists because they actually need to be accessed as Admin. So, to fix this issue, simply run whatever application you are using to execute the sql as an administrator. | unknown | |
d19386 | test | Your dataset needs to be instantiated using the "New" keyword. The object reference in this case is ds, and it's just set to type dataset. New creates an "instance" of the DataSet.
Dim ds as New Course_assignmentsDataSet
Then you'll want to do:
txtCourseReference.Text = ds.Tables("tblCourse").Rows(i).Item(1)
txtCourseName.Text = ds.Tables("tblCourse").Rows(i).Item(2)
Edit: As Jay said below, you'll want to fill the dataset first | unknown | |
d19387 | test | To get the values instead of percentages :
*
*Edit the datawindow, select the "Text" tab
*Select "Pie Graph Labels" in the TextObject drop-down list
*In the "Display Expression" field type "value"
I'm using PB10.5, I hope it's same with 12. | unknown | |
d19388 | test | If you are not passing Date in default format then you need to intimate system that I am passing this string as date by mentioning format of date as describe below.
INSERT INTO test VALUES STR_TO_DATE('03-12-2016','%d-%m-%Y');
Hopefully this will help.
A: Try this and also check your date format(data type) set in the database
INSERT INTO test VALUES ('2-03-2016')
A: you must ensure that the value passed to mysql is in year-month-day sequence ("YYYY-MM-DD")
INSERT INTO test VALUES ('2016-03-02');
note:- please use another keyword instead inbuilt keyword.date is inbuilt mysql keyword.
Read here
A: Trial and error? This isn't some uncharted scientific territory where you need to strap on some goggles and use a bunsen burner. There's a whole chapter in the manual devoted to it.
Dates in MySQL should be in ISO-8601 format, that is YYYY-MM-DD or YYYY-MM-DD HH:MM:SS in 24-hour notation.
Please, before wasting tons of your time on pointless experimentation:
READ THE MANUAL | unknown | |
d19389 | test | In package.json you can use scripts or even at commandline you can use environment variable.s
"scripts": {
"dev": "NODE_ENV=development webpack",
"production": "NODE_ENV=production webpack",
"watch": "npm run dev -- --watch"
},
In webpack.config.js you can use
const inProduction = process.env.NODE_ENV === 'production';
const inDevelopment = process.env.NODE_ENV === "development";
if(inProduction)
//do this
if(inDevelopment)
//do that
webpack by default looks for weback.config.js however for custom config you can use
webpack --config config_local.js | unknown | |
d19390 | test | appendChild returns the child back try consoling the the parent node para - console.log(para); to see the result of the append, The last line will look like this :
nearby_places.appendChild(para);
A: The appendChild() method modifies para directly, rather than leaving the original intact and returning a modified value. So, you should continue to use your para variable for the paragraph, rather than mypara. Your modified code would be:
for (var i = 0; i < results.length; i++) {
//console.log(results[i].vicinity);
para = document.createElement('p');
aTag = document.createElement('a');
aTag.setAttribute('href',"/restaurants");
aTag.innerHTML = results[i].name;
para.appendChild(aTag);
nearby_places.appendChild(para);
}
More info: according to MDN, appendChild() returns the appended node. That's why your console.log() call was just showing the <a> tag. See: https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild.
A: Here is a sample fiddle that works:
https://jsfiddle.net/fNPvf/22007/
para = document.createElement('p');
aTag = document.createElement('a');
aTag.setAttribute('href',"/restaurants");
aTag.innerHTML = "wendys";
para.appendChild(aTag);
document.body.appendChild(para); | unknown | |
d19391 | test | The Exception e, which you catch may contain useful information on what exactly went wrong. Do e.printStackTrace(); inside your catch-block to print all available information to the standard output.
If that does not help you solve the problem post the stacktrace here.
A: You cannot manipulate UI thread from background thread thats why you are getting this error.
ClassName.this.runOnUiThread(new Runnable() {
public void run() {
//Do something on UiThread
// enclose your UI manipulated code here in these braces.
}
}); | unknown | |
d19392 | test | Test your code sample and it has some issues.
1.In your code, it is missing authentication credentials. You can try to create PAT and use it in authentication .
2.When you use ConvertTo-Json, you need to add depth parameter to expand the json body.
3.For the buildurl, you need to modify the id format in the url.
$TFSProjectURL/_apis/build/definitions/$($Id)?api-version=5.0
Here is the example:
$token = "PAT"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$BuildName = "Test-demo"
$buildTaskName = 'Print Hello World'
$BuildDefinitions = Invoke-WebRequest -Headers @{Authorization = "Basic $token"} -Uri ("{0}/_apis/build/definitions?api-version=5.0" -f $TFSProjectURL)
$BuildDefinitionsDetail = convertFrom-JSON $BuildDefinitions.Content
foreach($BuildDetail in $BuildDefinitionsDetail.value){
if($BuildDetail.name -eq $BuildName)
{
$Id = $BuildDetail.id
$name = $BuildDetail.name
$Project = $BuildDetail.project.name
$BuildTask = Invoke-WebRequest -Headers @{Authorization = "Basic $token"} -Uri ("{0}/_apis/build/definitions/$($Id)?api-version=5.0" -f $TFSProjectURL)
$BuildTaskDetails = convertFrom-JSON $BuildTask.Content
foreach($TaskDetail in $BuildTaskDetails.process.phases.steps){
if($TaskDetail.displayName -eq $buildTaskName)
{
$taskName = $TaskDetail.displayName
$TaskDetail.enabled = "false"
}
}
Write-Host $BuildTaskDetails
$Updatedbuilddef = ConvertTo-Json $BuildTaskDetails -Depth 99
buildUri = "$TFSProjectURL/_apis/build/definitions/$($Id)?api-version=5.0"
$buildResponse =Invoke-WebRequest -Headers @{Authorization = "Basic $token"} -Uri $buildUri -Method Put -ContentType "application/json" -Body $Updatedbuilddef
}
} | unknown | |
d19393 | test | When you create the session, the default graph is launched by default, which does not contain the operations you are looking for (they are all in self.graph). You should do something like this:
with tf.Session(self.graph) as sess:
sess.run(...)
Now, sess will have access to self.input_operation and self.output_operation. In your code, this means you should create the session after you create self.graph. By the way, most of the time it is more convenient to just use the default graph (exactly to avoid problems like these). May be this post will also help you in this regard. | unknown | |
d19394 | test | i think it's helpful for you.
and also check the clipToBounds
Checking "Clip Subviews" is equal to the code addMessageLabel.clipsToBounds = YES;
A: You can use this code and method on your controller
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
yourLabel.clipsToBounds = true
yourLabel.layoutIfNeeded()
print("Frame ------> ",yourLabel.frame)
} | unknown | |
d19395 | test | I've been down this path, and I don't recommend you actually make deep hierarchies of windows. Lots of Windows helper functions (e.g., IsDialogMessage) work better with "traditional" layouts. Also, windows in Windows are relatively heavy objects, mostly for historical reasons. So if you have tons of objects, you could run into limitations, performance problems, etc.
What I've done instead is to represent the deeply-nested layout as a tree of regular C++ objects that parallels the flatter hierarchy of actual windows. Some nodes of the object hierarchy have the HWNDs of the "real" windows they represent. You tell the hierarchy to lay out, and the nodes apply the results to the corresponding windows.
For example, the root of the hierarchy may represent a dialog window, and the leaf nodes represent the child windows. But the hierarchy has several layers of non-window objects in between that know about layout.
A: A rough take on this:
*
*memory overhead for the window management on application- and os-side
*reduced speed due to calls to external library / os which do way more for windows than needed for your application
*possibly quite some overhead through long window message paths in complex layouts
It probably depends on wether you want a very fast implementation and do efficient buffered drawing by yourself or want it to work more reliably and with less time invested. | unknown | |
d19396 | test | You don't reset the key. Read the docs again:
Once the events have been processed the consumer invokes the key's
reset method to reset the key which allows the key to be signalled and
re-queued with further events.
Probably here
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind kind = event.kind();
WatchEvent<Path> ev = cast(event);
Path name = ev.context();
Path child = dir.resolve(name);
return new myTuple(event.kind().name(), child);
}
key.reset();
return null; | unknown | |
d19397 | test | This is a great question because it brings up the complicated problem of sorting a table with columns of unlike types. Later versions of Java implement new sorting tools you can use. Here's my solution to your problem using JDK 1.8 (Java 8). It's printing only fields 0,1,7 although you can easily add in the rest of the fields.
First class file:
package intquestions;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System.out;
import intquestions.StaffComparator;
public class SortDataList {
public static void main(String[] args) {
runit(); }
public static void runit() {
Object[] list1 = {"192.168.1.101-67.212.184.66-2156-80-6","192.168.1.101","2156","67.212.184.66","80","6","13/06/2010 06:01:11",2328040,"2","0" };
Object[] list2 = {"192.168.1.101-67.212.184.66-2159-80-6","192.168.1.101","2159","67.212.184.66","80","6","13/06/2010 06:01:11",2328006,"2","0"};
Object[] list3 = {"192.168.2.106-192.168.2.113-3709-139-6","192.168.2.106","3709","192.168.2.113","139","6","13/06/2010 06:01:16",7917,"10","9"};
Object[] list4 = {"192.168.5.122-64.12.90.98-59707-25-6","192.168.5.122","59707","64.12.90.98","25","6","13/06/2010 06:01:25",113992,"6","3"};
ArrayList<DataList> mList=new java.util.ArrayList<DataList>();
mList.add(new DataList(list1));
mList.add(new DataList(list2));
mList.add(new DataList(list3));
mList.add(new DataList(list4));
String sep = " | " ;
out.println("BEFORE SORTING - ONLY PRINTING FIELDS 1,2,8 (0,1,7) ---------------------- : " );
out.println(mList.get(0).s.toString() +sep+ mList.get(0).f.toString() +sep+ mList.get(0).eighth.toString());
out.println(mList.get(1).s.toString() +sep+ mList.get(1).f.toString() +sep+ mList.get(1).eighth.toString());
out.println(mList.get(2).s.toString() +sep+ mList.get(2).f.toString() +sep+ mList.get(2).eighth.toString());
out.println(mList.get(3).s.toString() +sep+ mList.get(3).f.toString() +sep+ mList.get(3).eighth.toString());
StaffComparator myComparator = new StaffComparator();
try { Collections.sort(mList, myComparator);
} catch (Exception e) { out.println(e); }
out.println("\nDONE SORTING - ONLY PRINTING FIELDS 1,2,8 (0,1,7) ----------------------- : " );
out.println(mList.get(0).s.toString() +sep+ mList.get(0).f.toString() +sep+ mList.get(0).eighth.toString());
out.println(mList.get(1).s.toString() +sep+ mList.get(1).f.toString() +sep+ mList.get(1).eighth.toString());
out.println(mList.get(2).s.toString() +sep+ mList.get(2).f.toString() +sep+ mList.get(2).eighth.toString());
out.println(mList.get(3).s.toString() +sep+ mList.get(3).f.toString() +sep+ mList.get(3).eighth.toString());
}
}
class DataList extends DataListAbstract {
public DataList(Object[] myObj) {
super(myObj); }
public Integer getEighth(DataList locVarDataList) {
return locVarDataList.eighth; }
@Override
public int compareTo(DataListAbstract o) {
return 0; }
}
abstract class DataListAbstract implements Comparable<DataListAbstract> {
String f; // first
String s; //second
Integer eighth;
DataListAbstract(Object[] myo) {
this.eighth = (Integer)myo[7];
this.f = (String)myo[0];
this.s = (String)myo[1];
}
}
Second class:
package intquestions;
import java.util.Comparator;
public class StaffComparator implements Comparator<DataList> {
public int compare(DataList c1, DataList c2) {
Integer firstInt = c1.getEighth(c1);
Integer secondInt = c2.getEighth(c2);
return firstInt.compareTo(secondInt);
}
}
Output:
BEFORE SORTING - ONLY PRINTING FIELDS 1,2,8 (0,1,7) ---------------------- :
192.168.1.101 | 192.168.1.101-67.212.184.66-2156-80-6 | 2328040
192.168.1.101 | 192.168.1.101-67.212.184.66-2159-80-6 | 2328006
192.168.2.106 | 192.168.2.106-192.168.2.113-3709-139-6 | 7917
192.168.5.122 | 192.168.5.122-64.12.90.98-59707-25-6 | 113992
DONE SORTING - ONLY PRINTING FIELDS 1,2,8 (0,1,7) ----------------------- :
192.168.2.106 | 192.168.2.106-192.168.2.113-3709-139-6 | 7917
192.168.5.122 | 192.168.5.122-64.12.90.98-59707-25-6 | 113992
192.168.1.101 | 192.168.1.101-67.212.184.66-2159-80-6 | 2328006
192.168.1.101 | 192.168.1.101-67.212.184.66-2156-80-6 | 2328040 | unknown | |
d19398 | test | Use relative size/location instead of absolute (example -> Use Grid.RowDefinition = */Auto, instead of fixed size, Use stackpanel, use dock panel)
Automatic layout overview
Resolution independent or monitor size independent WPF apps
Same question on MSDN with links in answer
Metro Apps are supposed to run on different form factors. You can look at Guidelines for the different form factors on metro UI. It will help in understanding the challenges, and how to plan/resolve these challenges. | unknown | |
d19399 | test | From the look of your returned JSON, you are returning an array of objects. To access these you can use the index of the object within the array. For example:
$.getJSON("Controller/Data", function(result) {
console.log(result[0].Name);
});
Alternatively, you can loop through all the returned items:
$.getJSON("Controller/Data", function(result) {
for (var i = 0; i < result.length; i++) {
console.log(result[i].Name);
}
});
A: Try this:
$.ajax({
cache: false,
type: "POST",
data: {},
async: true,
url: "/Controller/Data/",
datatype: "json",
success: function (data) {
$.each(data, function (key, data) {
alert(data.Name);
alert(data.Region);
});
}
});
A: you could do
$.getJSON("Controller/Data", function(result) {
console.log('result');
$.each(result, function(key,value) {
console.log(value.name);
// all other computations
});
}); | unknown | |
d19400 | test | A StackOverflowError merely indicates that there’s no space available in the stack for a new frame. In your case, the recursive calls still fill up most of the stack but, since the method calls other methods besides itself, those can also exhaust the stack.
If, for example, your recursive method called only itself, the stack would always be exhausted when calling that one method. | unknown |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.