_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d1001 | train | You have missed one of the conditions. You also want whenever PARENT is NULL the Value of PRIMARY_PARENT be equal to the value of PARENT in the next row. You can take care of it this way:
SELECT * FROM
(SELECT *, LEAD(PARENT) OVER(Order BY (SELECT NULL)) as LeadParent FROM COMPANY_TABLE) T
WHERE PARENT IS NOT NULL AND PRIMARY_PARENT IS NULL
OR ((PARENT IS NULL) AND LeadParent != PRIMARY_PARENT);
A: As Kumar stated, you could try and test to see if the values Parent and Primary_Parent by default are NULL's or blanks.
Did you try:
SELECT * FROM COMPANY_TABLE WHERE PARENT <> '' AND PRIMARY_PARENT <> '' | unknown | |
d1002 | train | seems that your are passing List<String> to fragment.
You should use Bundle to hold your data and then pass to fragment use Fragment.setArguments.
here is a example:
Bundle data = new Bundle();
data.putStringArrayList("your_argument_name", dataList);
Fragment f = ...;
f.setArguments(data);
here is how to read value in your fragment's code, like in onCreateView :
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle data = getArguments();
if (data != null) {
List<String> dataList = data.getStringArrayList("yout_argument_name");
}
...
} | unknown | |
d1003 | train | Short answer.
Currently (in 2.4.1) it contains only one field, IPROTO_ERROR_STACK (0). But in future more fields may be added to this map. The format of MP_MAP with a single key is chosen for better extendibility. All connectors should be able to parse IPROTO_ERROR_STACK key, and skip any other key. So even if in future Tarantool versions new fields are added to the map, the old connectors still would be able to parse responses.
Long answer.
In Tarantool most of the responses of the binary protocol (IProto) have form of a MessagePack map: MP_MAP. Even if there is just 1 or 2 fields in this map, it is still MP_MAP, not an MP_ARRAY, and of course not just a non-formatted byte array.
Some such responses exist for many years. There appear lots of connectors to Tarantool, which are able to send/receive and parse responses from Tarantool in IProto protocol.
And when it becomes necessary to change something in these responses after all the years of exploitation with all the created software to handle the responses, the MP_MAP comes in hand. With MP_MAP it is easy to add new fields into the response not breaking all the old connectors. Assuming that they are ready that some new unknown keys may be received, and they just skip them.
This is why MP_MAP is used in Tarantool a lot as a top level of response type. It is easy to extend and not break old code. Error MessagePack format, with IPROTO_ERROR_STACK, is MP_MAP by the same reason. In future there may be added more keys to the error object. | unknown | |
d1004 | train | First of all, interfaces only exist at compile time, so it is not possible to have conditions on them in the code.
Conditional return types do exist, but only seem to be partially supported:
enum ResultType {
INT = 'int',
BOOL = 'bool',
STRING = 'string',
}
interface TypeMap {
int: number;
bool: boolean;
string: string;
}
function getCookie<K extends ResultType>(name: string, type: K): TypeMap[K] {
let cookieValue;
// ...
switch (type) {
case ResultType.INT:
return parseInt(cookieValue, 10) as any;
case ResultType.BOOL:
return (cookieValue === 'true') as any;
case ResultType.STRING:
return cookieValue as any;
}
}
// usage:
getCookie('foo', ResultType.INT); // compiler correctly assumes number as return type
getCookie('foo', ResultType.BOOL); // compiler correctly assumes boolean as return type
You can see here that the return type is casted to any. The compiler does not properly infer this type. The issue addressing this is https://github.com/microsoft/TypeScript/issues/24929, but it seems to be closed without a fix. | unknown | |
d1005 | train | From help on the Doctrine IRC channel you need to create a custom DQL function.
Example:
https://github.com/beberlei/DoctrineExtensions/blob/master/lib/DoctrineExtensions/Query/Mysql/Day.php
Docs:
http://www.doctrine-project.org/blog/doctrine2-custom-dql-udfs.html
A: A bit late for OP, but maybe someone will find it handy. I was able to achieve that with the DQL query bellow:
$dql = '
SELECT
SUBSTRING(i.timestamp, 1, 10) as date,
COUNT(i) as count
FROM Entity i
GROUP BY date
';
$query = $entityManager->createQuery($dql);
return $query->getResult();
I think similar should be doable with Doctrine query builder. | unknown | |
d1006 | train | There is another repo which is officially maintained by the Froala team and would be better to use that one: https://github.com/froala/react-froala-wysiwyg. It also supports two way bindings. | unknown | |
d1007 | train | the logic of your formula may be correct, but more factors must be considered when playing with the calendar as humanity likes to adjust even the rules of adjustment. here are a few examples:
*
*the longest year in history: 46 BCE (708 AUC) lasting 445 days known as "the last year of confusion" as Ceasar added 3 more months (90 days) so that the next year (45 BCE) would start right after the winter solstice.
*the shortest year in history: 1582 CE lasting 355 days where October had only 21 days (4th Oct. was followed by 15th Oct.) but also it depends where you are
because British Empire decided to reinvent the wheel by accepting the "1582-wheel" in the year 1752 CE where September had only 19 days (2nd Sep. was followed by 14th Sep.) resulting the year to have 355 days as well. however, if we are technical, the British Empire also had a year that lasted only 282 days because their "old" new year started on 25 March and not 1 January therefore the year 1751 CE started on 25th Mar and ended on 31st Dec. Turkey, for example, joined the "gregorian train" in 1st Jan 1927 CE after their December of 1926 CE had only 18 days so that year was long only 352 days. the latest country to adopt the gregorian calendar was Saudi Arabia in 2016 CE when they jumped from 1437 AH
*the year zero: does not exist. 31st Dec. 1 BCE was followed by 1st Jan. 1 CE
753 AUC = 1 BCE
754 AUC = 1 CE
also, dude who invented this nonsense was born around 1223 AUC (470 CE) so that speaks for itself. this is important because offsetting DATEVALUE needs to be done in such a way that the calculation will not cross 0 eg. not drop bellow -693593:
=TO_DATE(-694324) - incorrect datevalue - 01/01/00-1
=TO_DATE(-693678) - incorrect datevalue - 08/10/0000
=TO_DATE(-693593) - 1st valid datevalue - 01/01/0001
=TO_DATE(35830290) - last valid datevalue - 31/12/99999
*it's also worth mentioning that 25th Dec. 200 CE was not Friday on the Roman peninsula because people in that era used 8-day system
*there are many calendar systems each with its own set of rules and up to this date there are still countries that do not recognize the gregorian calendar as a standard so if you want to re-live the year 2021 go to Ethiopia where today's 9 Oct. 2022 CE = 29 Mes. 2015 EC on the other hand if you prefer to live in the future try Nepal where today's 9 Oct. 2022 = 23 Ash. 2079 BS | unknown | |
d1008 | train | change
cordova plugin add cordova-plugin-firebase with
cordova plugin add cordova-plugin-firebasex
another option is after adding cordova-plugin-firebase add 2 another plugin
cordova-android-play-services-gradle-release
cordova-android-firebase-gradle-release
A: Here are the steps to make it work:
*
*cordova platform remove android
*cordova plugin remove cordova-plugin-firebase
*cordova plugin add cordova-plugin-firebase-lib
*cordova plugin add cordova-plugin-androidx
*cordova plugin add cordova-plugin-androidx-adapter
That's it! | unknown | |
d1009 | train | You could look at the table.assign(<new column> = <formula>) function to build out your dataframe. | unknown | |
d1010 | train | You can use the ClientResponse type in Jackson. For example, using a GET operation:
ClientResponse response = Client.create()
.resource(url)
.get(ClientResponse.class);
String contentType = response.getHeaders()
.getFirst("Content-Type");
System.out.println(contentType); | unknown | |
d1011 | train | When I changed the arguments to gevetn patch all:
...
elif async_mode == 'gevent':
from gevent import monkey
monkey.patch_all(ssl=False)
...
It seems to work. | unknown | |
d1012 | train | You need to set the timestamp on the AVPacket before you call av_write_frame() or av_interleaved_write_frame() | unknown | |
d1013 | train | Timsort is stable, which means that you can get what you want with something like
>>> assert not message.islower()
>>> ''.join(sorted(message, key=lambda c: not c.isupper())).upper()
'HAPPY NEW MONTH'
The trick is that booleans are a subclass of integers in python. The key returns False == 0 for elements you want to move to the beginning, and True == 1 for elements that stay. You need to use lambda c: not c.isupper() because spaces and other characters will move back if you use str.islower as the key.
If you want the assertion to be more detailed, like checking if all the letter characters are lowercase, you can do it with something like
>>> assert any(c != c.lower() for c in message)
For more complex unicode code points, use c.casefold() instead of c.lower().
A: Here is a solution that uses a single list comprehension without imports. It is also linear in time with the length of the string unlike sorting solutions with have higher time complexity of O(n log n). It also has an assertion statement flagging strings with no uppercase letters (i.e., all alpha characters are lowercase).
def unravel_message(s):
assert any('A' <= c <= 'Z' for c in s)
return (duo := list(map(lambda x: ''.join(x).replace(chr(0), ''), zip(*[(c, chr(0)) if c.isupper() else (chr(0), c.upper()) for c in s]))))[0] + duo[1]
x = unravel_message(' neHAw moPPnthY')
print(x)
x = unravel_message(' no uppercase letters')
Output:
HAPPY NEW MONTH
Traceback (most recent call last):
File "C:\python\test.py", line 7, in <module>
x = unravel_message(' no uppercase letters')
File "C:\python\test.py", line 2, in unravel_message
assert any('A' <= c <= 'Z' for c in s)
AssertionError
Note that the solution uses the walrus operator := to make it a one-liner. If you are using Python earlier than version 3.8, you can do this instead:
def unravel_message(s):
assert any('A' <= c <= 'Z' for c in s)
duo = list(map(lambda x: ''.join(x).replace(chr(0), ''), zip(*[(c, chr(0)) if c.isupper() else (chr(0), c.upper()) for c in s])))
return duo[0] + duo[1] | unknown | |
d1014 | train | There is a bug in angular-cli when the swagger-codegen package is either linked using npm link or installed directly using: npm install PATH_TO_GENERATED_PACKAGE/dist --save (see: https://github.com/angular/angular-cli/issues/8284).
The issue seems to be with ng serve only, not with ng build --prod --base-href=..., but I did not test an 'ng build' yet.
The "You need to import the HttpClientModule in your AppModule!" message is not valid, but an error is thrown anyhow.
An (ugly) workaround described in this ticket is to generate the code using swagger-codegen-cli (or openapi-generator-cli), search for, and comment out the error message:
// if (!http) {
// throw new Error('You need to import the HttpClientModule in your AppModule! \n' +
// 'See also https://github.com/angular/angular/issues/20575');
// }
Next: run npm install && npm run build and install the package in the consuming project.
A cleaner solution would be to use a (private) npm registry.
UPDATE 14/7/2018
Further investigation showed that the workaround described above does not solve all problems.
Instead, I am now using a private npm registry Verdaccio and have no issues anymore.
-Arjen | unknown | |
d1015 | train | It is possible, but you'll need to do some work to get them calling properly. I've never done it myself, but until someone better equipped to answer the question comes along here's a few places to start.
Take a look at the JNI (Java Native Interface, google or wikipedia can tell you more), which lets you call out from Java to other languages. There seems to be a project called jni4net ( http://jni4net.sourceforge.net ) which is intended to do exactly what you want, but it's in alpha at the moment and might not be stable enough. Still it could be worth having a look.
You can also do it yourself, calling through the JNI as a C call which will then get through to the CLR eventually, but it looks like a lot of effort. I know this isn't a quick and easy solution, but it might give you a couple of places to get started. also http://www.codeproject.com/KB/cross-platform/javacsharp.aspx seemed to be a fairly good look at how to go about it.
As all of the other answers so far have said though, it's fiddly and a pain. If you can do something else instead, it will probably be worth it.
A: Have a look at Jni4Net and this stack overflow question: is there an effective tool to convert c# to java?
A: You would have to use native calls which would a) be really irritating to keep up to date and B) defeat the huge advantage of java being cross-platform.
Your best bet might be to try to find something that can convert C# to java--or better yet recode your C# code into java.
In the long run it will save you a lot of stress.
A: No sure about this possibility but your idea is not so good.
You still can use COM or hook or try ngen but this ways all are weird.
Java is very similar C# . Try to code in Java or something like stab , I think that is much easer to code in some JVM-based langue for jvm.
A: Diferent compilers dud, it's not possible. Unless You use java sharp language in visual studio, then the compilers mach. | unknown | |
d1016 | train | here is a list of Websocket errors codes that you might receive.
websocket-close-codes
Most likely you'll receive 1006 in case of an exception
A: Browser-side error events are actually related to "close codes" used by the WebSocket protocol, as detailed in section 11.7 to the RFC.
You can find the registered WebSocket closure codes here.
In addition to server-side specified errors, some parsing errors and protocol errors are also emitted by the client (such as UTF-8 requirements)... which are often mapped to a closure code (UTF-8 is mapped to code 1003).
AFAIK, these closure error codes are actually sent to the onclose callback, as part of the close event. (i.e., close_event.code). However, according to MDN when the closure isn't normal (code 1000), the onerror callback is also called.
Personally I've never tested or coded anything with these error-codes, since they are unreliable and optional:
When closing an established connection (e.g., when sending a Close frame, after the opening handshake has completed), an endpoint MAY indicate a reason for closure.
Exposing these "error codes" is optional for a reason. Sending error codes from a server to a client / application could (potentially) expose security vulnerabilities. | unknown | |
d1017 | train | Please look up https://gojs.net/latest/samples/index.html
- these are javascript based
- Individual classes are also available (which you can customize for a new visualization)
- It can be installed via npm, and, if you don't like it, can be easily removed from the system.
I hope this helps.
regards
SS | unknown | |
d1018 | train | Try the following :
JSON.stringify(updates.map(({point,value})=>({point,value})));
let updates = [{id : 1, point : 1, value: 2},{id : 1, point : 1, value: 2}];
console.log(JSON.stringify(updates.map(({point,value})=>({point,value}))));
A: If updates is an array. Then you might want something like this:
const newArrayWithoutId = updates.map(({ point, value }) => {
return {
point,
value,
}
}
A: Just ({id, ...rest}) => ({...rest}) is too short for an answer, so how about this?
const withoutId = ({id, ...rest}) => ({...rest})
const vals = [
{id: 'a', point: 1, value: 'foo'},
{id: 'b', point: 2, value: 'bar'},
{id: 'c', point: 3, value: 'baz', meaning: 42}
]
const reduced = vals.map(withoutId)
console.log(reduced) | unknown | |
d1019 | train | If your barcode scanner is a keyboard wedge, you should be able to configure the trailing character to a TAB.
It seems like, by default, your scanner is trailing with an ENTER (carriage return).
Another option would be to also check for a LF (decimal 10) in your javascript code.
A: You need to return false in order to prevent the enter key from submitting the form.
The answer to this question will help you: Prevent form submission with enter key
//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
if ( e.which == 13 ) // Enter key = keycode 13
{
$(this).next().focus(); //Use whatever selector necessary to focus the 'next' input
return false;
}
});
No need to make any changes to your bar scanner.
A: Looks like your function will never get called because browser submits the form on Enter. You may have to suppress submit until all fields are filled (or some other condition) by intercepting submit event first.
$( "form" ).submit(function( event ) {
if(/*all req. fields are filled -> submit the form*/)
$(this).submit();
event.preventDefault();
}); | unknown | |
d1020 | train | You haven't defined query if q isn't in POST or GET. Since that's the only place where this error would appear, you must not be passing in q. An empty QuerySet wouldn't cause this error.
To be sure, it would help to have the line that triggered the error (the traceback - please).
def search(request):
show_results = False
query = None # set default value for query
# check if POST
if 'q' in request.POST:
query = request.POST['q'].strip()
# check if GET (paginated)
if 'q' in request.GET:
query = request.GET['q'].strip()
###########################
# was `query` defined here if 'q' isn't in POST or GET?
###########################
# check if query length is more than 2 characters and proceed
if query and len(query) > 2: # error probably on this line?
A: At the start, query is never set to a default.
if 'q' in request.POST:
query = request.POST['q'].strip()
# check if GET (paginated)
if 'q' in request.GET:
query = request.GET['q'].strip()
Then in your elif, you try to determine the len() of query which isn't defined anywhere yet if 'q' is not in GET or POST.
elif len(query) <= 2:
short_string = True | unknown | |
d1021 | train | I guess you meant:
__shared__ int snums[512];
Will there be any bank conflict and performance penalty?
Assuming at some point your code does something like:
int a = snums[2*threadIdx.x]; // this would access every even location
the above line of code would generate an access pattern with 2-way bank conflicts. 2-way bank conflicts means the above line of code takes approximately twice as long to execute as the optimal no-bank-conflict line of code (depicted below).
If we were to focus only on the above line of code, the obvious approach to eliminating the bank conflict would be to re-order the storage pattern in shared memory so that all of the data items previously stored at snums[0], snums[2], snums[4] ... are now stored at snums[0], snums[1], snums[2] ... thus effectively moving the "even" items to the beginning of the array and the "odd" items to the end of the array. That would allow an access like so:
int a = snums[threadIdx.x]; // no bank conflicts
However you have stated that a calculation neighborhood is important:
Function f(x) acts on the local neighborhood of the given number x,...
So this sort of reorganization might require some special indexing arithmetic.
On newer architectures, shared memory bank conflicts don't occur when threads access the same location but do occur if they access locations in the same bank (that are not the same location). The bank is simply the lowest order bits of the 32-bit index address:
snums[0] : bank 0
snums[1] : bank 1
snums[2] : bank 2
...
snums[32] : bank 0
snums[33] : bank 1
...
(the above assumes 32-bit bank mode)
This answer may also be of interest | unknown | |
d1022 | train | I think dataframe.rolling is operating on the original dataframe only, it actually provides a rolling transformation. If any data is modified in a rolling window of the dataframe, it will NOT be updated in the consequential rolling windows.
Actually I am facing the same issue here. So far the alternative I am using is to manually loop through each rolling window, and put the logic inside the loop. I know it is slow, but I have no idea if there is a better way to do this.
BTW, the same question is asked by other people:
Sliding window iterator using rolling in pandas
Why doesn't my pandas rolling().apply() work when the series contains collections? | unknown | |
d1023 | train | You must run this program as administrator in order for it to work correctly. I just tested it working and GetLastError() = 0 after each line, which means there were no problems. | unknown | |
d1024 | train | The easiest approach is to use %in%:
germany_yields[germany_yields$Date %in% italy_yields$Date, ]
A: We can also use dplyr
library(dplyr)
germany_yields %>%
filter(Date %in% italy_yields$Date) | unknown | |
d1025 | train | Try out/target/product/XXXXX from your build directory where XXXXX if your build target, maguro for the Galaxy Nexus for instance or generic for the emulator. | unknown | |
d1026 | train | Here's a function I wrote for that a while back. I've been using it.
#Christopher Barry, 28/01/2015
insertRows <- function(DF, mtx, row){
if(is.vector(mtx)){
mtx <- matrix(mtx, 1, length(mtx), byrow=T)
}
nrow0 <- nrow(DF)
nrows <- nrow(mtx)
ncols <- ncol(DF) #should be same as for mtx
if(is.matrix(DF)){DF <- rbind(DF, matrix(0, nrows, ncols))}
if(nrow0 >= row){
DF[seq(row+nrows,nrow0+nrows),] <- DF[seq(row,nrow0),]
DF[row:(row+nrows-1),] <- mtx
}else{
DF[seq(nrow0+1,nrow0+nrows),] <- mtx
}
return (DF)
}
Edited to work for matrices and data frames.
A: One way of doing this can be :
aa<- matrix(rnorm(9),ncol=3,nrow=5)
x<-c(1,7,8)
rbind(aa[1:2,],x,aa[3:5,])
A similar solution ot this, actually:
R: Insert a vector as a row in data.frame | unknown | |
d1027 | train | Something like this ought to work
import tensorflow as tf
import numpy as np
def y_pred(x, w):
return [x[0]*w[0]+x[1]*w[0], x[2]*w[1]+x[3]*w[1]]
def loss_fun(y_true, y_pred):
return tf.reduce_sum(tf.pow(y_pred - y_true, 2))
x = np.array([1, 2, 3, 4], dtype="float32")
y_true = np.array([10, 11], dtype="float32")
w = tf.Variable(initial_value=np.random.normal(size=(2)), name='weights', dtype=tf.float32)
xt = tf.convert_to_tensor(x)
yt = tf.convert_to_tensor(y_true)
sgd_opt = tf.optimizers.SGD()
training_steps = 100
display_steps = 10
for step in range(training_steps):
with tf.GradientTape() as tape:
tape.watch(w)
yp = y_pred(xt, w)
loss = loss_fun(yt, yp)
dl_dw = tape.gradient(loss, w)
sgd_opt.apply_gradients(zip([dl_dw], [w]))
if step % display_steps == 0:
print(loss, w) | unknown | |
d1028 | train | In the $config array passed into the pagination initialize() method, you can set the number of links to display on either side of the current page with num_links:
$config['num_links'] = 2;
From the CI user guide:
The number of "digit" links you would like before and after the selected page number. For example, the number 2 will place two digits on either side, as in the example links at the very top of this page.
That should get you closer to exactly what you want. I don't know the exact HTML generated by this library, so if you post it maybe someone can give you a CSS solution. You could also look into extending the CI pagination library to suit you needs (check out "Extending Native Libraries"). | unknown | |
d1029 | train | In general, this used to be not allowed by design. It's a violation of the sandbox.
From Wikipedia -> Javascript -> Security:
JavaScript and the DOM provide the potential for malicious authors to deliver scripts to run on a client computer via the web. Browser authors contain this risk using two restrictions. First, scripts run in a sandbox in which they can only perform web-relatedactions, not general-purpose programming tasks like creating files.
However, it's now possible in current browsers using the FILE API specification.
This should in theory allow you to read it using the FileReader interface, although you might need to use something like JSON.parse() (or $.parseJSON if you're using JQuery) to then interpret it in the way you need. Lots more detail and examples of how to do this are here:
http://www.html5rocks.com/en/tutorials/file/dndfiles/ | unknown | |
d1030 | train | Take a look here. This tutorial was really helpful for me when I was a beginner. Hope that it will helps you too!
Good luck. | unknown | |
d1031 | train | bit shift operator
A: From documentation
If first operand is an int or uint
(32-bit quantity), the shift count is
given by the low-order five bits of
second operand.
If first operand is a long or ulong
(64-bit quantity), the shift count is
given by the low-order six bits of
second operand.
Note that i<<1 and i<<33 give the same
result, because 1 and 33 have the same
low-order five bits.
This will be the same as 2^( the actual value of the lower 5 bits ).
So in your case it would be 2^4=16.
A: I'm assuming you mean i in place of r...
<<n means "shift left by n* bits". Since you start with 1=binary 00...00001, if you shift left 4 times you get binary 00...10000 = 16 (it helps if you are familiar with binary arithmetic - otherwise "calc.exe" has a binary converter).
Each bit moves left n places, filling (on the right) with 0s. *=note that n is actually "mod 32" for int, so (as a corner case) 1 << 33 = 2, not 0 which you might expect.
There is also >> (right shift), which moves for the right, filling with 0 for uints and +ve ints, and 1 for -ve ints.
A: << is the left shift operator
x << y
means shift x to the left by y bits.
3 is 0011, 3<<1 is 0110 which 6.
It's usually used to multiply by 2 (shifting to the left is multiplying by 2)
A: As already mentioned, << is the left shift operator. In your particular example, the array size is being defined as a power of 2. The value 1 shifted left by some number is going to be 1, 2, 4, 8, 16, ... | unknown | |
d1032 | train | Solved it!
ExecStart='/etc/alternatives/python3' ./manage.py myCronJob --settings=server.settings.production
WorkingDirectory=/opt/myWebapp
User=myUser
The user ('myUser' in the above code) has access to Django. | unknown | |
d1033 | train | I think I see what he's getting at. Say like this:
Web client ---> Presentation web server ---> web service call to database
In this case you're depending on the middle server encrypting the data again before it gets to the database. If the message was encrypted instead, only the back end would know how to read it, so the middle doesn't matter.
A: Consider the case of SSL interception.
Generally, if you have an SSL encrypted connection to a server, you can trust that you "really are* connected to that server, and that the server's owners have identified themselves unambiguously to a mutually trusted third party, like Verisign, Entrust, or Thawte (by presenting credentials identifying their name, address, contact information, ability to do business, etc., and receiving a certificate countersigned by the third party's signature). Using SSL, this certificate is an assurance to the end user that traffic between the user's browser (client) and the server's SSL endpoint (which may not be the server itself, but some switch, router, or load-balancer where the SSL certificate is installed) is secure. Anyone intercepting that traffic gets gobbledygook and if they tamper with it in any way, then the traffic is rejected by the server.
But SSL interception is becoming common in many companies. With SSL interception, you "ask" for an HTTPS connection to (for example) www.google.com, the company's switch/router/proxy hands you a valid certificate naming www.google.com as the endpoint (so your browser doesn't complain about a name mismatch), but instead of being countersigned by a mutually trusted third party, it is countersigned by their own certificate authority (operating somewhere in the company), which also happens to be trusted by your browser (since it's in your trusted root CA list which the company has control over).
The company's proxy then establishes a separate SSL-encrypted connection to your target site (in this example, www.google.com), but the proxy/switch/router in the middle is now capable of logging all of your traffic.
You still see a lock icon in your browser, since the traffic is encrypted up to your company's inner SSL endpoint using their own certificate, and the traffic is re-encrypted from that endpoint to your final destination using the destination's SSL certificate, but the man in the middle (the proxy/router/switch) can now log, redirect, or even tamper with all of your traffic.
Message-level encryption would guarantee that the message remains encrypted, even during these intermediate "hops" where the traffic itself is decrypted.
Load-balancing is another good example, because the SSL certificate is generally installed on the load balancer, which represents the SSL endpoint. The load balancer is then responsible for deciding which physical machine to send the now-decrypted traffic to for processing. Your messages may go through several "hops" like this before it finally reaches the service endpoint that can understand and process the message. | unknown | |
d1034 | train | Because you're using var, i is hoisted: to the interpreter, your code actually looks something like this:
var i;
for (i=0; i<500; i++) {
var compare = cryptoSName[i].innerHTML
// ...
So at the end of your loop, i has a value of 500, and you don't have an element with an ID of ...500. Use let instead, since let has block scoping and isn't hoisted, unlike var:
for (let i = 0; i<500; i++) { | unknown | |
d1035 | train | Of course you should only return the properties required. If you wind up with several objects which only differ in a few properties, then that's ok. But don't include properties in the DTO that are not used in a particular situation. | unknown | |
d1036 | train | Try this
rbl.SelectedValue = "1"; | unknown | |
d1037 | train | To validate html forms , the simplest way is to combine two open source powerful frameworks twitter bootstrap ( to get nice form ) and jquery.validate.js plugin ( for validation ).
Bootstrap framework : http://getbootstrap.com/getting-started/ .
Jquery validation plugin : http://jqueryvalidation.org/
So your html code and your script may appear like this
Html code :
First add this link
<link href="bootstrap/bootstrap.min.css" rel="stylesheet" media="screen">
Then
<form method="post" action="/User/AddExperience" id="add-experience-form" class="form-horizontal">
<fieldset>
<h4 class="text-primary">fields required * </h4>
<div class="form-group">
<div class="control-group">
<label class="control-label col-xs-3" for="experienceTitle">Experience Title<span class="req">*</span></label>
<div class="col-xs-9">
<input type="text" class="form-control" id="eventTitle" name="eventTitle">
<span class="help-block"></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-3 col-xs-9">
<div class="form-actions">
<input type="submit" class="btn btn-primary" name="newsubmit" id="newsubmit" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
</div>
</div>
</fieldset>
</form>
Jquery script : put it in a js file called validate.js
$(document).ready(function(){
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
});
$('#add-experience-form').validate({
rules: {
eventTitle: {
minlength: 2,
lettersonly:true,
required: true
}
},
messages: {
eventTitle: {
required:"blablabla",
minlenght:"blablabla",
maxlenght:"50 character maximum",
lettersonly: "Letters only please"
}
},
highlight: function (element, errorClass, validClass) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
unhighlight: function (element, errorClass, validClass) {
$(element).closest('.control-group').removeClass('error').addClass('success');
},
success: function (label) {
$(label).closest('form').find('.valid').removeClass("invalid");
},
errorPlacement: function (error, element) {
element.closest('.control-group').find('.help-block').html(error.text());
}
}).cancelSubmit=true; // to block the submit of this plugin and call submit to php file
});
You can put all these scripts in one folder called js then add them in your code
<script src="//code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/docs.min.js"></script>
<script src="js/jquery.validate.js"></script>
<script src="js/validate.js"></script>
For more details you can refer to the documentation http://jqueryvalidation.org/documentation/ | unknown | |
d1038 | train | I downloaded you Plnkr and tried it in browser. Here is error from Chrome console:
ReferenceError: $compile is not defined
This means that AngularJS can't use $compile, because it is not injected into your controller. This should be done in controllers.js like this:
// I have added $compile
controller('DemoCtrl', ['$scope', 'c3SimpleService', '$compile', function ($scope, c3SimpleService, $compile)
{
// rest of the controller code
}
I also fixed your Plnkr. Hope it helps :) | unknown | |
d1039 | train | Use the jQuery outerWidth function to retrieve the width inclusive of padding, borders and optionally margin as well (if you send true as the only argument to the outerWidth method).
A: Tested Solution: Find height of a div and use it as margin top of another div.
$('.topmargindiv').css('margin-top', function() {
return $('.divheight').height();
}); | unknown | |
d1040 | train | Boost.GIL is not dead. There is a few maintainers interested in keeping the project up to date, fixing bugs, helping contributors to bring new features, etc.
Boost.GIL is preparing for refreshing release as part of the upcoming Boost 1.68, including new I/O implementation accepted to Boost.GIL during the official Boost review a longer while ago.
Stay tuned and if you have any specific questions, feel free to post to the official boost-gil mailing list
A: Boost is a widely accepted set of libraries, but it's not in the C++ standard. So don't feel that you've violated the ANSI/ISO code of conduct by using something that better suits your needs.
A: Do not use boost gil, recently I tried to use it to do a "complex" task of reading a png file, but for that it requires installing a bunch of libraries that have no install documentation for Windows, and to make matters worse gil documentation suggest the following regarding libpng and libjpeg(in year 2020):
The user has to make sure this library is properly installed. I
strongly recommend the user to build the library yourself. It could
potentially save you a lot of trouble. | unknown | |
d1041 | train | See this SO answer:
In the simplest terms, the tilde matches the most recent minor version (the middle number). ~1.2.3 will match all 1.2.x versions but will miss 1.3.0.
The caret, on the other hand, is more relaxed. It will update you to the most recent major version (the first number). ^1.2.3 will match any 1.x.x release including 1.3.0, but will hold off on 2.0.0.
As far as your other questions: you should definitely not commit your node_modules folder. You should rather commit a package-lock.json file, which will freezes your dependencies as they are. The shrinkwrap command was typically used for this, but as of npm v5 the lock file is generated by default
I would also suggest looking into yarn, which is an npm compatible package manager that is better and faster at managing complex dependency trees
Finally, since the npm repository more or less enforce semver, it helps to be aware what each increment is supposed to mean in term of breaking vs non-breaking changes. In your case, the changes should have been backward compatible if the package author had followed semantic versioning:
Given a version number MAJOR.MINOR.PATCH, increment the:
*
*MAJOR version when you make incompatible API changes,
*MINOR version when you add functionality in a backwards-compatible manner, and
*PATCH version when you make backwards-compatible bug fixes. | unknown | |
d1042 | train | For a column having several rows mode(x) can be an array as there can be multiple values with high frequency. We will take the first one by default always using: mode[0] at the end. | unknown | |
d1043 | train | Classic confusion caused by extending JPanel and using another JPanel. Replace frame.getContentPane().add(secPanel) with frame.add(this , BORDERLAYOUT.CENTER) and everything should work fine.
A: You are calling super.paintComponents(g); in paintComponent, not the s at the end, this is going to cause a StackOverflowException eventually, but don't actually ever add the ReadingImage JPanel to anything, so it's never actually painted
This means that there doesn't seem to be any point any point to the secPane
You should also avoid creating frames from within other components, especially from within the constructor, it provides a very limit use case for the component
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageInputStream;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ReadingImage extends JPanel {
private BufferedImage img;
public ReadingImage(String path) {
try {
FileImageInputStream fi = new FileImageInputStream(new File(path));
img = ImageIO.read(fi);
this.repaint();
} catch (IOException io) {
io.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, this);
repaint();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame();
frame.add(new ReadingImage("Your image"));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(300, 300);
frame.setSize(300, 500);
frame.setVisible(true);
}
});
}
}
I'm not sure exactly what you are trying to achieve, but I would also encourage you to override the ReadingImage's getPreferredSize method and return the size of the image, this makes it easier to layout
A: first load the image in Image Icon, lets say the object as 'pic'.
panel1.add(new JLabel(pic));
add and set panel1 to visible. | unknown | |
d1044 | train | I think dynamic rewrite based on the data in Redis is possible using embedded Lua.
Check these two links: Lua module, Lua Redis driver
Another solution is to write the redirect logic using the language of your choice with some web-server for that language and then use proxy_pass nginx directive to proxy your requests to that web-server. | unknown | |
d1045 | train | One approach is to collect the "failed" paths for each sender, and return the path collections that have more than 10 items:
MATCH path = (a:Sender)-[:FAILED_TO]->(r:Recipient)
WITH a, COLLECT(path) AS paths
WHERE SIZE(paths) > 10
RETURN paths | unknown | |
d1046 | train | You can just replace $_GET['c.id'] with $_GET['id']. | unknown | |
d1047 | train | Since it's a table, I'd suggest structured references like:
=COUNTIF(Table1[[#Headers],[Product]]:[@Product],[@Product])
A: I don't get the same results as you do -- when I insert a row, the criteria cell changes.
In any event, since this is a Table, you can use structured references:
B2: =COUNTIF(INDEX([Product],1):@[Product],@[Product])
A: David, if your cells are not formatted as an Excel Table, this formula can do the job:
=COUNTIF(INDIRECT("A1:A" & COUNTA(A:A)),A1)-COUNTIF(INDIRECT("A"&ROW() & ":A" & COUNTA(A:A)),A1)+1 | unknown | |
d1048 | train | I don't know exactly why it doesn't work on processing.js.
However, you are doing the image processing (drawing the black stripes) each time the draw() function is called, this seems unnecessary and might be too intensive for the browser.
Remember that the setup() function gets called once when the sketch starts whereas the draw() function gets called in an infinite loop while the sketch is running (it stops when you close the sketch).
So basically do the image processing once in the setup() function and then draw the processed image in the draw() function (you don't need to, you could draw the image also in the setup() function).
Looking at your other examples at http://sketchpad.cc/sp/pad/view/ro.TExeW6NhoU8/rev.163 this code might do:
PImage img;
void setup() { // this is run once.
size(600, 400);
img=loadImage("http://c.tadst.com/gfx/600x400/int-mountain-day.jpg?1");
img.loadPixels();
int dimension = (img.width*img.height);
for (int i=0; i < dimension; i+=2) {
img.pixels[i] = color(0, 0, 0);
}
img.updatePixels();
}
void draw() { // this is run repeatedly. It only draws the image again and again.
image(img, 0, 0);
}
A: I've been dealing with this very issue. The problem appears to be that the documentation is just flat out wrong.
I was doing almost exactly what you show above with the same result, but it turns out that this is the way you have to do it:
var pixels = bg.pixels.toArray();
for(var i=0;i<pixels.length;++i){
pixels[i] = color(0);
}
bg.pixels.set(pixels);
JSFiddle | unknown | |
d1049 | train | The second image are default references. If you set them they are automatically applied after adding this script to an object.
They are not required. And only apply to a script added via the Editor (not by script!). What matters later on runtime are only the values on the GameObject.
Further you can only reference assets from the Assets folder here. They make sense e.g. if you have a button script that uses a certain Click sound, a texture and e.g. a prefab. For these three you now could already define default values so someone using your component doesn't have to assign everything everytime but already has the default references as a kind of fallback.
So in your case it would only make sense, if the borders are prefabs from the Assets that are spawned by this script. The FoodPrefab is even called like this and makes sense to have as a default reference so you don't have to drag it into each and every instance of SpawnFood you create.
And btw just by looking at your settings you should probably directly make your fields of type RectTransform so you can't accidentally reference another object there. | unknown | |
d1050 | train | From the machine running the server, search what is my ip on google (http://google.com/search?q=what+is+my+ip). It will show your public IP address, use that to access your web server from your mobile phone.
192.168.. are private IP addresses. They can only be accessed from devices on same local network. | unknown | |
d1051 | train | This is a sandbox problem. The browser does not allow loading local resources for security reasons. If you need it still, use a local webserver on your machine.
A: Most major browsers don't allow you to load in local files, since that poses a security error, e.g. people stealing secure files.
You need to test this on localhost, or setup some other server to test it.
Or, if you're using Chrome, you can turn on the flag that'll allow you to load in local files.
chrome --allow-file-access-from-files
run this from command line | unknown | |
d1052 | train | You could use an argument to pull the xml file and then build it into the image.
FROM alpine
ARG SERVER_CONF
RUN curl ${SERVER_CONF}
EXEC server.sh
Then you can run build and pass in the location of the xml file
docker build --build-arg SERVER_CONF=http://localhost/server.xml
Alternatively you could set this as an environment variable so that you can get the xml file at runtime.
FROM alpine
ARG SERVER_CONF
ENV SERVER_CONF=${SERVER_CONF}
RUN server.sh --config=$SERVER_CONF
This would allow you to set the config dynamically when you build the image.
If you would like to set the config at runtime then you could pass it as an environment variable when starting the docker container
FROM alpine
RUN server.sh --config=$SERVER_CONF
Then start your container by passing in the environment variable
docker run -e "SERVER_CONF=http://localhost/server.xml" server
You don't have to pass a url, you could pass the entire contents of the xml file as a string. You can use an entry point to write the contents of the environment to a file before your application starts.
A:
Is there any way to do it instead of keeping in dockerfile?
As long as you have fetched that server.xml (or simply copied its content to a local file), you can:
*
*either COPY it in your Dockerfile
*or put it in a public place, remotely accessible, which your container could, at runtime, fetch from (instead of having to try and clone a private repo, which your container should not be able to do) | unknown | |
d1053 | train | $('article *',document.body).click(
function(e){
e.stopPropagation();
var selectedElement = this.tagName;
$(selectedElement).css('border','1px dotted #333');
}
);
Demo at JS Bin, albeit I've used the universal selector (since I only posted a couple of lists (one an ol the other a ul).
Above code edited in response to comments from @Peter Ajtai, and linked JS Bin demo up-dated to reflect the change:
Why run around the block once before you look at the tagName? How about var selectedElement = this.tagName;. Also it's e.stopPropagation(), since you're calling a method.
A: I don't know how many elements are nested under your article elements, but it would seem wasteful to add click event handlers to all of them using *.
Instead, just add the handler to article, and get the tagName of the e.target that was clicked.
$("article", document.body).click(function ( e ) {
e.stopPropagation();
$( e.target.tagName ).css("border", "1px dotted #333")
});
This will be much more efficient. | unknown | |
d1054 | train | You are just missing the declaration of result in the code blocks.. personally I would suggest the second code block anyway (when corrected) but here...
public string test(){
bool a = true;
string result = string.Empty;
if(a){
result = "A is true";
}else{
result = "A is not true";
}
return result;
}
And if you were going to go with the second block you could simplify it to:
public string test(){
bool a = true;
if(a){
return "A is true";
}else{
return "A is not true";
}
}
Or further to:
public string test(){
bool a = true;
return a ? "A is true" : "A is not true";
}
And several other iterations of similar code (string formatting etc). | unknown | |
d1055 | train | Are you querying the data in from info path or using visual studio, if you are querying in info path check the condition as Display name matches the username() and the query the data | unknown | |
d1056 | train | This should basically do what you want, using a simple open struct to create a message class which has accessors for each of the keys in your message hash
require 'ostruct'
class MessageParser
Message = Struct.new(:type, :id, :number, :message, :log_no, :log_msg_no, :message_v1, :message_v2, :message_v3, :message_v4, :parameter, :row, :field, :system)
attr_reader :messages
def initialize(data)
@data = data.fetch("MESSAGES",[])
@messages = []
parse_data
end
private
def parse_data
@data.each do | msg |
message = Message.new
msg.fetch("MESSAGE",{}).each do |key, value|
message[key.downcase.to_sym] = value
end
@messages << message
end
end
end
parser = MessageParser.new(result.body["RESULT"])
parser.messages.each do |message|
puts message.message
puts message.type
end
A: Something like this should work:
class ParsedMessages
include Enumerable
attr_reader :messages
def initialize(data)
@messages = extract_messages_from_data(data)
end
def extract_messages_from_data(data)
# TODO: Parse data and return message objects
end
def each &block
@messages.each do |message|
if block_given?
block.call message
else
yield message
end
end
end
end
Now you can use all methods from Enumerable on ParsedMessages, like each, find, map etc etc. | unknown | |
d1057 | train | Modify your cell class as
class BaseFormCollectionViewCell: UICollectionViewCell {
var formComponent: FormComponent!{
didSet {
//this is unnecessary. You can achieve what u want with a bit more cleaner way using configure function as shown below
//data can be print out here
print("Passed value is: \(formComponent)")
}
}
override init(frame: CGRect) {
super.init(frame: frame)
//this part is always nill
print(formComponent)
}
func configure() {
//configure your UI of cell using self.formComponent here
}
}
finally
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! BaseFormCollectionViewCell
cell.backgroundColor = .green
//Data could be print out here
print(self.formData?.components?[indexPath.row])
cell.formComponent = (self.formData?.components?[indexPath.row])!
(cell as! BaseFormCollectionViewCell).configure()
return cell
}
Look for (cell as! BaseFormCollectionViewCell).configure() in cellForItemAt thats how u trigger the UI configuration of cell after passing data to cell in statement above it.
Quite frankly u can get rid of didSet and relay on configure as shown
Hope it helps | unknown | |
d1058 | train | Here's a suggestion. There's a neat module in the standard library called fileinput that allows you to easily read several files in a row and also gives you access to the filenames, line numbers, etc. Try something like the following and see if it fits your needs:
import glob
import fileinput
file_list = glob.glob(...)
with fileinput.input(file_list) as fin,\
open("error.csv", "a") as fout:
out = "Filename: {}, Line: {}, {}: {}\n"
write = False
for line in fin:
line = line.rstrip()
line_folded = line.casefold()
if "error" in line_folded:
write, var = True, "Error"
elif "success" in line_folded:
write, var = True, "Success"
if write:
fout.write(out.format(fin.filename(), fin.filelineno(), var, line))
write = False
It's a bit unclear why you want to write a CSV-file: Your output doesn't look like it's in a csv-format? | unknown | |
d1059 | train | The following snippet hides the navigation bar and status bar:
window.decorView.apply {
// Hide both the navigation bar and the status bar.
// SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
// a general rule, you should design your app to hide the status bar whenever you
// hide the navigation bar.
systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN
}
From https://developer.android.com/training/system-ui/navigation
Nonetheless for your case you need two things to happen.
*
*First, set windowFullScreen to true to allow the dialog to paint every pixel in the screen. (i.e. Use any FullScreen theme).
*Then, on you dialog, set the systemUiVisibility to View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION.
This will stop the navigationBar from ever showing until you reset the flags or dismiss the dialog.
The complete snippet:
class SomeActivity {
fun showDialog() {
FullScrenDialog()
.apply {
setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_NoTitleBar_Fullscreen)
}
.show(supportFragmentManager, "TAG")
}
}
class FullScrenDialog : DialogFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
dialog.window?.decorView?.systemUiVisibility = View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
return inflater.inflate(R.layout.dialog, container)
}
}
A: Please try below code for dialog:
final Dialog dialog = new Dialog(this);
dialog.setCancelable(false);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().setGravity(Gravity.CENTER);
dialog.setContentView(R.layout.dialog_logout);
Window window = dialog.getWindow();
window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
window.getDecorView().setSystemUiVisibility(uiOptions);
dialog.show();
Output is:
I hope it works for you. | unknown | |
d1060 | train | Your example data makes the question clearer. You could collect the manager levels as you descend:
; with Tree as
(
SELECT empid
, mgrid
, 1 as lv
, 1 as level1
, null as level2
, null as level3
, null as level4
, null as level5
FROM Employees
WHERE mgrid IS NULL
UNION ALL
SELECT E.empid
, E.mgrid
, T.lv + 1
, T.level1
, case when T.lv = 1 then E.empid else t.level2 end
, case when T.lv = 2 then E.empid else t.level3 end
, case when T.lv = 3 then E.empid else t.level4 end
, case when T.lv = 4 then E.empid else t.level5 end
FROM Employees AS E
JOIN Tree T
ON E.mgrid = T.empid
)
select *
from Tree
Example at SQL Fiddle.
A: ;WITH Tree (empid, level, level1, level2, level3, level4, level5)
AS (
SELECT empid, 1, empid, NULL, NULL, NULL, NULL
FROM Employees
WHERE mgrid IS NULL
UNION ALL
SELECT E.empid, T.level + 1,
CASE WHEN T.level+1 = 1 THEN E.empid ELSE T.level1 END,
CASE WHEN T.level+1 = 2 THEN E.empid ELSE T.level2 END,
CASE WHEN T.level+1 = 3 THEN E.empid ELSE T.level3 END,
CASE WHEN T.level+1 = 4 THEN E.empid ELSE T.level4 END,
CASE WHEN T.level+1 = 5 THEN E.empid ELSE T.level5 END
FROM Employees AS E
JOIN Tree T
ON E.mgrid= T.empid
)
SELECT empid, level, level1, level2, level3, level4, level5
FROM Tree
A: With a pivot?
;WITH Tree (empid, mgrid, lv)
AS (
SELECT empid, mgrid, 1
FROM @Employees
WHERE mgrid IS NULL
UNION ALL
SELECT E.empid, E.mgrid, lv + 1
FROM @Employees AS E
JOIN Tree
ON E.mgrid= Tree.empid
)
select *
from
Tree
pivot
(count(empid) for lv in ([1],[2],[3],[4],[5]))p | unknown | |
d1061 | train | I found an answer. Rather than using the vague blockquote conversion method, I instead used PHP to print a JS script for each container with a unique twitter ID. 100% success rate:
<?php /* OUTPUT */
// Count tweets for debug
$number_tweets = count($tweet_array['statuses']);
echo "<div class='cols'>";
// Loop through each tweet
foreach ($tweet_array['statuses'] as $tweet ) {
// Get tweet ID
$id = $tweet["id"];
// Create grid item to be targeted by Twitter's widgets.js
echo "<div class='grid-item'><div id='container-$id'></div></div>";
// Add to array for JS objet
$js_array[] = "twttr.widgets.createTweet('$id', document.getElementById('container-$id'));";
}
echo "</div>";
// Begin Javascript
echo '<script>';
// Print out JS to convert items to Tweets
$t = 1;
foreach ($js_array as $js ) {
echo $js;
$t++;
}
echo '</script>'; | unknown | |
d1062 | train | You can also use the dict initializator that takes an iterable of key-value tuples. So this would be perfect for your function that already returns a tuple:
>>> dict(map(foo, list_of_vals))
{2: 200, 4: 400, 6: 600}
In general though, having a function that returns a key-value tuple with the identical key seems somewhat rare. Most commonly, you would just have a function that returns the value. In those cases you would use a dictionary comprehension like this:
{ x: foo(x) for x in list_of_vals }
A: Just convert the result of map to dict directly
>>> list_of_vals = [2, 4, 6]
>>> dict(map(foo, list_of_vals))
{2: 200, 4: 400, 6: 600} | unknown | |
d1063 | train | Native C++ "kernels" are essentially just functions that you want to execute within command queue to preserve order of commands.
AFAIK they are not supported on GPU. If you want to execute C++ functions across all devices, you should consider to use cl_event callbacks (when status == CL_COMPLETE).
Assume you have a buffer object you want to read from device and pass to your C++ function. Also you want to pass some integer value as well
(I use C++ OpenCL wrapper):
// First of all, we should define a struct which describes our arguments list.
struct Arguments
{
int integer;
void* buffer_host;
};
// Define C/C++ function you want to call.
void CFunction(void *args)
{
Arguments args = reinterpret_cast<Arguments*>(args);
// Do something with args->integer and args->buffer_host.
}
// ...
Arguments args = {.integer = 0, .buffer_host = NULL};
// First, we should define Buffer objects in arguments.
std::vector<cl::Memory> buffers_dev;
buffers_dev.push_back(a_buffer);
// Then we should define pointers to *pointer in args* which will be set
// when OpenCL read data from buffers_dev to the host memory.
std::vector<const void*> buffers_host;
buffers_host.push_back(&args.buffer_host);
// Finally, set integer
args.integer = 10;
queue.enqueueNativeKernel(CFunction,
std::make_pair(&args, siezof(Arguments)),
&buffers_dev,
&buffers_host);
// At this point args were copied by OpenCL and you may reuse or delete it. | unknown | |
d1064 | train | All you need is define custom bearerTokenResolver method in SecurityConfig and put access token into cookies or parameter.
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/user/info", "/api/foos/**")
.hasAuthority("SCOPE_read")
.antMatchers(HttpMethod.POST, "/api/foos")
.hasAuthority("SCOPE_write")
.anyRequest()
.authenticated()
.and()
.oauth2ResourceServer()
.jwt().and().bearerTokenResolver(this::tokenExtractor);
}
...
}
public String tokenExtractor(HttpServletRequest request) {
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (header != null)
return header.replace("Bearer ", "");
Cookie cookie = WebUtils.getCookie(request, "access_token");
if (cookie != null)
return cookie.getValue();
return null;
} | unknown | |
d1065 | train | ROWID is a unique identifier of each row in the database.
ROWNUM is a unique identifier for each row in a result set.
You should be using the ROWNUM version, but you will need an ORDER BY to enforce a sorting order, otherwise you won't have any guarantees what is the "first" row returned by your query and you might be updating another row.
update addrView
set home='current'
where (tl, tr) = (
select tl, tr
from (select tl, tr
from addrView
where (tl = '7' and tr = '2')
order by col_1
, col_2
, col_3 etc.
) result_set
where rownum = 1);
But, if you don't care about what data is in the first row returned by your query, then you can use only rownum = 1.
update addrView
set home = 'current'
where (tl = '7' and tr = '2')
and rownum = 1; | unknown | |
d1066 | train | why dont u clean out whatever is being put into the _GET value? (using php)
at the top of the php file put something like:
if(isset($_GET['q'])){
header('Location: homepage.php');
}
A: If someone is spamming you hard enough to overload your server you should look at blocking their IP address/addresses or something along those lines if possible.
Also I would suggest letting those requests die() rather than making them send you another request when they load your homepage. Or maybe keep them busy by redirecting to a domain that doesn't exist or something but that may or may not have an impact on them.
A: have you thought about counting "X"?
if the ?q=X == true, continue,
otherwise if q>9 then you know someone is messing with it and restrict them | unknown | |
d1067 | train | You missed each:
And match each response.errors[*].reason contains "this is reason"
Refer: https://github.com/karatelabs/karate#match-each | unknown | |
d1068 | train | I suggest an answer to this thread because it isn't marked as resolved and despite the answer given it didn't allow me to resolve the issue as of the time of reading this.
Resources
*
*select2.org
*npm
I have since found a functional solution of which here are the details in relation to the question of the OP. Verified and working with Laravel 8
*
*Install package via npm
npm install select2
*Edit /resources/js/app.js to import javascript from package
require('./bootstrap');
/* ... */
require('select2'); // Add this
/* ... */
Alpine.start();
*Edit /resources/css/app.css to import styles from package
/* ... */
@import 'select2'; // Add this
*Edit /resources/js/bootstrap.js to enable the use of .select2();
window._ = require('lodash');
/* ... */
window.select2 = require('select2'); // Add this
*Run NPM
npm run dev
npm run watch
*NPM result in my case
Laravel Mix v6.0.39
✔ Compiled Successfully in 2982ms
√ Mix: Compiled successfully in 3.05s
webpack compiled successfully
Testing
According to configuration documentation
HTML
<input type="text" class="form-control js-example-basic-single">
JS
<script type="text/javascript">
$(document).ready(function () {
$('.js-example-basic-single').select2({
placeholder: 'Select2 testing purpose'
});
});
</script>
Render
A: Run npm run watch , because keeps track of all changes in .js.
In app.js add
require('select2/dist/js/select2');
In app.blade.php example:
<div>
<select class="js-select2 css-select2-50">
<option>1</option>
</select>
</div> | unknown | |
d1069 | train | What you're describing is a state machine.
Older SO question discussing the various gems and plugins of the time, plus some basics.
Newer blog post discussing the hows and whys. | unknown | |
d1070 | train | But problem is when am upload multiple images with 2mb size...
It's likely your running into the default maximum upload size that's set for ASP.NET (4MB). you can add this to your web.config to increase from the default:
<system.web>
<httpRuntime executionTimeout="240" maxRequestLength="20480" />
</system.web>
This would increase the maximum upload size to 20MB at a time.
There's a pretty detailed article about this topic here if you'd like to read further: Large file uploads in ASP.NET.
Note: You said the "javascript was not working", but didn't really elaborate. If you could expand on that, I'd be glad to take another look | unknown | |
d1071 | train | DISTINCT LOCATION_ID,
CONTINENT,
COUNTRY,
PLANT,
BUSINESS_UNIT,
PRODUCT,
--Measures (KPI's):
--Count:
CASE
WHEN <Parameters.BU> = '%' AND <Parameters.Plant> = '%' THEN SUM(COUNT_IO) OVER (PARTITION BY BUSINESS_UNIT)
WHEN <Parameters.BU> != '%' AND <Parameters.Plant> = '%' THEN SUM(COUNT_IO) OVER (PARTITION BY PLANT)
ELSE SUM(COUNT_IO) OVER (PARTITION BY LOCATION_ID)
END AS "COUNT_IO",
--OEE:
CASE
WHEN TIME_IO = 0 OR TIME_TARGET_OEE_100 = 0
THEN 0
ELSE
CASE
WHEN <Parameters.BU> = '%' AND <Parameters.Plant> = '%' THEN SUM(TIME_IO) OVER (PARTITION BY BUSINESS_UNIT) *100/SUM(TIME_TARGET_OEE_100_FILTERED) OVER (PARTITION BY BUSINESS_UNIT)
WHEN <Parameters.BU> != '%' AND <Parameters.Plant> = '%' THEN SUM(TIME_IO) OVER (PARTITION BY PLANT) *100/SUM(TIME_TARGET_OEE_100_FILTERED) OVER (PARTITION BY PLANT)
ELSE SUM(TIME_IO) OVER (PARTITION BY LOCATION_ID) *100/SUM(TIME_TARGET_OEE_100_FILTERED) OVER (PARTITION BY LOCATION_ID)
END
END AS "OEE"
FROM VALUES_FOR_TABLEAU_METADATA
WHERE
COUNT_TARGET_OEE != 0 AND PLANT LIKE <Parameters.Plant> AND BUSINESS_UNIT LIKE <Parameters.BU> AND LOCATION_ID LIKE <Parameters.LocationID> AND WORKING_DAY BETWEEN <Parameters.WorkingDay_Start> AND <Parameters.WorkingDay_End>
GROUP BY
CASE
WHEN <Parameters.BU> = '%' AND <Parameters.Plant> = '%' THEN LOCATION_ID
WHEN <Parameters.BU> != '%' AND <Parameters.Plant> = '%' THEN LOCATION_ID
ELSE ROLLUP(LOCATION_ID)
END,
CASE
WHEN <Parameters.BU> = '%' AND <Parameters.Plant> = '%' THEN PLANT
WHEN <Parameters.BU> != '%' AND <Parameters.Plant> = '%' THEN ROLLUP(PLANT)
ELSE PLANT
END,
CASE
WHEN <Parameters.BU> = '%' AND <Parameters.Plant> = '%' THEN ROLLUP(BUSINESS_UNIT)
WHEN <Parameters.BU> != '%' AND <Parameters.Plant> = '%' THEN BUSINESS_UNIT
ELSE BUSINESS_UNIT
END,
CONTINENT, COUNTRY, PRODUCT, COUNT_IO, COUNT_TARGET_OEE, TIME_IO, TIME_TARGET_OEE_100, TIME_TARGET_OEE_100_FILTERED
I guess that the problem is caused by the ROLLUP in the CASE statement, since the code up to the GROUP BY is working fine. Also I am not quite sure if the usage of my CASE statement is used properly.
The Parameters may look quite weird, but they are for use in Tableau and work fine.
The error I get is:
ORA-00904: "ROLLUP": invalid identifier
A: The best and easiest way to work with Tableau is to let it generate optimized SQL based on what you express in Tableau. Don't use custom SQL with Tableau except in rare situations. You get a lot more flexibility and performance that way.
In this case, I recommend just connecting to VALUES_FOR_TABLEAU_METADATA from Tableau.
*
*Define a string valued parameter to allow the user to choose the dimension for his "rollup", say called Dimension_For_Rollup with a list of two possible values: "Location" and "Plant".
*Define a calculated field called Selected_Dimension defined as if [Dimension_For_Rollup] = "Location" then [Location Id] else [Plant] end
*Use Selected_Dimension on your viz as desired.
*Show the parameter control for Dimension_For_Rollup
So the user can toggle between Dimensions for Rollup as he wishes, and Tableau will generate optimized SQL, cache the query as needed.
Your Count_IO or Time_IO stats can be expressed in different ways in Tableau, possible needing Tableau's level of detail (LOD) calcs, but again -- your Tableau experience will be better if you don't try to hard code everything in SQL in advance. You can use Tableau that way, but you're making life hard on yourself and giving up a good part of the benefit. | unknown | |
d1072 | train | use
.hidden_item{
display:none;
} | unknown | |
d1073 | train | *
*Every endorsing peer is also a committing peer.
*An orderer and a peer are totally different binaries, and have completely different APIs, so - you can't have one fill the role of the other. | unknown | |
d1074 | train | It seems like the answer to this question depends on how you're doing the zooming of the graph itself.
You'll basically want to scale the majorIntervalLength in the same way you're scaling the ranges for your plot space. That is, if you expand the range by a factor of 2 then you want to also change the value of majorIntervalLength to twice it's current value. If you expand by 1.1, you'll multiply the current value of majorIntervalLength by 1.1 and then set majorIntervalLength to that new value.
If you post your code for the graph scaling I can provide a more detailed answer with some code.
[UPDATE]
After looking at your code. I would recommend the following changes
before you update PlotSpaceX do this:
intervalScale = (PlotSpaceX + 0.1 / PlotSpaceX)
then update majorInterval like this
majorInterval = majorInterval*intervalScale
This should scale your axis interval in exactly the same way as your x coordinate. | unknown | |
d1075 | train | If you are asking how could I render navbar and sidebar to all components except login, then you can check the browser url.
There are many ways of doing this, but one of which is like following:
<Route path="*" render={props => <Layout {...props} />} />
This will appear for all your routes now. Then inside Layout, you can check the route, and only render something if the route does not equal to login.
render(){
if(this.props.location === "login"){return null}
...
}
While typing this, you can do it directly in React Router, maybe excluding certain route. | unknown | |
d1076 | train | You can send message from one window to another with postMessage, and access it via addEventListener and remember that the iframe is the child of your flutter page (and flutter is the parent), so:
To send data from flutter to the iframe, you can use _iFrameElement.contentWindow?.postMessage (after the iframe loaded), and to get that data in iframe, you can use window.addEventListener.
To send data from iframe, you can use window.parent.postMessage, and
to get that data in flutter, you can use window.addEventListener.
A sample code would be:
Flutter:
import 'dart:html';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
class IFramePage extends StatefulWidget {
const IFramePage({Key? key}) : super(key: key);
@override
State<IFramePage> createState() => _IFramePageState();
}
class _IFramePageState extends State<IFramePage> {
int i = 0;
IFrameElement _iFrameElement = IFrameElement();
@override
void initState() {
_iFrameElement.src = 'http://localhost/iframe/iframe.html';
// ignore: undefined_prefixed_name
ui.platformViewRegistry.registerViewFactory(
'iframeElement',
(int viewId) => _iFrameElement,
);
_iFrameElement.onLoad.listen((event) {
// Send message to iframe when loaded
_iFrameElement.contentWindow
?.postMessage('Hello! Clicked: $i times', "*");
});
// Get message from iframe
window.addEventListener("message", (event) {
var data = (event as MessageEvent).data ?? '-';
if (data == 'clicked') {
setState(() {
i++;
});
}
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Text('clicked $i time(s)'),
SizedBox(
width: 300,
height: 300,
child: HtmlElementView(
key: UniqueKey(),
viewType: 'iframeElement',
),
),
],
),
);
}
}
and IFrame:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<div>This is my iframe</div>
<button type="button" onclick="sendData()">Click Me!</button>
</body>
<script>
// Send data to parent window
const sendData = () => window.parent.postMessage('clicked', "*");
// Get data from parent window
window.addEventListener("message", (event) => console.log(event.data));
</script>
</html> | unknown | |
d1077 | train | I don't know how your tasks are coded, but it seems that they could be encapsulated in commands, which would then be put in a queue, or some other data structure. Once they are dequeued, their logic is checked. If they need to run, they are executed, and they're not put back in the queue. If their logic says that they shouldn't run, they're just put back in the queue to be able to run later.
Your interface would be something like:
public interface ITaskSink {
void AddTask(ICommandTask task);
}
public interface ICommandTask {
bool ShouldRun();
void Run(ITaskSink sink);
}
Tasks could also be able to add other tasks to the data structure (so Run takes an ITaskSink as a parameter), covering your subtask creation requirement. A task could even add itself back to the sink, obviating the need for the ShouldRun method and simplifying your task processor class.
A: If you're using .NET 4.0, the Lazy<T> generic might be the solution to what you're describing, because it evaluates its value at most once.
I'm not sure I exactly understand your use case, but there's no reason you couldn't nest Lazys together to accomplish the nested children issue.
A: I'm not exactly sure what you're talking about, but a helpful pattern for complex chained logic is the rules engine. They're really simple to code, and can be driven by simple truth tables, which are either compiled into your code or stored as data.
A: Create a private static variable, create a read only property to check for null on the private variable, if the variable is null instantiate/initialize and just return the private variable value. In your implementation code reference the property, never the private variable. | unknown | |
d1078 | train | Which Qt version are you using? 4.7 has QByteArray(const char*, size) which should work and QByteArray::fromRawData(const char*, int size) which also should work.
A: QByteArray test("\xa4\x00\x00", 3); | unknown | |
d1079 | train | You need to be able to iterate over the list of directories and over the list of files in each directories. This can be done using a FOR loop. See FOR /? for more details.
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
PUSHD "C:\the directory\of interest"
FOR /F "usebackq tokens=*" %%d IN (`DIR /B /A:D .`) DO (
DIR /B /A:-D %%d >NUL 2>&1
IF !ERRORLEVEL! EQU 0 (
FOR /F "usebackq tokens=*" %%f IN (`DIR /B /A:-D /O:D %%d`) DO (
SET LASTFILE=%%f
)
ECHO %%d\!LASTFILE!
)
)
POPD | unknown | |
d1080 | train | I have written one-liner in a Python(280 characters of code) for this.
python -c"import re,sys;o=lambda f,m:open(f,m);x=lambda h:[i for i in o(h,'r').readlines()];y=lambda s:len(re.findall(r'(\w+)',s)[2].split('A'))>2;z=lambda f,s:o(f,'a'if len(s)else'w').write(s);a,b=sys.argv[1:3];w=zip(x(a),x(b));z(a,'');z(b,'');[(z(a,c),z(b,d))for(c,d)in w if y(c)and y(d)]" a.txt b.txt
Note: this code does not close file descriptors. I assume that OS does that. | unknown | |
d1081 | train | My default assumption would be that there is a typo in the real code and the constructor is assigning a value from a field to itself. However, frankly: since you have a public Batch() {} constructor, I'm not sure what the benefit of the second one is - it just adds risk of errors. Likewise with the fields and manual properties.
So if this as me, where you currently have (simplified to two properties):
public class Batch
{
private string cendid;
private string bmhfmc;
public Batch() {}
public Batch(string cendid, string bmhfmc)
{
this.cendid = cendid;
this.bmhfmc = bmhfmc;
}
public string Cendid
{
get { return cendid; }
set { cendid = value; }
}
public string Bmhfmc
{
get { return bmhfmc; }
set { bmhfmc = value; }
}
}
I would have literally just:
public class Batch
{
public string Cendid {get;set;}
public string Bmhfmc {get;set;}
}
All of the rest of the code is just opportunities to make coding errors.
Now: the reason that Cendid is null is because: the column is CENID - only one d. This means that dapper isn't even using your custom constructor, because it isn't a perfect match between the constructor and the columns. Ditto the other fields like BRAID vs BRADID.
So the next thing to do is to fix the typos. | unknown | |
d1082 | train | You can do it without bootstrap col-*-* and by giving the explicit width to both divs, plus little extra style to your icon bar.
Updated Code
<div class="activity-panel-item--header">
<div class="pull-left" style="width: 75%;">
<p>02 Development, LLC v. 607 South Park, LLC </p>
</div>
<div class="pull-right" style="position: absolute; right: 0px; min-width: 25%;"><span class="icon icon-trash-o pull-right">1</span><span class="icon icon-cog2 pull-right">2</span><span class="icon icon-pencil3 pull-right">3</span></div>
</div>
jsFiddle
EDIT 1
If you think deeply according to this solution we both are at same point. Let me explain, I am giving minimum width 25% to icon bar and 75% width to left element. That mean depending on situation width of icon bar can be increase but it must be at least 25% of total screen or container and width of left element is 75% that can be decrease depending on situation.
And you are giving width 125px or any to icon bar that means it can be increase or decrease depending on situation but the original is 125px
Here the situation I mean area and screen resolution. If icon are larger and not fit in 25% then this width can be increase and left element can be decrease same is your edited case if icon bar not fit in 125px then this width can be increase because we are not mentioning the maximum width to icon bar or minimum width to left element.
.
EDIT 2
I hope this is not illegal on stackoverflow to edit answer as many time as I need.
Apart from coding let’s do some math. Suppose we have 3 icon of (32x32) each. So the total width of icon wrapper will (32+32+32) 96px add little margin of 12px to each icon (12x3=36) on right side for beauty. Now the wrapper width is 96+36 = 132px. And we are on device that has width of 400px. My icon wrapper is (25%) 100px of 400px (device width) and your wrapper is 125px. I am saying OK browser minimum width of icon wrapper is 100px but if icons are larger and not fit in 100px you can increase this width according to you need, In this case it will increase 100px to 132px or any. But I don't want to break these icons to next line. They should be display in their original size and style (32x32) plus margin. You can break left content (text) to wrap around these icons but don't break the icons itself. They should retain their original size. No matter what ever device width is. Browser, Please don't decrease the icon size just increase wrapper width.
And your 125px is less than 132px. So your wrapper will break and one of its icon will move to next line. Until you have to go to you CSS and explicitly wrote 132px or any in width. And what if after one month your boss said please place icon of 40x40 and after 3 month and so on...?
Try it, place larger icons and see what happens to your width: 125px.
A: Unless I am totally misunderstanding you.. here is a easy method. Too much CSS
classes so I used my own but you get the concept.
<div class="top">
<div class="content1">
<p>02 Development, LLC v. 607 South Park, LLC </p>
</div>
<div class="content2">
<span>1</span>
<span>2</span>
<span>3</span>
</div>
</div>
<div class="content3">
<p>test 123345.</p>
<h3>Nothing Here</h3>
<p>cases</p>
</div>
Demo: https://jsfiddle.net/norcaljohnny/ovo83p5k/ | unknown | |
d1083 | train | You have to improve your code with a couple of changes
First
Your form is not pointing to any action (Maybe you are using Js for activating the view that generates the PDF) and the easiest way to delivering the form data to the view is making the form action attribute points to the target view.
Let's say your view has an URL named generate_pdf (see Naming URL patterns) then you could in your template:
<form method=POST action="{% url generate_pdf %}">
{{ reference_list }}
<button type="submit" class="btn btn-primary" name="button">Add Order</button>
</form>
Second
... having the form pointing to your view, you can read the Reference_IDs from the post data in order to obtain the Order instance and use it:
def generate_view(request, *args, **kwargs):
context = {}
if request.method == 'POST':
order_reference = self.request.POST.get('Reference_IDs')
if order_reference is not None:
order = Orders.objects.get(reference=order_reference)
template = get_template('invoice.html')
context.update({
"ultimate_consignee": order.ultimate_consignee,
# ...
})
html = template.render(context)
pdf = render_to_pdf('invoice.html', context)
return HttpResponse(pdf, content_type='application/pdf')
Good luck!
Note: I've not tested this, it is just an effort to show you one of the approaches you can follow to achieve what you want. | unknown | |
d1084 | train | There is already a concat function.
myString.concat(parameter);
You can use it as that. Reference: Arduino Official Link | unknown | |
d1085 | train | C++ streams are not compatible with C stdio streams. In other words, you can't use C++ iterators with FILE* or fread. However, if you use the C++ std::fstream facilities along with istream_iterator, you can use an insertion iterator to insert into a C++ container.
Assuming you have an input file "input.txt" which contains ASCII text numbers separated by whitespace, you can do:
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
int main()
{
std::ifstream ifs("input.txt");
std::vector<int> vec;
// read in the numbers from disk
std::copy(std::istream_iterator<int>(ifs), std::istream_iterator<int>(), std::back_inserter(vec));
// now output the integers
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, "\n"));
}
A: no you can't. And it's fundamentally not-portable to store int like that. Your code will break if you write your file with a big-endian machine and try to read it with a little-endian machine.
But nobody prevents you to. Just define your own forward iterator that reads binary from a istream. You will likely want to stop using FILE and fread/fopen/fclose function as they are from C era.
then you will be able to write :
std::copy_n(your_custom_forward_iterator, count, back_inserter<std::list<....> >); | unknown | |
d1086 | train | I can't figure out what the problem is.. The css is really messy, there is a lot of useless or overwritten properties.. You have to optimize it..
But somehow I found a workaround : set the width of the #css-slider to 864px.. It's not really a proper solution but it works anyway..
A: As you can see you have some margin between the images, which makes their widths effectively bigger a little bit. I see you applied a reset in your css, so this is probably coming from the white space in your html. A quick fix would be to put all the li and img on a single line with no spaces or carriage returns between them, like so:
<ul id="css-slider"><li><img src="http://cdn.gtm.net.au/images/catalogue/sp_image_108.jpg" alt="slider"></li><li><img src="http://cdn.gtm.net.au/images/catalogue/sp_image_62.jpg" alt="slider"></li><li><img src="http://cdn.gtm.net.au/images/catalogue/sp_image_59.jpg" alt="slider"></li><li><img src="http://cdn.gtm.net.au/images/catalogue/sp_image_66.jpg" alt="slider"></li></ul>
I know, it's weird. | unknown | |
d1087 | train | Try looping through all ChartObjects in your worksheet, and delete each one of them (if exists).
Code:
Option Explicit
Sub CheckCharts()
Dim ChtObj As ChartObject
For Each ChtObj In Worksheets("Sheet1").ChartObjects '<-- modify "Sheet1" with your sheet's name
ChtObj.Delete
Next ChtObj
End Sub | unknown | |
d1088 | train | That is the old version. Change the line in your web.config to use the 3.5 version:
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
(Yes, this is a common conversion error.)
A: I have this issue a lot from web.config inheritance. You can also add binding re-directs. Below will re-direct any calls to the old version to the new version, you can also set this to work the other way round.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.61025.0" newVersion="3.5.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime> | unknown | |
d1089 | train | Make sure you include jQuery:
<script src="http://code.jquery.com/jquery-latest.js"></script>
IMPORTANT: Also put your code inside a document-ready function and I would suggest you to use jQuery click() function instead of the way you have done, but that's okay:
$(document).ready(function () {
$('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function(){
if ($(this).children('a').hasClass('holder_notify_drop_link')){
$(this).on('click',function(e) {
var url = $(this).children('a').attr('href');
$(this).children('a').attr('onClick',"openFrame('"+url+"','yes')");
e.preventDefault();
});
};
)};
});
A: Here's a working example http://jsfiddle.net/g248G/.
HTML:
<div class="holder_notify_drop_data">
<a class="holder_notify_drop_link"
href="http://stackoverflow.com">Stackoverflow.com</a>
</div>
<ul>
<li class="holder_notify_drop_data">
<a class="holder_notify_drop_link"
href="http://google.com">Google.com</a>
</li>
</ul>
Javascript:
function openFrame(URL, option) {
window.open(URL);
}
$(document).ready(function() {
$('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function() {
$(this).children('a').each(function() {
var $link = $(this);
if ($link.hasClass('holder_notify_drop_link')) {
var URL = $link.attr('href');
$link.on('click', function(event) {
event.preventDefault();
openFrame(URL, 'yes');
});
}
});
});
});
A: Why not use jQuery.on() for that?
This will bind click function to all current and future elements of a in holder_notify_drop_data container.
$('.holder_notify_drop_data').on('click', 'a', function (ev) {
ev.preventDefault();
openFrame($(this).prop('href'), 'yes');
}); | unknown | |
d1090 | train | In case anyone has sizing/layout issues with Android apps for different screen sizes/display dpis - I highly recommend this sdk https://github.com/intuit/sdp/commits?author=elhanan-mishraky which solved my problem above! | unknown | |
d1091 | train | Yes you need to add an .CreateAleas
.CreateAlias("Product", "product", JoinType.InnerJoin)
please change JoinType to your need, and use "product" alias instead of property name "Product"
so final should be something like:
.CreateCriteria(typeof(ProductCategory))
.CreateAlias("Product", "product", JoinType.InnerJoin)
.Add(Restrictions.Eq("CompanyId", companyId))
.Add(Restrictions.Eq("CategoryId", id))
.Add(Restrictions.Eq("product.IsPopItem", true))
.List<ProductCategory>());
return products; | unknown | |
d1092 | train | Atlast, this is what I had to do to connect an external service from VM to connect to the PCF managed Config Server.
When the profile property was not set to 'dev' in the bootstrap.yml, the profile was set to 'default' which triggered a login prompt even though I had a relaxed security config in place. I still don't know if this is a best practice. But, once I set the profile property as 'dev', I was able to consume the resouces seamlessly. | unknown | |
d1093 | train | To start, you might want to know this:
the first code you get to run after the application has finished launching, is the one you put in the Application Delegate in the method application:didFinishLaunchingWithOptions. The app delegate is the class that is set to receive general notifications about what's going on with the app, like it finished launching :)
The other kind of 'notifications' of changes in the state of the app, or the life cycle of views are:
-viewDidLoad
-viewWillAppear:animated:
-viewDidAppear:animated:
-viewWillDisappear:animated:
-viewDidDisappear:animated:
-viewDidUnload
Those methods are declared in UIViewController, and you can implement them in your UIViewController subclasses to customize the behaviour of a view in those situations (each method name is self explanatory)
The life cycle of an app is pretty well covered here: http://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/iphoneappprogrammingguide.pdf page 27
About showing a logo when the app launches, apps achieve that setting a "splash" image by putting its name in the info.plist property-list file, in the UILaunchImageFile key.
A: I think the official developer guide delivered by apple will help you. This is the link:
http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/ViewLoadingandUnloading/ViewLoadingandUnloading.html | unknown | |
d1094 | train | If you have a number as a string and it is an integer with no leading 0s, you can compare it by comparing the length first and then the value. For instance, the following will order by col1 correctly (assuming the above):
select t.*
from t
order by char_length(col1), col1;
So, one way to get the minimum is:
select col1
from t
order by char_length(col1), col1
limit 1;
You can also get both in a group by by doing:
select substring_index(group_concat(col1 order by char_length(col1), col1), ',', 1
) as mincol1,
substring_index(group_concat(col1 order by char_length(col1) desc, col1 desc), ',', 1
) as maxcol1
from t;
If you have zeros in front of the numbers and or decimal places, the ideas are the same, but the coding is a bit more complicated.
A: I don't have a MySQL instance to test on, but it looks like a workaround may solve your problem. I don't know that the issue here is the numbers are too large for conversion, but if they can't be integers in the database, why should it be possible to convert them to integers outside the database?
Try something like this:
"SELECT end_timestamp FROM ".$db_table_prefix."user_events ORDER BY CHAR_LENGTH(end_timestamp) DESC, end_timestamp DESC LIMIT 1"
That will sort by the number of characters first, which is where string sorts on numbers fall apart (as long as you don't have any leading zeros), followed by a numerical sort on numbers which are the same length. If that still doesn't work you may need to `SELECT CHAR_LENGTH(end_timestamp) AS ts_len' to calculate the value outside of the sort command. That is where I really don't know which will work because I don't have a MySQL instance available to test on.
You also may want to consider a data type more suited to timestamps, like TIMESTAMP or DATETIME, which could likely be converted to the format you need once they're outside the database. | unknown | |
d1095 | train | It sounds like you need something similar to an answer I have provided before to perform simple client certificate authentication. Here is the code for convenience modified slightly for your question:
import httplib
import urllib2
PEM_FILE = '/path/certif.pem' # Renamed from PEM_FILE to avoid confusion
CLIENT_CERT_FILE = '/path/clientcert.p12' # This is your client cert!
# HTTPS Client Auth solution for urllib2, inspired by
# http://bugs.python.org/issue3466
# and improved by David Norton of Three Pillar Software. In this
# implementation, we use properties passed in rather than static module
# fields.
class HTTPSClientAuthHandler(urllib2.HTTPSHandler):
def __init__(self, key, cert):
urllib2.HTTPSHandler.__init__(self)
self.key = key
self.cert = cert
def https_open(self, req):
#Rather than pass in a reference to a connection class, we pass in
# a reference to a function which, for all intents and purposes,
# will behave as a constructor
return self.do_open(self.getConnection, req)
def getConnection(self, host):
return httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert)
cert_handler = HTTPSClientAuthHandler(PEM_FILE, CLIENT_CERT_FILE)
opener = urllib2.build_opener(cert_handler)
urllib2.install_opener(opener)
f = urllib2.urlopen("https://10.10.10.10")
print f.code
A: See http://docs.python.org/library/httplib.html
httplib.HTTPSConnection does not do any verification of the server’s certificate.
The option to include your private certificate is when the server is doing certificate based authentication of clients. I.e. the server is checking the client has a certificate signed by a CA that it trusts and is allowed to access it's resources.
If you don't specify the cert optional argument, you should be able to connect to the HTTPS server, but not validate the server certificate.
Update
Following your comment that you've tried basic auth, it looks like the server still wants you to authenticate using basic auth. Either your credentials are invalid (have you independently verified them?) or your Authenticate header isn't formatted correctly. Modifying your example code to include a basic auth header and an empty post payload:
import httplib
conn = httplib.HTTPSConnection('10.10.10.10','443')
auth_header = 'Basic %s' % (":".join(["myusername","mypassword"]).encode('Base64').strip('\r\n'))
conn.request("POST", "/","",{'Authorization':auth_header})
response = conn.getresponse()
print response.status, response.reason
conn.close()
A: What you're doing is trying to connect to a Web service that requires authentication based on client certificate.
Are you sure you have a PEM file and not a PKCS#12 file? A PEM file looks like this (yes, I know I included a private key...this is just a dummy that I generated for this example):
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDDOKpQZexZtGMqb7F1OMwdcFpcQ/pqtCoOVCGIAUxT3uP0hOw8
CZNjLT2LoG4Tdl7Cl6t66SNzMVyUeFUrk5rkfnCJ+W9RIPkht3mv5A8yespeH27x
FjGVbyQ/3DvDOp9Hc2AOPbYDUMRmVa1amawxwqAFPBp9UZ3/vfU8nxwExwIDAQAB
AoGBAMCvt3svfr9zysViBTf8XYtZD/ctqYeUWEZYR9hj36CQyVLZuAnyMaWcS7j7
GmrfVNygs0LXxoO2Xvi0ZOxj/mZ6EcZd8n37LxTo0GcWvAE4JjPr7I4MR2OvGYa/
1696e82xwEnUdpyBv9z3ebleowQ1UWP88iq40oZYukUeignRAkEA9c7MABi5OJUq
hf9gwm/IBie63wHQbB2wVgB3UuCYEa4Zd5zcvJIKz7NfhsZKKcZJ6CBVxwUd84aQ
Aue2DRwYQwJBAMtQ5yBA8howP2FDqcl9sovYR0jw7Etb9mwsRNzJwQRYYnqCC5yS
nOaNn8uHKzBcjvkNiSOEZFGKhKtSrlc9qy0CQQDfNMzMHac7uUAm85JynTyeUj9/
t88CDieMwNmZuXZ9P4HCuv86gMcueex5nt/DdVqxXYNmuL/M3lkxOiV3XBavAkAA
xow7KURDKU/0lQd+x0X5FpgfBRxBpVYpT3nrxbFAzP2DLh/RNxX2IzAq3JcjlhbN
iGmvgv/G99pNtQEJQCj5AkAJcOvGM8+Qhg2xM0yXK0M79gxgPh2KEjppwhUmKEv9
o9agBLWNU3EH9a6oOfsZZcapvUbWIw+OCx5MlxSFDamg
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIIDfjCCAuegAwIBAgIJAOYJ/e6lsjrUMA0GCSqGSIb3DQEBBQUAMIGHMQswCQYD
VQQGEwJVUzELMAkGA1UECBMCRkwxDjAMBgNVBAcTBVRhbXBhMRQwEgYDVQQKEwtG
b29iYXIgSW5jLjEQMA4GA1UECxMHTnV0IEh1dDEXMBUGA1UEAxMOd3d3LmZvb2Jh
ci5jb20xGjAYBgkqhkiG9w0BCQEWC2Zvb0BiYXIuY29tMB4XDTExMDUwNTE0MDk0
N1oXDTEyMDUwNDE0MDk0N1owgYcxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJGTDEO
MAwGA1UEBxMFVGFtcGExFDASBgNVBAoTC0Zvb2JhciBJbmMuMRAwDgYDVQQLEwdO
dXQgSHV0MRcwFQYDVQQDEw53d3cuZm9vYmFyLmNvbTEaMBgGCSqGSIb3DQEJARYL
Zm9vQGJhci5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMM4qlBl7Fm0
YypvsXU4zB1wWlxD+mq0Kg5UIYgBTFPe4/SE7DwJk2MtPYugbhN2XsKXq3rpI3Mx
XJR4VSuTmuR+cIn5b1Eg+SG3ea/kDzJ6yl4fbvEWMZVvJD/cO8M6n0dzYA49tgNQ
xGZVrVqZrDHCoAU8Gn1Rnf+99TyfHATHAgMBAAGjge8wgewwHQYDVR0OBBYEFHZ+
CPLqn8jlT9Fmq7wy/kDSN8STMIG8BgNVHSMEgbQwgbGAFHZ+CPLqn8jlT9Fmq7wy
/kDSN8SToYGNpIGKMIGHMQswCQYDVQQGEwJVUzELMAkGA1UECBMCRkwxDjAMBgNV
BAcTBVRhbXBhMRQwEgYDVQQKEwtGb29iYXIgSW5jLjEQMA4GA1UECxMHTnV0IEh1
dDEXMBUGA1UEAxMOd3d3LmZvb2Jhci5jb20xGjAYBgkqhkiG9w0BCQEWC2Zvb0Bi
YXIuY29tggkA5gn97qWyOtQwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOB
gQAv13ewjgrIsm3Yo8tyqTUHCr/lLekWcucClaDgcHlCAH+WU8+fGY8cyLrFFRdk
4U5sD+P313Adg4VDyoocTO6enA9Vf1Ar5XMZ3l6k5yARjZNIbGO50IZfC/iblIZD
UpR2T7J/ggfq830ACfpOQF/+7K+LgFLekJ5dIRuD1KKyFg==
-----END CERTIFICATE-----
Read this question. | unknown | |
d1096 | train | The best way to handle this case is to create a sparse matrix using scipy.sparse.diags as follows:
a = numpy.float32(numpy.random.rand(10))
a = sparse.diags(a)
If the shape of your diagonal numpy array is n*n, utilizing sparse.diags would result in a matrix n times smaller. Almost all matrix operations are supported for sparse matrices. | unknown | |
d1097 | train | Although it seems not to be mentioned in the documentation, I also experienced that classes annotated with @Test must have a void return type. If you need data provided by some other method, you could try the Data Provider mechanism of TestNG. | unknown | |
d1098 | train | You have to escape the |, as that has a special meaning in Windows:
echo user Servername^|domain/username> ftp.txt
The above will get you
user Servername|domain/username
in the ftp.exe. | unknown | |
d1099 | train | It appears you are looking in the wrong place for the resource. You are looking in the XAML of the metro window however you should be looking in the main window XAML specify to the program where to look using something like this: (I am not currently on visual studio)
private void MetroWindow_StateChanged(object sender, EventArgs e)
{
if (WindowState == WindowState.Minimized)
{
tb = (TaskbarIcon)this.FindResource("TestNotifyIcon");
}
}
or
private void MetroWindow_StateChanged(object sender, EventArgs e)
{
if (WindowState == WindowState.Minimized)
{
tb = (TaskbarIcon)MainWindow.FindResource("TestNotifyIcon");
}
} | unknown | |
d1100 | train | To answer my own question: for some strange reason webhook calls from remote API have 13 digits long timestamps and that's why my dates were so wrong. | unknown |
Subsets and Splits