_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d4301 | train | It's depends how you try to use this files. I have made a simple test app with Skeleton as submodule and it works. You can see it here.
If don't want to require skeleton css in application.css and use it as separated precompiled file you neeed tell rails to precompile that file. In your application.rb:
config.assets.precompile << 'skeleton.css' | unknown | |
d4302 | train | You should be able to use get_the_terms($id, $taxonomy). Returns false if no terms of that taxonomy are attached to the post.
https://codex.wordpress.org/Function_Reference/get_the_terms | unknown | |
d4303 | train | Deleted my last answer - it does not work either. In standards compliant modes the only content that can not be scrolled to is content inside a parent which is hidden. And except for bugs it is not shown. What I was looking at was a IE bug.
Sorry no can do in CSS as it stands today.
If you need to do a calc today you would need to use jquery to get the heights of the elements then calculate the height needed for the footer; And, use CSS gradients http://robertnyman.com/2010/02/15/css-gradients-for-all-web-browsers-without-using-images/ so you can go from your shade of navy to your shade of black. I would discourage this approach as when you start to consider all of the possible resolution situations the calculation it will become rather complex and I assume they may want to redesign the heights depending on different resolutions. | unknown | |
d4304 | train | Yes you can debug Android Activity's using eclipse :-)
Post your Logcat if you want help with the issue.
A: Remember to add android:debuggable="true" to the application element in AndroidManifest.xml | unknown | |
d4305 | train | You can not directly do it, because you need a query whose columns are variable, based on some value.
Slightly different, what you can do is build a dynamic SQL to have your query created by Oracle:
SETUP:
SQL> create table dataTable(q1,q2,q3) as
2 select 1,2,3 from dual union all
3 select 4,5,6 from dual
4 ;
Table created.
SQL> create table translationTable(descName, meanName) as
2 select 'q1', 'meaning1' from dual union all
3 select 'q2', 'meaning2' from dual union all
4 select 'q3', 'meaning3' from dual ;
Table created.
This will create and print your query:
SQL> declare
2 vSQL varchar2(1000);
3 begin
4 select listagg (column_name || ' AS "' || meanName || '"', ', ') within group (order by column_name)
5 into vSQL
6 from user_tab_columns col
7 inner join translationTable tr
8 on (upper(tr.descName) = col.column_name)
9 where table_name = upper('dataTable');
10 --
11 vSQL := 'select ' || vSQL || ' from dataTable';
12 dbms_output.put_line(vSQL);
13 end;
14 /
select Q1 AS "meaning1", Q2 AS "meaning2", Q3 AS "meaning3" from dataTable
PL/SQL procedure successfully completed.
If you copy the statement and run it:
SQL> select Q1 AS "meaning1", Q2 AS "meaning2", Q3 AS "meaning3" from dataTable;
meaning1 meaning2 meaning3
---------- ---------- ----------
1 2 3
4 5 6
SQL>
This way you have your query, but you can not fetch it, because it still has variable columns.
You can easily edit this code to make it build a query that returns strings, composed by concatenating the felds; this way you will always have a single field, but it's different from what you asked:
SQL> select 'meaning1, meaning2, meaning3' from dual
2 union all
3 select Q1 || ',' || Q2 || ',' || Q3 from dataTable;
'MEANING1,MEANING2,MEANING3'
--------------------------------------------------------------------------------
meaning1, meaning2, meaning3
1,2,3
4,5,6 | unknown | |
d4306 | train | Use array.prototype.filter method then map the returned array
const arr = [{
"id": "2",
"namn": "Blekinge",
"url": "/blekinge"
},
{
"id": "23",
"namn": "Karlshamn",
"url": "/blekinge/karlshamn"
},
{
"id": "24",
"namn": "Karlskrona",
"url": "/blekinge/karlskrona"
},
{
"id": "25",
"namn": "Olofström",
"url": "/blekinge/olofstrom"
},
{
"id": "26",
"namn": "Ronneby",
"url": "/blekinge/ronneby"
}]
let filtered = (a) => a.url.includes("/blekinge")
console.log(arr.filter(filtered))
then map the result
A: You should first try to narrow down by matching the object which contains the url /blekinge using the filter method. Once you have filtered, the resulting array can be used to present a list.
To keep things simple, I implemented an unordered list to present the result, but the core of what you need is in the resulting filtered array.
let listElement = document.getElementById('name-list');
let data = [
{
"id": "2",
"name": "Blekinge",
"url": "/blekinge"
},
{
"id": "23",
"name": "Karlshamn",
"url": "/blekinge/karlshamn"
},
{
"id": "24",
"name": "Karlskrona",
"url": "/blekinge/karlskrona"
},
{
"id": "25",
"name": "Olofström",
"url": "/blekinge/olofstrom"
},
{
"id": "26",
"name": "Ronneby",
"url": "/test/ronneby"
}
];
let updateList = (list, content) => {
let li = document.createElement("li");
li.innerHTML = content;
list.appendChild(li);
};
let filteredData = data.filter(elem => elem.url.indexOf('/blekinge') !== -1);
filteredData.map(elem => updateList(listElement, elem.name));
<label for="name-list">Matching names</label>
<ul id="name-list">
<ul>
A: Working Demo :
const data = [{
"id": "2",
"namn": "Blekinge",
"url": "/blekinge"
},
{
"id": "23",
"namn": "Karlshamn",
"url": "/alpha/beta"
},
{
"id": "24",
"namn": "Karlskrona",
"url": "/blekinge/karlskrona"
},
{
"id": "25",
"namn": "Olofström",
"url": "/abc/def"
},
{
"id": "26",
"namn": "Ronneby",
"url": "/blekinge/ronneby"
}];
const res = data.filter((obj) => obj.url.indexOf('/blekinge') !== -1);
console.log(res); | unknown | |
d4307 | train | You need to actually call the method:
private void kryptonButton1_Click(object sender, EventArgs e)
{
var value = reg_value(@"Control Panel\Desktop", "WheelScrollLines");
MessageBox.Show(value);
}
Also consider some changes to your class:
public static class Reg_v_no_string
{
public static string reg_value(string key_place, string key)
{
string value = string.Empty;
RegistryKey klase = Registry.CurrentUser;
// todo: add some error checking to make sure the key is opened, etc.
klase = klase.OpenSubKey(key_place);
value = klase.GetValue(key).ToString();
klase.Close();
return value;
}
}
And then when you call this static class it is like this:
// you don't need to `new` this class if it is static:
var value = Reg_v_no_string.reg_value(@"Control Panel\Desktop", "WheelScrollLines");
Or, to keep it so that it is not static:
public class Reg_v_no_string
{
public string reg_value(string key_place, string key)
{
string value = string.Empty;
RegistryKey klase = Registry.CurrentUser;
// todo: add some error checking to make sure the key is opened, etc.
klase = klase.OpenSubKey(key_place);
value = klase.GetValue(key).ToString();
klase.Close();
return value;
}
}
Then call it like this:
Reg_v_no_string obj = new Reg_v_no_string ();
var value = reg_value(@"Control Panel\Desktop", "WheelScrollLines");
A: There is no code that calls reg_value.
As result you are getting default (also shared between instances) value of value field.
A: Reg_v_no_string.value is not set yet.
You have to call reg_value(string key_place, string key) function that will return the value. | unknown | |
d4308 | train | This is an assembly level attribute. You need it only once. This is the "flag" that the NUnit Test Runner uses to determine if the tests supports parallelism.
SpecFlow 2.0 is not adding this attribute automatically to your code, so have to do it manually once. | unknown | |
d4309 | train | In the code, the guy used a foreach to access an array member which he had its name already! As far as I understand - it's a waste of resources and a bad(even strange) practice.
The first parameter is always an array on one key and its value, the second parameter comes from the call to that function, in a block named as the key... So, all you need is to send the key and no need to iterate
The code uses foreach to iterate through $field, which is an array of one key value pair. It all starts when the validation routine invokes identicalFieldValues, passing it two values - $field, which would be an array that looks like:
array (
[email] => 'user entered value 1'
)
The second parameter $compare_field would be set to the string confirm_email.
In this particular case, it doesn't look like it makes a lot of sense to use foreach since your array only has one key-value pair. But you must write code this way because CakePHP will pass an array to the method.
I believe the reason why CakePHP does this is because an array is the only way to pass both the field name and its value. While in this case the field name (email) is irrelevant, you might need in other cases.
What you are seeing here is one of the caveats of using frameworks. Most of the time, they simplify your code. But sometimes you have to write code that you wouldn't write normally just so the framework is happy.
One more thing about the code: I don't understand the usage of the continue there. it's a single field array, isn't it? the comparison should happen once and the loop will be over. Please enlighten me.
Indeed. And since there are no statements in the foreach loop following continue, the whole else block could also be omitted.
A simplified version of this would be:
function identicalFieldValues($field=array(), $compare_field=null)
{
foreach ($field as $field) {
$compare = $this->data[$this->name][$compare_field];
if ($field !== $compare) {
return FALSE;
}
}
return TRUE;
}
And I agree with you, the loop only goes through one iteration when validating the email field. regardless of the field. You still need the foreach because you are getting an array though. | unknown | |
d4310 | train | Yes; the service still runs in foreground when "Show notifications" is unticked.
Run adb shell dumpsys activity services and check the value of the isForeground flag for your service.
* ServiceRecord{e66dea9 u0 com.example.foregroundservice/.ForegroundService}
intent={cmp=com.example.foregroundservice/.ForegroundService}
packageName=com.example.foregroundservice
processName=com.example.foregroundservice:backgroundproc
baseDir=/data/app/com.example.foregroundservice-2/base.apk
dataDir=/data/user/0/com.example.foregroundservice
app=ProcessRecord{254dd51 14363:com.example.foregroundservice:backgroundproc/u0a65}
isForeground=true foregroundId=101 foregroundNoti=Notification(pri=0 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE)
createTime=-55s70ms startingBgTimeout=--
lastActivity=-55s70ms restartTime=-55s70ms createdFromFg=true
startRequested=true delayedStop=false stopIfKilled=false callStart=true lastStartId=1
Compatibility (using official Android emulators)
Not working:
*
*4.0.2 (the "Show notifications" setting isn't available)
Working:
*
*4.1.2
*4.2.2
*4.3.1
*4.4.2
*5.0.2
*5.1.1
*6.0
*7.0
*7.1 | unknown | |
d4311 | train | I don't know of a way to prevent the scenario you described as the customer in question is explicitly deciding to pay you twice for two different subscriptions.
That said, if your use case requires a customer to have only a single Subscription you could add logic on your end that would do the following:
*
*Set up a webhook endpoint to listen for customer.subscription.created events.
*Whenever a new Subscription is created list the Subscriptions belonging to the Customer.
*If the Customer has more than one active Subscription cancel the newest one(s) and refund the associated payments. You may also want to send the customer an email letting them know what happened. | unknown | |
d4312 | train | The syntax for the "IN" condition is:
expression in (value1, value2, .... value_n);
In your example:
sqlDelete = "delete from vul_detail where scanno = ? and id in (?, ?)"; | unknown | |
d4313 | train | No they are not exactly equivalent, although the difference is unlikely to be significant.
class A(object):
const = 'abc'
def lengthy_op(self):
const = self.const
for i in xrange(AVOGADRO):
# do something which involves reading const
This creates a local variable so any access of const will use the LOAD_FAST opcode.
const = 'abc'
class A(object):
def lengthy_op(self):
# global const
for i in xrange(AVOGADRO):
# do something which involves reading const
This, with or without the redundant global const uses LOAD_GLOBAL to access the value of the global variables const, xrange, and AVOGADRO.
In C Python LOAD_GLOBAL will perform a fast dictionary lookup to access the variable (fast because the global variables are in a dictionary using only string keys and the hash values are pre-calculated). LOAD_FAST on the other hand simply accesses the first, second, third etc. local variables which is an array indexing operation.
Other versions of Python (e.g. PyPy) may be able to optimise accessing the global variable in which case there may not be any difference at all.
The first code (with n=i+const as the loop body) disassembles to:
>>> dis.dis(A.lengthy_op)
5 0 LOAD_FAST 0 (self)
3 LOAD_ATTR 0 (const)
6 STORE_FAST 1 (const)
6 9 SETUP_LOOP 30 (to 42)
12 LOAD_GLOBAL 1 (xrange)
15 LOAD_GLOBAL 2 (AVOGADRO)
18 CALL_FUNCTION 1
21 GET_ITER
>> 22 FOR_ITER 16 (to 41)
25 STORE_FAST 2 (i)
8 28 LOAD_FAST 2 (i)
31 LOAD_FAST 1 (const)
34 BINARY_ADD
35 STORE_FAST 3 (n)
38 JUMP_ABSOLUTE 22
>> 41 POP_BLOCK
>> 42 LOAD_CONST 0 (None)
45 RETURN_VALUE
while the second block gives:
>>> dis.dis(A.lengthy_op)
5 0 SETUP_LOOP 30 (to 33)
3 LOAD_GLOBAL 0 (xrange)
6 LOAD_GLOBAL 1 (AVOGADRO)
9 CALL_FUNCTION 1
12 GET_ITER
>> 13 FOR_ITER 16 (to 32)
16 STORE_FAST 1 (i)
7 19 LOAD_FAST 1 (i)
22 LOAD_GLOBAL 2 (const)
25 BINARY_ADD
26 STORE_FAST 2 (n)
29 JUMP_ABSOLUTE 13
>> 32 POP_BLOCK
>> 33 LOAD_CONST 0 (None)
36 RETURN_VALUE
Python won't make a local copy of the global because there is no easy way to be sure that the global value won't change while the code is running. Anything, even another thread or a debugger, could modify the value while the loop is executing.
A: Whether it is faster or slower actually depends on your scope, the scopes are stored in dictionaries and the smaller the dictionary is the (marginally) faster the access will be. Since dictionaries are implemented as hashsets the lookup performance is O(1).
Whenever you try to access a variable Python will walk the scopes in this order:
*
*Local. The local namespace which is the current function scope.
*Enclosing function locals. Depending on the amount of nested functions/lambda's there can be more of these.
*Global. The global scope which is just another dictionary (which you can access through globals())
*Built-ins. The standard Python built-ins that are available in all scopes such as list, int, etc..
Accessing a function/class attribute works in a similar fashion but involves:
*
*__getattribute__
*__dict__
*__getattr__
And that over all inherited classes as well.
The rest of your question was answered perfectly by Duncan | unknown | |
d4314 | train | It's no longer possible to generate an API token on its own for Slack. If it helps, you can just think of a Slack app as a simple container representing what you want to accomplish. Install the Slack app to get the token and then use the token for that purpose. You don't need to learn or implement OAuth or provide much more than a name to retrieve a token scoped to the activities you wish to accomplish. | unknown | |
d4315 | train | Unfortunately, the presence or absence of const on a non-static member function is not a feature that can be deduced separately from the function type it appertains to. Therefore, if you want to write a single foo template declaration that is limited to accepting pointers to members (but accepts both const and non-const member functions) then it would have to be:
template <class MemberOf, class F>
void foo(F MemberOf::*func);
For example:
#include <type_traits>
template <class MemberOf, class F>
void foo(F MemberOf::*func) {
static_assert(std::is_same<F, void(int) const>::value);
}
struct S {
void bar(int) const {}
};
int main() {
foo(&S::bar);
}
You cannot have F's argument types deduced at that point. You would have to dispatch to a helper function. (But we cannot deduce all the types at once while also writing a single declaration that accepts both const and non-const. If that's the only thing you'll accept, then sorry, it's not possible.) We can do this like so:
template <class T>
struct remove_mf_const;
template <class R, class... Args>
struct remove_mf_const<R(Args...)> {
using type = R(Args...);
};
template <class R, class... Args>
struct remove_mf_const<R(Args...) const> {
using type = R(Args...);
};
template <bool is_const, class F, class OutType, class MemberOf, class... ArgTypes>
void foo_helper(F func, OutType (MemberOf::*)(ArgTypes...)) {
// now you have all the types you need
}
template <class MemberOf, class F>
void foo(F MemberOf::*func) {
static_assert(std::is_function<F>::value, "func must be a pointer to member function");
using NonConstF = typename remove_mf_const<F>::type;
constexpr bool is_const = !std::is_same<F, NonConstF>::value;
foo_helper<is_const>(func, (NonConstF MemberOf::*)nullptr);
}
Coliru link | unknown | |
d4316 | train | Cheers to you for observing TOS. That's good business.
You could use SmartyStreets. LiveAddress API supports city/state and ZIP code lookups. It now has auto-complete as you type an address, too.
I work at SmartyStreets. In fact, we developed the jQuery plugin which does address validation and auto-complete for you. It even supports freeform address fields.
Related question by yours truly, over on UX stack exchange: https://ux.stackexchange.com/questions/22196/combining-all-the-address-fields-into-one | unknown | |
d4317 | train | If the key could appear anywhere, the answer is pretty simple:
function update_hash(&$item, $key, $base64String)
{
if ($key == "job_payload_hash") {
$item = $base64String;
}
}
array_walk_recursive($json, 'update_hash', 'something');
Update
The structure is something different that previously assumed; while the above will work, probably the below is a more direct approach:
foreach (array_keys($json['jobs']) as $jobId) {
$json['jobs'][$jobId]['job']['security_block']['job_payload_hash'] = 'something';
}
A: You use $key & $row variable in multiple time. for this reason, value of $key is changed each time, so parent loop does not work..
You can use recursive function lik answer of @Ja͢ck .
A: Decode the JSON string using json_decode(), edit your resulting array, then use json_encode(); to return the array to a JSON encoded string.
Also, use array_key_exists() rather than comparing array key strings.
$array = json_decode($json);
if(array_key_exists("job_payload_hash", $array){
$array["job_payload_hash"] = base64encode($var);
}
$json = json_encode($array);
A: this is because you have to save not in variables you defined after => in a foreach.
You have to store this in format:
$json[0][0] ... = $base64String;
OR
You have to add a new array like $result = array() before you write the foreach and then store it in $result. | unknown | |
d4318 | train | Yes you can do that with DAX and virtual relationship:
SumSales = calculate( sum('B'[Sales])
, TREATAS(SUMMARIZE('A','A'[Date],'A'[Country]), 'B'[Date],'B'[Country])
) | unknown | |
d4319 | train | pretty sure this will work, change it to meet your requirements though.
var messages = {
email: {
required:"Email is required field. Please enter valid email address",
email:"Please enter valid email address",
}
};
$(function(){
$("#test-form").validate({
onfocusout:false,
onkeyup:false,
messages:messages
});
});
Visit this JS Fiddle: http://jsfiddle.net/JcFYr/1/ | unknown | |
d4320 | train | You don't want to let the picturebox display complete images. Instead, you use the Paint event to draw the visible image portion yourself | unknown | |
d4321 | train | add one more element in your HTTPHandler tag for specific file type for example
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*.*" type="MyProject.Web.FileSecurityHandler, MyProject.Web"/>
<add path="*.jpg,*.jpeg,*.bmp,*.tif,*.tiff" verb="*" type="NameofYourHandler" />
</httpHandlers>
</system.web>
</configuration> | unknown | |
d4322 | train | You can use df.filter to filter all columns containing feat and calculate mean across axis=1 , and convert to int after comparison.
df['label'] = df.filter(like='feat').mean(1).gt(0).astype(int)
print(df)
feat1 feat2 feat3 feat4 label
0 0.18560 -0.18600 1.68100 0.56781 1
1 0.78671 0.17610 -0.67100 0.17600 1
2 -1.68100 0.15689 -0.18689 0.68100 0 | unknown | |
d4323 | train | change to this:
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mp != null) {
mp.stop();
mp.release();
}
}
});
A: Don't use stop() for pausing media. Use pause() and check isPlaying() or not before pausing() it. | unknown | |
d4324 | train | I've created a plunkr with your code here and it is working fine. I suppose you are not calling myFunc() correctly.
And also instead of using
for (var i = 0; i < 3; i++) {
if ($scope.result[i].Selected) {
...
}
}
You can make use of angular.forEach which will give you the object directly
angular.forEach(($scope.result, function(result, index){
if (result.selected){
...
}); | unknown | |
d4325 | train | Use a join. For example:
select user_id, text from posts
inner join followings on posts.user_id = followings.followed_id
where followings.follower_id = :user_id;
If I may recommend, stop using the mysql_ functions; they are deprecated and should not be used in newer applications. Instead, I'd recommend using PDO. | unknown | |
d4326 | train | After some research, I found out that when an area has a scrolling area doesn't propergate touch events, if not specified otherwise. For eaxample, if an area has horzontal scrolling, I have to spezify, that vertical touch events are still allowed. This can be done with the touch-action property (http://msdn.microsoft.com/en-us/library/windows/apps/hh767313.aspx ).
This fixes my problem:
<style>
body {
overflow-y: auto;
touch-action: pan-x:
}
</style> | unknown | |
d4327 | train | As I seem to be a lone crank in my interest in this question I have cranked
out an answer for myself, with a header file essentially like this:
exceptionalized_static_assert.h
#ifndef TEST__EXCEPTIONALIZE_STATIC_ASSERT_H
#define TEST__EXCEPTIONALIZE_STATIC_ASSERT_H
/* Conditionally compilable apparatus for replacing `static_assert`
with a runtime exception of type `exceptionalized_static_assert`
within (portions of) a test suite.
*/
#if TEST__EXCEPTIONALIZE_STATIC_ASSERT == 1
#include <string>
#include <stdexcept>
namespace test {
struct exceptionalized_static_assert : std::logic_error
{
exceptionalized_static_assert(char const *what)
: std::logic_error(what){};
virtual ~exceptionalized_static_assert() noexcept {}
};
template<bool Cond>
struct exceptionalize_static_assert;
template<>
struct exceptionalize_static_assert<true>
{
explicit exceptionalize_static_assert(char const * reason) {
(void)reason;
}
};
template<>
struct exceptionalize_static_assert<false>
{
explicit exceptionalize_static_assert(char const * reason) {
std::string s("static_assert would fail with reason: ");
s += reason;
throw exceptionalized_static_assert(s.c_str());
}
};
} // namespace test
// A macro redefinition of `static_assert`
#define static_assert(cond,gripe) \
struct _1_test \
: test::exceptionalize_static_assert<cond> \
{ _1_test() : \
test::exceptionalize_static_assert<cond>(gripe){}; \
}; \
_1_test _2_test
#endif // TEST__EXCEPTIONALIZE_STATIC_ASSERT == 1
#endif // EOF
This header is for inclusion only in a test suite, and then it will make
visible the macro redefinition of static_assert visible only when the test suite
is built with
`-DTEST__EXCEPTIONALIZE_STATIC_ASSERT=1`
The use of this apparatus can be sketched with a toy template library:
my_template.h
#ifndef MY_TEMPLATE_H
#define MY_TEMPLATE_H
#include <type_traits>
template<typename T>
struct my_template
{
static_assert(std::is_pod<T>::value,"T must be POD in my_template<T>");
explicit my_template(T const & t = T())
: _t(t){}
// ...
template<int U>
static int increase(int i) {
static_assert(U != 0,"I cannot be 0 in my_template<T>::increase<I>");
return i + U;
}
template<int U>
static constexpr int decrease(int i) {
static_assert(U != 0,"I cannot be 0 in my_template<T>::decrease<I>");
return i - U;
}
// ...
T _t;
// ...
};
#endif // EOF
Try to imagine that the code is sufficiently large and complex that you
cannot at the drop of a hat just survey it and pick out the static_asserts and
satisfy yourself that you know why they are there and that they fulfil
their design purposes. You put your trust in regression testing.
Here then is a toy regression test suite for my_template.h:
test.cpp
#include "exceptionalized_static_assert.h"
#include "my_template.h"
#include <iostream>
template<typename T, int I>
struct a_test_template
{
a_test_template(){};
my_template<T> _specimen;
//...
bool pass = true;
};
template<typename T, int I>
struct another_test_template
{
another_test_template(int i) {
my_template<T> specimen;
auto j = specimen.template increase<I>(i);
//...
(void)j;
}
bool pass = true;
};
template<typename T, int I>
struct yet_another_test_template
{
yet_another_test_template(int i) {
my_template<T> specimen;
auto j = specimen.template decrease<I>(i);
//...
(void)j;
}
bool pass = true;
};
using namespace std;
int main()
{
unsigned tests = 0;
unsigned passes = 0;
cout << "Test: " << ++tests << endl;
a_test_template<int,0> t0;
passes += t0.pass;
cout << "Test: " << ++tests << endl;
another_test_template<int,1> t1(1);
passes += t1.pass;
cout << "Test: " << ++tests << endl;
yet_another_test_template<int,1> t2(1);
passes += t2.pass;
#if TEST__EXCEPTIONALIZE_STATIC_ASSERT == 1
try {
// Cannot instantiate my_template<T> with non-POD T
using type = a_test_template<int,0>;
cout << "Test: " << ++tests << endl;
a_test_template<type,0> specimen;
}
catch(test::exceptionalized_static_assert const & esa) {
++passes;
cout << esa.what() << endl;
}
try {
// Cannot call my_template<T>::increase<I> with I == 0
cout << "Test: " << ++tests << endl;
another_test_template<int,0>(1);
}
catch(test::exceptionalized_static_assert const & esa) {
++passes;
cout << esa.what() << endl;
}
try {
// Cannot call my_template<T>::decrease<I> with I == 0
cout << "Test: " << ++tests << endl;
yet_another_test_template<int,0>(1);
}
catch(test::exceptionalized_static_assert const & esa) {
++passes;
cout << esa.what() << endl;
}
#endif // TEST__EXCEPTIONALIZE_STATIC_ASSERT == 1
cout << "Passed " << passes << " out of " << tests << " tests" << endl;
cout << (passes == tests ? "*** Success :)" : "*** Failure :(") << endl;
return 0;
}
// EOF
You can compile test.cpp with at least gcc 6.1, clang 3.8 and option
-std=c++14, or VC++ 19.10.24631.0 and option /std:c++latest. Do so first without defining TEST__EXCEPTIONALIZE_STATIC_ASSERT
(or defining it = 0). Then run and the the output should be:
Test: 1
Test: 2
Test: 3
Passed 3 out of 3 tests
*** Success :)
If you then repeat, but compile with -DTEST__EXCEPTIONALIZE_STATIC_ASSERT=1,
Test: 1
Test: 2
Test: 3
Test: 4
static_assert would fail with reason: T must be POD in my_template<T>
Test: 5
static_assert would fail with reason: I cannot be 0 in my_template<T>::increase<I>
Test: 6
static_assert would fail with reason: I cannot be 0 in my_template<T>::decrease<I>
Passed 6 out of 6 tests
*** Success :)
Clearly the repetitious coding of try/catch blocks in the static-assert
test cases is tedious, but in the setting of a real and respectable
unit-test framework one would expect it to package exception-testing apparatus to generate such stuff out of your sight. In googletest, for example, you are able to write the like of:
TYPED_TEST(t_my_template,insist_non_zero_increase)
{
ASSERT_THROW(TypeParam::template increase<0>(1),
exceptionalized_static_assert);
}
Now I can get back to my calculations of the date of Armageddon :) | unknown | |
d4328 | train | use a custom layout like this
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/pressed"></item>
<item android:state_focused="true" android:drawable="@drawable/focus"></item>
<item android:drawable="@drawable/normal"></item>
</selector>
Also note that the the selector should be defined in this particular way else they will give problem .i.e.
1)state_pressed
2)state_focused ( work only if you scroll to that button using the hardware key)
3)drawable i.e. normal
If you changed the ordering of the selector then it won't work. One easy way to remember it is visualizing a qwerty phone - first i saw the button (normal), then moved to that particular button using arrow keys (state_focused), then i pressed that button (state_pressed). Now write them backwards.
A: Instead of button,create ImageView and do necessary things on click of the image.
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="Method_Name"
android:src="@drawable/selector" >
</ImageView>
Also inorder to give different images on click and focus,create selector.xml in drawable folder and set background of imageview as selector file.
selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/image1" android:state_focussed="true" />
<!-- Inactive tab -->
<item android:drawable="@drawable/image2" android:state_pressed="true" />
<!-- Pressed tab -->
</selector>
Hope this will help you! | unknown | |
d4329 | train | If I understand what you want you must just click on the button at the bottom in yellow highlight: | unknown | |
d4330 | train | implement overridden toString method in object
example
class Dashboard{
private double re, im;
public Dashboard(double re, double im) {
this.re = re;
this.im = im;
}
@Override
public String toString() {
return String.format(re + " + i" + im);
}
} | unknown | |
d4331 | train | Tried this
a = {}
for i in range(10000):
a.update({"test" + str(i): ((MapObject.HASH_MAP,
{"key_1": ((1, ["value_1", 1.0]), CollectionObject),
"key_2": ((1, [["value_2_1", "1.0"], ["value_2_2", "0.25"]]), CollectionObject),
"key_3": ((1, [["value_3_1", "1.0"], ["value_3_2", "0.25"]]), CollectionObject),
"key_4": ((1, [["value_4_1", "1.0"], ["value_4_2", "0.25"]]), CollectionObject),
'key_5': False,
"key_6": "value_6"}), MapObject)})
start = time.time()
cache.put_all(a)
print(f'duration {time.time() - start}')
on master branch -- works as expected, took about 7 sec. to complete against 4 ignite nodes on average laptop. We will release 0.4.0 soon, stay tuned! | unknown | |
d4332 | train | My pom.xml in a maven android project. It works fine:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>empresa</groupId>
<version>1.0.0.BUILD-SNAPSHOT</version>
<artifactId>maestro-empresas</artifactId>
<packaging>apk</packaging>
<name>maestro-empresas</name>
<properties>
<maven-android-plugin-version>3.0.0-alpha-13</maven-android-plugin-version>
<maven-compiler-plugin-version>2.3.2</maven-compiler-plugin-version>
<com.google.android-version>2.2.1</com.google.android-version>
<org.springframework.android-version>1.0.0.BUILD-SNAPSHOT</org.springframework.android-version>
<commons-httpclient-version>3.1</commons-httpclient-version>
<org.codehaus.jackson-version>1.8.8</org.codehaus.jackson-version>
<android-platform>8</android-platform>
</properties>
<pluginRepositories>
<pluginRepository>
<id>oss.sonatype.org-jayway-snapshots</id>
<name>Jayway OpenSource SNAPSHOTs on Sonatype.org</name>
<url>http://oss.sonatype.org/content/repositories/jayway-snapshots/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<build>
<sourceDirectory>src</sourceDirectory>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>com.jayway.maven.plugins.android.generation2</groupId>
<artifactId>android-maven-plugin</artifactId>
<version>${maven-android-plugin-version}</version>
<configuration>
<sdk>
<!-- D:/SW/android-sdks/ -->
<!-- <path>${android.home}</path> -->
<platform>${android-platform}</platform>
</sdk>
<emulator>
<avd>Android2.2</avd>
</emulator>
<deleteConflictingFiles>true</deleteConflictingFiles>
<undeployBeforeDeploy>true</undeployBeforeDeploy>
</configuration>
<extensions>true</extensions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin-version}</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.google.android</groupId>
<artifactId>android</artifactId>
<version>${com.google.android-version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.android</groupId>
<artifactId>spring-android-rest-template</artifactId>
<version>${org.springframework.android-version}</version>
</dependency>
<dependency>
<!-- Para json -->
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${org.codehaus.jackson-version}</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>org.springframework.maven.snapshot</id>
<name>Spring Maven Snapshot Repository</name>
<url>http://maven.springframework.org/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>org.springframework.maven.milestone</id>
<name>Spring Maven Milestone Repository</name>
<url>http://maven.springframework.org/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>android-rome-feed-reader-repository</id>
<name>Android ROME Feed Reader Repository</name>
<url>https://android-rome-feed-reader.googlecode.com/svn/maven2/releases</url>
</repository>
</repositories>
</project> | unknown | |
d4333 | train | SELECT '{"Dtl": {"campaignId":"12345","offerId":"67789"}}' :: jsonb #> '{Dtl,campaignId}' => "12345"
SELECT '{"Dtl": {"campaignId":"12345","offerId":"67789"}}' :: jsonb #> '{Dtl,offerId}' => "67789"
see test result in dbfiddle | unknown | |
d4334 | train | I think you can manually checkout when spider finished:
def closed(self, reason):
if reason == "finished":
return requests.post(checkout_url, data=param)
print("Spider closed but not finished.")
See closed.
update
class MySpider(scrapy.Spider):
name = 'whatever'
def start_requests(self):
params = getShopList()
for param in params:
yield scrapy.FormRequest('https://foo.bar/shop', callback=self.addToBasket,
method='POST', formdata=param)
def addToBasket(self, response):
yield scrapy.FormRequest('https://foo.bar/addToBasket',
method='POST', formdata=param)
def closed(self, reason):
if reason == "finished":
return requests.post(checkout_url, data=param)
print("Spider closed but not finished.")
A: I solved it by using Scrapy signals and spider_idle call.
Sent when a spider has gone idle, which means the spider has no
further:
*
*requests waiting to be downloaded
*requests scheduled items being
*processed in the item pipeline
https://doc.scrapy.org/en/latest/topics/signals.html
from scrapy import signals, Spider
class MySpider(scrapy.Spider):
name = 'whatever'
def start_requests(self):
self.crawler.signals.connect(self.spider_idle, signals.spider_idle) ## notice this
params = getShopList()
for param in params:
yield scrapy.FormRequest('https://foo.bar/shop', callback=self.addToBasket,
method='POST', formdata=param)
def addToBasket(self, response):
yield scrapy.FormRequest('https://foo.bar/addToBasket',
method='POST', formdata=param)
def spider_idle(self, spider): ## when all requests are finished, this is called
req = scrapy.Request('https://foo.bar/checkout', callback=self.checkoutFinished)
self.crawler.engine.crawl(req, spider)
def checkoutFinished(self, response):
print("Checkout finished") | unknown | |
d4335 | train | You can try like this:
'purchaser_first_name' => Rule::requiredIf(function () use ($request) {
return $request->input('gift') && !$request->input('authenticated');
}),
In the function, you can set your logic. I'm not sure what you need for real, but it's good for a start.
Also, check docs for more info about that.
A: Try to change your validation code as below :
return [
'gift' => 'required',
'authenticated'=>'required',
'purchaser_first_name' => 'required_if:gift,true|required_if:authenticated,false',
'purchaser_last_name' => 'required_if:gift,true|required_if:authenticated,false',
]; | unknown | |
d4336 | train | I had the similar issue and took a while to figure out the problem and fix.
Please include the following code after
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000" />
</webServices>
</scripting>
</system.web.extensions> | unknown | |
d4337 | train | Self solved, was grouping on wrong variable | unknown | |
d4338 | train | The biggest problem I see in your questions is that you seem to be severly overcomplicating simple things. First and foremost, Qt's containers are implicitly shared. Thus taking their copies is cheap if said copies are not modified. Thus you can freely pass the outermost container by reference, and have it take the innards by value.
It'd be reasonably cheap, for example, to simply pass QList<vector_t> to your method. It would involve no copying of any kind. Even then, it costs a tiny bit less to pass a const reference instead of a value, namely const QList<vector_t> &.
Why are you taking the address of v? Let's dissect the type of v:
QList<vector_t*> = QList<QVector<QStringList>>*>
To access the innermost element you need to:
*
*Access a list element: v[0]
*Dereference the pointer: *exp
*Access the vector element: exp[0]
By exp I mean the preceding expression, taken as a unit.
Thus:
QStringList & sl = (*(v[0]))[0];
This is C++, not C, you should use a reference instead of a pointer.
If you insist on a pointer:
QStringList * sl = *((*(v[0]))[0]);
But then you can do silly things like delete sl or free(sl) and it will compile but will result in, maybe, your hard drive getting formatted. | unknown | |
d4339 | train | The ternary
counts[ch] = count ? count + 1 : 1;
The condition in this expression is not counts[ch] = count but just count and is equivalent to
if (count){
counts[ch] = count + 1;
}
else {
counts[ch] = 1;
}
The right hand side of an assignment expression is always evaluated first and the counts[ch] is assigned the result of count ? count + 1 ? 1.
A: You're conflating the ternary with the assignment expression.
The code
counts[ch] = count ? count + 1 : 1;
can also be written as
counts[ch] = (count ? count + 1 : 1);
// but not (counts[ch] = count) ? count + 1 : 1
// that does something entirely different
And then, writing the matching if/else becomes pretty clear
if (count) {
counts[ch] = count + 1;
} else {
counts[ch] = 1;
} | unknown | |
d4340 | train | You could create helper method:
function query(resource, query) {
function querySucceeded(data) {
$localStorage[resource] = data.results;
}
function queryFailed() {}
ParseFactory.provider(resource, query)
.getAll()
.success(querySucceeded)
.error(queryFailed);
}
and, then just call:
query('Favourites', query);
query('Customers', query);
and so on.
Alternatively, you could factor queryFailed out, as such:
function query(resource, query) {
function querySucceeded(data) {
$localStorage[resource] = data.results;
}
return ParseFactory.provider(resource, query)
.getAll()
.success(querySucceeded);
}
function queryFailed() {
}
$q.all([
query('Favourites', query1),
query('UserItems', query2)])
.error(queryFailed);
A: $q.all takes an array (or object) of promises, and returns a single one.
The returned promise is resolved when all the original promises are resolved. It's rejected as soon as one of the original promises is rejected.
So, what you can simply do is something like
var request = function(path) {
return ParseFactory.provider(path, query).getAll();
};
var promises = {
favourites: request('Favourites'),
programmes: request('Somethings/'),
exercises: request('UserItems'),
customers: request('Customers')
};
$q.all(promises).then(function(results) {
$localStorage.Favourites = results.favourites.data.results;
// ...
}).catch(function() {
// ...
}); | unknown | |
d4341 | train | You get the error because the conectar method returns an object, which you then assign to Dt1, which is a DataTable, and so you get the message that the value cannot be implicitly converted..
You can explicitly cast the return value to a DataTable, as the conectar method never returns null:
Dt1 = (DataTable)conectar("select Tabla from DigitoVerificador");
Alternatively, and probably better, you would change the return type of conectar to DataTable. | unknown | |
d4342 | train | This is wrong:
FB.init({ apiKey: 'SECRET_KEY' });
Not secret key, just the application id.
A: From the documentation for the JavaScript SDK:
You can see that your secret key is not needed, as the JavaScript is available for anyone to read. Facebook's authentication uses the domain of your request to verify that it is, in fact, your application.
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script> | unknown | |
d4343 | train | If you're using HttpClient.execute(), it's a synchronous method - it returns once the upload is done.
EDIT: there's no asynchronous HTTP client on Android, as far as I know. For non-blocking upload, use HttpClient is a worker thread, and use Handler.post(Runnable) to process the completion back in the main thread.
EDIT2: the async HTTP looks like this:
final Handler Ha = new Handler(); //Used to post the results back to the main thread
new Thread(new Runnable(){
public void run()
{
HttpPost pr = new HttpPost(MyURL);
pr.setEntity(MyUploadData);
//More request setup...
HttpResponse Resp = new DefaultHttpClient().execute(pr);
//Process response here... detect errors, for one thing
Ha.post(new Runnable(){
public void run()
{
//This executes back in the main thread!
}
});
}
}).start(); | unknown | |
d4344 | train | The problem resided with how IE handles NTLM authentication protocol. An optimization in IE that is not present in Chrome and Firefox strips the request body, which therefore creates an unexpected response for my update panels. To solve this issue you must either allow anonymous requests in IIS when using NTLM or ensure Kerberos is used instead. The KB article explains the issue and how to deal with it.KB251404 | unknown | |
d4345 | train | I don't fully understand your question but you might be able to filter the collection with the type attribute. eg type_id='configurable' or type_id='simple'.
->addAttributeToFilter('type_id', array('eq' => 'configurable'));
->addAttributeToFilter('type_id', array('eq' => 'simple'));
**EDIT following comments below
So, then, I think what you want to do is run the collection as-is, then from the simple product, find out what its configurable is using the function
$productParentId = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($simpleProductId);
The function will return an array and you may need additional logic to deduce which configurable but I expect most stores operate with only one configurable product per simple product. I use $productParentId[0] to identify the configurable products in my store. | unknown | |
d4346 | train | *
*"repository at a windows share" is The Bad&Ugly Idea (tm)
*Use post-* hook in INTERNAL for pushing to EXTERNAL as it happens
*Pseudo-CVCS in DVCS is ugly (everybody can bring local travel-repo to workplace and sync from it) | unknown | |
d4347 | train | Without using IN, you can use OR:
SELECT * FROM `table` WHERE co1 = `value1` OR col1 = `value2` | unknown | |
d4348 | train | The R class is generated automatically by the Android Eclipse plugin when it can. Here, I can see a red cross on your "res" folder so I think you should have some errors on your resources naming or type or something else : just look what your IDE is telling you !
Fix all errors that are not "R class missing" related and this class will be generated.
A: try this :
1 - File->Import (android-sdk\extras\android\support\v7). Choose "appcompat"
2 - Project-> properties->Android. In the section library "Add" and choose "appCompat"
3 - That is all! | unknown | |
d4349 | train | You can use reflection to solve your problem. As I don't know actually what you're gonna get and set from those two objects, I am giving a minimal example to show what you can do in this case.
You can get all the declared fields in your Summary class as follows:
Field[] arrayOfFields = Summary.class.getDeclaredFields();
As you have all the fields of the class summary, you can iterate through each field and do the get and set easily for different objects of that class as follows. Remember to set field.setAccessible(true) if the fields are private inside the class:
for (Field field: arrayOfFields) {
try {
field.setAccessible(true);
if (field.getType() == Double.class) {
Double prevVal = field.get(previous);
Double currentVal = field.get(current);
//do calculation and store to someval
field.set(resultSummary, someval);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
Well, you may need to check all type of classes that your class Summary has and do the get and set according to that type. Please keep in mind that you cannot use primitive type fields for this if condition check as they are not Class. So, you may need to convert the primitive type variables in the summary class to corresponding Object Class. Like double to Double etc.
The field.get(Object obj) method gets the value for the field in the Object obj. Similarly, field.set(Object obj, Object value) sets the Object value to the field in the Object obj
With this approach you can achieve the goal easily with less hassle and dynamic coding. | unknown | |
d4350 | train | Check the .asoundrc file on the /home/pi folder. Mine did the same thing because I had extra commands in that file that mucked everything up. | unknown | |
d4351 | train | Python Mutable Default Arguments are counter-intuitive!
Python creates the list once when the method is defined not when it is called. Therefore the list obj is shared between instances. Here's A good article on the issue.
I would instead remove the default argument and check/set it in the init method.
class bookshelf:
def __init__(self,books):
self.books = []
if books:
self.books = books | unknown | |
d4352 | train | This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.
https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html
In other words, The TreeSet class does not maintain the uniqueness of its elements via the equals method but with the compareTo method of the class implementation, if the class implements Comparable, or with the compareTo of the given Comparator.
As others have pointed out in the comments, if you want to maintain uniqueness among your Points by their coordinates, you should override the equals and hashCode methods, as the general hashcode contract states and utilize a HashSet to store your Points.
In the following snippet, I've updated your class by implementing the equals, hashCode and toString methods to show how only three elements are printed instead of four.
public class Point implements Comparable<Point> {
double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
// ... your implementation ...
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj == this) return true;
if (obj.getClass() != getClass()) return false;
Point other = (Point) obj;
return x == other.x && y == other.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public String toString() {
return String.format("(%g;%g)", x, y);
}
public static void main(String[] args) {
HashSet<Point> tp = new HashSet<>();
tp.add(new Point(0.125, 0.5));
tp.add(new Point(0. - 125, 0.25));
tp.add(new Point(0.15, -0.75));
tp.add(new Point(0.125, 0.5));
System.out.println(tp);
}
} | unknown | |
d4353 | train | That's not what you originally posted!!! You have a hash of reference to arrays. Read the perl reference tutorial (perlreftut) to learn about them.
(Use the command
perldoc perlreftut
to access this tutorial)
A: This should work.
my $key;
my $value;
while (($key, $value) = each %hash) {
$sth->bind_param(1, $key);
$sth->bind_param(2, $value);
$sth->execute();
}
A: UPDATE:
I suggest that you grab one of the functional examples from the previous thread and get it working on your machine with your database. Once you can get one of these examples working then you should be able to fix your own code.
Previous answer:
My reply on the other thread that uses execute_array() also works, I tested it before posting it. | unknown | |
d4354 | train | The problem is due to the Razor Scripting settings in the umbracoSettings.config file. It is there that several HTML items are listed that will be ignored as DynamicXml. I have added several to mine to make this problem go away.
<scripting>
<razor>
<!-- razor DynamicNode typecasting detects XML and returns DynamicXml - Root elements that won't convert to DynamicXml -->
<notDynamicXmlDocumentElements>
<element>p</element>
<element>div</element>
<element>ul</element>
<element>span</element>
<element>script</element>
<element>iframe</element>
</notDynamicXmlDocumentElements>
</razor>
</scripting> | unknown | |
d4355 | train | I found a solution, in which I put the rigidbody in a gameobject that parented the negatively scaled mesh. | unknown | |
d4356 | train | Crawling them is the only sensible option, you probably only need to hit their homepages. I'd make use of Feed::Find to fetch the pages and detect the feed URIs.
A: When you just paste a blog URL to google reader, it can automatically save RSS path. Most probably what Google Reader does is inspecting the source code for things like
<link rel="alternate" type="application/atom+xml" .. or
<link rel="alternate" type="application/rss" ..
That's how Firefox and some other browsers can show a RSS icon when you are surfing on a regular page. You can see Firefox source code for a healthy result.
In addition to those, you may consider looking at /blog, /rss, /blog/feed, blog.*.com/feed, /atom or URLs like *.xml, *.feed, *.rss Those are almost most popular RSS paths imho. | unknown | |
d4357 | train | *
*Derive a sub class of TComponentProperty.
*Override its GetValues method to apply your filter.
*Register this TComponentProperty as the property editor for your property.
Here is a very simple example:
Component
unit uComponent;
interface
uses
System.Classes;
type
TMyComponent = class(TComponent)
private
FRef: TComponent;
published
property Ref: TComponent read FRef write FRef;
end;
implementation
end.
Registration
unit uRegister;
interface
uses
System.SysUtils, System.Classes, DesignIntf, DesignEditors, uComponent;
procedure Register;
implementation
type
TRefEditor = class(TComponentProperty)
private
FGetValuesProc: TGetStrProc;
procedure FilteredGetValuesProc(const S: string);
public
procedure GetValues(Proc: TGetStrProc); override;
end;
procedure TRefEditor.FilteredGetValuesProc(const S: string);
begin
if S.StartsWith('A') then
FGetValuesProc(S);
end;
procedure TRefEditor.GetValues(Proc: TGetStrProc);
begin
FGetValuesProc := Proc;
try
inherited GetValues(FilteredGetValuesProc);
finally
FGetValuesProc := nil;
end;
end;
procedure Register;
begin
RegisterComponents('Test', [TMyComponent]);
RegisterPropertyEditor(TypeInfo(TComponent), nil, 'Ref', TRefEditor);
end;
end.
This rather useless property editor will only offer you components whose names begin with A. Despite its complete lack of utility, this does illustrate the ability to filter that you desire. You'll likely want to call Designer.GetComponent(...) passing a component name to obtain the component instance, and implement your filtering based on the type and state of that component instance.
A: As @TLama already pointed out you need to change the tpe of handler field/property.
Now in case if you want to ba able to assign specific type of component to this field/property then set this field type to the same type of that compomnent.
But if you want to be able to assign several different component types but not all components make sure that Handler field/property type is the type of the first common ancestor class/component of your desired components that you want to be able to assign to the Handler field/property. | unknown | |
d4358 | train | You can now use the following:
<%= f.association :store, selected: 1 %>
A: Use the following:
selected: 1 | unknown | |
d4359 | train | Any SQL statement always runs in a single transaction (the exception to this rule is CALL).
So your DO statement will run in a single transaction, and either all three SQL statements are successful, or all will be rolled back. | unknown | |
d4360 | train | Under the conditions in which that code is executed, and supposing that IEEE-754 double-precision floating point representations and arithmetic are in use, 1.0 + x will always evaluate to 1.0, so x * (1.0 + x) will always evaluate to x. The only externally (to the function) observable effect of performing the computation as is done instead of just returning x would be to set the IEEE "inexact" status flag.
Although I know no way to query the FP status flags from Java, other native code could conceivably query them. More likely than not, however, the practical reason for the implementation is given by by these remarks in the Javadocs for java.StrictMath:
To help ensure portability of Java programs, the definitions of some of the numeric functions in this package require that they produce the same results as certain published algorithms. These algorithms are available from the well-known network library netlib as the package "Freely Distributable Math Library," fdlibm. These algorithms, which are written in the C programming language, are then to be understood as executed with all floating-point operations following the rules of Java floating-point arithmetic.
The Java math library is defined with respect to fdlibm version 5.3. Where fdlibm provides more than one definition for a function (such as acos), use the "IEEE 754 core function" version (residing in a file whose name begins with the letter e). The methods which require fdlibm semantics are sin, cos, tan, asin, acos, atan, exp, log, log10, cbrt, atan2, pow, sinh, cosh, tanh, hypot, expm1, and log1p.
(Emphasis added.) You will note in the C source code an #include "fdlibm.h" that seems to tie it to the Javadoc comments. | unknown | |
d4361 | train | You can use Timespan
DateTime oldDate = DateTime.Now.AddDays(-4);
DateTime today = DateTime.Now;
TimeSpan span = oldDate.Subtract(today);
string diff = span.Days.ToString();
A: Since you are using MySQL, your select statement should be like:
SELECT DATEDIFF(CURDATE(), MAX(AmountPay.DateUpto)) AS [ PaidUpTo],
TimeTable.Name,
......
DATEDIFF will give you values like -1, 1, -5 ...and your DataGridView should display those values just fine.
A: SELECT DATEDIFF(day,GetDate(), MAX(AmountPay.DateUpto)) AS [ PaidUpTo], TimeTable.Name, TimeTable.Ref, TimeTable.Time11to12 FROM AmountPay FULL OUTER JOIN TimeTable ON AmountPay.Ref = TimeTable.Ref WHERE (TimeTable.Time11to12 = @Time11to12) GROUP BY TimeTable.Name, TimeTable.Ref, TimeTable.Time11to12 | unknown | |
d4362 | train | The simplest way would be to implement Jquery autocomplete. I won't do the code for you but if you find it difficult create a new question posting some of the code you tried and someone will help.
A: Two nice alternatives to jQuery autocomplete which was already mentioned are Chosen and Select2. Both of these require jQuery or another supported JS framework. jQuery autocomplete and Select2 have great support for remote datasets. | unknown | |
d4363 | train | If I were you and had these number of variables which should be set to some value in a loop, I would use an array instead:
$arr = ['first value', 'second value','hundred value'];
Then you can access what you want by index in your loop, so instead of using:
$variable_one
You will use:
$arr[0]
And now you want to reset them all, so you can use array_map() like this:
$arr = array_map(function($val){ return '';}, $arr);
A: If you have such a high number of variables in your loop, you probably should refactor it to make it simpler. If you are sure that having 100 variables inside a loop is a way to go, you can use the following expression:
$variable_one = $variable_two = $variable_hundred = '';
This will set each variable to '' in one very long line.
Another option is to unset() all these variables in a single function call:
unset($variable_one, $variable_two, $variable_hundred);
But this will not set their value to '', but unset the variable itself. | unknown | |
d4364 | train | You can either create a class library and share it between projects or you can serialize the object to JSON and have equivalent classes on each side.
You don't mention what mechanism you are using to serialize but I am assuming it's a binary serialization you are using. If binary serialization is required a class library that is shared is your best choice.
A: Create Class Library(for .Net Core) project. Create there classes (or interfaces or something else you want to share) you want to transfer among projects.
Then add reference to that library in every project that needs that class. Add using directive with library namespace and you can use these classes.
A: If you don't want to share classes, or if you need another options, then you can use Serializatoin/Deserialization mechanisms that doesn't care about the original type, but rather for it compatibility with the Data. Like Json.Net by default.
Serialization in one solution:
var jsonSerializedString = JsonConvert.SerializeObject(myObjectInAssemblyA);
Deserialization in the other solution:
objectInAssemblyB = JsonConvert.DeserializeObject<ObjectClassName>(jsonSerializedString); | unknown | |
d4365 | train | Is it the blank call back?
res.render('test-index', {}, function(err, html) {
});
In my app I'm using
res.render('test-index', {}); | unknown | |
d4366 | train | I read your question and some of the comments as @sirdarius suggested you can use const_format for fancy formatting or simply use concat! from the standard library.
You mention that const_format requires everything to be const and that's not suitable for your case. Unfortunately, that's not possible. If you don't know the shape of the thing at compile time you cannot use it at compile time because it simply does not exist yet. Adding another str to the end of &str requires heap allocation due to the unknown size of the the runtime str you are planning to use.
I hope this made compile time vs runtime a little more clearer for you
A: The only way to satisfy the signature of foo() and return a dynamic string is by leaking it:
fn foo() -> &'static str {
let x = "Jeff";
return Box::leak(format!("Hello, {}", x).into_boxed_str());
}
Caveat emptor: the return &'static str will never be freed, so this is only usable in cases where foo() is known to be called a fixed and small number of times, such as at program startup.
A: Depending on your use case, once_cell may be what you are looking for. It provides the generic Lazy<T> type that can be used to lazily initialize global data. Since the data is initialized at runtime, said initialization can do things that are impossible with compile time initialization.
Your function could be written like this:
use once_cell::sync::Lazy;
fn foo() -> &'static str {
static VALUE: Lazy<String> = Lazy::new(|| {
let x = "Jeff";
format!("Hello, {}", x)
});
&VALUE
}
or, if the name can be a static too, you can move it outside of the function:
use once_cell::sync::Lazy;
static NAME: &str = "Jeff";
fn foo() -> &'static str {
static VALUE: Lazy<String> = Lazy::new(|| {
format!("Hello, {}", NAME)
});
&VALUE
} | unknown | |
d4367 | train | You do need to exercise some care.
1.0 + 2.0 == 3.0
is true because integers are exactly representable.
Math.sqrt(b) == Math.sqrt(c)
if b == c.
b / 3.0 == 10.0 / 3.0
if b == 10.0 which is what I think you meant.
The last two examples compare two different instances of the same calculation. When you have different calculations with non representable numbers then exact equality testing fails.
If you are testing the results of a calculation that is subject to floating point approximation then equality testing should be done up to a tolerance.
Do you have any specific real world examples? I think you will find that it is rare to want to test equality with floating point.
A: b / 3 != 10 / 3 - if b is a floating point variable like b = 10.0f, so b / 3 is 3.3333, while 10 / 3 is integer division, so is equal to 3.
If b == c, then Math.sqrt(b) == Math.sqrt(c) - this is because the sqrt function returns double anyways.
In general, you shouldn't be comparing doubles/floats for equation, because they are floating point numbers so you might get errors. You almost always want to compare them with a given precision, i.e.:
b - c < 0.000001
A: The safest way to compare a float/double with something else is actually to use see if their difference is a small number.
e.g.
Math.abs(a - b) < EPS
where EPS can be something like 0.0000001.
In this way you make sure that precision errors do not affect your results.
A: == comparison is not particularly safe for doubles/floats in basically any language. An epsilon comparison method (where you check that the difference between two floats is reasonably small) is your best bet.
For:
Math.sqrt(b) == Math.sqrt(c)
I'm not sure why you wouldn't just compare b and c, but an epsilon comparison would work here too.
For:
b / 3 == 10 / 3
Since 10/3 = 3 because of integer division, this will not necessarily give the results you're looking for. You could use 10.0 / 3, though i'm still not sure why you wouldn't just compare b and 10 (using the epsilon comparison method in either case).
A: In general, no it is not safe due to the fact that so many decimal numbers cannot be precisely represented as float or double values. The often stated solution is test if the difference between the numbers is less than some "small" value (often denoted by a greek 'epsilon' character in the maths literature).
However - you need to be a bit careful how you do the test. For instance, if you write:
if (Math.abs(a - b) < 0.000001) {
System.err.println("equal");
}
where a and b are supposed to be "the same", you are testing the absolute error. If you do this, you can get into trouble if a and b are (say_ 1,999,999.99 and 2,000,000.00 respectively. The difference between these two numbers is less than the smallest representable value at that scale for a float, and yet it is much bigger than our chosen epsilon.
Arguably, a better approach is to use the relative error; e.g. coded (defensively) as
if (a == b ||
Math.abs(a - b) / Math.max(Math.abs(a), Math.abs(b)) < 0.000001) {
System.err.println("close enough to be equal");
}
But even this is not the complete answer, because it does not take account of the way that certain calculations cause the errors to build up to unmanageable proportions. Take a look at this Wikipedia link for more details.
The bottom line is that dealing with errors in floating point calculations is a lot more difficult than it appears at first glance.
The other point to note is (as others have explained) integer arithmetic behaves very differently to floating point arithmetic in a couple of respects:
*
*integer division will truncate if the result is not integral
*integer addition subtraction and multiplication will overflow.
Both of these happen without any warning, either at compile time or at runtime.
A: Float wrapper class's compare method can be used to compare two float values.
Float.compare(float1,float2)==0
It will compare integer bits corresponding to each float object.
A: In java you can compare a float with another float,and a double with another double.And you will get true when comparing a double with a float when their precision is equal
A: b is float and 10 is integer then if you compare both with your this critearia then it will give false because...
b = flaot (meance ans 3.33333333333333333333333)
10 is integer so that make sence.
A: If you want a more complete explanation, here there is a good one: http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html (but it is a little bit long) | unknown | |
d4368 | train | Change request.json to request.form in the AddOne function. | unknown | |
d4369 | train | If you are sure the code is never passing the switch statement, there is only one other possibility:
There is an exception being thrown in the switch statement, and it is being caught somewhere higher up so the program just continues.
One thing you could try to verify this suggestion would be wrapping your switch in a temporary try{}catch{} block and showing a MessageBox on Exception, or use lots of breakpoints. | unknown | |
d4370 | train | In order to download a image from Firebase Storage, you first need to have the corresponding url of the image. To download a image, it requires more steps:
*
*Upload the image to Firebase Storage.
*Save the corresponding url to Firebase Database while uploading.
*Attach a listener on the folder you have saved the image.
*Display the image.
Let's say your Firebase Storage structure looks something like this:
Storage-root
|
--- Photos
|
--- FolderNo1
| |
| --- image1.jpg
| |
| --- image2.jpg
|
--- FolderNo2
|
--- image3.jpg
|
--- image3.jpg
The coresponding database structure of your Firebase database that stores the urls of the images should look like this:
Firebase-root
|
--- Photos
|
--- FolderNo1
| |
| --- imageName1: imageUrl1
| |
| --- imageName2: imageUrl2
|
--- FolderNo2
|
--- imageName3: imageUrl3
|
--- imageName4: imageUrl4
The folder names in the Firebase database can be simple names (but be sure when uploading to check the names for uniqueness) or can be random unique ids, in which case i recomand you using the push() method.
If you are saving the images through Firebase Console, you cannot get the image url, that's why you should do this programmatically.
Firestore documentation shows how to download just a single image because even if you download a single image or more images, the code is almost the same.
If you want to get all urls from a single folder, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference folderRef = rootRef.child("Photos").child("FolderNo1");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String imageName = ds.getKey();
String imageUrl = ds.getValue(String.class);
list.add(imageUrl);
}
Log.d("TAG", list);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
folderRef.addListenerForSingleValueEvent(eventListener);
If you want to get all urls from all folders, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference photosRef = rootRef.child("Photos");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String imageName = ds.getKey();
String imageUrl = ds.getValue(String.class);
list.add(imageUrl);
}
Log.d("TAG", list);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
photosRef.addListenerForSingleValueEvent(eventListener);
In both cases, as you probably see, you get a List of urls. Having this list, you can now download the desired images according to Firebase Storage Office Documentation but instead of using one url as mentioned there, you need to use a List of urls.
A: you need to save path and image name in realtime database at upload images time in firebase database than you will get all images
showing in below image | unknown | |
d4371 | train | Considering that the value of x is an expression that should be used inside the filter method, i.e x can be something like x = 'device_id=5', then you can do the following:
x = 'device_id=5'
temp_list = x.split('=')
Now that you have separated the keyword and the value from the expression, then you can use temp_list inside the filter method as follows, unpacking a dictionary created in-place:
DeviceData.objects.filter(**{temp_list[0]: temp_list[1]})
For the case x equals None or there's some other problem with the value of the keywords inside x, you can handle those exceptions as follows (following EAFP approach):
x = 'device_id=5'
try:
temp_list = x.split('=')
qs = DeviceData.objects.filter(**{temp_list[0]: temp_list[1]})
except (ValueError, TypeError, AttributeError) as e:
qs = DeviceData.objects.all() | unknown | |
d4372 | train | It's not possible to have solution that works on any type with a * method without writing a boilerplate conversion for each type you want to deal with. Essentially to do that you would need a recursive structural type, and Scala does not support those because of JVM type erasure. See this post for more details.
You can get fairly close to what you want using a type class along with the Numeric type class, (inspired by the answers to this and this question). This will work with most primitives:
//define the type class
trait Multipliable[X] { def *(x: X): X}
//define an implicit from A <% Numeric[A] -> Multipliable[Numeric[A]]
implicit def Numeric2Mult[A](a: A)(implicit num: Numeric[A]): Multipliable[A] = new Multipliable[A]{def *(b: A) = num.times(a, b)}
//now define your Enhanced class using the type class
class EnhancedMultipliable[T <% Multipliable[T]](x: T){ def squared = x * x}
//lastly define the conversion to the enhanced class
implicit def Mult2EnhancedMult[T <% Multipliable[T]](x: T) = new EnhancedMultipliable[T](x)
3.squared
//Int = 9
3.1415F.squared
//Float = 9.869022
123456789L.squared
//Long = 15241578750190521
A: Go visit Scala: How to define “generic” function parameters?
A: Think about it. Multiplication have different properties on different objects. Integer multiplication, for example, is associative and commutative, scalar multiplication is not commutative. And multiplication on floating point numbers...
But, of course, you can have what you want with trait or with "trait and implicit" construction which resembles a typeclass. | unknown | |
d4373 | train | Lifera service builder generates classes that can be used to do CRUD operations for database entity only. So its referred as database persistence. | unknown | |
d4374 | train | I think this could work:
var searchProduct = "select * from LISTOFPRODUCTS where UPPER(ITEM) LIKE UPPER('%" + searchValue + "%'")
Also the same with LOWER()
Note that the trick is parse both values to UPPER() or LOWER() to match them.
A: You can use the function LOWER().
For example:
var searchProduct = "select * from LISTOFPRODUCTS where LOWER(ITEM) LIKE '%" + searchValue + "%'"
A: You can also consider using REGEXP_LIKE which has a case-insensitive option i | unknown | |
d4375 | train | Try the following code below. The only difference is using terms as an array.
$getSearch=get_search_query();
$args = array(
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'product_tag',
'field' => 'slug',
'terms' => array($getSearch) // Using the terms as an array
),
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array($getSearch) // Using the terms as an array
)
),
'post_type' => 'product'
);
$the_query = new WP_Query( $args );
// ... functions.php
add_action( 'pre_get_posts', 'my_search_exclude' );
function my_search_exclude( $query )
{
if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) {
$query->set( 's', '' );
}
}
You can find more info here: https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters | unknown | |
d4376 | train | IsTooltipOpen: False <-- ToolTip Opened
IsTooltipOpen: False <-- ToolTip Closed
IsTooltipOpen: True <-- ToolTip Opened
IsTooltipOpen: False <-- ToolTip Closed
TreeViewItem B:
IsTooltipOpen: True <-- ToolTip Open
IsTooltipOpen: False <-- ToolTip Open, occured at the same time as the previous entry.
IsTooltipOpen: False <-- ToolTip Closed
IsTooltipOpen: True <-- ToolTip Opened
IsTooltipOpen: False <-- ToolTip Closed
So I was curious if anyone had any idea what was going on? and possible solutions?
A: It appears that the events are working as intended with the ToolTip class. So I created an attached property to fix the problem I was having.
I have a attached property to enable the registration of events:
public static readonly DependencyProperty EnableWatchProperty = DependencyProperty.RegisterAttached(
"EnableWatch",
typeof( bool ),
typeof( ToolTipFix ),
new PropertyMetadata( default( bool ), OnEnableWatchPropertyChanged ) );
private static void OnEnableWatchPropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
var toolTip = d as ToolTip;
if( toolTip == null ) return;
var newValue = (bool) e.NewValue;
if( newValue )
{
toolTip.Opened += OnTooltipOpened;
toolTip.Closed += OnTooltipClosed;
}
else
{
toolTip.Opened -= OnTooltipOpened;
toolTip.Closed -= OnTooltipClosed;
}
}
I also have an attached property that can be binded to, and it indicates the current state of the ToolTip:
public static readonly DependencyProperty IsOpenProperty = DependencyProperty.RegisterAttached(
"IsOpen",
typeof( bool ),
typeof( ToolTipFix ),
new PropertyMetadata( default( bool ) ) );
The event handlers just set the IsOpen property to true or false depending on the event that was invoked.
Here is how I used the the attached property in XAML:
<ToolTip local:ToolTipFix.EnableWatch="True"
local:ToolTipFix.IsOpen="{Binding IsToolTipOpen, Mode=OneWayToSource}">
...
</ToolTip>
If anyone has another solution, or reason for this problem, I would very much appreciate it.
A: This was confusing the heck out of me, and I couldn't help but poke at it for while to try and understand what's going on. I'm not entirely sure I arrived at a complete understanding, but I'm further than when I started =D
I replicated your behaviour for a very simple ToolTip in a Grid, I had a good look at events and the ToolTipService and got nowhere, then started using WPF Snoop (no affiliation) to examine the DataContext on the ToolTip when the application was first started.
Seemingly, the ToolTip has no DataContext. As soon as you open it for the first time.
The ToolTip inherits the DataContext.
So what I assume is happening (this is where I'm hazy), is that when you first mouse over the ToolTip, the DataContext has not yet been correctly bound, so your get/set can't fire correctly; the reason you see any messages at all is a result of the behaviour of the OneWayToSource binding mode explained here: OneWayToSource Binding seems broken in .NET 4.0.
If you choose TwoWay binding, you'll notice the ToolTip doesn't open at all the first time round, but will function correctly after the late binding of the DataContext.
The reason the ToolTip does this, is a result of the way it's implemented, and the possible sharing of ToolTips that can occur; it doesn't live within the visual tree:
A tooltip (and everything in it) is not part of the visual tree - it is not in a parent-child relationship with the Image, but rather in a property-value relationship.
When a tooltip is actually displayed, WPF does some special work to propagate the values of inheritable properties from the placement-target into the tooltip,
So, I think that's sounding plausible, but is there anything you could actually do about it?
Well, some people have wanted to bind the ToolTip to things on the visual tree, and given the difficulties faced in locating the parent objects, a few workarounds have arisen (I cameacross these while looking for a solution:
http://blogs.msdn.com/b/tom_mathews/archive/2006/11/06/binding-a-tooltip-in-xaml.aspx
Getting a tooltip in a user control to show databound text and stay open
Both rely on a neat property of the ToolTip, PlacementTarget, which "Gets or sets the UIElement relative to which the ToolTip is positioned when it opens. MSDN.
So, in summary, to get the IsOpen property to bind and behave correctly, I did this in my mockup:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow"
DataContext="{Binding RelativeSource={RelativeSource Self}}" Background="#FF95CAFF"
>
<Grid>
<TextBlock Text="{Binding Path=TestObject.Name}">
<TextBlock.ToolTip>
<ToolTip IsOpen="{Binding DataContext.TestObject.IsToolTipOpen}"
DataContext="{Binding Path=PlacementTarget,
RelativeSource={RelativeSource Self}}" >
<StackPanel Orientation="Vertical">
<!-- Show me what the `DataContext` is -->
<TextBlock Text="{Binding Path=DataContext}" />
</StackPanel>
</ToolTip>
</TextBlock.ToolTip>
</TextBlock>
</Grid>
Context found on program load.
In this case, the DataContext is WpfApplication1.MainWindow, and I'm binding to a property on that I'm using for testing, called TestObject. You would probably have to fiddle with the syntax a little bit to locate your desired `DataContext item in your template (it might be easier to do it the way you've already done it depending on your structure).
If I've said anything drastically incorrect, let me know. | unknown | |
d4377 | train | Relative paths in <stylesheet> in a gwt.xml files are relative to the "module base URL" (returned by GWT.getModuleBaseURL() on the client-side code; this is the folder into which GWT will generate the nocache.js file and everything else). Having a file output in this directory is as easy as putting it in your public path, which by default is a public subfolder of your GWT module (next to your client subpackage). It's worth noting that public paths are inherited from modules you <inherit>; this is how GWT's built-in themes work.
If you put your stylesheet in your war folder, then you shouldn't inject it from your gwt.xml, you should rather load it with a <link rel=stylesheet> in your HTML host page.
A: I changed the entry made in ABCD.gwt.xml to as below. Now its working.
<stylesheet src='/Sample.css' />
A: Use your browser developer panel to find out the location of css file.
A: You should create a folder named public in the same place where your client, server and shared folders are and put it in there, that's the default location it will look. | unknown | |
d4378 | train | LINK: pl/sq to find any data in a schema
Imagine, there are a few tables in your schema and you want to find a specific value in all columns within these tables. Ideally, there would be an sql function like
select * from * where any(column) = 'value';
Unfortunately, there is no such function.
However, a PL/SQL function can be written that does that. The following function iterates over all character columns in all tables of the current schema and tries to find val in them.
create or replace function find_in_schema(val varchar2)
return varchar2 is
v_old_table user_tab_columns.table_name%type;
v_where Varchar2(4000);
v_first_col boolean := true;
type rc is ref cursor;
c rc;
v_rowid varchar2(20);
begin
for r in (
select
t.*
from
user_tab_cols t, user_all_tables a
where t.table_name = a.table_name
and t.data_type like '%CHAR%'
order by t.table_name) loop
if v_old_table is null then
v_old_table := r.table_name;
end if;
if v_old_table <> r.table_name then
v_first_col := true;
-- dbms_output.put_line('searching ' || v_old_table);
open c for 'select rowid from "' || v_old_table || '" ' || v_where;
fetch c into v_rowid;
loop
exit when c%notfound;
dbms_output.put_line(' rowid: ' || v_rowid || ' in ' || v_old_table);
fetch c into v_rowid;
end loop;
v_old_table := r.table_name;
end if;
if v_first_col then
v_where := ' where ' || r.column_name || ' like ''%' || val || '%''';
v_first_col := false;
else
v_where := v_where || ' or ' || r.column_name || ' like ''%' || val || '%''';
end if;
end loop;
return 'Success';
end; | unknown | |
d4379 | train | The revocation part of a PKI infrastructure (e.g. what you get if you have your own CA) is usually done with CRL (certificate revocation lists) or OCSP (online certificate status protocol).
If this is too much effort for a small PKI with only few clients you can also hard code the fingerprints of the certificates your accept (white list) or which got revoked (blacklist) into your application and check on each connect if the certificate you got matches the fingerprint. Of course you need to update the application on each revocation (blacklist) or whenever you issue a new certificate (white list) so this does not scale very well. But the same problems occurs with CRLs which need to be distributed to each client.
OCSP scales much better because the client try to retrieve the revocation status on connect, but then you need to setup an OCSP responder. | unknown | |
d4380 | train | If it's reading from stdin for things like the password too, then you should be able to just put all your answers as lines in a file and redirect the script input from there.
./script.sh < answers.txt
A lot of apps won't accept passwords that way, though... | unknown | |
d4381 | train | Use data binding to bind the visibility flag of the text box to the current selected ListView Item.
In your Controller or ViewModel implement a property for the SelectedItem
public object SelectedItem { get; set; }
Bind it in the ListView to the SelectedItem property
<ListView
...
SelectedItem={Bining Path=SelectedItem}/>
Use a second property to determine if a ListView item is selected
public Visibility TextBoxVisibility=> SelectedItem != null
? System.Windows.Visibility.Visible
: System.Windows.Visibility.Hidden;
In your xaml bind the Visibility property to the IsSelected property
<TextBox
...
Visibility={Bining Path=TextBoxVisibility}/>
hope this helps.
A: Try this in the code behind (MainWindow.xaml.cs):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace WpfApp7
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private MyViewModel m_MyViewModel;
public MainWindow()
{
InitializeComponent();
m_MyViewModel = new MyViewModel();
myGrid.DataContext = MyVM;
}
public MyViewModel MyVM
{
get
{
return m_MyViewModel;
}
}
}
public class MyViewModel : ViewModelBase
{
public List<string> MyCollection
{
get
{
return new List<string> { "A", "B", "C" };
}
}
private bool isListViewItemSelected;
public bool IsListViewItemSelected
{
get
{
return isListViewItemSelected;
}
set
{
isListViewItemSelected = value;
RaisePropertyChanged("IsListViewItemSelected");
}
}
private string selectedItem;
public string SelectedItem
{
get { return selectedItem; }
set
{
if (value != selectedItem)
{
selectedItem = value;
if (selectedItem == null)
{
IsListViewItemSelected = false;
}
else
{
IsListViewItemSelected = true;
}
RaisePropertyChanged("SelectedItem");
RaisePropertyChanged("SelectedTxtString");
}
}
}
public string SelectedTxtString
{
get
{
//return SelectedItem;
return "\"" + SelectedItem + "\" is selected!";
}
}
}
public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable
{
#region DisplayName
/// <summary>
/// Returns the user-friendly name of this object.
/// Child classes can set this property to a new value,
/// or override it to determine the value on-demand.
/// </summary>
public virtual string DisplayName { get; protected set; }
#endregion // DisplayName
#region Debugging Aides
/// <summary>
/// Warns the developer if this object does not have
/// a public property with the specified name. This
/// method does not exist in a Release build.
/// </summary>
[Conditional("DEBUG")]
[DebuggerStepThrough]
public void VerifyPropertyName(string propertyName)
{
// Verify that the property name matches a real,
// public, instance property on this object.
if (TypeDescriptor.GetProperties(this)[propertyName] == null)
{
string msg = "Invalid property name: " + propertyName;
if (this.ThrowOnInvalidPropertyName)
throw new Exception(msg);
else
Debug.Fail(msg);
}
}
/// <summary>
/// Returns whether an exception is thrown, or if a Debug.Fail() is used
/// when an invalid property name is passed to the VerifyPropertyName method.
/// The default value is false, but subclasses used by unit tests might
/// override this property's getter to return true.
/// </summary>
protected virtual bool ThrowOnInvalidPropertyName { get; private set; }
#endregion // Debugging Aides
#region INotifyPropertyChanged Members
/// <summary>
/// Raised when a property on this object has a new value.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
/// <param name="propertyName">The property that has a new value.</param>
protected virtual void RaisePropertyChanged(string propertyName)
{
VerifyPropertyName(propertyName);
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
#endregion // INotifyPropertyChanged Members
#region IDisposable Members
/// <summary>
/// Invoked when this object is being removed from the application
/// and will be subject to garbage collection.
/// </summary>
public void Dispose()
{
this.OnDispose();
}
/// <summary>
/// Child classes can override this method to perform
/// clean-up logic, such as removing event handlers.
/// </summary>
protected virtual void OnDispose()
{
}
#endregion // IDisposable Members
}
}
And this in the MainWindow.xaml
<Window x:Class="WpfApp7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp7"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>
<Grid x:Name="myGrid">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<ListView ItemsSource="{Binding MyCollection, Mode=OneWay}" SelectedItem="{Binding SelectedItem}">
</ListView>
<TextBox Grid.Row="1" Text="{Binding SelectedTxtString, Mode=OneWay}"
Visibility="{Binding IsListViewItemSelected, Converter={StaticResource BooleanToVisibilityConverter}}"/>
</Grid> | unknown | |
d4382 | train | Use case : I am going to build a tool for WebService testing. There I
need to present the entire request xml to the user (Like SOAPUI).
The idea of the place holder character isn't really going to work. For example ? is an ok default value for a string, but not an int, boolean, or for most complex values (i.e. representing the nested address information for a customer). Instead you will want a value that reflects the type.
Then I would have to write large and complex reflection based code. Just assume that
that is almost not possible in my case.
This reflection code probably won't be as bad as you are imagining. A quick search will probably also reveal libraries that populate objects with "dummy" data. When hooking it up with JAXB you could leverage a Marshaller.Listener to populate the object on the before marshal event. | unknown | |
d4383 | train | When you read the network stream you need to reencode your strings manually if the automatically way fails. It is possible that the libiary which you are using is ignoring the content encoding or maybe it is missing in the HTTP-response.
Somewhere in your code will be a byte array which you can convert in the String constructor:
String xxx = new String(bytes, "utf-8");
If you get the String with the wrong encoding you can check this code:
String rightEncoded = new String(wrongEncodedString.getBytes("Cp1252"), "utf-8");
A: You shouldn't be using the file.encoding system property.
The best way to avoid such encoding issues is to never assume anything about default platform encodings and always provide an encoding when constructing readers or when converting bytes to Strings and vice versa.
Your sendRequest method seems to be OK with respect to handling encodings: it reads characters from the input, explicitly mentioning that it expects the stream to be encoded in UTF-8.
However, we can't see the other end of the client/server sequence. Quoting you:
After that the String is being sent to server using Netty's
ChannelBuffer generated with ChannelBuffers.wrappedBuffer() and
NettyUtils.writeStrings()
You also mentioned that you can't attach the entire code here, which is understandable; therefore, I'd advise that you look into how exactly you're sending those strings out, and whether or not you're explicitly specifying an encoding while doing so.
EDIT as per OP's update: well, I'm sorry that I am not familiar with Netty, but still I'll take a shot here. Doesn't NettyUtils.writeStrings(), or any of the code that calls it, accept a character encoding? I can't find the JavaDoc to any NettyUtils online. Work with me here. :-) | unknown | |
d4384 | train | It is the new version of @angular/pwa package that has a few bugs. So running ng add @angular/[email protected] worked perfectly for me.
To test the service worker locally: If you have Firebase added to your project (hosting), you can run ng build --prod and then firebase serve. When you don't have Firebase, you can run ng build --prod, cd into the dist folder (depending on your config) and then run http-server -o. If you don't have http-server module, install it by running npm i -g http-server
A: Try using the Angular Console: https://angularconsole.com/
It abstracts away many of the need to know logic that the cli has.
It's in beta but it should help you create the base for your PWA. Give it a try it's build from the Nrwl Team that also builds Nx which is an enhancement to the angular/cli using schematics
A: I had the same issue. The problem was than this command:
ng add @angular/pwa
didn't add module @angular/pwa to package.json dependencies.
I decided it so.
First I run ng add @angular/pwa
Then I did:
npm install @angular/pwa
And it all works! | unknown | |
d4385 | train | Make the one you don't want to move kinematic
A: I've been through this, I had a wall and a character with RigidBody.
I didn't want the wall to move in a collision with the character, to solve that, I just made the wall a LOOOTT heavier than the character, just make the "MASS" of the wall very high! The character will not be able to move it! /o/
Hope that helps! | unknown | |
d4386 | train | I got the same Exception in Jelly Bean 4.1.2, then following changes I made to resolve this
1.added permission in manifest file.
<uses-permission
android:name="android.permission.VIBRATE"></uses-permission>
2.Notification Composing covered by Try-Catch
try
{
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_notif_alert)
.setContentTitle(getResources().getString(R.string.app_name))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setStyle(bigTextStyle)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
mBuilder.setAutoCancel(true);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d(TAG, "---- Notification Composed ----");
}
catch(SecurityException se)
{
se.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
A: Since this bug only occurs on Android 4.2 and 4.3 you might use this as a workaround (i.e. include the maxSdkVersion):
<uses-permission android:name="android.permission.VIBRATE" android:maxSdkVersion="18"/>
Note: the maxSdkVersion attribute was only added in API level 19, which in this case is luckily exactly the minimum we want! In theory we could put any value <= 18 to get the same effect, but that would be nasty.
A: This was a bug in Android 4.2 due to a change in the notification vibration policy; the permission bug was fixed by this change in 4.2.1. | unknown | |
d4387 | train | You could use the safeSearch parameter, set it to "strict" to avoid mature content. E.g.:
https://gdata.youtube.com/feeds/api/videos?q=football&max-results=10&v=2&safeSearch=strict
More info here:
https://developers.google.com/youtube/2.0/reference?csw=1#safeSearchsp
A: safeSearch is also supported in v3 of the API.
https://developers.google.com/youtube/v3/docs/search/list#safeSearch | unknown | |
d4388 | train | $ ";
cin>>loanAmountA;
cout<<endl;
cout<<"Enter annual percentage rate (APR): "<<"%";
cin>>annualRate;
cout<<endl;
cout<<"Enter the number of payments per year: ";
cin>>paymentsPerYear;
cout<<endl;
cout<<"Enter the total number of payments: ";
cin>>totalPayments;
cout<<endl;
cout<<"Payment Payment Amount Amount to Balance after";
cout<<endl;
cout<<"Number Amount Interest Principal This Payment";
cout<<endl;
cin.ignore(80,'\n');
while (paymentCount <=totalPayments)
{
annualRate = annualRate / 100;
balance = loanAmountA - totalPayments * paymentAmount;
ratePeriod = balance * annualRate;
paymentAmount = loanAmountA * (totalPayments / paymentsPerYear * annualRate) / totalPayments;
balanceAfter = balance - paymentAmount;
balance = loanAmountA - (paymentCount * paymentAmount);
cout<<left<<setprecision(0)<<setw(3)<<paymentCount;
cout<<setw(13)<<left<<fixed<<setprecision(2)<<paymentAmount;
cout<<setw(26)<<left<<fixed<<setprecision(2)<<ratePeriod;
cout<<setw(39)<<left<<fixed<<setprecision(2)<<balance;
cout<<setw(42)<<left<<fixed<<setprecision(2)<<balanceAfter;
if (paymentCount % 12 == 0)
{
cout<<endl;
cout<<"Hit <Enter> to continue: "<<endl;
cin.ignore(80,'\n');
cin.get();
}
paymentCount++;
loanCount++;
cout<<endl;
}
cout<<"Would you like to calculate another loan? y/n and <enter>";
cin>>response;
if (response == 'n')
{
anotherLoan = false;
cout<<endl<<endl;
cout<<"There were"<<loanCount<< "loans processed.";
cout<<endl<<endl;
}
}
return 0;
}
A: Did you try to use the debugger, and find the point of failure? | unknown | |
d4389 | train | I contend that there is nothing wrong with what you do. Your code just lacks an explicit cast which would get rid of the warning, indicating that your assignment is intentional.
You can access a one dimensional array through a pointer to its elements, and recursively applied, it follows that n-dimensional matrices can be accessed through pointers to the atomic elements.
C guarantees a contiguous memory layout for them. This pattern is common. In fact passing arrays is hard or impossible to do differently, given the little information C stores with types (as opposed to, say, C#). So the matrix decays to a pointer to its first element (in your case to the first one dimensional array), which can safely be cast to an address of its first element, a double. They all share the same numerical address.
Typical concerns with pointer type casting are aliasing issues with modern optimizing compilers (a compiler can assume that you don't access memory through pointers of unrelated types except char*), but there is an explicit exemption in the standard draft 1570 which I have, par. 6.5.7, which I think is applicable here:
An object [that would be a double in your matrix, -ps] shall have its stored value accessed only by an lvalue
expression that has one of the following types:
— a type compatible with the effective type of the object [that would be a dereferenced double pointer, -ps]
[...]
— an aggregate [e.g. array, -ps]
[...] type that includes one of the aforementioned types among its
members (including, recursively, a member of a subaggregate or
contained union) [that would be your matrix variable, containing, eventually, doubles, -ps]
[...] | unknown | |
d4390 | train | You don't need to install any additional tools or libraries to query MS SQL Server from PowerShell, assuming you are running Windows 7 or newer.
The installed .NET framework has all ADO.NET components required to do this.
If you get an error, something is wrong with your script or your environment.
A: I am sure that there must be a better solution, thus I will not mark this response as an answer...
I checked the content of C:\Windows\assembly\GAC_MSIL\Microsoft.SqlServer.Types path and discovered that I have Microsoft.SqlServer.Types.dll for versions 12, 13 and 14.
Thus I just copy-paste mentioned file for version 10.0.0.0__89845dcd8080cc91 from the server to my computer...and it works
So, it seems that somewhere it's hardcoded to use this specific version of Assembly when connecting to SQL Server from Powershell (?) | unknown | |
d4391 | train | The kube-apiserver is configured with a static manifest file, which is stored in /etc/kubernetes/manifests/kube-apiserver.yaml.
So find out the ID of the container that is the Kubernetes control plane node in kind:
docker ps|grep cluster-control-plane
Get a shell in it:
docker exec -it 4aeedccce928 bash
Install an editor (e.g. emacs) and edit the aforementioned file to add/remove/replace the desired arguments:
apt-get update
apt-get install emacs-nox
emacs /etc/kubernetes/manifests/kube-apiserver.yaml
Kubernetes will detect the file change and automatically restart the server, which can be validated with:
ps -Afl|grep kube-apiserver
If it crashes on startup, you can find the logs using
apt-get install less
less /var/log/pods/kube-system_kube-apiserver-cluster-control-plane_*/*/*.log
If the container fails to start at all, there will not be any log file there - check the manifest file for syntax errors by referring to the Kubernetes documentation. | unknown | |
d4392 | train | In order to deploy and serve Rails 4 static assets on Heroku you must include the rails12_factor Gem in the prod group of your Gemfile.
gem 'rails_12factor', group: :production
In addition you must confirm that config/application.rb serve_static_assets is set to true.
config.serve_static_assets = true
Check out Heroku documentation for more information. | unknown | |
d4393 | train | try like this:
item.gd$when[0].startTime = item.gd$when[0].startTime.replace('Date: ', '');
item.gd$when[0].startTime = item.gd$when[0].startTime.split(' - ');
var firstDate = item.gd$when[0].startTime[0];
var secondDate = item.gd$when[0].startTime[1];
var _firstDate = new Date(firstDate);
var _secondDate = new Date(secondDate);
alert(_firstDate.getMonth());
alert(_secondDate.getMonth()); | unknown | |
d4394 | train | Refer to the following Answer to determine the Height and Width of Text properties.
For determining if you have the right text, Enter unique text into your slide and use the Open XML Productivity Tool to find it. You can use the tool to search for your unique string in your slide and reflect the code to generate it.
Lastly, to understand the Presentation Slide XML, I recommend reading the free e-book Open XML Explained to give an explanation of how a correct Presentation document is formed to help you better understand where things should be.
A: If you have powerpoint installed from Microsoft office. You can do the following, though this is not programmatic, but can help you to get the job done.
Steps:
*
*Open ppt
*Click on your chart or whatever object you like.
*Right click and select or use shortcut CMD + SHIFT + 1
*Click on 3rd icons select Size Position, and you can see the following
Note:
I'm demoing with Microsoft Powerpoint for Mac Version 2018.
Hope it helps. | unknown | |
d4395 | train | As I know your application server (Tomcat) isn't able to be aware of a reverse proxy presence. Generally speaking, it can be contacted through any number of reverse proxies or directly by browsers. A network configuration is usually used to limit this, not HTTP or Java.
So, you must accurately rely on relative URLs to make your application work well.
When I have to deal with reverse proxy presence (almost always due to SSO architectures), I embed a "junction" configuration string item (the portion of the URL used in the proxy to map the application) and use it in the only places where I need to build an absolute URL. | unknown | |
d4396 | train | Session state consumes either RAM or database resources, depending on which provider you use (InProc vs. SQL). It also requires a cookie, in order for the server to associate an incoming request with a particular Session collection.
For something like a site ID, I would suggest storing it in a cookie if you can. For best performance, configure the cookie with a path property so the browser doesn't include it with requests for images and other static files. | unknown | |
d4397 | train | Someone correct me if I'm wrong but it seems like it's correct from this quote:
3 A template-argument matches a template template-parameter (call it P) when each of the template parameters in the template-parameter-list of the template-argument’s corresponding class template or [FI 11] template aliasalias template (call it A) matches the corresponding template parameter in the template-parameter-list of P
A (the given template) has to match each of it's templates parameters to P's the template template.
From the second part of the section we learn the restriction doesn't apply in the reverse, meaning a template template containing a parameter pack can match anything.
When P’s template-parameter-list contains a template parameter pack (14.5.3), the template parameter pack will match zero or more template parameters or template parameter packs in the template-parameter- list of A with the same type and form as the template parameter pack in P
As you probably already knew the way to make it work is
template<template<class> class T,class U>
struct apply
{
typedef T<U> type;
};
template<class T> using tuple_type = std::tuple<T>;
typedef apply<tuple_type,int>::type tuple_of_one_int;
The c++11 standard also has an equivalent example to yours.
template <class ... Types> class C { /∗ ... ∗/ };
template<template<class> class P> class X { /∗ ... ∗/ };
X<C> xc; //ill-formed: a template parameter pack does not match a template parameter
The last comment completely describes your situation, class C would be the equivalent of std::tuple in this case.
A: Your code is ill-formed, there is equivalent example in the standard (under 14.3.3/2):
...
template <class ... Types> class C { /∗ ... ∗/ };
template<template<class> class P> class X { /∗ ... ∗/ };
...
X<C> xc; // ill-formed: a template parameter pack does not match a template parameter
...
A: The fix:
template<template<class...> class T,class U>
struct apply
{
typedef T<U> type;
};
typedef apply<std::tuple,int>::type tuple_of_one_int;
typedef apply<std::vector,int>::type vector_of_int; | unknown | |
d4398 | train | You shouldn't be using background image properties in HTML Emails, especially Outlook.
Most email clients don't support this attrubute - some web clients will, but its best practise to stick to inline images.
A: Outlook needs a chunk of Microsoft's VML code to render backgrounds in Outlook 2007 - 2013 since they use MS Word to render the HTML. Try this:
<table border="0" cellpadding="0" cellspacing="0" width="640" style="border-collapse:collapse; padding:0; margin:0px;">
<tr valign="top">
<td background="http://place-hoff.com/640/487" bgcolor="#000000" width="640" height="487" valign="top">
<!--[if gte mso 9]>
<v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" style="width:640px;height:487px;">
<v:fill type="tile" src="http://place-hoff.com/640/487" color="#000000" />
<v:textbox inset="0,0,0,0">
<![endif]-->
<div>
<table border="0" cellpadding="0" cellspacing="0" width="640" style="border-collapse:collapse; padding:0; margin:0px;">
</table>
</div>
<!--[if gte mso 9]>
</v:textbox>
</v:rect>
<![endif]-->
</td>
</tr>
</table> | unknown | |
d4399 | train | props.content need {}
const AppMount = props => {
return {props.content};
} | unknown | |
d4400 | train | Can you try this ? Basically this inside the ajax is not exactly the one you would expect.
var example = new Vue({
el: '#example',
data:{
myArr: []
},
created: function () {
var vm = this;
$.getJSON('data.json', function(data) {
vm.myArr = data;
});
}
});
You can also use reactivity setting method $set instead of directly assigning to the vm.myArr : https://v2.vuejs.org/v2/guide/reactivity.html | 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.