query_id stringlengths 4 64 | query_authorID stringlengths 6 40 | query_text stringlengths 66 72.1k | candidate_id stringlengths 5 64 | candidate_authorID stringlengths 6 40 | candidate_text stringlengths 9 101k |
|---|---|---|---|---|---|
1dc45f25d2fdd94f558e36771905c9d1ac2b383398d625882fb5e3adf32d0820 | ['39c8d292c3c449728e1d943752920c5a'] | UPDATE: Thanks to <PERSON>'s help I was able to do more research on the textinput() method and found the Python documents page for the method itself, here is the link for anyone who might need it in the future:
[1]: https://docs.python.org/3.1/library/turtle.html#turtle.textinput
| 36a4a82206f58d72ea5fcc378dfd515d02e414a07c74eb921a7add37a24cc34a | ['39c8d292c3c449728e1d943752920c5a'] | I have worked on many projects (school projects, I'm not too advanced), and have found that in many programs where I require the user to input a value that is an integer, or decimal(float), I need to use a "try-except" statement, within a while loop, in order to make certain that the user inputs the required value type.
For example:
def main():
userValue = input("Please enter an integer: ")
while(True):
try:
userValue = int(userValue)
break
except:
userValue = input("That is not an integer, try again: ")
print("The integer you entered is: " + str(userValue))
main()
# Input: SADASD (A non-integer value)
# Output: "That is not an integer, try again: "
# Second-Input: 3
# Second-Output: "The integer you entered is: 3"
Understandably, typing out this entire section of code repeatedly, in a program that requires user input multiple times, is not really efficient. So understanding, that user-defined functions help when I need to perform one action, multiple times. With this in mind, I defined my own function with that same try-except statement in a while loop. However, now, when I use the function, instead of printing the same output previously, rather, it prints out the first value the user had input.
For example:
def valueCheck_Integer(userInput):
while(True):
try:
userInput= int(userInput)
break
except:
userInput = input("That is not an integer, try again: ")
def main():
userValue = input("Please enter an integer: ")
valueCheck_Integer(userValue)
print("The integer you entered is: " + str(userValue))
main()
# Input: SADASD (A non-integer value)
# Output: "That is not an integer, try again: "
# Second-Input: SASASD
# Second-Output: "That is not an integer, try again: "
# Third-Input: 3
# Third-Output: SADASD (The first value that the user Input, instead of 3)
Can someone please explain to me why this happens, and some suggestions on how to fix it?
Thank you!
|
39aa01c1d1671847f4776b9081481adaa53fb6ea7e7ad04f3e632d69c6c04e7e | ['39cc9ba1ec2b421c95fe4f4dd6d6e557'] | In order to find the blocks of missing data inside a Series you can do something along the lines of Finding consecutive segments in a pandas data frame:
s = pd.Series([1, 2, np.nan, np.nan, 5, 6, np.nan, np.nan, np.nan, 10])
x = s.isnull().reset_index(name='null')
# computes unique numbers for each block of consecutive nan/non-nan values
x['block'] = (x['null'].shift(1) != x['null']).astype(int).cumsum()
# select those blocks that relate to null values
x[x['null']].groupby('block')['index'].apply(np.array)
This will result in the following series where the values are arrays of all index-entries containing nan values for each block:
block
2 [2, 3]
4 [6, 7, 8]
Name: index, dtype: object
You can iterate over these and apply custom fixing logic. Getting values before and after should be easy then.
| 7e3bded2955321724f5330ec4d2f15975ca7aca9192a48ae8f2a17b50c5370bd | ['39cc9ba1ec2b421c95fe4f4dd6d6e557'] | itertools.combinations will help you:
import itertools
pd.DataFrame({'{}{}'.format(a, b): df[a] - df[b] for a, b in itertools.combinations(df.columns, 2)})
Which results in:
AB AC AD BC BD CD
Dt
11-apr 0 0 0 0 0 0
10-apr -1 1 0 2 1 -1
|
793be3c55a6e121ed7b356dc5b609c480c86c15148e56a048054259da3ed1dc8 | ['39d9b89e02204afabbcc27f4e722352d'] | I am trying to use workmanager: ^0.2.0 plugin for the background process inside the flutter project. While running the application in iOS, it throws an error as below, But in Android plugin is working seamlessly
MissingPluginException(No implementation found for method initialize on channel be.tramckrijte.workmanager/foreground_channel_work_manager)
#0 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:319:7)
<asynchronous suspension>
#1 Workmanager.initialize (package:workmanager/src/workmanager.dart:100:30)
#2 main (package:worksample/main.dart:29:15)
I manually registered the Workmanager plugin inside the AppDelegate.swift code, still it doesn’t autogenerating plugin registration code inside GeneratedPluginRegistrant.m class file.
Below are my code snippets,
import UIKit
import Flutter
import workmanager
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
UIApplication.shared.setMinimumBackgroundFetchInterval(TimeInterval(60*15))
UNUserNotificationCenter.current().delegate = self
WorkmanagerPlugin.setPluginRegistrantCallback { registry in
AppDelegate.registerPlugins(with: registry)
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
static func registerPlugins(with registry: FlutterPluginRegistry) {
GeneratedPluginRegistrant.register(with: registry)
}
override func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.alert)
}
}
WorkManager plugin is missed in the below generated file
//
// Generated file. Do not edit.
//
#import "GeneratedPluginRegistrant.h"
#if __has_include(<flutter_native_timezone/FlutterNativeTimezonePlugin.h>)
#import <flutter_native_timezone/FlutterNativeTimezonePlugin.h>
#else
@import flutter_native_timezone;
#endif
#if __has_include(<shared_preferences/FLTSharedPreferencesPlugin.h>)
#import <shared_preferences/FLTSharedPreferencesPlugin.h>
#else
@import shared_preferences;
#endif
@implementation GeneratedPluginRegistrant
+ (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry {
[FlutterNativeTimezonePlugin registerWithRegistrar:[registry registrarForPlugin:@"FlutterNativeTimezonePlugin"]];
[FLTSharedPreferencesPlugin registerWithRegistrar:[registry registrarForPlugin:@"FLTSharedPreferencesPlugin"]];
}
@end
How can I resolve this issue?
| 32757e1e2b0701ddfcd730986b4d26f65c9afc3dec968844ed84dd67a1431f2f | ['39d9b89e02204afabbcc27f4e722352d'] | I am trying to integrate the Background fetch feature inside a Flutter project using Workmanager plugin. So I enabled the background fetch feature under 'Background Modes' of my iOS project Capability.
But the following block is not added to project.pbxproj file. As I understood, it should be automatically added by XCode.
SystemCapabilities = {
com.apple.BackgroundModes = {
enabled = 1;
};
};
Currently, I am working with Xcode 11.3.1 and Swift 5.0. So how do I bring the above snippet in project.pbxproj file?. Or please help me if my understanding is wrong.
|
9aa7d40bb2389d5cf68a3568ce51859d8a2829d81a236db8fc60a4849f565137 | ['39dea284363a45519700526a6a6d258d'] | This is such a basic thing, but I need pointers on how to set up the field widths so that the table prints out nice and neatly for all values allowed. I have been playing around with it for a while and am having troubles. Is there maybe some trick to quickly figure it out? Just a push in the right direction would be appreciated.
//Print the results in a table
printf("\n#============================================#\n");
printf("| Description | Input Data |\n");
printf("|============================================|\n");
printf("| Loan amount | $ %8.2f |\n", loan);
printf("| Yearly interest rate | %6.2f% |\n", rate);
printf("| Number of years | %d |\n", years);
printf("|============================================|\n");
printf("| Payment Details | Results |\n");
printf("|============================================|\n");
printf("| The monthly payment will be | $ %5.2f |\n", monthlyPayment);
printf("| Interest paid | $ %6.2f |\n", interestEarned);
printf("#============================================#\n\n");
| 88e29ca0da7cffdda4db72d3863d8b91f86596d4929be5fa3b6eb4d26aa4974c | ['39dea284363a45519700526a6a6d258d'] | Trying to get the program to exit if any of the three if statements are true, but only after all three have been processed. I have formatted this a number of ways but I can only get it to exit after each statement, not after all three. So basically it will continue on with the rest of the functions even if two of the if statements are true.
int getValues(float* loan, float* rate, int* years)
{
//Prompt the user for the loan amount, the yearly interest rate, and the loan length in years, then make sure each value is large enough
printf("Enter a loan amount (dollars and cents): ");
scanf("%f", loan);
printf("Enter a yearly interest rate (ex. 2.5 for 2.5%): ");
scanf("%f", rate);
printf("Enter the loan length in years (integer number): ");
scanf("%d", years);
if (*loan < 1)
printf("\nStarting amount must be at least one dollar.\n");
if (*rate < .1)
printf("Interest rate must be at least .1%.\n");
if (*years < 1)
{ printf("Number of years must be at least 1.\n");
exit (100);
}
return(0);
}
This is just the most recent attempt. I am extremely new to programming and am spending countless hours on this one little program.
|
a1fac958b4f5a1d53673aba76e56e213f7db30ac29f31a8bafb81f431b0d020a | ['39e21ac672964fc9a7e0973e5aa34b08'] | I want to create a dropdown(not a spinner) using gingerbread.
I thought of using a dialog box without buttons.But since its a list i dont think that would be possible. Moreover each item should be clickable.
It should be more like dropdowns in websites.
To get the dialog box i have used.Basically i am moving the position of the dialog box from the center to any specified position. How do i get a list in this dialog box?
| fc77b7c1ab8352516831c573fb0dc39fd4fa106d510439daee4d92bd7119c5cd | ['39e21ac672964fc9a7e0973e5aa34b08'] | I can open google maps from my application and have a pointer over the location i am pointing to.
Instead i wanted to open google maps application from my application---- as is when user clicks on an address google maps application opens up with that particular point.
for that i used
startActivity(new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:lat,lng?q=lat,lng")));
Here lat=34.456373 and lng=-45.464748
Google maps application is opening but that particular location is not coming up instead my present location is coming up.How to rectify that?
|
1f54e17cb0731ae8fd46c9b4df2e84330aaca5a44dc6e63c07a5de151475463d | ['39e5d8687fec47eeae907ec592b31878'] | I don't blame you at all for your confusion. It seems that he's attempting to scientifically demonstrate or argue something on the basis of electromagnetism, but his assertion is rather unprofessional; I've read many scientific research papers, and not once have I encountered one that appeared so paranoid about people accusing the author of "trickery"! The video's descriptions and comments don't really elaborate on his point either, unfortunately.
Anyways, onto the actual argument he's making...assuming he is actually making one..? It's pretty well-known and understood why magnets have that sort of effect on older TV screens. Old television monitors worked because of cathode ray tubes, which created the picture we see on a TV screen using beams of electrons (in the video, this guy explicitly mentions that he's using an older TV). The presence of a magnet nearby will interfere with the electron's movements. If you grew up being warned not to put magnets close to the TV, this is generally the reason why.
So yeah, I'm not quite sure what he's claiming to have proven here. The only thing he says is that this is a demonstration of some sort of "magnetic vortex", but I believe he's misusing the word. A quick Wikipedia search reveals that the word "vortex" in physics primarily refers to a phenomenon in fluid mechanics, completely irrelevant to what <PERSON> (TA) is talking about. It would help if <PERSON> defined "vortex" in his video, or explained what he means specifically when he uses the word, but because he doesn't, his video ends up feeling rather incomplete.
I think he's falling into the common misunderstanding that "vortex" can be used to refer to just any old shape that happens to resemble a "swirl" pattern, but once again, the imagery in the video is not a new discovery.
It might be worth looking into his older videos (to see if more info is buried in his uploads), or simply ask him for a technical explanation of what he's talking about. ...Considering his apparent attitude (and his clear resistance to criticism, evident on his more popular uploads), I'm not sure how well that will go, but I digress.
| 683c49c767166bb7293098b8d6e44b3bb3ca32660c949a7167ee6d15d9459b19 | ['39e5d8687fec47eeae907ec592b31878'] | I have a very large data set (~300'000 data points) and a subset of it (6000 data points), which shows the difference of travel time [in seconds] of agents before and after a road closure. I want to show the difference in their distribution.
However, the data set is so large, that the outliers are still so many and nothing can be read from the boxplot. A simple table would be an option of course, but I believe if done right, a graph can be more helpful to see the difference.
Really interesting, for the analysis, is the difference between -1000 and 1000. So I wonder, is it ok to simply truncate the data set or is it more appropriate to transform the data?
|
515230905285d256473bd92d134a3311b8c3bbcf666b2280fbe29b55ad046411 | ['39ea5148eebf42019eb9c6ceb16f6e68'] | <PERSON>, I was wondering if I have a circle C and radius r and centre o = (1,1), how does that change things? I have to find the radius of the circle C' (in terms of r) which is the image of C after inversion in the unit circle about the origin. | 6ea70483dcd61202a58a306f858ae6e78b5c1c877923b290ca5a6a65635ea4d9 | ['39ea5148eebf42019eb9c6ceb16f6e68'] | Write down in the form ${Z}\rightarrow{AZ+B}$ the following transformations of the complex plane:
(a) translation in the direction $(2,-3)$
(b) rotation about (0,1) through $\pi/4$
I know from my student answer key that the answer for
part (b) is ${Z}\rightarrow{AZ-iA+i}$
where $A=\frac{(1+i)}{\sqrt2}$
can someone explain the steps for part (b)? Part (a) is straightforward.
|
bd3c0480636d6949edce78df50c723756d83e303ad6cb4f92cec18e176a80a29 | ['39f24012139c48b38634cbc5ca1cf800'] | This happens because your data structure is an array of objects, and each one of those contains a field called date. To check if a specific date is in that specific array, you should do:
<?php
$sql = "SELECT date FROM wp_table";
$result = $wpdb->get_results($sql);
foreach ($result as $res)
if ($res->date == '2019-01-02') {
echo "Yes, the date is in the array!";
break;
}
print_r($result);
?>
| c323f0b0a388ed38f41f156a7ca29c042a53b0f781a8fc40687f4541511d356d | ['39f24012139c48b38634cbc5ca1cf800'] | I have a PHP project where I manage data structures (in a $data variable) defined like this:
array:35 [▼
"2020-03-16" => array:12 [▼
"00:00:00" => 17.185
"02:00:00" => 17.235
"04:00:00" => 17.25
"06:00:00" => <PHONE_NUMBER>
"08:00:00" => 21.205
"10:00:00" => 23.47
"12:00:00" => 24.42
"14:00:00" => 27.245
"16:00:00" => 30.94
"18:00:00" => 30.78
"20:00:00" => 29.735
"22:00:00" => 28.64
]
"2020-03-17" => array:12 [▼
"00:00:00" => 29.985
"02:00:00" => 32.455
"04:00:00" => 31.28
"06:00:00" => 34.33
"08:00:00" => 29.755
"10:00:00" => 26.92
"12:00:00" => 29.72
"14:00:00" => 28.36
"16:00:00" => 30.815
"18:00:00" => 34.605
"20:00:00" => 34.315
"22:00:00" => 33.125
]
"2020-03-18" => array:12 [▶]
...
]
They come from an external service so I can't modify them in origin.
I need to "rewrite" $data so that I finally have something like:
array:420 [▼
"2020-03-16 00:00:00" => 17.185
"2020-03-16 02:00:00" => 17.235
"2020-03-16 04:00:00" => 17.25
...
"2020-03-20 00:00:00" => 22.675
"2020-03-20 02:00:00" => 24.67
...
]
Could you please tell me a smart way of doing that?
Many thanks in advance.
|
0a233716d3876ca0bd1572b94ed739f822956dd72854c9a08e9aafe6bfb32721 | ['39f36eb1bd9a4fbb916e1ce5562354b9'] | Suppose there is a population of trees, and in each period, each tree faces a probability $p$ of getting cut down.
If a tree is cut down, its height is reset to zero (it doesn't die, this is merely a setback for it); if a tree is not cut down, then its height increases by $1$ unit.
Namely, if $h_{t}$ is the height of some tree, then
$$
h_{t+1} = \begin{cases}
h_{t}+1 & \textrm{with probability } 1-p; \\
0 & \textrm{with probability } p.
\end{cases}
$$
What I am looking for is the stationary probability distribution $f(h)$ (for the forest as a whole); I initially thought this would be some trivial extension of the geometric/exponential distribution (ideally I would find a result for continuous time), maybe using convolution? but now I am less sure.
I found this question, but it doesn't seem to be quite what I'm looking for.
I've also started reading <PERSON> An Introduction to Probability Theory and Its Applications, so perhaps that will help.
Any suggestions/leads would be appreciated; part of the difficulty has just been figuring out the relevant terms to search for…
| 8e3b92d515f64a6a68ef3ebad4abe856e55ed9175a4d4b4130ecd3869882e40f | ['39f36eb1bd9a4fbb916e1ce5562354b9'] | When considering the probability of 1 head, you have to consider the three different ways it could happen (HTT, THT, TTH), and so you have 3 times (0.6*0.4*0.4). You may want to look up the Binomial distribution for some intuition on why what you describe doesn't make sense, but consider what your logic implies about zero heads: P(0)=0.6^0=1 ? |
25ea795ed695fd3000f4c3c71ab60e21784c1824fda1f9f75a6d398011ec4be3 | ['3a067e2afc054c91a7139a3e957d13d1'] | The word dilemma has caused a dilemma.
According to Oxford Dictionary (http://www.oxforddictionaries.com/definition/english/dilemma)
Pronunciation is : /dɪˈlɛmə, dʌɪ-/
Which is di-lema or dye-lema.
The website "howjsay" (http://www.howjsay.com/index.php?word=dilemma) also gives two pronunciations.
I just don't understand why it has two pronunciations. Also, is one UK and the other US? I am unclear as to which pronunciation I should stick to. Does it vary according to its position in the sentence? Or should I randomly shoot the one the pops up in mind?
Any assistance would be highly appreciated.
| a52dc7e8f49c63d5a8d696b726fbf94be2051ec755fa4c459283e498b9e925e2 | ['3a067e2afc054c91a7139a3e957d13d1'] | I am trying to add a product with an image via the WooCommerce REST API but getting this error:
Fatal error: Uncaught
Automattic\WooCommerce\HttpClient\HttpClientException: Error: #0 is an
invalid image ID.
Despite many other threads similar, no one seems to have an actual answer to why this happens despite the same code in the example of the docs. The image I am trying to use is not already in the media library.
The code:
$woocommerce = new Client(
'https://www.example.co.uk',
'123456789',
'123456789',
[
'wp_api' => true,
'version' => 'wc/v3',
'sslverify' => false,
]
);
$data = array();
foreach ( $records->getRecords() as $record ) {
$data = [
'name' => $record['TITLE'],
'description' => $record['DESCRIPTION'],
'regular_price' => $record['PRICE'],
'quantity' => $record['QUANTITY'],
'images' => [
'src' => 'https://via.placeholder.com/350x150.png',
],
];
$woocommerce->post( 'products', $data );
}
I see nothing wrong. It’s setup in the same way as the example too:
https://woocommerce.github.io/woocommerce-rest-api-docs/?php#create-a-product
|
0ece0d59db8c8a7e9248fccfcda64b949177eb908f029d0fe91e5703f0d1fba3 | ['3a071d4072594ceaa8b2d83674c2a81f'] | i was wondering what is wrong with this code?
<style type="text/css">
.recipe h2{
float:left;
}
.recipe .intro,
.recipe ol{
float:right;
width:500px;
}
</style>
</head>
<body>
<h1>Recipes for Cheese</h1>
<p class="intro">Cheese is a remarkably versatile food, available in literally hundreds of varieties with different flavores and textures.</p>
<div class="recipe">
<h2>Welsh Rarebit</h2>
<p class="intro">Welsh Rarebit is a savory dish made from melted cheese, often Cheddar, on toasted bread, and a variety of other ingredients such as mustard, egg or bacon. Here is one take on this classic.</p>
<ol>
<li>Lightly toast the bread</li>
<li>Place a baking tray, and spread with butter.</li>
<li>Add the grated Cheddar cheese and 2 tablespoons of beer to a saucepan. Place the saucepan over a medium heat, and stir the cheese continuously until it has melted. Add a teaspoon of wholegrain mustard and grind in a little pepper. Keep stirring.</li>
<li>When thick and smooth, pour over each piece of toast spreading it to the edges to stop the toast from burning.</li>
<li>Place undre the grill for a couple of minutes or until golden brown.</li>
</ol>
</div>
</body>
</html>
Originally, the solution of this code should be just like the picture in the book here:
https://picasaweb.google.com/lh/photo/fDg4GiRbz3mCZvh2krcsqdMTjNZETYmyPJy0liipFm0?feat=directlink
This code above give me this:
https://picasaweb.google.com/lh/photo/kaH-7AE5K-UKMcxxlJdkrtMTjNZETYmyPJy0liipFm0?feat=directlink
I have read over and over afew times now and could not find anything wrong with this but have no idea why it does this.
Could anyone explain why it does this and how to correct it please?
Thanks so much in advance!
| a047e1cd4dd87c846572d671d1178b2a866abefdf8fa7f8e8b1ee6f8b62353ae | ['3a071d4072594ceaa8b2d83674c2a81f'] | i want to apply for this job as description below:
This employer is looking for a competent and experienced student to create a website. You will be required to update web site content through a content management system online. Initially the employer needs an online store product upload and monthly newsletter/VIP voucher content design. You will need to have HTML skills, experience with content management Back End editing and design ability. Once the website is up and running you will be required for ongoing maintenance.
Experience needed: HTML and Webdesign.
Since i'm a second year in uni majoring in IT. I wasn't sure if i'm up to this job so i kinda need you guys opinion or if any of you guys have experience this kinda job before, might give me some hints.
I've learned some programming languages such as HTML, CSS and alittle bit of JavaScript and the experience needed for this job is HTML and webdesign. I'm not sure about creating Newsletters/VIP vouchers and Content Management BACK END editing.
Please advice me what i should do since i've got only that much experiences.
Can i do this job?
Thanks in advance!
|
0354b3aa6ac8cb8ce1245ebd5c1f76356e3d320e31dfe25b1c5d9d5b43987c1b | ['3a09aab29c3e471b9b24913817d2347a'] | Estoy tratandod e consumir un API a traves de Jquery, al momento he logrado conectarme sin problema e incluso obtengo la respuesta del API el cual tiene el siguiente formato:
{
"status": "OK",
"status_codes": [
200
],
"status_messages": [
{
"request": "Request processed."
}
],
"data": {
"package": {
"contentValue": 120.01,
"weight": 1.01,
"length": 30.01,
"height": 15.01
},
"insurance": {
"contentValue": 120.01,
"amountInsurance": 2.09
},
"originZipCode": "44100",
"destinationZipCode": "44510",
"rates": [
{
"idRates": 999999,
"idProduct": 11,
"product": "Dos días",
"vehicle": "bike",
"idCarrier": 6,
"carrier": "ESTAFETA",
"total": 203.15,
"deliveryType": "Ocurre",
"deliveryDays": 1
}
],
"idCarriersNoWsResult": "44510"
}
}
Esta información la puedo ver en la consola mediante console.log, pero no he podido plasmarla en un div, el código que uso es:
$.ajax({
headers: {'Authorization':'Mi Clave de Usuario o API KEY', 'Content-Type':'application/json'},
url: 'https://api.envioclickpro.com/api/v1/quotation',
type: 'POST',
dataType: 'json',
data: packInfo,
success: function(respuesta){
console.log(respuesta);
}
})
Como puedo almacenar ese JSON en un array ya sea de php o JS para poder acceder a su información?
| f1f07c28a4b4b4780319b9dd6bd0070b27c9518f8d4105ec9e18da926e5313d5 | ['3a09aab29c3e471b9b24913817d2347a'] | creo que no hay mucha actividad por aquí. Estuve buscando un poco mas de información sobre el uso del API de Instagram y encontré un código que me funcionó muy bien y es:
$client_id = '# de Cliente';
$client_secret ='# de Cliente SECRETO';
$redirect_uri = 'URI Autorizada';
$code ='Código generado al iniciar sesión';
$url = "https://api.instagram.com/oauth/access_token";
$access_token_parameters = array(
'client_id' => $client_id,
'client_secret' => $client_secret,
'grant_type' => 'authorization_code',
'redirect_uri' => $redirect_uri,
'code' => $code
);
$curl = curl_init($url); // we init curl by passing the url
curl_setopt($curl,CURLOPT_POST,true); // to send a POST request
curl_setopt($curl,CURLOPT_POSTFIELDS,$access_token_parameters); // indicate the data to send
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // to stop cURL from verifying the peer's certificate.
$result = curl_exec($curl); // to perform the curl session
curl_close($curl); // to close the curl session
var_dump($result);
Esto me devuelve en pantalla todos los parámetros del API de Instagram como lo son el acceso token, usuario y la información básica que proporciona el API en su uso mas sencillo.
|
4b61a5c4e2831ee6486115f70afb55db0824af8c894f64436372c30ac9dac5c6 | ['3a0a42a7936745328668aca640283789'] | I have a code;
x = np.linspace(0, 12, 200, False, True, None)
when I print x, I get;
(array([ 0. , 0.06, 0.12, 0.18, 0.24, 0.3 , 0.36, 0.42, 0.48,
0.54, 0.6 , 0.66, 0.72, 0.78, 0.84, 0.9 , 0.96, 1.02,
1.08, 1.14, 1.2 , 1.26, 1.32, 1.38, 1.44, 1.5 , 1.56,
1.62, 1.68, 1.74, 1.8 , 1.86, 1.92, 1.98, 2.04, 2.1 ,
2.16, 2.22, 2.28, 2.34, 2.4 , 2.46, 2.52, 2.58, 2.64,
2.7 , 2.76, 2.82, 2.88, 2.94, 3. , 3.06, 3.12, 3.18,
3.24, 3.3 , 3.36, 3.42, 3.48, 3.54, 3.6 , 3.66, 3.72,
3.78, 3.84, 3.9 , 3.96, 4.02, 4.08, 4.14, 4.2 , 4.26,
4.32, 4.38, 4.44, 4.5 , 4.56, 4.62, 4.68, 4.74, 4.8 ,
4.86, 4.92, 4.98, 5.04, 5.1 , 5.16, 5.22, 5.28, 5.34,
5.4 , 5.46, 5.52, 5.58, 5.64, 5.7 , 5.76, 5.82, 5.88,
5.94, 6. , 6.06, 6.12, 6.18, 6.24, 6.3 , 6.36, 6.42,
6.48, 6.54, 6.6 , 6.66, 6.72, 6.78, 6.84, 6.9 , 6.96,
7.02, 7.08, 7.14, 7.2 , 7.26, 7.32, 7.38, 7.44, 7.5 ,
7.56, 7.62, 7.68, 7.74, 7.8 , 7.86, 7.92, 7.98, 8.04,
8.1 , 8.16, 8.22, 8.28, 8.34, 8.4 , 8.46, 8.52, 8.58,
8.64, 8.7 , 8.76, 8.82, 8.88, 8.94, 9. , 9.06, 9.12,
9.18, 9.24, 9.3 , 9.36, 9.42, 9.48, 9.54, 9.6 , 9.66,
9.72, 9.78, 9.84, 9.9 , 9.96, 10.02, 10.08, 10.14, 10.2 ,
10.26, 10.32, 10.38, 10.44, 10.5 , 10.56, 10.62, 10.68, 10.74,
10.8 , 10.86, 10.92, 10.98, 11.04, 11.1 , 11.16, 11.22, 11.28,
11.34, 11.4 , 11.46, 11.52, 11.58, 11.64, 11.7 , 11.76, 11.82,
11.88, 11.94]), 0.06)
I want to find how many variables are returned.
To do this I've tried
print (len(x))
which I get 2.
This can't be correct, can it? Are there only two variables as one are the False in [] then the True. Or have I made a mistake somewhere If so what do I need to do to get the number of variables returned.
| 9ea671381d5ec9067c140b16da27f7355acb42a064682c08a3e7a8a53f89df40 | ['3a0a42a7936745328668aca640283789'] | I have a selection of lists of variables
import numpy.random as npr
w = [0.02, 0.03, 0.05, 0.07, 0.11, 0.13, 0.17]
x = 1
y = False
z = [0.12, 0.2, 0.25, 0.05, 0.08, 0.125, 0.175]
v = npr.choice(w, x, y, z)
I want to find the probability of the value V being a selection of variables eg; False or 0.12.
How do I do this.
Heres what I've tried;
import numpy.random as npr
import math
w = [0.02, 0.03, 0.05, 0.07, 0.11, 0.13, 0.17]
x = 1
y = False
z = [0.12, 0.2, 0.25, 0.05, 0.08, 0.125, 0.175]
v = npr.choice(w, x, y, z)
from collections import Counter
c = Counter(0.02, 0.03, 0.05, 0.07, 0.11, 0.13, 0.17,1,False,0.12, 0.2, 0.25, 0.05, 0.08, 0.125, 0.175)
def probability(0.12):
return float(c[v]/len(w,x,y,z))
which I'm getting that 0.12 is an invalid syntax
|
e909cbdddc76a84d7c83fe6bafaca09e66125e7bc1040e251cbb690b77cf5a0b | ['3a113195372d4be595049c3e5d2f9d13'] | Пишу программу, которая весь на весь экран рисует сетку квадратов. В каждом квадрате нарисована цифра "0". Когда пользователь нажимает на какой-либо квадрат, то в этом квадрате вместо "0" отображается "-1". ( Хочу использовать эту программу в дальнейшем для создания алгоритма для поиска пути ). Рисование происходит в отдельном классе унаследованном от Thread. А конкретно, в методе run рисуется сетка из квадратов, и в каждый квадрат должна рисоваться цифра. Что бы понять, какая цифра рисуется в квадрате, вне метода run создаю таблицу ( ячеек столько же сколько квадратов на экране ), в которой по стандарту все ячейки равны "0". Но вне метода run нельзя использовать методы getHight(), getWidth(), и нельзя сделать таблицу. Может кто помочь нубу, какими методами нужно создавать таблицу вне метода run?
public class DrawMap extends Thread {
private SurfaceHolder surfaceHolder;
int CellSize = 50;
int xm, ym;
int xw = CellSize; // Размеры квадрата по X
int yw = CellSize; // Размеры квадрата по Y
int finx, finy;
int[][] map;
float movex = 0;
float movey = 0;
private volatile boolean running = true;//флаг для остановки потока
{
finx = (canvas.getWidth() / xw); // Создание массива который содержит информацию о квадратах
finy = (canvas.getHeight() / yw);
map = new int[finx][finy];
for (int i = 0; i < finx; i++) {
for (int z = 0; z < finy; z++) { // Заполнение массива нулями
map[i][z] = 0;
}
}
}
public DrawMap(Context context, SurfaceHolder surfaceHolder) {
this.surfaceHolder = surfaceHolder;
}
public void requestStop() {
running = false;
}
@Override
public void run() {
while (running) {
Canvas canvas = surfaceHolder.lockCanvas();
if (canvas != null) {
try {
// рисование на canvas
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.STROKE);
if (canvas.getWidth() % xw != 0) {
xw++;
}
if (canvas.getHeight() % yw != 0) {
yw++;
}
while (movex < canvas.getWidth()) {
canvas.drawLine(movex, 0, movex, canvas.getHeight(), paint);
movex += xw;
}
while (movey < canvas.getHeight()) {
canvas.drawLine(0, movey, canvas.getWidth(), movey, paint);
movey += yw;
}
} finally {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}
| 3700c69ecec2bda2de9060c45c4177910234c7d8f789f0c51f16ebd8ef387d7d | ['3a113195372d4be595049c3e5d2f9d13'] | every time I am in Game on steam the sound keep lowering and then every sound disappears
and the sound will only come back when i close the game from steam itself
i have been having this problem in 4 days and i want to know what this problem is
what i discover is when i go to sound and fixes the sounds then it just comes back for a while
and then the sound disappears..i can only see the game but i cant hear voices or sounds
even the backrounds sounds disappears out side of steam
|
ffa0fb152ad16804e59c406f9d6a3c09043da40eb9338e7cf5c7fa357d009a6f | ['3a153b4deaeb42d9921b5d1c153da96d'] | i used .val() function in jquery to post value from textbox. when i alert i can see whole string .but when putting on a textbox only data before space is coming.anybody know this issue,please help
am sharing my code here
$('#add_input').click(function(){
var item = $('input[id="itemname"]').val();
i++;
$('#dynamic1').append('<tr id="row'+i+'">\n\
<><td> <input type="text" name="serial_id" id="serial" value='+i+' ></td>\n\
<td><input type="text" name="item1[]" value='+item+'></td></tr>');
in item texbox only getting first part of input value.
| 63618d3918c477952aec488f128e5067779397e8cf501c884345221d61d7135a | ['3a153b4deaeb42d9921b5d1c153da96d'] | i have a function to display pdf on a modal popup when click on a button.
i want to integrate this on another modal popup.
but its not working.
my code to display pdf on a modal pop up on button click
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
var fileName = "AFarm.pdf";
$("#btnShow").click(function () {
$("#dialog").dialog({
modal: true,
title: fileName,
width: 540,
height: 450,
buttons: {
Close: function () {
$(this).dialog('close');
}
},
open: function () {
var object = "<object data=\"http://vho.org/aaargh/fran/livres4/AFarm.pdf\" type=\"application/pdf\" width=\"500px\" height=\"300px\">";
object += "If you are unable to view file, you can download from <a href = \"http://vho.org/aaargh/fran/livres4/AFarm.pdf\">here</a>";
object += " or download <a target = \"_blank\" href = \"AFarm.pdf/\">Adobe PDF Reader</a> to view the file.";
object += "</object>";
object = object.replace(/{FileName}/g, "Files/" + fileName);
$("#dialog").html(object);
}
});
});
});
</script>
<input id="btnShow" type="button" value="Show PDF" />
<div id="dialog" style="display: none">
</div>
And the below function where i want to integrate this
$('#manageApplicantModel').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var applicaitonid = button.data('id');
var modal = $(this);
$.get(getURL('ManageApplication/getApplicationDetailByid/' + applicaitonid), function (data) {
var json = new Object();
json = JSON.parse(data);
modal.find('#name').text(json.name);
modal.find('#email').text(json.email);
modal.find('#phonenum').text(json.phone);
modal.find('#propertyname').text(json.property_name);
modal.find('#applieddate').text(json.date_applied);
modal.find('#address').text(json.property_address);
modal.find('#divrequirementchecks .reqcheckslbl').empty();
$.each(json.check, function (index, value) {
//list-group-item
modal.find('#divrequirementchecks .reqcheckslbl').append(
'<li class="">'
+ value
+ '</li>');
});
modal.find('#divattacheddoc .attacheddoclst').empty();
$.each(json.documents, function (index, value) {
modal.find('#divattacheddoc .attacheddoclst').append(
'<li class="list-group-item">'
+ value.document_name
+ '<a href="' + value.link + '" download class="pull-right">Download</a>'
+'<br>'
+ '<a id="#mypdf" href="#" class="pull-right">View</a>'
+ '</li>');
});
});
}
);
See the view link in this function. on click on this link. i want to show that modal popup with pdf. anybody knows please help me
|
49a36b9c111d3e38deb6779dd195f12185c4d3b553de07b07dfb56473ec02357 | ['3a21fe09b11f4a7f932cfcab3e7e6eae'] | i have a function that give me the text between two words:
Private Shared Function GetBetween(ByRef strSource As String, ByRef strStart As String, ByRef strEnd As String, Optional ByRef startPos As Integer = 0) As String
Dim iPos As Integer, iEnd As Integer, lenStart As Integer = strStart.Length
Dim strResult As String
strResult = String.Empty
iPos = strSource.IndexOf(strStart, startPos)
iEnd = strSource.IndexOf(strEnd, iPos + lenStart)
If iPos <> -1 AndAlso iEnd <> -1 Then
strResult = strSource.Substring(iPos + lenStart, iEnd - (iPos + lenStart))
End If
Return strResult
End Function
So my html code is:
<div class="upper-right-section">
<div class="header-stats">
<div class="stat-entry">
<span class="stat-value">48998</span>
<span class="stat-name">iscritti</span>
</div>
<div class="stat-entry">
<span class="stat-value">22760801</span>
<span class="stat-name">visualizzazioni video</span>
</div>
</div>
<span class="valign-shim"></span>
</div>
I got two times <span class="stat-value"> and i want to get the value of second match, how can i do? thanks, <PERSON>.
| c836e49338991216ade9f0ea5cf38cf3f95d05fd79c22536d5c6bfd548533cd0 | ['3a21fe09b11f4a7f932cfcab3e7e6eae'] | i am currently using this code for the registration:
value1 = registerEmail.getText().toString();
value2 = registerPassword.getText().toString();
value3 = registerName.getText().toString();
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, pass);
Statement st = con.createStatement();
Log.d("Connectc","executing check");
ResultSet res = st.executeQuery("SELECT * FROM user where email='"+value1+"'");
while (res.next()) {
userc = res.getString("email");
}
if (value1.equals(userc)) {
tv.setText("Email already in use!");
}
else{
Log.d("Connectc","registering");
st.executeUpdate("INSERT INTO user (email, password, name) VALUES('"+value1+"', '"+value2+"', '"+value3+"' )");
tv.setText("Data is successfully saved." );
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
finish();
Log.d("Connectl","pfffffffff");
}
Yes, it would be better using json, but i neet to use this... so the code check if the email exist, i also need to check if the username exist, how can i do? I have to add another sql query or i can edit this to check also if the username exist on db?
Thanks.
|
987a27285108b3d1891cac5e41b0e2207fbd3a5f2c8a91d4494eb2ccc0963695 | ['3a2b0d8cdffe484483b5b2bd34d733c4'] | Estou abrindo um arquivo .csv com a biblioteca pandas, porém me é informado no momento de abertura deste arquivo que uma determinada coluna apresenta valores de tipos diferentes. Sei que o caracter "/" foi utilizado neste arquivo para denotar dado ausente, muito provável que seja este o problema. Minha dúvida é, como substituir o caracter "/" por outro valor?
| 1660d31f2aa27fe70df1efc7cefbc9ab116206f3e479ea8d483d5a03e416947c | ['3a2b0d8cdffe484483b5b2bd34d733c4'] | I am a Material Science and Engineering major.What I am having doubt with is how I am supposed to write long answers.Lets say someone asks,"What is a Lomer Cottrell barrier?" or may be,"What is solid solution strengthening?"Actually I write answers to these but those answers never fetch me a more than 50% marks.How do I get through?Please help.
|
132ddd84ddc5367a19a4a93a84c7e869adf5f6cfb379a244ab54b3fe4969820a | ['3a3bf78680f54e399939faa31d264596'] | I solved the problem meanwhile.
The code was something like this:
$ldaphost = "ldaps://XXX";
$ldapport = YY;
$ldaprdn="uid=username,ou=OU1,ou=OU2,ou=OU3,dc=dc1,dc=dc2,dc=dc3,dc=dc4";
$ldappass="password";
// Connecting to LDAP
$ldapconn = ldap_connect($ldaphost, $ldapport)
or die("Could not connect to {$ldaphost}");
if ($ldapconn) {
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);
// verify binding
if ($ldapbind) {
echo "LDAP bind successful...";
} else {
echo "LDAP bind failed...";
}
}
I was not setting the proper organisational units(ous). The usernamewas in other ou. After setting the correct one everything was fine.
| 38c095ef482167c123c6c3a413602126bb5496ab35e8039bc234493fb8777bf9 | ['3a3bf78680f54e399939faa31d264596'] | I'm trying to get the list of all my friends from the Google plus via API. The user on whose behalf I'm doing this operation previously authorized my request and I got the auth token. I've tried the following code in php:
function CallAPI() {
$opts = array(
"http" => array(
"method" => "GET"
)
);
$url = 'https://www.googleapis.com/plus/v1/people/me/people/visible?key=XXXX';
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
var_dump($response);
}
but I keep receiving HTTP request failed! HTTP/1.0 401 Unauthorized. How can I prove that the user authorized my operations or what am I doing wrong?
Any help is much appreciated.
|
07c8fe28983e7bd0753ef90f3b67b337b0d7e8beeac6c13c6a1fb4542a245e18 | ['3a4221bcbe574162a16f3bdebe5661ca'] | I've actually went another way instead of calling the method by its name, I simply make a lambda function to extract whatever attribute I want from the Task object.
class Task:
def __init__(self,id,name,category="",priority=1):
self.id = id
self.name = name
self.category = category
self.priority = priority
self.concluded = False
self.active_days = 0
print("Beggining Class")
def get_name(self):
return self.name
def get_category(self):
return self.category
def get_priority(self):
return self.priority
def set_name(self,name):
self.name = name
def set_category(self,category):
self.category = category
def set_priority(self,priority):
self.priority = priority
def __str__(self):
return str(self.id) + " | " + self.name + " | " + self.category + " | " + str(self.priority) + " | "
class TaskManager(object):
"""docstring forTaskManager."""
def __init__(self):
print("Initing TaskManager")
self.taskArray = []
"""Adding task ordered by priority"""
"""Maibe adding a check for autheticity of the object """
def addTask(self,task):
if len(self.taskArray) == 0 or self.taskArray[0].get_priority() <= task.get_priority():
self.taskArray.insert(0,task)
else:
index = self.__binarySearchIndex(task.get_priority(),self.taskArray, lambda task: task.get_priority())
self.taskArray.insert(index,task)
def __binarySearchIndex(self,value,array,accessMethod):
if len(array) == 0:
return 0
middle = (len(self.taskArray) / 2) if ((len(self.taskArray) % 2) == 0) else (len(self.taskArray) // 2) + 1
if middle == 1:
middle = 0
if value == accessMethod(array[middle]):
return middle
elif value < accessMethod(array[middle]):
return <PERSON> + self.__binarySearchIndex(value,array[:middle],accessMethod)
else:
return middle - self.__binarySearchIndex(value,array[middle:],accessMethod)
def __str__(self):
taskString = ""
for task in self.taskArray:
taskString = taskString + str(task) + " \n"
return taskString
if __name__ == "__main__":
taskA = Task(1, "taskA", priority=2)
taskB = Task(2, "taskB", priority=1)
taskC = Task(3, "taskC", priority=1)
taskD = Task(4, "taskD", priority=3)
manager = TaskManager()
manager.addTask(taskA)
manager.addTask(taskB)
manager.addTask(taskC)
manager.addTask(taskD)
for task in manager.taskArray:
print(task)
I've also helped debug your program a little. For starters, your recursive calls to the binary search doesn't return values, which is a behavior that you want.
| 2277c56772412ce5a4bd0b01be037c53400b88f1b78ae7eef705514423edcc25 | ['3a4221bcbe574162a16f3bdebe5661ca'] | When I tried to run this same program on my computer and my school's server, I get these two different behaviors from struct.pack(...).
This is from my computer
Python 3.7.0 (default, Oct 9 2018, 10:31:47)
[GCC 7.3.0] <IP_ADDRESS> Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import struct
>>> struct.pack('HL',0,123456)
b'\x00\x00\x00\x00\x00\x00\x00\x00@\xe2\x01\x00\x00\x00\x00\x00'
This is from my school server
Python 3.7.0 (default, Aug 1 2018, 14:55:42)
[GCC 4.8.4] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> import struct
>>> struct.pack('HL',0,123)
b'\x00\x00\x00\x00\x00\x00\x00{'
As you can see, the length of the output is different on both systems, for reasons unrelated to Python version. Is there a way to coerce or force the output to be 8 or 16 bytes long? The HL format is actually only 6 bytes long, but on the school server, it expands to be 8 bytes. On my local computer, 'HL' expands to 16 bytes for some reason.
This behavior is critical because I need to pass this function later on to struct.unpack(...) which would require different length inputs on depending on the length of the output from struct.pack(...).
|
e6fae84775a585cb5190db401f84f1cc60d4499f15fea54fba0e7eac7d4dbd50 | ['3a520545e8d8416f80c6fa8a765e00ad'] | You can create half octagon using :after.
.halfOctagon {
width: 100px;
height: 50px;
background: #f35916;
position: relative;
top:25px;
left:50px;
}
.halfOctagon:after {
content: "";
position: absolute;
bottom: 0;
left: 0;
border-top: 29px solid #f35916;
border-left: 29px solid #eee;
border-right: 29px solid #eee;
width: 42px;
height: 0;
}
you can try live example in https://jsfiddle.net/kb2tzxq4/
To move the half octagon adjust top and left in css for .halfOctagon
| 75e081d9b47b501e03e753b2a96bbab3dcaa198e2a840a361580e50400211fa9 | ['3a520545e8d8416f80c6fa8a765e00ad'] | You can achieve this by doing something like this.
I have used a function to split comma separated value into a table to demostrate.
CREATE FUNCTION [dbo].[Split]
(
@RowData nvarchar(2000),
@SplitOn nvarchar(5)
)
RETURNS @RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
Declare @Cnt int
Set @Cnt = 1
While (Charindex(@SplitOn,@RowData)>0)
Begin
Insert Into @RtnValue (data)
Select
Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))
Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
Set @Cnt = @Cnt + 1
End
Insert Into @RtnValue (data)
Select Data = ltrim(rtrim(@RowData))
Return
END
GO
DECLARE @WB_LIST varchar(1024) = '123,125,764,256,157';
DECLARE @WB_LIST_IN_DB varchar(1024) = '123,125,795,256,157,789';
DECLARE @TABLE_UPDATE_LIST_IN_DB TABLE ( id varchar(20));
DECLARE @TABLE_UPDATE_LIST TABLE ( id varchar(20));
INSERT INTO @TABLE_UPDATE_LIST
SELECT data FROM dbo.Split(@WB_LIST,',');
INSERT INTO @TABLE_UPDATE_LIST_IN_DB
SELECT data FROM dbo.Split(@LIST_IN_DB,',');
SELECT * FROM @TABLE_UPDATE_LIST
EXCEPT
SELECT * FROM @TABLE_UPDATE_LIST_IN_DB
UNION
SELECT * FROM @TABLE_UPDATE_LIST_IN_DB
EXCEPT
SELECT * FROM @TABLE_UPDATE_LIST;
|
80d53e0a77cfed36300365737bac63591d6bfe50271f7a0a74c59d9c62ef6346 | ['3a570c39cbde4a67872b148b2328da9e'] | I have a dataset which contains continues and categorical type of data.
Can anyone help with below questions.
Can i use k-means clustering and euclidean distance or should i use Gower's distance?
When to use euclidean distance/Gower's distance?
How can we know we have formed the correct clusters?
| bf104bf74de93cd6224bd0b0101b60cba3518f3569b3a8c780b388c40cd09b94 | ['3a570c39cbde4a67872b148b2328da9e'] | Am trying to understand the difference in assumptions required for Naive Bayes and Logistic Regression.
As per my knowledge both Naive Bayes and Logistic Regression should have features independent to each other ie predictors should not have any multi co-linearity.
and only in Logistic Regression should follow linearity of independent variables and log-odds.
Correct me if am wrong and is there any other assumptions/differences between Naive and logistic regression
|
754ffaf4c34626a682e427fc9ea55635e98aee3f49c6c149f5522b4ec032c9e0 | ['3a7208b7fad34bbd8cbbe92ed2fdac41'] | I use Python slackclient's module for handling interactive message.
I create and post a message successfully with an "accessory" image:
{
"type": "section",
...
"accessory": {
"type": "image",
"image_url": "https://avatars0.githubusercontent.com/u/44036562",
"alt_text": "GitHub Worflow"
}
}
After the user interaction Slack send me back my message that I handle to edit the same one with some alteration.
My edit is to remove the last element of my message to change it to something else.
I then post my message to Slack API and received an error:
{
'response_metadata': {
'messages': [
'[ERROR] invalid additional property: fallback [json-pointer:/blocks/1/accessory]',
'[ERROR] invalid additional property: image_width [json-pointer:/blocks/1/accessory]',
'[ERROR] invalid additional property: image_height [json-pointer:/blocks/1/accessory]',
'[ERROR] invalid additional property: image_bytes [json-pointer:/blocks/1/accessory]'
]
}
}
Apparently Slack add fields fallback, image_width, image_height and image_bytes to the image type element but don't allow us to send it back as it.
My solution is to parse all my message to detect images type and remove these keys.
It work but it's not really optimal, these keys should be whether allowed or not sent from Slack.
The error is a response from Slack API not a slackclient validation.
Did someone know where I can report this?
| 7ace0eaa770630ecc9a4124fcf2bb51ed9a516dd2f640ced5ba8173878bfe46d | ['3a7208b7fad34bbd8cbbe92ed2fdac41'] | I'm try do simulate a two-fingers action when one-finger is detected, I successfully make a one-finger touch with GestudeDescription and I know that I can't do two-fingers with it but I wandering if I can make it think I'm using the two-fingers doing the same action(swipe for exemple) when I use only one finger.
|
a6b875a40b2e3aa2e5cf94b65142325e1e47514044c5aa51a4cf4a718ef226cc | ['3a7b2ce6eb2a494a8e900bc4aa158798'] | When I use 'dd' to make an image of my sad, I get the message:
dd: /dev/disk1: Input/output error
I've tried on Mac and Ubuntu (the Mac output is above) and the result is the same. My question is: what is wrong with my one week old SDHC card (Kingston Class 4, 8GB)? And more importantly, what tools (preferably GUI) exist on Ubuntu to analyse and fix this problem?
| 07dfd1ea59061a766242e74ced4131145b916fab13c03014b165e82d46c602e1 | ['3a7b2ce6eb2a494a8e900bc4aa158798'] | I've tried VLC, Totem and MPlayer and while they differ in their unique kind of choppiness, none of them play smoothly.
The Ubuntu documentation suggest enabling DMA[1] but the instructions don't seem to apply to a SCSI device.
How can I get the playback of DVDs to be smooth?
In case it matters, it's a BluRay player:
-scsi:0
physical id: 1
logical name: scsi0
capabilities: emulated
*-cdrom
description: DVD-RAM writer
product: BD-CMB UJ-120
vendor: MATSHITA
physical id: 0.0.0
bus info: scsi@0:0.0.0
logical name: /dev/cdrom
logical name: /dev/cdrw
logical name: /dev/dvd
logical name: /dev/dvdrw
logical name: /dev/sr0
logical name: /media/jarlath/TGWTDT
version: 1.00
capabilities: removable audio cd-r cd-rw dvd dvd-r dvd-ram
configuration: ansiversion=5 mount.fstype=udf mount.options=ro,nosuid,nodev,relatime,uid=1000,gid=1000,iocharset=utf8 state=mounted status=ready
*-medium
physical id: 0
logical name: /dev/cdrom
logical name: /media/jarlath/TGWTDT
configuration: mount.fstype=udf mount.options=ro,nosuid,nodev,relatime,uid=1000,gid=1000,iocharset=utf8 state=mounted
1: https://help.ubuntu.com/community/DMA
|
191ceaae964186e70ca8f10872bf794a4da4c1633033c6809fce2efa747e4326 | ['3a8297068682402aa045dd52dba5c498'] | I'm suggesting you to use iwatch which perl program that uses inotify internally.( It is possible to run it as daemon )
When you setup it to watch folder with files , you can simply run touch * inside watched folder. This will update timestamps of files and inotify events will trigger.
Be careful with IN_CREATE event if you need to do something with files that are created or moved, because this event will be fired immediately after file has been created. In that case you can use event CLOSE_WRITE which will fire after file has been closed.
Hope this helps!
| 1152ca5ef87bf9090df6db2474f8b0da5978eee7c599182f7a66be6b733c6d71 | ['3a8297068682402aa045dd52dba5c498'] | First ensure that mod_expires has been loaded then ,you can define in httpd.conf file or inside VirtualHost following:
<IfModule mod_expires.c>
FileETag MTime Size
ExpiresActive on
ExpiresByType application/javascript "access plus 1 week"
ExpiresByType application/x-javascript "access plus 1 week"
ExpiresByType application/x-shockwave-flash "access plus 1 week"
ExpiresByType text/css "access plus 1 week"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/x-icon "access plus 6 month"
ExpiresByType image/ico "access plus 6 month"
</IfModule>
Hope this helps !
|
6d5da5af798d20b745eb9f888bde71efb4db9bd66a7abd5aead6687611f2ab05 | ['3a95ff3321324b63a6ce275760268bee'] | In the model Tesla K20 the peak single-precision floating point performance is about 3.52 TFlops but the double-precision is 1.17 TFlops,so the ratio is 3. The Tesla K20X has 3.95 and 1.31, and Tesla K40 has 4.29 and 1.43 TFlops, the ratio seems to repeat. My question is if there is a reason to the ratio be 3 and not 2, that seems logical to me because the difference between single and double precision. I am learning about GPUS and GPGPUS, so i don't know very much about it.
In the second page of this pdf there is a specs table.
NVIDIA-Tesla-Kepler-Family-Datasheet.pdf
| 68be177a76d1c55a0addda8bf17a64c59fc558f94d869f88172e6925a1d038cc | ['3a95ff3321324b63a6ce275760268bee'] | I'm using Gstreamer version 1.8.3 and the following pipelines to send and receive a rtp/rtcp streaming.
Vars:
export SAMPLE="overwatch.mjpeg"
export IMAGE_CAPS="image/jpeg,width=1280,height=720,framerate=1/10,format=I420"
Listener:
test_play_rtpbin(){
gst-launch-1.0 --gst-debug=3 rtpbin name=rtpbin \
udpsrc port=25000 ! application/x-rtp,media=video,payload=26,clock-rate=90000,encoding-name=JPEG,width=1280,height=720 ! rtpbin.recv_rtp_sink_0 \
rtpbin ! rtpjpegdepay ! queue ! jpegparse ! jpegdec ! videoconvert ! fpsdisplaysink \
udpsrc port=25001 ! rtpbin.recv_rtcp_sink_0 \
rtpbin.send_rtcp_src_0 ! udpsink port=25005 host="<IP_ADDRESS>" sync=false async=false
}
Publisher:
test_record_rtpbin(){
gst-launch-1.0 --gst-debug=3 rtpbin name=t \
multifilesrc location=$SAMPLE loop=true ! queue ! $IMAGE_CAPS ! jpegparse ! $IMAGE_CAPS ! queue ! rtpjpegpay pt=26 ! application/x-rtp,media=video,payload=26,clock-rate=90000,encoding-name=JPEG,width=1280,height=720 ! t.send_rtp_sink_0 \
t.send_rtp_src_0 ! udpsink port=25000 host="<IP_ADDRESS>" \
t.send_rtcp_src_0 ! udpsink port=25001 host="<IP_ADDRESS>" sync=false async=false \
udpsrc port=25005 ! t.recv_rtcp_sink_0
}
But for some reason it keeps throwing me the following error:
Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
Setting pipeline to PLAYING ...
New clock: GstSystemClock
0:00:22.564008753 16798 0x1f6b540 WARN rtpjitterbuffer rtpjitterbuffer.c:487:calculate_skew: delta - skew: 0:00:<PHONE_NUMBER> too big, reset skew
0:00:26.750010395 16798 0x1f6b540 WARN basesrc gstbasesrc.c:2948:gst_base_src_loop:<udpsrc0> error: Internal data flow error.
0:00:26.750027345 16798 0x1f6b540 WARN basesrc gstbasesrc.c:2948:gst_base_src_loop:<udpsrc0> error: streaming task paused, reason not-linked (-1)
ERROR: from element /GstPipeline:pipeline0/GstUDPSrc:udpsrc0: Internal data flow error.
Additional debug info:
gstbasesrc.c(2948): gst_base_src_loop (): /GstPipeline:pipeline0/GstUDPSrc:udpsrc0:
streaming task paused, reason not-linked (-1)
Execution ended after 0:00:26.709638512
Setting pipeline to PAUSED ...
Setting pipeline to READY ...
Setting pipeline to NULL ...
Freeing pipeline ...
A full level 5 log is here.
The sample file have the following format:
$ mediainfo overwatch.mjpeg
General
Complete name : overwatch.mjpeg
Format : JPEG
File size : 1.63 GiB
Image
Format : JPEG
Width : 1 280 pixels
Height : 720 pixels
Color space : YUV
Chroma subsampling : 4:2:0
Bit depth : 8 bits
Compression mode : Lossy
Stream size : 1.63 GiB (100%)
The pipelines work when I use rtp only but when I try to run a simple rtpbin example it keeps failing. Please help!
|
00cd7b473c81a65d58d32bfef2123fb583d63f8df31805870e00e76f9ec56457 | ['3a9cf915eeda4cdd967d278a68f57389'] | Thank you <PERSON>. I am seriously computer language illiterate. I did try <PERSON>'s answer and got the result I wanted, but wanted to try yours as well. Yes, I get the blue window. Unfortunately, I'm not doing something right as I'm not getting the result. You have "optional-target" italicized.That indicates to me that something else should be there? Am I correct? And do I literally type
cmd
dir....
exit | 5b0f0ad8ab57e6cd7feb6efcb424465b2d750685b4bcb8a770bc600f5323629b | ['3a9cf915eeda4cdd967d278a68f57389'] | Just curious if I would have problems with my computer if I were to uninstall the various @.... fonts? For example, @arial unicode ms, @batang, @dotum, @kaiti, @microsoft...., or the various microsoft... fonts, like microsoft jhenghei, microsoft yahei, etc. It may seem petty, but I'm a scrapbooker and I use a multitude of fonts and these "get in my way", for lack of a better explanation. I never use them (that I know of...unless they run in the background). So I'm asking here. Thanks. <PERSON>
|
2903547bc8fac36a841e5d005e2033d981c8c1e7f4285ccaa1c3f5b27966bfb0 | ['3a9d5a9fa2f1426bb24b8fe48482cac2'] | SUMIFS() Should solve your issue here. You can use something like =SUMIFS(F:F,A:A,A2,B:B,B2,C:C,C2,D:D,D2,E:E,E2) if it is essential that A-E match. This will give you a Column G with the result you are after however this way will also give you multiple rows.
IF B-E are always the same for a Column A value then you can always paste the unique Column A values in a separate sheet and then use =SUMIFS(Sheet1!F:F,Sheet1!A:A,Sheet2!A2)
and display something like this
| 74a2f96da4e7a42317af93b47e9272a13914b69ddf13a359625ae2ee9af3cc84 | ['3a9d5a9fa2f1426bb24b8fe48482cac2'] | The problem is not the coding of the CSS but the mathematics of a circle.
Essentially your border-inner-radius (I know this property does not exist) is equal to the border-radius - border-width.
Quite simply work out what you want your inner radius to be and then add the width of the border to achieve the desired effect.
border-inner-radius + border-width = border-radius
|
636f2926db764d90a0f4857016d077d5eb3d00f77b2ff88aa44e675db82f0028 | ['3a9de2c9b64b4c258d8f7ac83c44c921'] | <PERSON>: thanks for replying - I appreciate learning that. However, I want to adjust the screen lock time, and according to the Ubuntu Help menu under the upper-right hand gear icon on my screen, that feature should be under the "Brightness & Lock" feature. But I don't have that feature listed on my system. | d4405a6325b00ff84450bf9a55442fdbd611fa9bb476fda1a43a61b387908a03 | ['3a9de2c9b64b4c258d8f7ac83c44c921'] | I did a clean install of 20.04 a couple of days ago and have been customizing my machine since then. When I right-click on the top panel, the context menu doesn't appear. I am used to using earlier versions of Ubuntu and adding apps to the top panel. Please advise. Thank you.
|
d3a1e5dc752e51b4c9952c505ed8f4af6df3c803489ab30f93b80ff115bdc10e | ['3aa271f67dbf4daab109fd39e87d1794'] | I'm working on a simple game using Phaser.
My code:
preload() {
this.load.image('player', 'img/player.png');
}
create() {
var player = this.add.sprite(100,100,'player');
player.inputEnabled = true;
player.input.on('pointerdown', () => {
this.scene.stop('ThisScene');
this.scene.start('NextScene');
})
}
The game should switch from one scene to another when you click on the sprite 'player'. Unfortunately, this gives an error: Cannot read property 'on' of null
Any ideas?
| d773ace4b02bf7a1c9c7a4442ebd6fc8066c15c3c6b97a45584d475e36340ca1 | ['3aa271f67dbf4daab109fd39e87d1794'] | I would like to learn brain.js so I decided to make a little project. I would like to make a rock, paper, scissors game where the background color would randomly change between three colors after every play.
If you'd choose that you will play one option every time a certain background color appears, the website should use brain.js and learn the pattern.
At first, the website also chooses a random option.
example:
background-color=blue youPlay=rock
background-color=red youPlay=paper
background-color=yellow youPlay=scissors
//when all three colors were used, the website will use a function with brain.js
background-color=red -> website knows that you will most likely play paper based on your previous plays and it will play scissors to win
This is the most crucial part of the function:
const net = new brain.NeuralNetwork();
for(i=0; i < dataPlay.length; i++){
net.train([{ input: [dataColor[i]], output: [dataPlay[i]] }]);
}
var output = net.run([colorVar]);
The background-colors are saved in dataColor[] and your plays are saved in dataPlay[]. The actual background-color is saved in colorVar.
The problem with the for loop is that the output is only based on the last item in dataColor and dataPlay. I would like to train the data from all items in dataColor and dataPlay.
|
620d97a9af2cc4b3da3ef8a9ed9ac643ec2e8a073414fe102dc484dc839082a4 | ['3aa45a1e8ae54a68a5c1b0bbe9556ed9'] | If you call $this->ActionResult_Index() from within the Controller class, you'll get a fatal error, because the Controller class doesn't implement that method. Parents don't inherit from their children, it's the other way around.
Also: your extends syntax is wrong; get rid of the () after the name of the base class.
| 99d4507109051cad7502b078ccd52945e834df92c2af640bbc5c40687cbdf271 | ['3aa45a1e8ae54a68a5c1b0bbe9556ed9'] | The most likely reasons are:
You're re-initializing curl after you get the CRSF token, so it becomes invalid for the subsequent request, because that's a completely different session as far as the site is concerned.
Your $postinfo is a string, so you need to urlencode() the values by hand (CURLOPT_POSTFIELDS also accept associative arrays, in which case you don't need to do that).
|
3018f70ccc3a6700cbfe40e06d4a7033329c4c8a1a6ab923656905e6f44246ad | ['3aaabffec3ad4f62ac52049457f3134c'] | I am working on my homework and am currently stuck at the following question:
Let $\mathcal S_{10}$ be the group of all permutations of the set of elements {1, 2, ..., 10}. Find an Abelian subgroup of size 24 to $\mathcal S_{10}$.
Thanks a lot in advance for any advice/hints! :)
| 284d55b0df42bc1e9a1c22a4310924825824b9134348e5aa3c09458fcb2fbed5 | ['3aaabffec3ad4f62ac52049457f3134c'] | \counterwithin{figure}{section}
\usepackage[all]{hypcap}
in the preamble after the hyperref-package. In this case \counterwithin{figure}{section} aswell \usepackage[all]{hypcap} is enough, but sometimes you need both, also \usepackage{caption} often helps.
This question uses
https://stackoverflow.com/a/6696146/6747994
https://stackoverflow.com/a/4024019/6747994
https://tex.stackexchange.com/a/298399/110064
https://tex.stackexchange.com/a/28334/110064
https://texblog.org/2014/12/04/continuous-figuretable-numbering-in-latex/
|
fddd9cfabf721d11d0bc6b0cad7163835d6b5089673213219d8ae0db8984b8e1 | ['3ac5a92c32964164b92985c6ec6ac85e'] | sphinxql's execute function returns the data in string but you can use it in geodist query as it is. just remember not to use quotes on the columns name in your query, if you put quotes over it sphinx treats it as a string and i wont produce any result.
| b683b123348b46e8b53fcade94c5d06462b1b1c1c5ee4ff911f9c8869526557d | ['3ac5a92c32964164b92985c6ec6ac85e'] | check this out.
'query' => ['bool' => [
'must' => [
['match' => ['approvalStatus' => 'approved']],
[ 'ids' => [
'values' => [new MongoDB\BSON\ObjectId($documentid)]
]
]
],
'must_not' => ['term' => ['muteFeedUserIds' => $userID]],
'must_not' => ['term' => ['muteUserIds' => $userID]]
]
If that doesnt work i am giving you the raw as i am not good with elasticphp
{
"query": {
"bool": {
"must": [
{
"ids": {
"type": "type_of_index"
"values": ["AVbqtjXfoKQ0pubF_-NA"]
}
}
]
}
}
}
type is optional
Just add this ids part under must area.
|
6966e4a74c273be4e26818b129cf1163dfb81da22591a4b7820c8e71688e0510 | ['3acea34f11d142e39c22963d5821745c'] | I have a following data frame:
tests <- c("test1", "test1", "test1")
obs <- c("observation1", "observation2", "observation3")
test <- data.frame(tests, obs, stringsAsFactors = FALSE)
I want to turn that into an XML file with specific formatting:
library(XML)
example <- newXMLNode("example")
addAttributes(example, name=test$tests[1])
observations <- lapply(seq_along(test$obs),function(x){newXMLNode("obs",
attrs = c(ID = paste(test$tests[1], "-", as.character(x), sep="")),
.children = test$obs[x])
})
addChildren(example, observations)
saveXML(example, file=paste0(test$tests[1], ".xml"))
This saves to my working directory this item with name test1.xml:
<example name="test1">
<obs ID="test1-1">observation1</obs>
<obs ID="test1-2">observation2</obs>
<obs ID="test1-3">observation3</obs>
</example>
But what if I have instead a single data frame a list of data frames? Like this:
tests <- c("test1", "test1", "test1", "test2", "test2", "test2", "test3", "test3")
obs <- c("observation1", "observation2", "observation3", "observation4", "observation5", "observation6", "observation7", "observation8")
test <- data.frame(tests, obs, stringsAsFactors = FALSE)
test <- split(test, test$tests)
I want to save each of them as their own XML file, now as test1.xml, test2.xml, test3.xml, but the code above doesn't work and I'm not getting it fixed. I understand I should somehow loop through each list item.
| 0e6770f7454f78aa918fee1009abc835ae4830111d2dba9feca39c66cf81022e | ['3acea34f11d142e39c22963d5821745c'] | I have data frames in R which can be reproduced with this code:
id1 <- c("NP", "AK", "HT")
id2 <- c("t1", "t5", "t2")
Sentence <- c("This is an example .", "This too !", "Ok")
df <- data.frame(id1, id2, Sentence)
It looks like this:
id1 id2 Sentence
1 NP t1 This is an example .
2 AK t5 This too !
3 HT t2 Ok
And I would like to restructure it into something like this, where each unit in Sentence column is divided by the spaces:
id1 id2 Sentence
1 NP t1 This
2 NP t1 is
3 NP t1 an
4 NP t1 example
5 NP t1 .
6 AK t5 This
7 AK t5 too
8 AK t5 !
9 HT t2 Ok
I know there is the function strsplit, then package tm seems to have also function called tokenizer, but I don't really understand how I can do something like this inside a data frame.
Thank you!
|
1f9353ea82cd000d3838f87acd4e1f49960be62c88707a3b3de2c4886b590c8f | ['3ad311d8c5744967b4bc680bd4ae3aaa'] | When you're using setFont method you need to make sure you pass absolute path of the font:
$im->setFont("/var/www/html/mysite/media/fonts/myCustomFont.ttf");
Same would apply for your localhost development just change the absolute path.
(This is a bit old question but I figured to answer it anyways.)
| 5b3d05585ce5c13d6e234f2e878c2dc99062ff52ff78e9263873e7c3bfded8a2 | ['3ad311d8c5744967b4bc680bd4ae3aaa'] | Box-Shadow
CSS3 box-shadow property has following attributes: (W3Schools)
box-shadow: h-shadow v-shadow blur spread color inset;
In your example you're offsetting shadow by 10px vertically and horizontally.
Like in other comments set first two values to 0px in order to have even shadow on all sides.
More on Shadows
The main prefix for shadow to support latest browsers is box-shadow.
There are 2 other ones that I recommend to use for older Mozilla and Webkit:
-moz-box-shadow
-webkit-box-shadow
Also, by using rgba instead of hex color value you can set the alpha/opacity of the shadow:
box-shadow: 0px 0px 20px 10px rgba(0, 0, 0, 0.3);
|
d35c607fe793967be4de8062d85e830a9d5ba03cfc9f5ed385331e93e526bc81 | ['3ade4f0dedd2459bb1aea7ae735a0b1a'] | It seems at present there is no way to get Pycharm to access and use Python on a worker node of the HPC cluster (though the above answer using forwarding might work for some??). Pycharm support suggested posting a vote on the feature request system
https://youtrack.jetbrains.com/issue/PY-18828
| a8652390506cb4faa6c7b5dc3072b49220bd253e8c6c315421c1775abd8e42bc | ['3ade4f0dedd2459bb1aea7ae735a0b1a'] | I have a gui script that has a button for users to click and select a file for running some processing on. I want to create a save path which is the same directory as the original file was opened from so that the saved file is saved back there.
I use a try/except in the code in case of errors and I just can't get the savepath code to work. It's breaking the try/except so it's always going to the exception. I know it's something to do with the format of the os and the pyqt path/filename but I'm not sure what I need to do to fix it?
It's currently saving working directory unless I put a second button to choose the output location which seems pointless when the users will save in the same location as the input file every time, but this will be a different folder location each time so I can't hard code the path.
This is my code:
try:
self.inputfile = open(QtGui.QFileDialog.getOpenFileName(self,"Open File", "", "txt files (*.txt)"),'r+')
self.save_path = os.path.dirname(self.inputfile)
with self.inputfile as f:
for line in f:
#....do some processing
except:
#show an error message#
|
ca969d3e1f2aa8aff69304e34029ad1df168caae13b0234881d570a5b1e4d63b | ['3ae374551fb54c5ca9faa24b5207518a'] |
Dose anyone have idea to resolve UWP project problem
Ref this document
For Android and iOS platform, we can use FontName property, but for Windows Phone platform, it uses FriendlyFontName property:
Quote:
This property is only necessary for the Windows Phone platform. This
can be found on the first line of the font or in the font preview. If
not given then the file name excluding the extension is used. However
this cannot be guaranteed to work.
But seems like XLabs didn't handle the FriendlyFontName setting correctly. I just tried its official sample for UWP
For the ExtendedLabel scenario, the font setting is incorrect.
After some investigations, based on this issue, I found a workaround to fit Windows Phone and UWP scenario.
Setting FontName and using OnePlatform for WINRT scenario in xaml:
<controls:ExtendedLabel FontName="Kristen ITC"
FontSize="20"
FriendlyFontName="Kristen ITC"
HorizontalOptions="StartAndExpand"
Text="This uses 'FontName' = '<PERSON>' set in XAML and 'OnPlatform' properties, size 20">
<controls:ExtendedLabel.FontFamily>
<OnPlatform x:TypeArguments="x:String"
iOS=""
Android=""
WinPhone="Kristen ITC"/>
</controls:ExtendedLabel.FontFamily>
</controls:ExtendedLabel>
Please notice that the specific Font should be installed in your platform OS.
Screenshot:
Check my forked repository
| 7cf2f371813e2cc3eaf752d0d9ee385a63787f756296904b42f668466ec506aa | ['3ae374551fb54c5ca9faa24b5207518a'] |
When debugging into my ContentTemplateSelector, my binding is always
null
You need to set data binding for the Content property of ContentControl control, see Remarks in MSDN:
The Content property of a ContentControl can be any type of object,
such as a string, a UIElement, or a DateTime. By default, when the
Content property is set to a UIElement, the UIElement is displayed in
the ContentControl. When Content is set to another type of object, a
string representation of the object is displayed in the
ContentControl.
So the following xaml should work:
<StackPanel>
<ContentControl Content="{Binding}"
ContentTemplateSelector="{StaticResource MyTemplateSelector}"/>
</StackPanel>
Check my completed sample in Github
|
a0644ef3fdbbd0812379a413f901b2545ab9af9933d2d937b92f5460ed5aedcf | ['3af0b4cf659c41c299a5141d1c16c0d3'] | I want to determine if a user or his friends already like a specified external URL. Using the Graph API Explorer, I am trying to perform this FQL: SELECT user_id FROM url_like WHERE url="<URL>" AND (user_id = me() OR user_id IN (SELECT uid2 FROM friend WHERE uid1 = me()))
I do not get back any results, the AJAX bar keeps on spinning.
A simpler query leaving out the friends connection works fine, such as fql?q=SELECT url FROM url_like WHERE user_id = me() AND url = "<URL>"
Is there a problem with my query? Is there an alternative way to achieve my result?
Thanks,
<PERSON>.
| 677ef3d343c831a74fc3c21a40425008fa27da63ddffac670dd36d47fd0f44f7 | ['3af0b4cf659c41c299a5141d1c16c0d3'] | Simply get the claim "http://schemas.microsoft.com/2017/07/functions/claims/keyid" from the req.HttpContext.User.Claims object. It contains the key id in case a Function key was used.
Works like a charm, and does not require external lookups.
const string KEY_CLAIM = "http://schemas.microsoft.com/2017/07/functions/claims/keyid";
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
var claim = req.HttpContext.User.Claims.FirstOrDefault(c => c.Type == KEY_CLAIM);
if (claim == null)
{
log.LogError("Something went SUPER wrong");
throw new UnauthorizedAccessException();
}
else
{
log.LogInformation( "Processing call from {callSource}", claim.Value);
}
|
8e40d237a37821c046699cb1312e61c7d01a0d6784f9386fb9127d27471a9521 | ['3af10e4d6e824702bfe21094c7ee2d10'] | I have run into a bit of (what I think is) strange behaviour when using Castle's Dynamic Proxy.
With the following code:
class Program
{
static void Main(string[] args)
{
var c = new InterceptedClass();
var i = new Interceptor();
var cp = new ProxyGenerator().CreateClassProxyWithTarget(c, i);
cp.Method1();
cp.Method2();
Console.ReadLine();
}
}
public class Interceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine(string.Format("Intercepted call to: " + invocation.Method.Name));
invocation.Proceed();
}
}
public class InterceptedClass
{
public virtual void Method1()
{
Console.WriteLine("Called Method 1");
Method2();
}
public virtual void Method2()
{
Console.WriteLine("Called Method 2");
}
}
I was expecting to get the output:
Intercepted call to: Method1
Called Method 1
Intercepted call to: Method2
Called Method 2
Intercepted call to: Method2
Called Method 2
However what I got was:
Intercepted call to: Method1
Called Method 1
Called Method 2
Intercepted call to: Method2
Called Method 2
As far as I can tell then the dynamic proxy is only able to proxy method calls if the call comes from outside the class itself as Method2 was intercepted when called from Program but not from within InterceptedClass.
I can kind of understand that when making calls from within the proxied class it would no longer go through the proxy, but just wanted to check that this was expected and if it is then see if there is there anyway to get all calls intercepted regardless of where they're called from?
Thanks
| 872165d1a5355e22384ae163fb860edf512e5bb7713e87fba92a1c731e8793a4 | ['3af10e4d6e824702bfe21094c7ee2d10'] | maybe yes, not sure, checking out your suggestion now on google, I had a software that did some management and there I could always see how many times a file was accesed, but that software is gone, files are still in use, so I want to be able to easylie fast to see what files are still being used daily, sothat I can timely remove older files that nobody access anymore. |
98b215ee8d5e6fe022d99eff554dad21a68fad4e12a39733c5ed8c6e6e258847 | ['3af81d0aa9504dafacae95158de65004'] | I have 6GB sql file of insert statements where I would like to add a GO statement after each 150 lines. There are a total 9M lines in the file.
I found some code using Powershell script and most recommended the stream or .NET commands for performance with large files.
$reader = [System.IO.File]<IP_ADDRESS>OpenText("C:\src\customers1.sql")
$pathAndFilename = "c:\src\files\_customers_1.sql"
$streamout = new-object System.IO.StreamWriter $pathAndFilename
$batchSize = 150
$counter = 0
try {
for ( $line = $reader.ReadLine(); $line -ne $null; $line = $reader.ReadLine() )
{
$streamout.writeline($line)
$counter +=1
if ($counter -eq $batchsize)
{
$counter =0
$_ # send the current line to output
if ($_ -match ", NULL, NULL")
{
#Add Lines after the selected pattern
$line="GO"
$streamout.writeline($line)
}
}
}
}
finally {
$reader.Close()
$streamOut.close()
}
The above reads the source file and writes into the destination path in 3 minutes. However, it does not write the GO after each 150 lines of code. It seems to just copy the file over. Is there something I am missing in the code?
| a98cd0213aa953115f3f23cebdf56ed59db57f3bb8f75a4758fb15c1515b123f | ['3af81d0aa9504dafacae95158de65004'] | I updated my code and got rid of the functions and included the namespace in the main code. This may not be the most elegant solution but here is the revised code that worked:
if($files)
{
foreach ($file in $files) {
[xml]$fileContent = Get-Content($file)
attrib $file -r
$XPath = "/ns:Project/ns:ItemGroup/ns:ArtifactReference[@Include='..\cwdb.dacpac']"
$namespace = $fileContent.DocumentElement.NamespaceURI
$ns = New-Object System.Xml.XmlNamespaceManager($fileContent.NameTable)
$ns.AddNamespace("ns", $namespace)
$artifacts = $fileContent.SelectSingleNode($XPath, $ns)
# update HintPath node value
$artifacts.SelectSingleNode("./ns:HintPath", $ns)."#text" = $NewText
Foreach ($artifact in $artifacts)
{ # update Include attribute value
$artifact.SetAttribute("Include", $NewText)
}
$fileContent.Save($file)
Write-Output "$file.FullName = update applied"
}
}
else
{
Write-Output "Found no *.sqlproj files."
}
|
f88de1be40ca445091e4f2fd0ca39b06219e1eb72a935ad0c803cc1ce4421254 | ['3b03b878dd834185a114bbe9effa1cfb'] | Yes the sensor didn't change, but the processor has changed... that means that the iso performance on the t5i is better than on the t2i and it will "clean up" the image better... I owned both these cameras and I can say that I noticed a difference, specially when shooting at higher iso values... So i would recommend you pick up the t6i or the t5i for which i can say from personal experience is a fantastic camera for its price :)
and on the subject what else is going to affect the image quality it depends on what you will shoot... you will definitely need a tripod, a fast lens and perhaps a remote to trigger your camera to reduce the camera shake if you are going to do long exposures...
My answer is written on my experience and my varry on different situations and shooting style so keep that in mind :)
| fd67641f2b0ebda29f4b5f8c758e6edb77ada36aa445faa120524df3eb21102f | ['3b03b878dd834185a114bbe9effa1cfb'] | @ShimonRura Unfortunately is is the case, the HVAC guy checked last night. He said he couldv'e swron when the unit was being remodelled, there was a return duct, but neither of us saw it. On the main floor of the house, in the foyer (2 floors below the loft), there is a return. So all the air has to go downstairs, under my apartment door, then down to the main floor to get to the return. That doesn't seem proper, does it? |
1facb1f6ded3460115476f7ca132d540e98eafb89a3fb5aae23cb644b7df98ca | ['3b0c6840401d45aa8bb4bb24acdde1ca'] | Does someone understand what's going on in my nodeJS application.
When I do an asynchronous call using ajax the server first responds with a 404 error then loads the page. The application works fine but I have a lot of boring logs saying "Can't set headers after they are sent."
Here is the route part
module.exports = function(passport) {
var router = express.Router();
........
router.get('/dashboard', isLogged, dashcontroller.showdashboard);
router.get('/dashboard/general', isLogged, dashcontroller.general);
........
return router;
}
here the controller
exports.showdashboard = function(req, res, next) {
if (req.user.status == 'active')
res.render('dashboard', { title: 'title' , user: req.user});
else
res.redirect('/user/logout');
next();
}
exports.general = function(req, res, next) {
if (req.user.status == 'active')
res.render('general', { title: 'title' , user: req.user});
else
res.redirect('/user/logout');
next();
}
The asynchronous request, this code is reachable by the client from /dashboard and resides in public/javascripts/code.js. The client found it and executes it with no problems.
$(function() {
$("li.infos").click(function() {
$("li.basket").removeClass("active")
$("li.infos").addClass("active")
$('.main-container')
.load('/user/dashboard/general');
});
});
All works fine but i still get those boring logs
GET /stylesheets/dashboard.css 304 0.555 ms - -
GET /javascripts/dashboard.js 304 0.280 ms - -
GET /javascripts/basket.js 304 0.323 ms - -
abc deserializeUser
Executing (default): SELECT `id`, `username`, `public_key`, `email`, `password`, `last_login`, `basketcount`, `status`, `activation_token`, `createdAt`, `updatedAt` FROM `users` AS `user` WHERE `user`.`id` = 6;
GET /user/dashboard/general 404 35.837 ms - 2290
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
at ServerResponse.header (/home/me/Documents/app/node_modules/express/lib/response.js:730:10)
and the trace goes on
Does anyone understand what is happening?
thank you in advice
| b3a428bc034ed32bc304dfc3c400d804b1573adb6eab5b28ca394f05833c2726 | ['3b0c6840401d45aa8bb4bb24acdde1ca'] | Problem solved.
"Just" changed how to reference the model in passport.js as follow
var User = user;
had to rewritten as
var User = db.user;
Here the definitive passport strategy file
const db = require('./../models/');
var bCrypt = require('bcrypt-nodejs');
module.exports = function(passport) {
var User = db.user;
var LocalStrategy = require('passport-local').Strategy;
passport.use('local-signup', new LocalStrategy(
{
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(req, email, password, done) {
var generateHash = function(password) {
return bCrypt.hashSync(password, bCrypt.genSaltSync(8), null);
};
User.findOne({
where: {
email: email
}
}).then(function(user) {
if (user) {
return done(null, false, {message: req.flash('email already taken')});
console.log('mail already taken');
}
else {
var pass = generateHash(password);
var data =
{
email: email,
password: pass,
username: req.body.username,
public_key: '0',
last_login: null
};
User.create(data).then(function(newUser, created) {
if (!newUser) {
return done(null, false);
}
if (newUser) {
return done(null, newUser, {message: req.flash('tappost')});
}
});
}
}).catch(function(err) {
console.log(err);
});
}
));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id).then(function(user){
done(null, user);
}).catch(function(e){
done(e, false);
});
});
}
|
e1d1d2e5e29bdad7f8ffba6c3b9bf89b34ea4d30da6990b6904963d81ce33ff4 | ['3b0fa5f6b542406bab0277e41808d3c1'] | right now when I press my touchableopacitys very quickly, it will stack up a bunch of calls to the onpress callback and then execute them over time. What I want instead is to be able to prevent further callbacks while the touchableopacity is "pressed" or faded, so that the onpress is only called once for each time the touchableopacity is "down", i.e. one full cycle of fading out then back in. How would I do this?
| 686813ce028d4c254be7ee24f212d77d657099389c9f7e14dc3e3c5a8ea3bf1f | ['3b0fa5f6b542406bab0277e41808d3c1'] | The solution that worked best for my specific situation was monkeypatching/refining specific methods to account for possibly nil values, and mixing it into the file that performed these calculations.
Again, this is my very specific case in which the syntax needed to closely resemble a certain style.
Many thanks all!
|
1e8754b561f75624b9b6e957a4f5a2bc8f946aff5b9052f46a644fdec43b51bb | ['3b33b70a2ad942388a116923ae700016'] | in the $("#mainTask").focus event handler you can set a global boolean variable to true, set it to false in an blur event handler and check on the value of that variable in the #taskInput mouseout event handler
var preventSlide = false;
$("#taskInput").mouseout(function(evt){
if (!preventSlide) {
$(this).stop().animate({top:-80}, 200, function(){});
}
})
$("#mainTask").focus(function(){
preventSlide = true;
})
$("#mainTask").blur(function(){
preventSlide = false;
})
| f87314397a7f4b883d7c95ce89842dcc6d0217a5d24c64faf296b3d7816c6aed | ['3b33b70a2ad942388a116923ae700016'] | in your code you could replace the entire string with all the option elements with a for loop going from 0 to 17, like
for (var age = 0; age < 18; age++) {
d.innerHtml += "<option value='" + age + "'>" + age + "</option>"
}
although I think it is not so nice coding to keep on appending to innerHTML the way you do.
one alternative is to have a variable called 'selectHtml' and add the code to that, and set
d.innerHTML to selectHtml in the end.
|
540ba130e0ff5a507b8370ea50a59002c638234c057e4cb7883984ce1acd7a81 | ['3b43e9c67f3345acb025b53744a68628'] | I am using IMX6 Saberauto board on Linux OS. I have 2 displays primary is HDMI and secondary is LVDS. I want to run 2 applications.
One QT on primary display, which I am able to do. Second application is airplay application I want this applicaiton to run on seondary display ie /dev/fb2. But I am not able to do.
It is coming on primary display only. Please let me know the command to direct airplay output to /dev/fb2
| ebf805f82ccf7d7f6f200c60e8badab990f60218ee0979cb24807e8725689da3 | ['3b43e9c67f3345acb025b53744a68628'] | I am executing dhrystone 2.1 on freescale IMX6 quad processor with 1GHz.Below are the things I tried.
1. Executed dhrystone alone first time.
2. With an application running in the background, I executed dhrystone.
In either cases I am getting DMIPS value same. I do not understand. In second case DMIPS should reduce.Please let me know
|
c28bc202c55a3f1259258a2de4ec2a26fcfc466b466e4ddf8bc66c9ad290165b | ['3b50e4d8fbbe4b6399b5deb75d63fea3'] | This may seem like a duplicate question but the answers provided in the other posts did not help.
I am making a C# ASP.NET website, currently it works fine when testing in the Visual Studio IDE. The site uses the default login controls that are created when you create a new asp.net web application. The problem is, when loaded through the IIS (going to the hosting computers IP address from another computer) every page loads, but the login part fails. Here is the error screen:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.
)
Stack Trace:
[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.
)]
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling) +1394
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +1120
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +70
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +910
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +114
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1637
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +117
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +267
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +318
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +211
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +393
System.Data.SqlClient.SqlConnection.Open() +122
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +104
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext) +509
System.Data.Entity.SqlServer.<>c__DisplayClass33.<UsingConnection>b__32() +567
System.Data.Entity.SqlServer.<>c__DisplayClass1.<Execute>b__0() +15
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +238
System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act) +916
System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript) +117
System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection) +212
System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection) +135
System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +175
System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) +116
System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext) +121
System.Data.Entity.Database.Create(DatabaseExistenceState existenceState) +293
System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context) +187
System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +72
System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +483
System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) +177
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) +274
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +38
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +77
System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +21
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +59
System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable`1 source, Expression`1 predicate, CancellationToken cancellationToken) +208
System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable`1 source, Expression`1 predicate) +172
Microsoft.AspNet.Identity.EntityFramework.<GetUserAggregateAsync>d__6c.MoveNext() +502
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13891908
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
Microsoft.AspNet.Identity.CultureAwaiter`1.GetResult() +48
Microsoft.AspNet.Identity.<FindAsync>d__12.MoveNext() +357
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13891908
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
Microsoft.AspNet.Identity.AsyncHelper.RunSync(Func`1 func) +348
Account_Login.LogIn(Object sender, EventArgs e) +119
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +11762637
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +150
System.Web.UI.<ProcessRequestMainAsync>d__523.MoveNext() +7798
Here is the connection string in the web.config file
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=aspnet-nes-a6ab9e95-1ec8-4eee-af0f-bc33406759d6;AttachDbFilename=|DataDirectory|\aspnet-nes-a6ab9e95-1ec8-4eee-af0f-bc33406759d6.mdf;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>
Things I have tried:
added iusr(aspnet user not found) to the list of users in SQL management console
made sure the account is loaded in IIS application pool
Checked and verified the SQL service is running
Changed the IIS site connection string to the string provided during SQL Express install
So far no matter what change I make it is the same error message. Also in case it matters I am using Visual Studio community 2017 and SQL express server 2016
| c7cf160d23aac425e544bee812f1d8a6c0418c29020d69e2422175098bbbddfd | ['3b50e4d8fbbe4b6399b5deb75d63fea3'] | I'm working through a book and have come to an issue. it's a top down shooting game that has the player rotate with the mouse and move with the keyboard. problem is when testing if either the mouse or the keyboard set off movement the image vibrates. If i push the arrow keys it moves in a circle the longer I hold the key the wider the circle. Below is the script I'm working with.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlayerBehaviour : MonoBehaviour
{
//movement modifier applied to directional movement
public float playerSpeed = 2.0f;
//current player speed
private float currentSpeed = 0.0f;
/*
* Allows us to have multiple inputs and supports keyboard,
* joystick, etc.
*/
public List<KeyCode> upButton;
public List<KeyCode> downButton;
public List<KeyCode> leftButton;
public List<KeyCode> rightButton;
//last movement made
private Vector3 lastMovement = new Vector3();
// Update is called once per frame
void Update()
{
//rotates ship to face mouse
Rotation();
//moves ship
Movement();
}
void Rotation()
{
//finds mouse in relation to player location
Vector3 worldPos = Input.mousePosition;
worldPos = Camera.main.ScreenToWorldPoint(worldPos);
/*
get x and y screen positions
*/
float dx = this.transform.position.x - worldPos.x;
float dy = this.transform.position.y - worldPos.y;
//find the angle between objects
float angle = Mathf.Atan2(dy, dx) * Mathf.Rad2Deg;
/*
* The transform's rotation property uses a Quaternion,
* so we need to convert the angle in a Vector
* (The Z axis is for rotation for 2D).
*/
Quaternion rot = Quaternion.Euler(new Vector3(0, 0, angle + 90));
// Assign the ship's rotation
this.transform.rotation = rot;
}
// Will move the player based off of keys pressed
void Movement()
{
// The movement that needs to occur this frame
Vector3 movement = new Vector3();
// Check for input
movement += MoveIfPressed(upButton, Vector3.up);
movement += MoveIfPressed(downButton, Vector3.down);
movement += MoveIfPressed(leftButton, Vector3.left);
movement += MoveIfPressed(rightButton, Vector3.right);
/*
* If we pressed multiple buttons, make sure we're only
* moving the same length.
*/
movement.Normalize();
// Check if we pressed anything
if (movement.magnitude > 0)
{
// If we did, move in that direction
currentSpeed = playerSpeed;
this.transform.Translate(movement * Time.deltaTime * playerSpeed, Space.World);
lastMovement = movement;
}
else
{
// Otherwise, move in the direction we were going
this.transform.Translate(lastMovement * Time.deltaTime * currentSpeed, Space.World);
// Slow down over time
currentSpeed *= .9f;
}
}
/*
* Will return the movement if any of the keys are pressed,
* otherwise it will return (0,0,0)
*/
Vector3 MoveIfPressed(List<KeyCode> keyList, Vector3 Movement)
{
// Check each key in our list
foreach (KeyCode element in keyList)
{
if (Input.GetKey(element))
{
/*
* It was pressed so we leave the function
* with the movement applied.
*/
return Movement;
}
}
// None of the keys were pressed, so don't need to move
return Vector3.zero;
}
}
|
66dda046d4d2664e6504df1042efbff0adc91aafda5008d6a61e8aa46966a5ff | ['3b5401b79acd42c3a39a86f8079677c3'] | Well, ErrorException: Trying to get property 'id' of non-object in file isn't very helpful, could you see the exact line it's talking about? If it means $id = $request->user()->id;, then it seems like id is not part of user(). Maybe try dumping $request->user().
If you are sending user_id and email, then you can just do $request->user_id and $request->email. Are you sure there is an active session?
| 3f1031641f9719d2e820cc4b322064aa3cd1f4f413a9579f20f445fe865f1ad9 | ['3b5401b79acd42c3a39a86f8079677c3'] | It's the port that your server will listen on. So, if you are listening on port 2000, you would go to http://YourDomain.com:2000. Make sure the port you are listening on is open of course! Port 80 is the standard port for http, and port 443 for https.
I commonly see node sites using 8080 (which is an alternative to 80)
|
1f59654c23dbed3645dae0b46511c7a087cd3cb7572b1b354a5210d2e25e0fb4 | ['3b5b3212c68f4ee6b8b346766f51d7f8'] | That does not make a point to log in and logout a number of times to execute test cases if we bind everything in the suite. So I think that cannot be the root cause. Because without pom I tried to run all this in one of my earlier projects. Everything ran properly there. | eb9d1d5bb1ff32e2d8d51fd94ad3833e7697b37ece275e4d05bac2b8417c2c23 | ['3b5b3212c68f4ee6b8b346766f51d7f8'] | A surprising one I learned about recently: If you're in an environment that might be audited you'll want to save all the output of your build, the script output, the compiler output, etc.
That's the only way you can verify your compiler settings, build steps, etc.
Also, how long to save them for, and where to save them?
Save them until you know that build won't be going to production, iow as long as you have the compiled bits around.
One logical place to save them is your SCM system. Another option is to use a tool that will automatically save them for you, like AnthillPro and its ilk.
|
6830d69b2b5e44f93b13117c256b2b0269f2fe351c3460caf44e2a53273ea3c1 | ['3b68b209e2ff4b069dc371e00edd44b3'] | It seems as if i have erred and that the credentials format i stated earlier are for Google App Engine
If you are on Google Compute Engine, you have two options:
Connect to the public IP address of your Cloud SQL instance. This requires you whitelist your GCE instance on the ACL for the Cloud SQL instance.
Use the Cloud SQL proxy. This is a extra daemon you run on your GCE instance that allows you to connect via TCP on localhost or a socket.
| da4b6d0bdb2c9fe4a324fd65edb476d0715387f56c18618de69ce6c464957afa | ['3b68b209e2ff4b069dc371e00edd44b3'] | Looking for a best practice solution.
I currently have metatags in my script to show Open Graph metadata when forwarding links from the webpage.
All icons are 112x112 ie square and these come out v well on WhatsApp etc.
They also come out well on Facebook when inputted into the NewsFeed.
However - if i try and forward that feed via Facebook Messenger - the image is of different dimensions and seems like i need a higher resolution.
What script adjustments would one need to accomodate for this? I don't want to have to redefine, or add newer images.
Thanks
|
22df07c5d86e15ec22d13662fb5f4ec48cac03f03d4edb3e343709cf9935c2d4 | ['3b838ce7c1074a47b13cdcf177562dad'] | This version addresses an issue raised by <PERSON> and is capable of dealing with a long with an arbitrary number of bits.
After the necessary precautions treating non-positive arguments, we calculate the log of the argument in base 2 and change the log base to base 10 by multiplying by lod_10(2).
The number of digits from the base 10 log of 2 must be chosen accordingly. The following version is good from 1 to 1000 bits longs, uses no floating point, one integer multiplication, one interger division and a maximum of N-1 shifts, where N is the number of bits of the argument.
/*
* Using 3 digits from log_10(2), we have enough precision to calculate the
* number of digits of a 1000 bit number.
*/
/* #define LOG_10_2 301029995663981198 */
#define LOG_10_2_NUMERATOR 301
#define LOG_10_2_DENOMINATOR 1000
long get_num_digits3(long a)
{
long c;
long i;
if (a == 0) {
return 1;
}
if (a < 0) {
a = -a;
}
/* i = log_2(a); */
i = 0;
while (a) {
a >>= 1;
++i;
}
/* c = log_10(a) + 1 */
c = (long)(LOG_10_2_NUMERATOR * i);
c /= LOG_10_2_DENOMINATOR;
++c;
return c;
}
| 43c1ae7750a22ea855740ea0ebdfc47f141e4d2d1499ba3ec519ecf14f195bd9 | ['3b838ce7c1074a47b13cdcf177562dad'] | The definition of independent events requires that
P(A B) = P(A) . P(B) [equation 1]
In this case, we have
P(A|B) = P(A) [equation 2]
By definition,
P(A|B) = P(A B) / P(B) [equation 3]
Combinig equations 2 and 3, we obtain
P(A B) / P(B) = P(A) =>
P(A B) = P(A) . P(B)
Which is equation 1. So the answer is P(A|B) = P(A) implies independence.
Notice that only one of P(A|B) = P(A) or P(B|A) = P(B) is necessary, because what has been shown is that P(A|B) = P(A) <=> P(B|A) = P(B) <=> P(A B) = P(A) . P(B).
Also notice that changing the number of students changes the probabilities, so the answer to your second question is that no, the original relationship does not hold for any value of probability. The values of the probability are what define the events to be independent.
|
a3c06c3c878396467c12c2ec81602d8d85645280ea9ea56b1a7caff42685e72e | ['3bbd286690124ef88e7e4736c964aa29'] | I want to create a Document in Google Drive from a BLOB generated from another document.
I've tried this simple example :
var doc = DocumentApp.openByUrl("https://docs.google.com/document/d/[My document]/edit");
var docContentBlob = doc.getBlob();
var newDocBlob = Utilities.newBlob(
docContentBlob.getDataAsString(),
"application/vnd.google-apps.document",
"TEST DOC BLOB");
This script create a document, but I can't open it (it display 'Loading, please wait' when I try to open the document and It never opens.
Why this script don't work?
| d872701f1c27db203e66b6df7ea7aee05a9ddf6bf4cef3ebafd085a1f417ba85 | ['3bbd286690124ef88e7e4736c964aa29'] | According to Google Apps Quotas guide : "Service using too much computer time for one day : This indicates that the script exceeded the total allowable execution time for one day. It most commonly occurs for scripts that run on a trigger, which have a lower daily limit than scripts executed manually."
Triggers cannot run for longer than 30 seconds.
Your script might exceed this execution time.
|
654cc9065e3a75864b6760b7ec515fab0d3ae63c507f6372c6b5b93547f20e40 | ['3bc117a7921e419f90f5af2cdddae30d'] | I recommend to read capter: Embedding Controller
http://symfony.com/doc/2.0/book/templating.html
<div id="sidebar">
{% render "AcmeArticleBundle:Article:recentArticles" with {'max': 3} %}
</div>
You can make a for loop within Twig Template and call an action (with parameter if needed) where you render the form. -> QuestionsAction in your case.
| 464edf51027b6f7de23cf2b8fbb9783eb9035911dce5b24fe29c4ba36f2515b5 | ['3bc117a7921e419f90f5af2cdddae30d'] | Since you're talking already about steps within your form process I suggest to use the CraueFormFlowBundle for this. Here you have the possibility to build a form type for each step in your form process. https://github.com/craue/CraueFormFlowBundle
You could solve the problem as follows:
Order Entity:
User (N Order has 1 User)
Collection of BikesOrders (1 Order has N BikeOrder)
(Maybe total price)
BikeOrder Entity:
OrderEntity (N BikeOrder has 1 Order)
BikeEntity (N BikeOrder has 1 Bike)
Quantity
All your settings (e.g. height, ...)
Bike Entity:
Name
Brand
...
That's just a way you can do relations with orders and products. Customize it to your needs - especially if you want bidirectional or unidirectional association mapping is up to you.
|
f51bc3201e12519c18bae348deafbf7dc57a9b9c3b1cbd9201c5dca358cfee82 | ['3bd3bf2720a74fd7a0d2363c9e5a36aa'] | The uncertainty in the multimeter is the measurement uncertainty. The apparatus that you use will always have some sort of uncertainty associated with them; this has nothing to do with the resistor. The resistor will have its own tolerance.
The tolerance and the uncertainty however, will propagate together to create a larger uncertainty in the value of your resistor.
| 24c59385572709fb90e302984158fab5a81aab0ded24056a82500fc9a1012032 | ['3bd3bf2720a74fd7a0d2363c9e5a36aa'] | Есть таблица, вот кусок:
<tbody>
<tr><td><label><input type="checkbox" class="checkbox2"><span class="checkbox-custom2"></span></label></td><td>27.04.2017</td><td>28.04.2017</td><td>118725-31521</td><td></tr>
<tr><td><label><input type="checkbox" class="checkbox2"><span class="checkbox-custom2"></span></label></td><td>27.04.2017</td><td>28.04.2017</td><td>118725-31521</td><td></tr>
<tr><td><label><input type="checkbox" class="checkbox2"><span class="checkbox-custom2"></span></label></td><td>27.04.2017</td><td>28.04.2017</td><td>118725-31521</td><td></tr>
</tbody>
нужно чтобы по клику на строке выбирался чекбокс этой строки. Помогите пожалуйста.
P.S> стиль чекбоксов заменён на свой
|
55ec68ccb88b01020122d928b2b84679bf1e9eb4321f7b8c1f40605f60b48382 | ['3bedf55cce454e06aae5be2c530c9b9b'] | I develop an application with WebKit-based forms and it’s important that, when on a form, a user can press Backspace without returning to previous page. How do I do this in QtWebKit?
I found out that one can inherit a class from QWebPage and overload QWebPage<IP_ADDRESS>triggerAction() to selectively filter out events, e.g. QWebPage<IP_ADDRESS>Back. Nevertheless, it works only on the first page, and if you open another page in the same webview child the triggerAction() overload will not be called.
| 526bde56e474fe9ea93dda9e2c8ea9e90d6a59ac6e1ea9782d72fbc59ff5d0fd | ['3bedf55cce454e06aae5be2c530c9b9b'] | The problem is due to bug in the dynamic RTL which I use in the release build (description). The bug was not fixed in the version of IDE I use, so the only working solution is to upgrade to a higher version. Nevertheless, having a clear explanation helps a lot.
|
e7ef907bc1304d3ae894d656aae3f4425f39b0a0f1fb062ca878a3a7830f5405 | ['3bfc7400a6414118bd045619e31157a0'] | For languages which don't support a block-comment syntax (e.g. /*...*/ vs // in C), "Un/Comment Block" and "Un/Comment Lines" are functionally the same.
There are some ...curiosities involving how spaces are managed after line comment delimiters. If the declared delimiter for the language has trailing spaces, BBEdit tries to figure out what you wanted to do. Some languages care and some don't; and sometimes the outcome has relevance to the language's syntax. It's an area for future study. :-)
| aec4348edd9e4f5c22aa93f0e6f1ed45cbe10a86fb2248678347419d851fcd29 | ['3bfc7400a6414118bd045619e31157a0'] | The language setting is in the status bar at the bottom of the editing view. For new untitled documents it says "(none)", click there to open a menu from which you can choose your desired language.
If you always want a specific language for untitled documents, there is an expert preference, which you can set with this Terminal command (for example, setting it to Markdown):
defaults write com.barebones.bbedit DefaultLanguageNameForNewDocuments -string "Markdown"
In quotes instead of "Markdown" you can use the human-readable name of the language as it appears in the menu.
|
25c4b366b9b7bfa14805e4f71aa67cbabcd74d8cfe0c3744fc17f51225f2a0c2 | ['3bfd0d64c3bf43d8a24e1f8fe08a9d65'] | I have a problem in my symfony 1.4 using CKFinder. My CKFinder is used to create a custom message for email template. But now I need to put an attached piece in the mail. So I saw the CKEditor can help me to do this. I activate the file in CKFinder and I can upload a file in the server.
But after sending my email the link which created in the message was not good. I have in the page this message: "Cannot GET /js/ckfinder/userfiles/files/myfile.pdf "
So I try an other url with the path of my application (like this "http: //localhost/web/js/ckfinder/userfiles/files/myfile.pdf" in localhost. But he redirect me on login page in my application.
I try to find the best url to access at my file but unfortunately I failed :(.
Someone can help me please ?? I have no more idea to resolve my problem.
I have this parameters in config.php:
$baseUrl = '/js/ckfinder/userfiles/';
$baseDir = resolveUrl($baseUrl);;
$config['ResourceType'][] = Array(
'name' => 'Files', // Single quotes not allowed
'url' => $baseUrl . 'files',
'directory' => $baseDir . 'files',
'maxSize' => "16M",
'allowedExtensions' => '7z,aiff,asf,avi,bmp,csv,doc,docx,fla,flv,gif,gz,gzip,jpeg,jpg,mid,mov,mp3,mp4,mpc,mpeg,mpg,ods,odt,pdf,png,ppt,pptx,pxd,qt,ram,rar,rm,rmi,rmvb,rtf,sdc,sitd,swf,sxc,sxw,tar,tgz,tif,tiff,txt,vsd,wav,wma,wmv,xls,xlsx,zip',
'deniedExtensions' => '');
$config['AccessControl'][] = Array(
'role' => '*',
'resourceType' => '*',
'folder' => '/',
'folderView' => true,
'folderCreate' => true,
'folderRename' => true,
'folderDelete' => true,
'fileView' => true,
'fileUpload' => true,
'fileRename' => true,
'fileDelete' => true);
| 86fcba7f2803283f94911559ff6ae339614676bf2dc870757fbb5b4f4b1bd782 | ['3bfd0d64c3bf43d8a24e1f8fe08a9d65'] | I'm working on PHPExcel Library on symfony!! I work on how to create a comment in a cell on my excel file. With the documentation I know how I can create a comment in mys excel file with this:
$objCommentRichText = $objPHPExcel->getActiveSheet(0)->getComment('E5')->getText()->createTextRun('My first comment :)');
And it's work perfectly!! But now I try to modify the comment in cell E5 (who has comment "My first comment :)"). I just want to replace this comment by another one. I try something like that:
$objPHPExcel = PHPExcel_IOFactory::load($file);//On lit le fichier avec la librairie excel
$sheet = $objPHPExcel->getSheet(0);
//$objCommentRichText = $objPHPExcel->getActiveSheet(0)->getComment('E5')->getText()->createTextRun('My first comment :)');
$objCommentRichText = $objPHPExcel->getActiveSheet(0)->getComment('E5')->setText("My 2nd comment");//here I try to modify the comment
$objCommentRichText->getFont()->setBold(true);
$styleArray = array(
'font' => array(
'color' => array('rgb' => 'FF0000'),
'name' => '<PERSON><IP_ADDRESS>load($file);//On lit le fichier avec la librairie excel
$sheet = $objPHPExcel->getSheet(0);
//$objCommentRichText = $objPHPExcel->getActiveSheet(0)->getComment('E5')->getText()->createTextRun('My first comment :)');
$objCommentRichText = $objPHPExcel->getActiveSheet(0)->getComment('E5')->setText("My 2nd comment");//here I try to modify the comment
$objCommentRichText->getFont()->setBold(true);
$styleArray = array(
'font' => array(
'color' => array('rgb' => 'FF0000'),
'name' => 'Verdana'
));
$objPHPExcel->getActiveSheet(0)->getStyle('E5')->applyFromArray($styleArray);
$writer = PHPExcel_IOFactory<IP_ADDRESS>createWriter($objPHPExcel, "Excel2007");
But it doesn't work :(. I try other but not work again... Someone can help me please ? Or have an idea to modify a comment ?? It will be great!
|
97ab620a0517d2e529449abddb8223e149b88dd98955716f61c28efa88388266 | ['3c02d6160cef40919458078c0e80e857'] | Using an extension such as Greasemonkey, you can add a new script containing a bit of javascript.
// ==UserScript==
// @name All Links in New Tab
// @namespace *
// ==/UserScript==
(function(){
var script = document.createElement("script");
script.type = "application/javascript";
script.innerHTML = "$(function(){$('a').attr('target', '_blank');});";
document.body.appendChild(script);
})();
The asterisk allows the script to be run on all websites.
| 3ff9b2a9daccc7fa6b0430cd3928dd647168b44a71a5c0e6c9fc1ea6871906ae | ['3c02d6160cef40919458078c0e80e857'] | Есть таблица продления длительности логинов пользователей:
id,login,date_prolong(дата когда продлили),date_finished (дата когда заканчивался логин),time_added (время на сколько продлили)
Задача отчета - в период от даты 1 до даты 2 (смотрим на дату окончания логина) выбрать какие логины продлялись, какие нет, и на сколько.
Как пытаюсь решить:
SELECT * FROM stb_prolong LEFT JOIN
( SELECT date_prolong as last_prolong_date, date_finished as date_ended, p.login, time_added as this_prolong_time_added FROM stb_prolong p
INNER JOIN (
SELECT login , min(abs(UNIX_TIMESTAMP(date_prolong)-UNIX_TIMESTAMP( stb_prolong.date_finished )) ) as diff
FROM stb_prolong
GROUP BY(login)
) mx ON mx.login=p.login AND mx.diff = (abs(UNIX_TIMESTAMP(p.date_prolong)-UNIX_TIMESTAMP( stb_prolong.date_finished )) )
GROUP BY(login)
) a ON a.login =stb_prolong.login
WHERE date_finished >'2018-12-01' AND date_finished < '2018-12-31'
Т.е. я для для каждого логина пытаюсь найти строчку из той же таблицы с ближайшей к дате окончания логина датой продления, для чего сначала ищу ближайшую дату
min(abs(UNIX_TIMESTAMP(date_prolong)-UNIX_TIMESTAMP( stb_prolong.date_finished )) )
еще одним подзапросом.
Но во вложенных подзапросах у меня поля stb_prolong.date_finished нет, что логично. Как бы его туда "протащить"?. Ну или вообще буду раз если подскажете вообще новый подход к решению.. И да, это mySQL.
|
307a07afa42145262f373f83bb1ed9790691a1d1646d7a40119601bbe838757b | ['3c0e6f8b2c17462198d4a260a8569205'] | I have a custom ros node, that subscribes data from robot-joints. in order to access the joint data, I have a None variable to which the joint positions are being assigned during function callback. Now, the problem is , i can only access that variable when the subscriber is running, once its stopped, the variable is being reset to None. If the ros node keeps running, my program can not skip to the next line unless this loop is stopped. So i am either struck with this loop where I get all this data printed through loginfo or if i remove the line rospy.spin(), in the next lines where I am using that position stored data, its returning None as the node is stopped. Can anyone please suggest me a work around for this ?
def callback(data):
Position = data.position
I am using this callback in the subscriber
I want to access the position values of the robot when I call position, as I have assigned data.position to position. but its returning None, I believe its because, since position is None type, it only gets the data.position values assigned to it as long as the node is spinning or running, once its stopped it might be getting reset to None. but if i let it keep spinning using rospy.spin(), my program does not move forward to the next step as it gets stuck in the infinite loop of rospy.spin
| 7afce0dc5ce295c7166b9daea5876bf2fc4045b1b58d4f149952bab172a8c38e | ['3c0e6f8b2c17462198d4a260a8569205'] | I believe it might a python path related issues. when you do such binary installations, in general those packages get installed in dist-package file of the respective python either python 2.7 or python 3. And ros-kinetic uses python 2.7 for its basic commands such as roslib and rospy. So please try to check whether the installed netifaces are in the same pythonpath, if not try to export python path before launching the file.
<PERSON> please try to check the python path from the terminal you are launching your file, that way you will know which python paths are imported, if python3 path is not imported, please try to export that path aswell.
|
38e013489d7805b4ffe41cfabec7bb9f395d80d10da05ee213e34de24f8d66d2 | ['3c34a49dd38644d58935e776bb0c113a'] | You can use function array_filter, so in php 5.3 code will looks like this:
$data1 = array(40, 'P1');
$data2 = array(70, 'P3');
$data3 = array(35, 'P2');
$data4 = array(55, 'P3');
$data5 = array(25, 'P1');
$data = array($data1, $data2, $data3, $data4, $data5);
$result = array_filter($data, function($_item) {
return $_item[0] > 50;
});
| 2ad06d387f0b574a3a0ba5eb6be62c78643e01697e2db6ce44bbc9eac5f80cc0 | ['3c34a49dd38644d58935e776bb0c113a'] | Datepicker stores value only in input element, so if you don't have a year in format string, datepicker merely doesn't store it. Here one of jquery.ui developers says, that this is not a bug and "Datepicker is only designed to pick a full date".
Anyway, I had the same problem in my project, and solved it by ugly trick, that forces datepicker to store full date:
(function($) {
$.datepicker._selectDateParent = $.datepicker._selectDate;
$.datepicker._adjustInstDateParent = $.datepicker._adjustInstDate;
$.datepicker._adjustInstDate = function(inst, offset, period) {
var fullDate = inst.input.data('fullDate');
if(fullDate && !period) {
inst.drawYear = inst.currentYear = fullDate.getFullYear();
}
this._adjustInstDateParent(inst, offset, period);
};
$.datepicker._selectDate = function(id, dateStr) {
var target = $(id);
var inst = this._getInst(target[0]);
var date = this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay));
inst.input.data('fullDate', date);
this._selectDateParent(id, dateStr);
}
})(jQuery);
I've tested it only with datepicker 1.9.0+ and I'm not sure, that this is a good solution, but it works for me :)
|
ad3f8fc231f7a54e181c2ba9b42db49fbb8c9049b6d9c8ec2ab6caae973c9cf8 | ['3c38a52dd9cb4eed8ce6e085c291a645'] | {
geometry:
{
location:
{
lat: 20.012256,
lng: 73.761541
}
},
icon: "http://maps.gstatic.com/mapfiles/place_api/icons/fitness-71.png",
id: "3e59d6a764e44c969e632c659e0d4284e7bd2561",
name: "<PERSON> & GARBHASANSKAR",
photos: [
{
height: 1024,
html_attributions: ["From a Google User"],
photo_reference: "CpQBjQAAAIn74syEAB4wtDfRxQqHrEuETcQYYJ2PgAy-uCtQ5UjSsfmWhGLvij6zL4rdHCEUSHOvKOyyhcOO7N-i-mcYpAjZKMNgbfNEaBNWPPRl6MTRf3BHb8DZ8i8bO-F3-IVF5kEvo4-8GQwDGsvNiIXdmkyTi0ugzo0Tj3K9Zicy-cakr25sgy8Mp-UeBqyPABv_AhIQIJzI11nBcIQWVHPBnSVMihoU69ou9PsrnIrvldruNVJma9EGnRU",
width: 768
}
],
place_id: "ChIJmx2FRZDr3TsRgNITjVbXAyU",
reference: "CpQBhQAAAH6wIR1m39e0NaDGqSvFAb6LHjcY3YzZbHJV33RRScqspe4s6NPNpMQZbufkMHhDv7-zhbYriOct-s1jX1Uy_tP4a6cgPboaBITMpgLR_uQO7j-k8ngDgvYuIeU70So0m-RygRMwK5Wsxj-j-dW6UswEIGiyctBvWD_eIW7j1dHh9GfS1YhBGAjDcEZuAOjNARIQOgtBWeqaHi6rPsZgc7g9TBoUBuz5fgZnaIwkGgZP8MiZG97fRl0",
scope: "GOOGLE",
types: [
"gym",
"health",
"establishment"
],
vicinity: "'<PERSON>, 37, Kamal Society, Near Kusumagraj Pratishtan, Gangapur Road, Na, Nashik"
}
I am using following web service through which i want to access the photo_reference to get the image, API is in JSON format.How can i retrieve the image from photo_reference
Thanks in advance.
| 1550d39ab0c156aa3d227c268930e4e1561fc0e97f31e878c4ed8b79de0a3eb7 | ['3c38a52dd9cb4eed8ce6e085c291a645'] | -(void)setFlagToZero:(BOOL)flg id:(NSString *)qid
{
NSLog(@"flag %hhd and ID:%@ ",flg,qid);
sqlite3 *database;
quiz = [[NSMutableArray alloc] init];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
const char *sqlStatement = &"UPDATE Question set Question_Flag="+flg+"where question_ID="+qid;
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
NSString *aQuestion = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
}
}
else
{
NSLog(@"Error occured in connection");
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
@end
it is showing error as below
Invalid operands to binary expression ('char (*)[36]' and 'char *')
please help me with the corrected code.
|
7250c569f92029d642e98f5471d47ce725b6f4e3730b0c9280fcb1e80ca17f06 | ['3c3f922ba98d41a7be4b6091fe339fca'] | you could try something like this to avoid runtime errors:
if let actualPath = path, !actualPath.isEmpty, let url = URL(string: actualPath) {
if let imageData = try? Data(contentsOf: url) {
if let image = UIImage(data: imageData) {
self.images.append(image)
}
}
}
instead of this
if!path!.isEmpty {
let url = URL(string: path!)!
let imageData = try? Data(contentsOf: url)
let image = UIImage(data: imageData!)!
self.images.append(image)
}
| 20ac74c8a1b905b8660793439c62d71be7b7fd0a605767a29fa6322beb87d337 | ['3c3f922ba98d41a7be4b6091fe339fca'] | Solution (based on <PERSON> answer) for SHA256 hash:
func sha256(url: URL) -> Data? {
do {
let bufferSize = 1024 * 1024
// Open file for reading:
let file = try FileHandle(forReadingFrom: url)
defer {
file.closeFile()
}
// Create and initialize SHA256 context:
var context = CC_SHA256_CTX()
CC_SHA256_Init(&context)
// Read up to `bufferSize` bytes, until EOF is reached, and update SHA256 context:
while autoreleasepool(invoking: {
// Read up to `bufferSize` bytes
let data = file.readData(ofLength: bufferSize)
if data.count > 0 {
data.withUnsafeBytes {
_ = CC_SHA256_Update(&context, $0, numericCast(data.count))
}
// Continue
return true
} else {
// End of file
return false
}
}) { }
// Compute the SHA256 digest:
var digest = Data(count: Int(CC_SHA256_DIGEST_LENGTH))
digest.withUnsafeMutableBytes {
_ = CC_SHA256_Final($0, &context)
}
return digest
} catch {
print(error)
return nil
}
}
Usage with instance of type URL with name fileURL previously created:
if let digestData = sha256(url: fileURL) {
let calculatedHash = digestData.map { String(format: "%02hhx", $0) }.joined()
DDLogDebug(calculatedHash)
}
|
7e958f757d2d2570fb1561d9854d9e03820c2b7ab9009774d48958914f76841a | ['3c51cd3eda62492085ec70859a3772e8'] | Sorry maybe I didn't properly explained it. v1 and v2 are positive functions defined on a subset of C( the complex plane) and I know both of them are of C2, and both log v1 and log v2 are subharmonic. Now I was asked to prove that log (v1+v2) is also subharmonic.(Forgive me I don't know how to type formulae on the cellphone) | 44036e1e5c54ca2bdff6a2a323d578d80f794a9f9ddf791fd6029e9bb7864933 | ['3c51cd3eda62492085ec70859a3772e8'] | I see the same issue with a Logitech M325 mouse. This is NOT a Bluetooth mouse; it uses the Logitech Unifying Receiver.
So I don't think it's a Bluetooth-related issue, but more likely something to do with GNOME and its underlying architecture for storing and applying hardware configuration settings.
Interestingly, this issue doesn't affect the touchpad on the same laptop. Possibly that's because the touchpad is always attached whereas the mouse is attached only when the laptop is docked (the Unifying Receiver is plugged into a USB port on the dock).
FWIW, KDE has a history of similar problems. I never saw this on GNOME until upgrading from Fedora 32 to 33 (and upgrading GNOME to 3.38.1).
Incidentally, you can toggle the setting in a terminal or a script with these commands:
$ gsettings set org.gnome.desktop.peripherals.mouse natural-scroll false
$ gsettings set org.gnome.desktop.peripherals.mouse natural-scroll true
|
5992c463e8710a1e759c86ddfac2b9244b1590b24f518be1b283db8e7d24bb18 | ['3c5ce38a42e74c879728f10240ee6df0'] | I have 6 edit texts on my screen (used to enter 6 digits)
If I enter 1 digit on one EditText field the focus should go onto the next one and so on.
If I hit back space on some edit text field the focus should come to the previous edittext field
For this I used the below code
EditText2.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (EditText2.getText().toString().length() == 1) {
EditText3.requestFocus();
}
else if (EditText2.getText().toString().length() == 0) {
EditText1.requestFocus();
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
}
});
Normally , the ontextchange listener works if I don't hit a backspace on any of the edit texts. If I hit backspace on EditText2 and land on EditText1(some value on it is present) and try to enter something on it. The cursor is not going to EditText2 as addTextChangedListener not working.
Any help is greatly appreciated.
| 4b553aef84eae6f4be96278a1f5920f8e18125b5ec0e2fc7ae9b07b24d2f48ac | ['3c5ce38a42e74c879728f10240ee6df0'] | Trying to solve a leetcode problem of "valid palindrome" below is the code . when I convert the stringbuffer to string and to lower case the string is getting printed as all lower case letters, but when I access it for comparisons using s.charAt(i), I am getting the uppercase letters as well.
public static void main(String []args){
String s = "aA";
String[] strings = s.split("[^A-Za-z0-9]");
StringBuffer sb = new StringBuffer();
for(int i =0; i<strings.length;i++){
sb.append(strings[i]);
}
String newString = sb.toString().toLowerCase();
System.out.println("New String "+newString);***// output : aa(lower case)***
for(int i =0; i<newString.length()/2;i++){
if(s.charAt(i) != s.charAt(newString.length()-i-1)){
System.out.println(s.charAt(i));//**output 'a**
System.out.println(s.charAt(newString.length()-i-1));//***output 'A'***
}
}
Can someone please explain why?
|
864a754a9f2d3e0ab8ccabdb33abaeef97ea468cf46468b0462c3e4d82e3e4bf | ['3c72899cf17045ae98886ed7980bfb62'] | The fix for me was to configure SQL server to allow an unlimited number of connections (set to value of "0"). I still had a few connection issues as described in the original post, but no where near as much. So I also setup a direct connection to the SQL server via the secondary Ethernet port on each server (Webserver to SQL Server),and kept the connection private using 196.168.1.x between the servers, and using it's own Ethernet switch not connected to the public switch.
| d88b93ff29f83e2ab3adcba1d3dc7a777700248cae2660baf7d1f860c9677cde | ['3c72899cf17045ae98886ed7980bfb62'] | Allaire's HomeSite 4.5 is what I have been using for about 20-years. I've tried NotePad++ and it works pretty good also, but is a bit more difficult to use. I also tried several versions of Visual "XXX" (Visual Studio, Visual Code, etc.) and all of them are monster programs, and load very slow, even on a very fast R610 server. Unfortunately, HomeSite is hard to find, as it is now owned by Adobe, and they have pretty much killed it. If you do find HomeSite, don't use the 5.0 or 5.5 versions, as they crash intermittently. HomeSite v4.5 is very stable.
|
6a55bf1a7410c7c0f91eb27a80298018860ff2f63be05e66201b0f3f6f2637f6 | ['3c72a584e3c247fb945e172f9773763b'] | When generating worlds that are old (1k-10k years), I have a very hard time stopping civilizations dying out and every fortress I visit in Adventurer mode is abandoned.
What aspects of world generation effect fortress abandonment and creation? Can you have an old world without many abandoned fortresses, or are they just abandoned as time progresses.
What greatly effects civilizations dying out? How can I generate an old world that has a balanced amount of beasts to civilizations? (i.e. not end up without any beasts nor without any people)
| 818e9a04c40365bd4fd247941cbe279b33b7422a897509c17ce55c67d92ea6d2 | ['3c72a584e3c247fb945e172f9773763b'] | You can rebel if you like, but this particular train is pulling out of the station. Not only is it becoming common for lay people and "partly computer-savvy" people to use *zip* generically, but programs that handle multiple formats are also becoming more widespread. If you had simply given your daughter 7-Zip (for example), she could have opened a huge plethora of file types, including ZIP and RAR. Even the dominant "brand-name" software, WinZIP, opens RAR these days (and is available as a free trial). |
8bdb336904805879b19f2271c70d66393106ea953f8f781f332064824504146e | ['3c837a0145b146bda2c9fbf9753fb65a'] | Django's manage.py runserver by default forks a child process from the main process.
If you add print('PID:', os.getpid(), 'Parent PID:', os.getppid()) to your __init__.py you will see that you get 2 numbers each line, the PID and the parent thread PID.
The output should look like this, more or less:
PID: 31019 Parent PID: 30633
PID: 31020 Parent PID: 31019
What you see here is the following:
30633 = shell PID.
31019 = manage.py runserver parent process.
31020 = manage.py runserver child process.
The reason actually lies in the default runserver behavior, to use a reloader. What it does is basically boot up manage.py runserver as a parent process. if you did not specify the --noreload option, then it will spawn a child manage.py runserver process.
After doing that, the parent runserver will track code changes so it can kill and reload the child process.
If you run manage.py runserver --noreload you will see that you get only one line of PID, Parent PID.
For more information about this, you can dig into Django's runserver command that resides in django.core.management.commands
| 54a7ec10673bc2863e9234c1154b3c74bf18091627ee42ed6c0c8d63acf5f81f | ['3c837a0145b146bda2c9fbf9753fb65a'] | I am a bit confused regarding metaclasses in case of multiple inheritance.
Consider the following code:
class MetaClass1(type):
def __init__(cls, name, bases, dict_):
print "MetaClass1"
class MetaClass2(type):
def __init__(cls, name, bases, dict_):
print "MetaClass2"
class A(object):
__metaclass__ = MetaClass1
class B(object):
__metaclass__ = MetaClass2
class C(A, B):
pass
The output of this will be the following:
"MetaClass1"
"MetaClass2"
TypeError regarding metaclass conflict, which is expected, no problems regarding this.
Next I will change the code a bit and do the following:
class MetaClass1(type):
def __init__(cls, name, bases, dict_):
print "MetaClass1"
class MetaClass2(MetaClass1):
def __init__(cls, name, bases, dict_):
print "MetaClass2 inherits"
super(MetaClass2, cls).__init__(name, bases, dict_)
class A(object):
__metaclass__ = MetaClass1
class B(object):
__metaclass__ = MetaClass2
class C(A, B):
pass
This time the output is going to be:
"MetaClass1"
"MetaClass2 inherits"
"MetaClass1"
"MetaClass2 inherits"
"MetaClass1"
The MRO of class C is:
[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>]
Why does class C receive MetaClass2 as its metaclass and not MetaClass1?
|
e685b39dfb86bffe8809c1a194ac5647faf7f92737b88881c8c70d7d239687d1 | ['3c8e477e72d0471a8663be4c75aeb4fe'] | I am trying to create a RadioButton in android. My requirement is that the label should be always left aligned and icon should be right aligned(evenly distributed, as first item in attached screenshot). I was able to achieve it. But this is not working when the label has no character and only digits between 0 to 9.
I also tried adding space, but no luck.
Can someone please help?
<RadioButton xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listRadioItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_weight="1"
android:ellipsize="end"
android:layoutDirection="rtl"
android:maxLines="1"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:text="123"
android:layout_gravity="start"
android:textAlignment="textStart" />
| f749b6ad61f859dc1eb25ec79b015ffdd07a0d84fb1aca4730d9c4393c023aec | ['3c8e477e72d0471a8663be4c75aeb4fe'] | An optgroup can't be made selectable. Only mat-option can be selected. But we can use a workaround by keeping all items in the select as mat-options and add some custom style to differentiate groups. You can refer the accepted answer for a similar question from this link.
Or you can think of using ng-select (link), Groups can be made selectable.
|
4638ed294dc7b50fc24aa497a50348d9cd939d2d141a0c25e3571fbb26986198 | ['3c99eb58eb8e4ef089d9b8d60e56d26f'] | This is a question I came across while going through some questions on alchemy puzzles. It seems pretty hard for me.The question stands:
You are studying alchemy and want to create the philosopher's stone. You have a grimoire full of recipes for the transmutations. Being methodical, you numbered all ingredients starting from 0, and wrote down all the transmutations in terms of ingredients required to perform them and their products. Thus, for each recipe t from the grimoire you know that it requires ingredient[t] ingredients, and that it produces product[t] ingredients after the transmutation.
You can perform a transmutation t only if you have enough ingredients in your inventory. More formally, for each ingredient i it should be true that inventory[i] ≥ ingredient[t][i].
When the transmutation is performed, the ingredients are consumed and the products are created. More formally, for each ingredient i your inventory changes as follows:
inventory[i] = inventory[i] - ingredient[t][i] + products[t][i]
You want to compute the shortest sequence of transmutations that produces the stone. Find the number of transmutations in the order they should be performed.
It is guaranteed that it is possible to create the philosopher's stone.
The shortest solution is guaranteed to be unique.
for ingredients=
\begin{bmatrix}
0 & 8 & 0 & 0 & 0 & 0 \\
0 & 0 & 3 & 5 & 9 & 3 \\
0 & 8 & 2 & 5 & 8 & 1 \\
0 & 3 & 0 & 0 & 4 & 5 \\
0 & 0 & 1 & 4 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 & 0 \\
\end{bmatrix}
and for products=
\begin{bmatrix}
0 & 6 & 3 & 0 & 4 & 0 \\
4 & 4 & 0 & 5 & 3 & 9 \\
0 & 1 & 4 & 3 & 4 & 8 \\
0 & 5 & 0 & 9 & 0 & 0 \\
0 & 4 & 0 & 7 & 0 & 3 \\
0 & 0 & 0 & 0 & 2 & 7 \\
\end{bmatrix}
and for inventory = [ 0, 6, 8, 4, 2, 0 ], the answer is [4,0,0,1]
I just need to understand the mathematics behind this problem and how have they solved it.
| e5bb1440dc94948248ca6f10834ce872aba7e8503bbf2fba06d9a77c232ce887 | ['3c99eb58eb8e4ef089d9b8d60e56d26f'] | I'm trying to compile a kernel module named DAHDI in a FreePBX (RHEL). I get the following make output error:
You do not appear to have the sources for the 3.10.0-957.21.3.el7.x86_64 kernel installed.
But I don't think that is the problem, cuz I already checked my kernel version, headers, config file and they all match. In the Makefile, I have this block:
KCONFIG:=$(KSRC)/.config
ifneq (,$(wildcard $(KCONFIG)))
HAS_KSRC:=yes
include $(KCONFIG)
else
HAS_KSRC:=no
endif
$(KCONFIG) returns "/.config". $(HAS_KSRC) return "no". $(wildcard $(KCONFIG)) doesn't return anything. This error comes from ifeq (no,$(HAS_KSRC)). In other words, it finds the kernel config file until it applies the "wildcard".
What does this wildcard (command??) do?
# cat /proc/version
Linux version 3.10.0-957.21.3.el7.x86_64 (<EMAIL_ADDRESS>) (gcc version 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC) ) #1 SMP Tue Jun 18 16:35:19 UTC 2019
|
c89aa2b49837635030a5798f6559dba5e00dfa4e21c41af6d6dbba04efd202e4 | ['3c9b9c67d7794d0ca07b8177b555aee2'] | I guess if I understood how the circuit in an outlet switch combo works I’d be home free. IF you connect hot to brass side of switch does that provide power to the outlet too, even if switch is off? If so, then I cap off the red as suggested, pigtail black to brass switch and brass line gfci. Then I pigtail white to silver switch, right lower black terminal (for outlet when switch is off) and to silver line gfci. Would that work? | a2d540d1370ad858ffe75f5c49871b84cf4e71a1cc4d336c00019c1431909fe6 | ['3c9b9c67d7794d0ca07b8177b555aee2'] | Wow, this is great, thanks! Only thing I could use clarification on is, aside from removing some of the autogen javadoc, what can be done with Character class? It's for the most part just a giant container that organizes the various stats and container classes, the only thing I could think of doing is making some larger containers to group things in, like a Skills or Sleights class? |
ff4989f0dba741038934f69a421ea98df47bf665ea3ee0f9c46ba622df3322dd | ['3c9f13c6eef347449e2cf061d6755eaa'] | Thanks <PERSON>. As I mentioned in my comment to your comment above, we van just totally drop the "cheater" word and choose "random selector". Another clarification is that I'm not seeking certainty in my decision, I just want to have an idea about the highest possible ratio between ones with odd answers, and those who gave the same answer of majority of the test takers, at which I can say there is really really a huge possibility that those with the odd answers were just randomly picking answers. One last thing, would you kindly simplify your answer as I'm not a statistician. | 47f480554280ce9c111effdce8fd600d33e8cef027dc22b606e67336fb223824 | ['3c9f13c6eef347449e2cf061d6755eaa'] | @whuber my question is just a hypothetical question to illustrate the scenario. But anyway I can modify it to be deciding if the color of a given cube is black or white. If 999 said it was black and only one said it was white, do you think that there's any other possibility that this person is either blind or selecting answers randomly? |
45132c00ca7f6cd5031e038d6e2d0eb33e95ff56198faae42cc4504900dd1322 | ['3c9f5501972548d887a18ce4295d0f5b'] | i'm trying to send a request to a webservice. For the requet i'm using this code. The testMessage must be correct, because with SOAPUI the same request is working.
StringEntity stringEntity = new StringEntity(testMessage, "UTF-8");
stringEntity.setChunked(true);
String endpointURL = "http://host:8000/wsdl";
String soapAction = "urn:anyAction";
HttpPost httpPost = new HttpPost(endpointURL);
httpPost.setEntity(stringEntity);
httpPost.addHeader("Accept-Encoding", "gzip,deflate");
httpPost.addHeader("Content-Type:", "text/xml;charset=UTF-8");
httpPost.addHeader("SOAPAction", soapAction);
String authorization = "user:pass";
String header = "Basic " + new String(Base64.getEncoder().encode(authorization.getBytes()));
httpPost.addHeader("Authorization", header);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
I always getting a fault response:
soap error message
I do not understand this message or what should I do... I have the correct wsdl url (it works with SOAPUI).
Thanks for help!
| f5abf40434449936204c2b2808debfdad19ee100bf78b290d32c63a9a7da8f92 | ['3c9f5501972548d887a18ce4295d0f5b'] | i've got a question for my study stuff: I have to decrypt a file(src-cipher.bin) using C. I have a corrupt key corrupt-src-key.bin (an initial vector is at the end of the file - dont know if i should this vector- maybe dont have to). final decrypted file should be a *.pdf one and it was encrypted with Camellia-192-OFB (openssl EVP_camellia_192_ofb() ). Byte number 23(start counting from 0) was set to 0. Now i have to write a small C app which decrypts this file. At least ive got 2 more files(src-cipher.bin and dest-key.bin)). Thanks very much for help. If someone is interested, i can send the files. Thx
|
a388095032701d352c2d5e169984a340622bc91c6f3bfd69b2b7372b955de99a | ['3ca9c59902d345659b744bb53fec8d69'] | There are two types of contracts:
Contracts, created by ordinary addresses
Contracts, created by othe contracts
And there are three possible ways to find type 2 contracts:
Check every block and every transaction in a block. Take “to” field of a transaction. Get code at address “to”. If code is not empty, than it is a contract. Add it to the database if not exists. Field “from” alway should contain ordinary address. (It is interesting to check if. If it is not, than someone managed to get a private key of a contract). Thus we will find only rhose type 2 contracts, that had any transactions to from ordinary addresses.
Every transaction should be traced via EVM (Ethereum Virtaul Machine) and checked for contract creation. To make this you need to build a specially patched geth or parity node.
Direct reading of node’s database. Database format is specified in geth’s or parity’s source code. It is LevelDB or RocksDB. I’ve failed in this at first. Somehow my db got corrupted and it took several days to rebuild it again. But the work in this direction continues.
For the present time (block ~ 5250000) there are ~2350000 contracts in ethereum blockchain. My search program worked for about a week.
| e04071b534671dfe581b27b1c49e420373e27cab825d55c835d54dbcca350450 | ['3ca9c59902d345659b744bb53fec8d69'] | The filter text field is a very neat idea. And the more I am fiddling with my mocks, I am moving away from proving sorting options for Location. So I am deciding just to allow a sort by the 'Name' which would be alphabetical Up or Down. The filter txt is kind of what linkedin does too. So I think I will have the top 5 values from Country, State and city with a single text input after these fields. When user enters valid tags (auto-complete) it is added to the relevant section (hidden meta-data) |
4fbdf8d83683654d162e633caa8c6e1dc56e8d726767f6036fb4a0f214257909 | ['3caebd437be5498ea8500dc1c94a50c7'] | I'm trying to create a simple discount calculator. These are my variables:
percentage = float(raw_input('Percentage: '))
price = float(raw_input('Price: $'))
discount = price*percentage
finalPrice = price - discount
At the moment, I have to enter "0.50" to calculate a 50% discount, but, I'd like to simply enter "50". Is there a simple way to add "0." to whichever number is entered as a percentage, as in, '0.' + 'percentage', so that it results in '0.percentage'?
| d883f9abbda843082307b51b00898f19f97539a537725495be330c1c80b1c0ab | ['3caebd437be5498ea8500dc1c94a50c7'] | Tried searching for this and I couldn't find an answer.
I have a container set at 728px with two divs inside of it, and both divs are set to width: auto;. I would like to center one of those divs, and have the other float on the right like in this example.
The closest I've gotten is using text-align: center; for the main container, display: inline-block; for the center div, and float: right for the right div, but I ended up with this result instead.
Any ideas?
|
b981ff6c1770b64fa0c6ddc2c2e7bf1d9d597b5d5fa18a69cff1b9701eec18b9 | ['3cc3a39485c0411098b4c0dde4c9b1b2'] | You can run a message queue on the parent, which should also allow it to not get overwhelmed by the children while processing the events in the order they arrive. Furthermore, you can expand this to a simple send-acknowledge model, where children will wait for their message to be acknowledged, before sending further messages, so you can allow the parent to control the rate at which it receives messages.
Regarding the number of threads to run, I agree with you, as you scale up the complexity of the parent program will increase.
The main factor, I believe, will be whether the threads need to share any data, or communicate, with each other. If that is not the case, the problem is simplified as you can use 1 thread per 1 or more children and just grab messages from the queue.
| 862b042b91b63000c3d6a0e60f209128c72aeafac8ed5eedcb04b39d6c885f01 | ['3cc3a39485c0411098b4c0dde4c9b1b2'] | Presumably these subnets, i.e. <IP_ADDRESS>/24 (?) and <IP_ADDRESS>/24, are part of your local network. You will need a Layer 3 device to perform inter-VLAN routing.
This will be a router with Layer 3 VLAN interfaces, in the Cisco world they would be SVIs, that would be acting as the default gateway of the subnets in your network. What happens is all traffic that needs to go between two hosts between different networks, has to go through their default gateway and it will be routed to the destination network/VLAN.
As long as the network devices between the two clients are able to route packets between these networks, the hosts will be able to reach each other. In your code, you simply need to specify that these packets need to go to the private IP address of the other host.
|
548f39fa64ae2715a96154e2aa4066f510d1d6a212ba398b1ec60d30a2eff6e4 | ['3cc81385f0fa474eb67d72e8a007dd1c'] | I'm moving the streaming app from flume to kafka. So needed help since I'm new to kafka.
I've a windows machine on which CSV Files are continously being generated by IOT sensors at a particular location say D:/Folder. I want to transfer it to a hadoop cluster.
There are millions of small files being generated daily in the folder. And i want to spool the folder with kafka for any new files.
Which Kafka connect should I use to spool the directory for new files.
I read about kafka connect fileStream but I think it only works with 1 file.
| 2210c07e02dc869771346c172b355d503618fecf8d539dc4c2171e491ce5eca7 | ['3cc81385f0fa474eb67d72e8a007dd1c'] | When loading 16 GB data using pig store command into Hbase, the HRegionserver gets killed. It throws OutofMemory error.
PFA the screen shot of the Hbase logs. We're using 4 datanodes of 12GB RAM each. Any pointers to resolve the issue.
Tried increasing HBASE_HEAPSIZE to 4GB in Hbase-env.sh without any success.
|
0be1a50cd3b2e9cb71a57fd8056631b6a2ba73f0c29ecdfa36ce6fb00cacbd1d | ['3ccd2d46b14b481e9e5c7af8d8aacd84'] | You are currently using
page.click('div[id="logOnFormSubmit"]');
There is no div in your given code example with that ID, but instead there is a button. You'd need to change that line to reflect this. The final code would look like below.
(async () => {
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
await page.goto('https://app.com');
await page.fill('input[type="text"]', '<EMAIL_ADDRESS>');
await page.fill('input[type="password"]', 'Abcd1234!');
// page.click('div[data-testid="LoginForm_Login_Button"]');
page.click('button[id="logOnFormSubmit"]');
}
)();
| b1f6a44bf5e766ef2df2b6a4bf4d5136d23b718769183aed9c26b4527ebd23f1 | ['3ccd2d46b14b481e9e5c7af8d8aacd84'] | You should be able to start Expo in offline mode so that your internet shouldn't be an issue. If you're using yarn the command would be yarn start --offline. You may also need to select Local once Expo launches.
Source: https://github.com/expo/expo-cli/issues/101
|
fbb6b48b3165563be5b57cefa35bb433239628ff2cf46fc758b814ad0f9c2187 | ['3cdb0941090a4eeaaae9910469ff59fa'] | I have a huge network of PCs that are all in a same domain (active directory). I want to enable WMI service and relative port, then set the domain's administrator credentials to WMI credentials over my entire network in the group policy.
For the Work Grouped network I created a batch file that does what I want but for the domain I want to do the best, execute the batch file remotely over entire network using active directory.
I know that the active directory lets me execute MSI Package.
The problem is: How can I create an MSI package that can execute a batch command like this:
@Netsh firewall set service RemoteAdmin enable
I would prefer to do this in C# .NET 4!
| bc535d2f0186b9b6cb6272dec475d87fa4ec8ec58751d077dea11431e462ba6b | ['3cdb0941090a4eeaaae9910469ff59fa'] | Well, thank you @WS2 then, seems like I managed to learn English somehow, barely. But I thought I provided enough information to make it clear, but I'm probably wrong... I tried to ask here because it seems like this is like, a broad question. Like, which term defines the method of study that concentrates on modeling (I) how the phenomena occurs and (II) how that phenomena reflects macroscopic on its environment. |
4ab8d0a08508e159fe2c9f38789e977d6c8011248e6ff59fa6fe2c4506c0d798 | ['3ce01a30079a40b392d0f401628b6f94'] | I am fairly new to Verilog and FPGA development. I am currently working on a project to control two motors using a Basys 3 board and an H bridge.
The module is currently built to use PWM to control the motor speed, sending the output to the ena and enb pins on the H-Bridge. The H inputs are currently constant for the sake of testing the PWM control.
Well long story short I have run into a variety of I/O errors that I just haven't been able to fully wrap my head around.
Here is my primary module:
module RDrive(
input clock,
input BUTTON,
input H1, H2, H3, H4,
output ena, enb
);
wire clock, BUTTON, H1, H2, H3, H4;
reg[1:0] speed;
reg[3:0] counter, width;
reg PWMtemp;
wire ena, enb;
// initial values
initial begin
counter <= 4'b0000;
speed = 0;
PWMtemp <= 0;
width <= 0;
end
// Every button press increments speed value
always @ (posedge BUTTON)
begin
speed <= speed + 1;
// width adjusted for PWM module
case (speed)
2'b00 : width <= 4'b0000;
2'b01 : width <= 4'b0101;
2'b10 : width <= 4'b1010;
2'b11 : width <= 4'b1111;
default : width <= 4'b0000;
endcase
end
// PWM
always @ (posedge clock)
begin
if (counter < width) PWMtemp <= 1;
else PWMtemp <= 0;
counter <= counter + 1;
end
assign ena = PWMtemp;
assign enb = PWMtemp;
endmodule
Here is my test bench:
module RDrive_TB(
);
reg clock;
wire ena = 0;
wire enb = 0;
reg BUTTON, H1, H2, H3, H4;
initial begin
BUTTON = 0;
clock = 0;
// H values for testing PWM speed control
H1 = 1;
H2 = 0;
H3 = 1;
H4 = 0;
// Simulating button presses
#1000;
BUTTON = 1;
#10;
BUTTON = 0;
#1000;
BUTTON = 1;
#10;
BUTTON = 0;
#1000;
BUTTON = 1;
#10;
BUTTON = 0;
#1000;
BUTTON = 1;
#10;
BUTTON = 0;
end
// clock generator
always begin
#1 clock = ~clock;
end
RDrive RDriveTest(clock, BUTTON, H1, H2, H3, H4, ena, enb);
endmodule
and here are my constraints:
set_property PACKAGE_PIN W5 [get_ports CLK100MH]
set_property <PERSON> [get_ports CLK100MH]
create_clock -add -name sys_clk_pin -period 10.00 -waveform {0 5} [get_ports
CLK100MH]
set_property PACKAGE_PIN U18 [get_ports BUTTON]
set_property <PERSON> [get_ports BUTTON]
##Sch name = JA8
set_property PACKAGE_PIN K2 [get_ports {enb}]
set_property IOSTANDARD LVCMOS33 [get_ports {enb}]
The first error (occurred during implementation) that I got was this:
ERROR: [Place 30-574] Poor placement for routing between an IO pin and BUFG.
I did some research, and I think the problem was a result of
always @ (posedge BUTTON)
not being exactly in time with the clock.
So I added this line to the constraints to ignore the error:
set_property CLOCK_DEDICATED_ROUTE FALSE [get_nets BUTTON_IBUF]
This allowed me to run the implementation successfully. However, I encountered the following error when attempting to generate the bitstream:
ERROR: [DRC NSTD-1] Unspecified I/O Standard: 1 out of 4 logical ports use I/O standard (IOSTANDARD) value 'DEFAULT', instead of a user assigned specific value.
From what I understand, this error occurs when inputs/outputs are not assigned an initial value, so they assume whatever the 'DEFAULT' value is. I fiddled around with the initial values and value types of each of the "problem pins" that were listed. I was able to fix most of them, but currently 'clock' is the only remaining problem pin. I've been trying to fix clock for a while now with no luck.
Some help would be greatly appreciated, thanks!
| f356dbd954968524e08261c889b68a4ce5d5694614b4bf85be6a51d3372bba78 | ['3ce01a30079a40b392d0f401628b6f94'] | I am fairly new to boost python, and I am attempting to follow this tutorial: https://www.boost.org/doc/libs/1_63_0/libs/python/doc/html/tutorial/tutorial/hello.html . Following the tutorial exactly, I receive this error upon building the project using either b2 or bjam:
" fatal error LNK1181: cannot open input file 'boost_python.lib' "
I believe I have properly configured my user-config.jam, jamfile, and jamroot files.
I also saw this thread here:
LNK1181: cannot open input file 'boost_python.lib' in windows, boost_1_68_0
but no solutions to the issue seemed to have been provided. Instead it is suggested that bjam/b2 are not needed at all, which seems to contradict the tutorial in the boost documentation.
The same user then suggested "linking" with the boost python and python libraries, which I assume means to add their directories to system environment variables. I have already done this, but I believe I could be misunderstanding what he meant.
The thread also links to this page:
https://learn.microsoft.com/en-us/visualstudio/python/working-with-c-cpp-python-in-visual-studio?view=vs-2017
detailing the creation of c++ extensions for Python, but after reading it I fail to see any mention of boost whatsoever except in passing at the very end of the article.
I have also searched the entire boost directory for a 'boost_python.lib' file and it seems that it does not exist. Any help would be greatly appreciated.
|
2ba30202f7bf0a6b6b3a9ef24fea015f62ab13df49293c4719db9e5312e584d9 | ['3ce2ad72b96f450fbd1a237f3433bc81'] | Look at ParallelArray class, it satisfies your requirements, but you need to learn a bit of functional programming concepts to use it efficiently.
The class does not come with JDK 6, but might come with JDK 7 (under discussion). Meanwhile you can use it as a library - download the JSR166y package from:
http://gee.cs.oswego.edu/dl/concurrency-interest/
See this tutorial for detailed explanation:
http://www.ibm.com/developerworks/java/library/j-jtp03048.html
It might sound complicated and it is (if you arew just digging in high performance multi-threaded algorithms). There is a Groovy project which tries to wrap a more user-friendly API around Parallel Array, so you might want to ttake a look at it as well: http://gpars.codehaus.org/ , http://gpars.codehaus.org/Parallelizer
| 2277990ff7ae1693caf5514d8e8e087c10e76ef91181cf315af643af26e9eb2f | ['3ce2ad72b96f450fbd1a237f3433bc81'] | As said above, Internal transfer are best way to start your career. If so you do not find any opportunity, then with free beta testing opportunity available for lots of Mobile application, build your reputation in testing community. Later you can start freelancing showing some testing portfolio/experience and get projects.
Also try to learn functional automation and non-functional testing in spare time.
|
3de6b770b10806dcc555eded35e2e7f654ea7321d8e49b1ac9b64980c5b149e0 | ['3d104a44f7d84896ba99709e7895cff5'] | I tried to block vpns and proxies to my website using iphub.info, but cloudflare ip’s get also blocked, so basicly no one can access my website!
Is there a way to whitelist cloudflare for https://iphub.info? I created the website with php.
Thanks in advance!
This is how iphub looks if an ip is bad:
<?php
namespace IPHub;
class Lookup {
public static function isBadIP(string $ip, string $key, bool $strict = false) {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => "http://v2.api.iphub.info/ip/{$ip}",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ["X-Key: {$key}"]
]);
try {
$block = json_decode(curl_exec($ch))->block;
} catch (Exception $e) {
throw $e;
}
if ($block) {
if ($strict) {
return true;
} elseif (!$strict && $block === 1) {
return true;
}
}
return false;
}
}
?>
| 2414996946ac90a6f8b5807190eeca08a5bd81e9b83fb1245c2dfd5337abcfd8 | ['3d104a44f7d84896ba99709e7895cff5'] | I'm using this script in beautifulsoup4<IP_ADDRESS>
url = ["url1", "url2," "url3", ...]
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'}
for item in url:
r = requests.get(item, headers=headers)
print(r.text)
To scrape a lot of shortened links. I don't want to send too much requests to the website because on the internet I saw it could cause a Denial of Service attack (I don't know if its true, but I don't want any problems). How can I add a delay between connecting to each link?
|
38994aed34c2997d178d1be0dc9f17ec81a390ee5d9eddada583b189bf5cffbc | ['3d157ecb3c73401197210269fd05090e'] | I've got a strip of LED lights that requires a 60V supply with 200mA of draw (15w). I am curious what would be required to get this to run off a significantly smaller voltage source (i.e. USB) I don't believe a traditional USB charger would work as they are 5V/1A and there is no way to turn that into 15W but if I had a USB C battery pack that was able to deliver >15W is it possible to use a step up converter to power this strip? Or a couple of 18650 batteries?
I've looked at TI's simple switcher site and it is suggesting the LM2587/LM2588 as a way of turning ~5V into 60V at 200mA. Are there more gotchas that I am missing?
The LED strip is from something like this. Our office recently got an upgrade and a few fell off a truck for experimentation.
| 2d07703caf3259f945a1df4e4346a1c33588e2f6c56c007ff79706d8dc9f1797 | ['3d157ecb3c73401197210269fd05090e'] | " If employees are worried about getting shot down or in trouble every time they need to take a day off, they may wait until the last minute to let you know they won't be in." // Undersigned. I myself have been the employee in this situation. The combination of dread and the lingering hope that maybe somehow, some way, you can swing something at the last second and avoid an undue, longlasting and unproductive conflict leads to people rushing around until the last minutes before shift pursuing unlikely solutions. |
f77eae7fa23cfc63881d999338234d79994e0919707a6aa9a3f3a80f3c0e6ca4 | ['3d1cdb3b66a94639b23011017a631d56'] | Suppose, I have multiple branches: feature_1, branched from HEAD of master, then feature_2 branched from HEAD of feature_1 and feature_3 branched from HEAD of feature_2.
And then I discover a bug in feature_1. I fix it and commit, now feature_2 and feature_3 still contain this bug. One way to fix this is to merge feature_1 onto feature_2 and feature_3.
Is this right way to do this?
| dca29a0c8b359ef45f195e6f8742ca527369ef2b5f75405102a0751167fa6025 | ['3d1cdb3b66a94639b23011017a631d56'] | I feel like you are misunderstanding a few things about working with interfaces. In your op() method you are creating an ArrayList. The type of the List is then "locked in" and cannot be changed. Even if you return only the List interface, the underlying object will still be an ArrayList. As Flame's answer already mentioned, you cannot cast this object to LinkedList because they are not compatible.
So there are two options:
Be specific about which kind of List implementation you are using. This means changing the return type of op() to ArrayList. The caller can then use all the functionality specified by ArrayList.
Keep your declaration as it is. The caller then has to work with only the List interface and cannot work with any extended functionality that the ArrayList provides. That is because it cannot make any guarantees which implementation is used.
I'd choose option 2 since very rarely does one need functionality which isn't already provided by the List interface. And again, in general, you cannot change the implementation from ArrayList to LinkedList by casting. You'd need to create a new List with the desired implementation and copy all the contents into it. An easy way to do this is: new LinkedList<>(someArrayList);
|
223500c0a3936f2757ec5ba99df38a1be1090a625138cedb68c8af3d7df7372c | ['3d1f6ef663aa4b0e8c053ffbe8db426a'] | I ran into this problem when trying to implement markdown using PHP.
Since the user generated links created with markdown need to open in a new tab but site links need to stay in tab I changed markdown to only generate links that open in a new tab. So not all links on the page link out, just the ones that use markdown.
In markdown I changed all the link output to be <a target='_blank' href="..."> which was easy enough using find/replace.
| 24b891247880cc82e24c762882bfdeed33030ccae859e627f74690dbb91a40f0 | ['3d1f6ef663aa4b0e8c053ffbe8db426a'] | According the Charles Proxy page for setting up SSL Certificates:
As of tvOS 10.2 it is no longer possible to trust the Charles Root Certificate, so it is not possible to use SSL Proxying with tvOS 10.2. This appears to be because the Certificate Trust Settings menu is not available (see iOS devices above). A bug has been filed with Apple and we hope that this will be resolved in the future.
|
50be23d5be69bdd292a34830ab07d432156e70b857e87b8a06cd5c54b43355ec | ['3d21148f87de4dd6b3469b677120f204'] | I found solution for the above problem. I modified my service in the following way. It works fine after the modification.
[Unit]
Description=/etc/rc.d/rc.local Compatibility
ConditionFileIsExecutable=/etc/rc.d/rc.local
After=network.target
[Service]
Type=forking
ExecStart=/etc/rc.d/rc.local start
ControlGroup=cpu:/
SysVStartPriority=99
| 3819efa2038c48934edcfb0914c174504bef7d1efae82e4e938623105bc60737 | ['3d21148f87de4dd6b3469b677120f204'] | I am new to systemd service scripts. I am trying to start my application from systemd service scripts. My application is a process that in turn invokes multiple process that includes Qt GUI as one of its child. But the service downt starting up my application.
This is how my service looks like:
[Unit]
Description=/etc/rc.d/rc.local Compatibility
ConditionFileIsExecutable=/etc/rc.d/rc.local
After=network.target
[Service]
Type=forking
ExecStart=/etc/rc.d/rc.local start
SysVStartPriority=99
rc.local script looks like:
#!/bin/bash
export DISPLAY=:0
sleep 5
cd /var/MINC3/apps
./PMonTsk
So when try to run the command "systemctl start rc-local.service", the command executes the script but doesnt invoke my application. If I replace some other QT GUI sample application in the plcae of my application in rc.local, it is working fine. Please help me on sorting this issue.
|
2d3b486c437d37028be042be1056f261ff317853266d376b037346a360a2aad3 | ['3d2c3f3a4f664d5e94dc505e85f8d6ec'] | I have the issue that when I'm moving my finger diagonal on my touchpad, it tends to make a zig-zag pattern when I go slow.
Also when I want to move the cursor, a few pixel over to a link, it doesn't react until I move my finger enough and then it makes a jump, making it hard to hit links.
I've tried to draw the pattern in kolourpaint https://i.imgur.com/MzXSI0F.png
This is done with a MSI GE60 2PC-Apache
| 5cd88bfb5119adfa1580face073cc592896e45651b1f67e5f4ed776eb1f71b16 | ['3d2c3f3a4f664d5e94dc505e85f8d6ec'] | You should try Remote Keyboard, available for Android 2.3+.
That app worked well with my Windows 10 computer and my OnePlus 3T, and you can try this tutorial which shows you how to use the app.
If you don't like this app or if it's not working with your phone, you can try this one : https://play.google.com/store/apps/details?id=com.volosyukivan
Or, as <PERSON> said, you can use an OTG wire.
|
6f04c861bf5c4111e11900dcf12e51de020aee7dc883317d924222f326e33094 | ['3d2de3a8203d4f58892f5c8ad19b102d'] | <PERSON> I understand, really the standards and being quality-based cause a site like SO to stay at top, a piece of blame should be for me that I didn't spend the time you said to learn more about posting, I'm about 3 years in SO with just about 20 questions, I had quite good respect for most of my posts, a silver badge, more than 3k views for one the other,and more (in just 20 questions), Yes, I tried to defend my point of views but as you mentioned described wrongly | 69b512bc44ec8f75028f312391a7e4a34094d357a2a78a48e3717063846d7f3a | ['3d2de3a8203d4f58892f5c8ad19b102d'] | @vcsjones the only comment that tried to give me an information which could help me find a problem within the post, I think this is again like what I said before, I didn't even wanted to give a single statement, maybe used some "English Words" incorrectly. e.g : Developers could have different opinions ... is it a statement in your language ? :D, Don't know really when it causes some negative results , so the post is in incorrect format. |
de5bdf4c75d86e12bb3f48ed8491e85663acbd57e5603d1f21eb22a81ff923f1 | ['3d3fc30deb084d728d521e62d795a779'] | I am trying to understand the return keyword and its functionality, however, I am getting a little confused.
I have read this which has been a good starting point, but I can't seem to understand the solution to what I imagine is a very simple problem.
Say I have a PHP file called index.php and I call a function from it like so (imagine it's not being called from within a class or function);
echo $fun -> editAnswer ($obj->answer_id, $obj->answerString ,$obj->correct, $questionID, $lecturer_id);
Then in my function.php I have:
public function editAnswer($answer_id, $answerString, $correct, $questionID, $lecturer_id){
$db = $this -> db;
if (!empty ($answer_id) && !empty ($answerString) && !empty($correct) && !empty($questionID) && !empty ($lecturer_id)){
$result = $db -> editAnswer($answer_id, $answerString, $correct, $questionID, $lecturer_id);
if ($result) {
return "The Updates To Your Answer Have Been Saved!";
} else {
$response["result"] = "failure";
$response["message"] = "The Updates To Your Answer Have Not Been Saved, Please Try Again";
return json_encode($response);
}
} else {
return $this -> getMsgParamNotEmpty();
}
}
If successful, I will return the string The Updates To Your Answer Have Been Saved!, however, this will be immediately echoed to the screen of index.php.
My thinking is that if after calling the function, the user was still on index.php, it might look a little ugly to have a string at the top of the page. Maybe I would want to catch the returned string and then create an alert dialog before displaying it.
How would I go about doing something like that rather than immediately echoing the returned string?
| b093e150c226d30dc339baa7bd23dd218200e882e87a6f03e0f45a1f78f63dff | ['3d3fc30deb084d728d521e62d795a779'] | I have a method that is being called, every time a user touches the screen. Once they have touched the screen enough times, the object that the script is attached to is deactivated.
The script in question is attached to layouts that I am looping out based on dynamic data.
So say I have 10 questions, that means I will have 10 layouts with 10 versions of the script attached.
I am not sure I am taking the best approach, but I am stuck and as I am new to Unity/C# I was hoping for some guidance.
I need the script to check a different index, based on the screen index. Currently, the if statements (in the method below) work perfectly, however, as I don't know many screens there will be (due to dealing with dynamic data), I need a way of doing these checks without a huge list of if statements.
I understand that I can use a for loop, but my problem is that I need the count to change depending on the screen index (as shown in my if statement). Is it possible to do what I am after with loops, or do I need to change the way I am approaching this?
A problem I am facing is that the only constant available between adding the new script to each instance is the ScreenIndex count variable. Hence why I am repeated referring to this in my if statements.
I tried wrapping my method in a for (ScreenIndex = 0; ScreenIndex < UIHandler.GetdynamicQuestionArray().Count; ScreenIndex += 4) but the count goes out of sync. Will I have to use nestled loops? I have tried but without success so far.
My method currently looks like this:
//Scratch pad 1 - Due to this method being called everytime a pixel is scratched, nestled if statements need to be used.
public void OnEraseProgressScratch1(float progress)
{
//Set a count of i, to make sure the screen index can be checked
int i = 0;
//While loop to help condition to make sure we know what page the user is currently on, keep looping i until it matches the index the user is on.
//This is necessary because i will keep getting reset everytime this method is called, so the while loop will make sure i matches the index
while (i != transform.parent.gameObject.transform.parent.gameObject.GetComponent<TeamQuizScreen>().ScreenIndex)
{
i++;
}
//Once the user has scratched more than 50% of the pad, deactivate it
if (Mathf.Round(progress * 100f) >= 50)
{
//If the user has scratched more than 50% stop the user from scratching any further and check if they are correct.
transform.parent.gameObject.transform.GetChild(0).GetChild(3).GetChild(0).GetChild(0).gameObject.SetActive(false);
//Loop through the array that holds if an answer is correct or not
//If the screen index is the same as the page number
if (transform.parent.gameObject.transform.parent.gameObject.GetComponent<TeamQuizScreen>().ScreenIndex == i)
{
int ScreenIndex = transform.parent.gameObject.transform.parent.gameObject.GetComponent<TeamQuizScreen>().ScreenIndex;
if (ScreenIndex == 0)
{
Debug.Log("X (should be 0) = " + ScreenIndex);
//If the user is at screen index 0, then a loop should be querying position 0 only here. If the user is at position 1 then a loop should be
//querying position 4 - this is because position 1,2,3 will be queried in 'OnEraseProgressScratch2', 'OnEraseProgressScratch3' and 'OnEraseProgressScratch4'.
if (UIHandler.GetDynamicCorrectAnswerArray()[ScreenIndex].ToString().Contains("Correct"))
{
Debug.Log("Answer 1 is correct");
}
}
else if(ScreenIndex == 1)
{
ScreenIndex += 3;
Debug.Log("X (should be 4) = " + ScreenIndex);
if (UIHandler.GetDynamicCorrectAnswerArray()[ScreenIndex].ToString().Contains("Correct"))
{
Debug.Log("Answer 1 is correct");
}
}
else if (ScreenIndex == 2)
{
ScreenIndex += 6;
Debug.Log("X (should be 8) = " + ScreenIndex);
if (UIHandler.GetDynamicCorrectAnswerArray()[ScreenIndex].ToString().Contains("Correct"))
{
Debug.Log("Answer 1 is correct");
}
}
else if (ScreenIndex == 3)
{
ScreenIndex += 9;
Debug.Log("X (should be 12) = " + ScreenIndex);
if (UIHandler.GetDynamicCorrectAnswerArray()[ScreenIndex].ToString().Contains("Correct"))
{
Debug.Log("Answer 1 is correct");
}
}
else if (ScreenIndex == 4)
{
ScreenIndex += 12;
Debug.Log("X (should be 16) = " + ScreenIndex);
if (UIHandler.GetDynamicCorrectAnswerArray()[ScreenIndex].ToString().Contains("Correct"))
{
Debug.Log("Answer 1 is correct");
}
}
else if (ScreenIndex == 5)
{
ScreenIndex += 15;
Debug.Log("X (should be 20) = " + ScreenIndex);
if (UIHandler.GetDynamicCorrectAnswerArray()[ScreenIndex].ToString().Contains("Correct"))
{
Debug.Log("Answer 1 is correct");
}
}
//This will need to continue based on the number of questions in the hierarchy
}
}
}
|
d0bb68c4ff98baa0f35f7e63f35daa2192d15d7821c0540b83eb62a0a1efd6bb | ['3d58064c5d6a407095a18fc7d0c2c810'] | timeSlot=[];
function reduceTime(st, et) {
var obj={
start_time:'',
end_time:''
};
if (st.indexOf(":00")>0){
obj.start_time=st.replace(":00", "")
}else{
obj.start_time=st;
}
if (et.indexOf(":00")>0){
obj.end_time=et.replace(':00', '')
}else{
obj.end_time=et;
}
timeSlot.push(obj)
}
usage:
for(i=0;i<response.length;i++){
reduceTime(response[i].start_time, response[i].end_time)
}
$scope.timeSlot=timeSlot;
Then we will get an array of objects.
| 936d61802960b1f4cd4d47dd5de781e67c86d541de24927fe649fa339c365415 | ['3d58064c5d6a407095a18fc7d0c2c810'] | I have a value
$scope.time = 13:30:00 (in 24 hour format)
Now I want to change this value to am/pm format using angularjs filter like
<th class="text-center">{{time | any filter}}</th>
Output: 1:30 pm
Is there any built in filter or do I have to create custom filter?
how can I use "date" filter to solve this issue?
|
1d4bd552b105ca64aece487e64dc997de4a257b53784d9c02255ddf73a9dbc44 | ['3d5aecc9ed2947a6ab2781f040b0ff25'] | To clarify. We have a linear mapping for $Bf(x)$ that goes from $L^2_{(R_+)} \to L^2_{(R_+)}$. We have $Bf_{n} \to Bf(0)$ when $f_{n} \to 0$ (True for all linear mappings). If we can then show that $f_{n} \to f$ we are done from there. This is true due to density (I believe.)
Unfortunately at times my teacher ran away with the problem and did not explain certain jumps in much detail, so I am doing my best to fill them in, as he is now away. This is what I have managed to come up with mostly after he helped with defining $F_{n}(x)$. | 4293a33cf4088d506113ef9dd8b73faa22369f642b6a3338d5e0db38fddad217 | ['3d5aecc9ed2947a6ab2781f040b0ff25'] | We have that f(t) is undefined, but is smooth so is differentiable. The issue with this is that this diverges as $x \to 0$.
For the purposes of the question as a whole, it needs to be shown to be a bounded operator (The Bf(x)) in $L^{2}_{R_{+}}$). My teacher hinted that this should result in a constant and use of Holders Inequality (I assume a norm $\lvert\lvert f \rvert \rvert$ in $L^{2}_{R_{+}}$. Thankyou for the help, any help if very appreciated! |
2091c02d192c67199e315dbdec4f33aa41c5f64eab13b004ee957cbb69b4b2ec | ['3d5c0914fc7d45b095ed0e6a82cc6d79'] | i have a collection view, with cells in a size of the all screen.
i'm trying to add spacing between the cells, so when ever i scroll between the cells there will be some space between - as in the iOS photo gallery, when you scroll between full screen images.
obviously i have paging enabled.
but for some reason when i scroll between the cells, the spacing is staying on the screen.
i.e. if the cell width is 320, and the space between the next cell is 20px, so when i scroll to the next cell, the space is reaching to x=0, and the new cell starts at x=20.
why is that?
how do i get the exact iOS photo gallery scrolling full screen images effect?
| 93683087c527936950d93bc1c6e47bf52801074a4c4b8f89c243fd3903d32049 | ['3d5c0914fc7d45b095ed0e6a82cc6d79'] | i'm having issues with the watch os2 handoff, specially when my iPhone app is not running.
what i see from the launchOptions is:
UIApplicationLaunchOptionsUserActivityDictionaryKey = {
UIApplicationLaunchOptionsUserActivityIdentifierKey = "xxx";
UIApplicationLaunchOptionsUserActivityTypeKey = "com.xxx";
};
it seems to be missing the UIApplicationLaunchOptionsUserActivityKey that will have the actual NSUserActivity object that i need for handling the handoff.
*when opening it on a running app from the
(BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray * __nullable restorableObjects))restorationHandler
i do get the correct NSUserActivity
and i can handle it properly.
any idea what could have gone wrong?
another thing i have to mention, is when opening core spotlight result on closed app, the NSUserActivity is being passed correctly, so it seems to be an issue only with the watch handoff.
|
f2d92219664f01334e844d3cb8275195e54d0b066946c54cdbee4f562391de40 | ['3d64046803004b67888af5a30e1b706d'] | in my case i solved following steps:
There are times when you do not want to change ownership of the
default directory that npm uses; for example, if you are sharing a
machine with other users.
In this case, you can configure npm to use a different directory.
Make a directory for global installations:
mkdir ~/npm-global
Configure npm to use the new directory path:
npm config set prefix '~/npm-global'
Open or create a ~/.profile file and add this line:
export PATH=~/npm-global/bin:$PATH
Back on the command line, update your system variables:
source ~/.profile; source ~/.bashrc
Reference: NPM DOC
| 8a3a7cbd02f4302ee82e31a7cc3e2eb4abf58dec7fa2fcdecbf4af4e75a46be0 | ['3d64046803004b67888af5a30e1b706d'] | The new value of HTML Fields, must be set before append
From what I understand, you're trying to initialize fields after "amount" as off, if that's it:
Set "disabled" in "Select" created in htmlcard
The new html instance created in jquery is not set like a disabled
<select disabled class='form-control w-30' id='NoTwo' placeholder='Choose'>
Check a pen working in here
|
149f7b45a6efacda22aec3e12878c34ef3f35682f34c6f76ca0cf3983303aad6 | ['3d7bf4b92de049159864cc0d45e5b87c'] | Uma vez que existem criticas a inspeção de normalidade usando testes formais, uma alternativa é fazer inspeção gráfica por meio de histograma e ver se ocorre a forma de sino na figura resultante. O comando hist(dados) faz isso. Busque imagens de histogramas distribuição normal e os use de referência. Se o seu histograma não tiver forma de sino, tente transformações nos dados e refaça o histograma.
| 8bb53f9f7b72948ecf1e88792b2d02638074fc065c00c1ba3f6c5bf707f3d697 | ['3d7bf4b92de049159864cc0d45e5b87c'] | Hi! The main problem is to find a graph with 3 vertices or more in which <PERSON>'s algorithm run at some vertex will find a maximum-weight spanning tree. The problem does not specify that the graph needs to contain cycles, so I guess your comment about the A-B-C vertices is a right answer. I am still curious though to find a tree *with* cycles where this also happens. @Evil |
dc589b4e8fcdbf39e6c1235cb5e56088831a752d94742a704a23ac83649cc255 | ['3d978dbc55d44a81bf58621b243da2d5'] | I used the following code for building a simple Python program which gets input from user.
Name = raw_input('Enter your name: ')
Age = raw_input('Enter you age:')
Qualifications = raw_input('Enter you Qualification(s):')
A = raw_input()
print "Hello" +'.'+ "Your Name is " + Name + ". " + "Your Age is " + Age + ". " + "Your Qualification(s) is/are:" + Qualifications + "."
print "If the above data is correct, type yes. If not, type no. Typing no will restart he program and make you write the form again." + A
if A in ['y', 'Y', 'yes', 'Yes', 'YES']:
print 'Thanks for your submission'
if A in ['No' , 'no' , 'NO' ,'n' , 'N']:
reload()
The program finishes before the if command.
| 93c0078c201a56b59b4d314dee3ffe5380c5b9ec5a90a41ffbf793208b059f3c | ['3d978dbc55d44a81bf58621b243da2d5'] | I am stuck on a problem of a aligning a image next to a division in HTML. Below is the code. I want the image to the right of the division but I can't seem to get it.
<h1><u><center> <PERSON> </center></u></h1>
<br/>
<div style="height:1000px; width:500px;">
<PERSON> (20 April 1889 – 30 April 1945) was an Austrian-born German politician and the leader of the Nazi Party. He was chancellor of Germany from 1933 to 1945 and dictator of Nazi Germany (as Führer und Reichskanzler) from 1934 to 1945. <PERSON> was at the centre of Nazi Germany, World War II in Europe, and the Holocaust.
<PERSON> was a decorated veteran of World War I. He joined the German Workers' Party (precursor of the NSDAP) in 1919, and became leader of the NSDAP in 1921. In 1923, he attempted a coup in Munich to seize power. The failed coup resulted in <PERSON>'s imprisonment, during which time he wrote his memoir, Mein Kampf (My Struggle). After his release in 1924, <PERSON> gained popular support by attacking the Treaty of Versailles and promoting Pan-Germanism, antisemitism, and anti-communism with charismatic oratory and Nazi propaganda. <PERSON> frequently denounced international capitalism and communism as being part of a Jewish conspiracy.
<PERSON>'s Nazi Party became the largest elected party in the German Reichstag, leading to his appointment as chancellor in 1933. Following fresh elections won by his coalition, the Reichstag passed the Enabling Act, which began the process of transforming the Weimar Republic into the Third Reich, a single-party dictatorship based on the totalitarian and autocratic ideology of National Socialism. <PERSON> aimed to eliminate Jews from Germany and establish a New Order to counter what he saw as the injustice of the post-World War I international order dominated by Britain and France. His first six years in power resulted in rapid economic recovery from the Great Depression, the denunciation of restrictions imposed on Germany after World War I, and the annexation of territories that were home to millions of ethnic Germans, actions which gave him significant popular support.
<PERSON> actively sought Lebensraum ("living space") for the German people. His aggressive foreign policy is considered to be the primary cause of the outbreak of World War II in Europe. He directed large-scale rearmament and on 1 September 1939 invaded Poland, resulting in British and French declarations of war on Germany. In June 1941, <PERSON> ordered an invasion of the Soviet Union. By the end of 1941 German forces and their European allies occupied most of Europe and North Africa. Failure to defeat the Soviets and the entry of the United States into the war forced Germany onto the defensive and it suffered a series of escalating defeats. In the final days of the war, during the Battle of Berlin in 1945, <PERSON> married his long-time lover, <PERSON>. On 30 April 1945, less than two days later, the two committed suicide to avoid capture by the Red Army, and their corpses were burned. Under <PERSON>'s leadership and racially motivated ideology, the regime was responsible for the genocide of at least 5.5 million Jews, and millions of other victims whom he and his followers deemed racially inferior.</div>
<div>
<img style="margin-bottom:600px; margin-top:0px;" src="/home/vishal/Pictures/hitler_retouched.jpg" align="right"></img>
</div>
|
40947800f4c953d9874c15c1c18611ce3b6c5ba79a59d3709583b7fa4de72cf0 | ['3da5a7e3b7434b8a892a0662a9429379'] | i have a difficulty and its about display:table , i was working on a one page website and i have a navbar and a .product section below it , now inside .product the section , i have a carousel and i want the carousel centered vertically and so i have used the following technique <IP_ADDRESS>
@media only screen and (min-width : 768px) {
.products {
height: 100%;
display: table;
width: 100%;
}
.products .carousel-wrapper {
display: table-cell;
vertical-align: middle;
}
}
FIDDLE HERE
unfortunatly there is a but gap between the .product section and the nav element , both sibling elements , if i add display:block to the products section than my layout gets screwed , but th gap is gone , so i need to stick to table . why is the gap there i have checked for margin and padding , but there is none , so i see nothing obvious for the gap to be there , but its still there .
can somebody tell me why i am getting this huge gap ?
| 0ef5523cb0c0e908aaae3256a17698c78e2d9bf037315828516f6d18eb375746 | ['3da5a7e3b7434b8a892a0662a9429379'] | I have the following grunt file:
module.exports = function(grunt) {
grunt.initConfig({
cssmin: {
options: {
shorthandCompacting: false,
roundingPrecision: -1
},
target: {
files: {
'css/output.css': ['css/one.css', 'css/two.css']
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.registerTask('default', ['cssmin']);
};
just started using grunt.js today and just had a look at the documentation and the examples , i am using the following plugin:
CSS-CONTRIB-MIN
Now, My files get minifined into one , but what i really want is for them to only be combined into one and not minified. how do i achieve that ?
|
b53002f0b79e4f09e2993fa60e06f051396851e130a009cf6887067eb0898386 | ['3dabb4caf72140a888b2a23d5789e7b2'] | As shown in code that data are read from CSV file and for applying conditions on same column inner for loop is used. This will extract data with all rows according to condition given.
with open(fName,'rt') as csvfile:
data = list(csv.reader(csvfile))
print(data)
df = pd.read_csv(fName)
print(df.loc[(df['Date'] == sdate)])
for x in df['Date']:
if (x<sdate) & (x>edate):
df1 = df(x)
print(df1)
| 600cece4617c970ac0f379cccc7f278e99d4c0e0f1c8335fd884c245b1364309 | ['3dabb4caf72140a888b2a23d5789e7b2'] | I have multiple data selected from checkbox bs table and i want to pass these data to the controller and redirect to another page. Below is the code which i have tried:
View:
<script type="text/javascript">
var checkedRows = [];
$('#eventsTable').on('check.bs.table', function (e, row) {
checkedRows.push({dc_no: row.dc_no, name: row.customer_name});
console.log(checkedRows);
});
$('#eventsTable').on('uncheck.bs.table', function (e, row) {
$.each(checkedRows, function(index, value) {
if (value.id === row.id) {
checkedRows.splice(index,1);
}
});
console.log(checkedRows);
});
$("#add_cart").click(function() {
$("#output").empty();
$.each(checkedRows, function(index, value) {
$('#output').append($('<li></li>').text(value.dc_no + " | " + value.name ));
});
});
</script>
Selected data is being listed by $.each(checkedRows, function(index, value).So, how to pass value of dc_no and some other field to the controller.
|
a0d747317a4d6f12e5418a5d527ed46102675e4af9693e9039f6fb10a66352cf | ['3db9997c103e4a15b9358255f5df55be'] | The "col-md-6" elements need to be within an element with class="row" for the bootstrap layout to work:
BOOTSTRAP GRID SYSTEM
<div class="row">
<div class="col-md-6">
<kendo-chart [categoryAxis]="{ categories: categories }">
<kendo-chart-title text="Gross domestic product growth /GDP annual %/"></kendo-chart-title>
<kendo-chart-legend position="bottom" orientation="horizontal"></kendo-chart-legend>
<kendo-chart-tooltip format="{0}%"></kendo-chart-tooltip>
<kendo-chart-series>
<kendo-chart-series-item *ngFor="let item of series"
type="line" [data]="item.data" [name]="item.name">
</kendo-chart-series-item>
</kendo-chart-series>
</kendo-chart>
</div>
<div class="col-md-6">
<kendo-chart [categoryAxis]="{ categories: categories }">
<kendo-chart-title text="Gross domestic product growth /GDP annual %/"></kendo-chart-title>
<kendo-chart-legend position="bottom" orientation="horizontal"></kendo-chart-legend>
<kendo-chart-tooltip format="{0}%"></kendo-chart-tooltip>
<kendo-chart-series>
<kendo-chart-series-item *ngFor="let item of series"
type="line" [data]="item.data" [name]="item.name">
</kendo-chart-series-item>
</kendo-chart-series>
</kendo-chart>
</div>
</div>
EXAMPLE
| cf1ca8330269e07d74284e6b2d3322027fba6293beff3258caf451d357d3cb11 | ['3db9997c103e4a15b9358255f5df55be'] | The provided code suggests that you are initializing new DropDownList widgets from the same HTML element every time, and also that new DataSources are created every time.
You can create the two different DataSources outside of the functions, and then in the functions bodies use the DropDownList setDataSource() method to switch between the two dataSources, and the setOptions() method to change the other options like dataTextField and dataValueField, e.g.:
Example
|
9506c26c1537eac4cb8b34f7b7c5bd2ec6cb19c56081bb41660988b62764ebde | ['3dbc24624dc64b76b136684ec56e7f38'] | Can someone help me out figuring how to write a model adapter for geddyjs or expressjs web frameworks for NodeJS?
I'm following this tutorial but they persist data in memory, I want to know how to do it with sqlite since I'm starting to get to know it.
Thanks
http://geddyjs.org/tutorial.html
| 1a4edc9f3ba417d4baa8256a5047124a7e2735b7c1165315c1aae68a16d2b7ef | ['3dbc24624dc64b76b136684ec56e7f38'] | Interesting, I was not aware of this kind of things. I looked it up very quickly on wikipedia and they say: "It operates by putting a short circuit or low resistance path across the voltage output". But I don't really like having a short circuit on my power supply either. |
7ed2a4a643790333e8c83b4f6807875d990c0cf17e010f1ad58990d06407f31c | ['3dbd8cfe0fd348e4b2a632663eec0329'] | I'm passing an ImageList to a usercontrol.
I have read that ByVal allows to change the object, but only ByRef allows setting the object to something else.
In my code I'm settings the imagelist to Nothing at some point in order to know that the imagelist has been destroyed.
Would it still be allowed to pass the imagelist as ByVal or should I use ByRef instead in this case?
"Nothing" is not an object, it's "Nothing", right?
| 595d4425ca07696e951a37d79ec7bb59888b43522aa51469c3a6bf1986e3b6fb | ['3dbd8cfe0fd348e4b2a632663eec0329'] | I'm creating a grid usercontrol, and I want to show grid lines.
As a reference, I took a look at Excel.
Between Excel cells there are thin grid lines.
Now when it comes to calculating the grid lines in my usercontrol, I wonder if these grid lines should be drawn as a part of a cell so that they just draw over the cells, or if they should be drawn between cells.
I'm asking about Excel specifically because in Excel, you can join / combine cells, so I'm even more confused if grid lines are actually part of a cell (and drawn over it) or some extra space.
Does anybody have any advice or knows how it's done in Excel?
I didn't see a way to investigate how Excel does this.
Thank you.
|
39b53b75098b4a4d0a64d935f54b51e46a16b834ff203168d78477cd1e481b96 | ['3dce3d1c86b649aea1d5ca2d5da7da5f'] | In my fragment I have material search bar with navigation button(humbugger).
How can I call Navigation Drawer which is in main activity with that humbugger button in my fragment
Do not get how to handle it inside DictionaryFragment
MainActivity:
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
LinearLayout content = (LinearLayout) findViewById(R.id.content);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,
drawer,
R.string.nav_open_drawer,
R.string.nav_close_drawer){
};
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
DictionaryFragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
materialSearchBar = (MaterialSearchBar) RootView.findViewById(R.id.search_bar);
...
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
@Override
public void onButtonClicked(int buttonCode) {
//***HOW TO HANDLE IT HERE?***
//switch (buttonCode) {
// case MaterialSearchBar.BUTTON_NAVIGATION:
// drawer.openDrawer(Gravity.START);
// break;}
}
});
//return RootView;
}
layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/searchBarDividerColor"
tools:context="com.hfad.catchat.DictionaryFragment">
<com.mancj.materialsearchbar.MaterialSearchBar
android:id="@+id/search_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:mt_hint="Search"
app:mt_navIconEnabled="true"
app:mt_speechMode="false" />
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_search"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="android.support.v7.widget.LinearLayoutManager"
app:layout_behavior="@string/appbar_scrolling_view_behavior" >
</android.support.v7.widget.RecyclerView>
</LinearLayout>
| 2d0223ce4df8cd48140b040163d1ff3d867a0bc491ca0c045d84859346707742 | ['3dce3d1c86b649aea1d5ca2d5da7da5f'] | I have text that comes from SQLite database to my onBindViewHolder in this form: Hello I am {<PERSON>}.
I want to be able to adjust size or colour of the text inside {} and hide those {} curly braces from output. So final desire to have text like this: Hello I am <PERSON>
For the first time I meet with Regex related thing, can anybody give me short step by step guide how to accomplish this.
I found similar question:
Regular Expression to find a string included between two characters while EXCLUDING the delimiters
But I do not understand how should I handle "(?<=[)(.*?)(?=])" in my case.
Now my onBindViewHolder looks like this:
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Question question = questionList.get(position);
holder.tvQuestion.setText(question.getQuestion());
// holder.tvQuestion.setTextColor(Color.parseColor("#ff0099cc"));
|
b779997e243a0f64a62a1e4a7507616d17142c7bef7d948dbc6d6a1810329000 | ['3de0d9b5cdf443c298ae0a0960048d0b'] | The sp unit of measurement is used for fonts and is pixel
density dependent in the exact same way that dp is. The extra calculation that an
Android device will take into account when deciding how big your font will be,
based on the value of sp you use, is the user's own font size settings. So, if you test
your app on devices and emulators with normal size fonts, then a user who has a
sight impairment (or just likes big fonts) and has the font setting on large, will see
something different to what you saw during testing.
| 26cf9dbf02ca6458e8832945092144d98ecedcf3f7ebae6e6aebdcb29fee3777 | ['3de0d9b5cdf443c298ae0a0960048d0b'] | The problem here is that you say to java do something if value 1 is true or value2 is true or value3 is true,and then you say on the else to do the same if using or.You got to understand that you need to use and && in order to help java to understand the else parameter.
|
8d185bcb141e52a88077d0a379d9ee0ab342539c3d7608be40e8c2d8afc5ef5f | ['3df56ebf5bb0466c98f59b5093874934'] | I am trying to bind combo box inside of a list view.
Here is the Xaml:
<UserControl
<UserControl.Resources>
<Style TargetType="ListViewItem">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="true">
<Setter Property="IsSelected" Value="true" />
</Trigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
<DockPanel MinWidth="724" Height="387" DataContext="{Binding DeviceDiagnosticsMainVeiwModel}">
<globals:SaveNotificationPopup IsOpen="{Binding IsSaveNotificationPopupOpen}" SaveCommand="{Binding SaveCommand}" CancelCommand="{Binding CloseSaveNotificationPopup}" Placement="Relative" VerticalOffset="300" HorizontalOffset="200" />
<StackPanel>
<Grid Width="250" HorizontalAlignment="Left" Margin="10,10,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" MinHeight="23" />
<RowDefinition Height="Auto" MinHeight="23" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Content="{x:Static ml:MultiLang._2001}" x:Name="ML_0209" />
<Label Grid.Row="1" Content="{x:Static ml:MultiLang._2009}" x:Name="ML_0211" />
<ComboBox Grid.Column="1" Grid.Row="0" ItemsSource="{Binding Manufacturers}" DisplayMemberPath="WorkingPlace" SelectedValuePath="PersonCode" SelectedValue="{Binding Path=ManufacturerID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<ComboBox Grid.Column="1" Grid.Row="1" ItemsSource="{Binding Devices}" DisplayMemberPath="Model" SelectedValue="{Binding Path=SelectedDevice, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
<ListView DockPanel.Dock="Top" Margin="10,25,10,10" Width="460" ScrollViewer.HorizontalScrollBarVisibility="Hidden" HorizontalAlignment="Left" ItemsSource="{Binding CurrentDeviceDiagnostics}" SelectedItem="{Binding SelectedDeviceDiagnostics}" BorderThickness="1">
<ListView.View>
<GridView>
<GridViewColumn Header="Command" Width="180" x:Name="ML_0007">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding DiagnosticsCommand, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" FontSize="12" Margin="0 5 0 0" Width="165" TextAlignment="Center" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Name" Width="180" x:Name="ML_0010">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding DiagnosticsName, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" FontSize="12" Margin="0 5 0 0" Width="165" TextAlignment="Center" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Units" Width="100" x:Name="ML_0013">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Units}" DisplayMemberPath="UnitName" SelectedValuePath="UnitCode" SelectedValue="{Binding DiagnosticsUnit, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Height="23" HorizontalAlignment="Left" VerticalAlignment="Top" Width="85" Margin="0,1,0,0" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
<ContentControl DockPanel.Dock="Top" Content="{Binding AddNewCAView}" />
<!-- No Diagnodtics message-->
<globals:NoItemsMessage DockPanel.Dock="Top" Visibility="{Binding NoDiagnosticsVisibility}" HorizontalAlignment="Left" Margin="10" Width="360" Height="40" Message="{x:Static ml:MultiLang._742}" x:Name="ML_0017" />
<!-- delete popup -->
<globals:DeletePopup IsOpen="{Binding IsConfirmDeletePopupOpen}" Message1="{x:Static ml:MultiLang._746}" DeleteCommand="{Binding DeleteCommand}" CancelCommand="{Binding CancelDeleteCommand}" Placement="Center" VerticalOffset="-200" HorizontalOffset="200" x:Name="ML_0018" />
</StackPanel>
</DockPanel>
</UserControl>
The Dock Panel binds to : DataContext="{Binding DeviceDiagnosticsMainVeiwModel}"
The list view binds are :
ItemsSource="{Binding CurrentDeviceDiagnostics}" SelectedItem="{Binding SelectedDeviceDiagnostics}"
and both CurrentDeviceDiagnostics and SelectedDeviceDiagnostics are members of DeviceDiagnosticsMainVeiwModel.
One text box (for example) in the list view bind like this :
Text="{Binding DiagnosticsCommand, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
CurrentDeviceDiagnostics is an observble collection of DeviceDiagnosticsVeiwModel which contains DiagnosticsCommand.
And works just fine (both of the textboxes).
The checkbox binds like this:
ItemsSource="{Binding Units}" DisplayMemberPath="UnitName" SelectedValuePath="UnitCode" SelectedValue="{Binding DiagnosticsUnit, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
And Units and DiagnosticsUnit are also members of DeviceDiagnosticsVeiwModel.
The Item source works fine and populated the way i need.
The problem is with the selected item... its initialized as empty although DiagnosticsUnit has an integer value.
Funny thing is that if I choose something from the combobox, the code goes to the DiagnosticsUnit property to the set function, so I'm not sure abou t this problem...
Even if I will change the combobox to a textbox using DiagnosticsUnit , it will work !
I used a lots of mvvm comboboxes and didnt have any binding problems but its the first time i have a combocox inside of a list view...
Please help me.
Thank you all !!!
| 1c7fd0fed809b0ebd7dc82e5b74c73243e041658c78933dfec3f4567946160a2 | ['3df56ebf5bb0466c98f59b5093874934'] | O.K
I finally found the problem !
It wasn't a binding problem.
this is very silly.
i had this code
public void GetItems()
{
_devicesDiagnostics = new ObservableCollection<DeviceDiagnosticsVeiwModel>(
(from dd in _dal.GetItems()
orderby dd.DeviceID
select new DeviceDiagnosticsVeiwModel(dd)
{
ObjectStatus = Status.NoChange,
Units = _manager.UnitRepository.Units
}
) .ToObservableCollection<DeviceDiagnosticsVeiwModel>()
);
}
The Units is a member in the view model (DeviceDiagnosticsVeiwModel) and it's actually the comboboxs item source.
Inside of DeviceDiagnosticsVeiwModel there's an int property which is the selected item. It didnt load it right.
The correct code will be
public void GetItems()
{
_devicesDiagnostics = new ObservableCollection<DeviceDiagnosticsVeiwModel>(
(from dd in _dal.GetItems()
orderby dd.DeviceID
select new DeviceDiagnosticsVeiwModel(dd)
{
ObjectStatus = Status.NoChange,
Units = new ObservableCollection<UnitViewModel>(this.Units),
}
)
.ToObservableCollection<DeviceDiagnosticsVeiwModel>()
);
}
I had to give every object a new list. It worked.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.