_id stringlengths 2 6 | text stringlengths 4 46k | title stringclasses 1 value |
|---|---|---|
d10901 | Utilize this piece of code:
return services.AddSwaggerGen(c =>
{
c.CustomOperationIds(e => $"{e.ActionDescriptor.RouteValues["action"]}"); | |
d10902 | I think it's because your way to writing data in files.
Working with files has 3 step:
1) Opening file
2) Read [from] / Write [to] file
3) Closing file
third step is what you don't handled it.
You want to write a list in file and you are opening that file in each iteration. It's not a good idea (opening and closing files have their overhead) when you can do it once.
I changed some of your new_booking function and wrote it here:
# New Booking *********
def new_booking():
askname = str(input("Please enter your name? "))
idnumber = random.randint(100, 999)
customer_total, numAdults, numChild = num_customers()
Num_people = numAdults + numChild
nights_total, asknights = num_nights(customer_total)
askbar = mini_bar()
askbreakfast = breakfast(Num_people, asknights)
askdinner = dinner(Num_people, asknights)
total = askdinner + askbreakfast + askbar + asknights
detailslist = (idnumber, askname, numAdults, numChild, asknights, askbar, askbreakfast, askdinner)
# I handled opening and closing file with [python with statement]
# It close files automatically at the end
with open('newbooking.txt', 'w') as f:
for i in detailslist:
f.write(str(detailslist) + '\n')
print(i)
print("your total amount is: £", total)
print("your Name & ID number is: ", askname, idnumber)
A: The problem here is that you havent actually defined askname in your pre_booked() function so you cant compare against it. In new_booking() you are asking for the username with askname = str(input("Please enter your name? ")) however in the pre_booked() case you dont so you cant use it there without first getting the values from somewhere.
Seeing that you save the new_booking() to a file you probably want to load the data from your file like this:
accounts = []
with open(r"<FILEPATH", "r") as booking_file:
for line in booking_file:
accounts.append(line)
In your new_booking function it might be better to put all the related data in line by line or maybe even use dicts so you can later be sure which values belong together instead of writing all the values into their own line. So you might want to do this instead:
with open('newbooking.txt', 'w') as booking_file:
f.write(detailslist)
Then you can read line by line and possibly use ´eval()´ to get a list or dictionary right from your string or atleast you know the values in one line belong together later on.
You might also want to consider using "a" for append instead of w for write in your bookings file depending if you want to have multiple booking values in your file or just the one. | |
d10903 | Okay, sticky bit's comment pointed me to the right solution. Thank you very much!
When specifying the ScanID with the table name/alias, then it is not considered as the SP Parameter "ScanID", but as a field name.
Solution:
DELETE FROM tbl_xmlfiles x WHERE x.`ScanID`=ScanID;
Can someone clarify, why the MySQL Parser thinks, that "ScanID" (sorry, here are backticks around the word - Stackoverflow makes this a quote automatically) is the SP Parameter? Aren't Backticks always meant to describe a MySQL field name? | |
d10904 | You could use this for a 3d plot:
ezsurf('x*sin(x*y)', [0,5,pi,2*pi])
You can also use ezmesh with the same arguments to draw the mesh only (with a transparent surface) | |
d10905 | I don't know if this helps you but the way I was able to automate python scripts on my web server was by using a windows 2016 server.
Then creating a .bat file that would run the script like this. Just make sure your file location is set correctly.
python C:\inetpub\wwwroot\top_10_week.py %*
Then use windows task scheduler to schedule the script to run after a certain time, I set mine to 3 hours but I'm sure you can do it every 5 minutes.
https://www.windowscentral.com/how-create-automated-task-using-task-scheduler-windows-10 | |
d10906 | You can use the collections.Counter class to help with counting:
from collections import Counter
in_str = '''5' TCAGATGTGTATAAGAGACAGTGCGTATTCTCAGTCAGTTGAAGTGATACAGAA
:: ::: :: : : : ||||| :
3' ATTCAGCCTGCACTCGTTACCGAGGCATGACAGAGAATTCACGTAGAGGCGAGCTAAGGTACTTGAAAGGGTGTATTAGAG'''
# split string into lines:
strs = in_str.split('\n')
line1 = strs[0]
line2 = strs[1]
length1 = len(line1)
assert length1 >= 15 # we assume this
# last 15 characters of the first line
suffix1 = line1[length1-15:length1] # or line1[-15:]
# the 15 characters of the second line that are under the above characters
suffix2 = line2[length1-15:length1]
# count occurrences of each characters:
c = Counter(suffix2)
found = c.get('|', 0) >= 5
print(found)
Prints:
True
A: How about something like this. First slice the second line based on the length of first line and then count the occurrence of | in that slice.
in_str = '''
5' TCAGATGTGTATAAGAGACAGTGCGTATTCTCAGTCAGTTGAAGTGATACAGAA
:: ::: :: : : : ||||| :
3' ATTCAGCCTGCACTCGTTACCGAGGCATGACAGAGAATTCACGTAGAGGCGAGCTAAGGTACTTGAAAGGGTGTATTAGAG'''
lines = in_str.strip().split("\n")
first_line_length = len(lines[0]) # 62
valid_char_start_index = (first_line_length - 15 if first_line_length > 15 else 1) - 1 # 46
required_slice = lines[1][valid_char_start_index:first_line_length] # : ||||| : #
occurrence_of_pipe_in_slice = required_slice.count("|") # 5
if occurrence_of_pipe_in_slice >= 5:
print("found")
In case the mapping is done in the beginning as mentioned in the comment, we can do something like this:
import re
in_str = '''
5' TCAGATGTGTATAAGAGACAGGTGTAATCGTTCCGCTTGAATGTACGTCATGAA
||||| :: : :: :: : : ::
3' ATTTGCAGTACACTCGTTACCGAGGCATGACAGAGAATATGTGTAGAGGCGAGCTAAGGTACTTGAAAGGGTGTATTAGAG'''
lines = in_str.strip().split("\n")
first_line_prefix = re.match(r"\d\'\s+", lines[0]).group() # "5' "
third_line_prefix = re.match(r"\d\'\s+",lines[2]).group() # "3' "
if len(first_line_prefix) < len(third_line_prefix): # To make sure that which ever line starts first we are picking correct index
valid_char_start_index = len(first_line_prefix)
else:
valid_char_start_index = len(third_line_prefix)
# valid_char_start_index = 3
try:
required_slice = lines[1][valid_char_start_index:valid_char_start_index+15] # ' ||||| '
except IndexError:
required_slice = lines[1][valid_char_start_index:] # in case the second line is smaller than the required slice it
# will consider to the end of the line
occurrence_of_pipe_in_slice = required_slice.count("|") # 5
if occurrence_of_pipe_in_slice >= 5:
print("found")
To Summarise we can create a function where can take input parameter as where we want to look for the mapping beginning or in the end. And then determine start and end indices accordingly. From there in both cases rest of the process is same. | |
d10907 | GetObject takes a resource name, not an index.
You need to construct the name of one of your resources.
The simplest way to do that is to name the resources Card0 through Card51 and call GetObject("Card" & CInt(LoopIndexInteger))
EDIT: You can also loop over My.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, false, true), but it may not be in order. | |
d10908 | I think this is due to the fact one (or more) item(s) is (are) being submitted in the collection you're trying to delete.
To check that, you can run the following PSQL query:
select workspace_item_id, item.item_id, submitter_id, handle from workspaceitem, item, handle where workspaceitem.item_id = item.item_id and handle.resource_type_id = '3' and handle.resource_id = workspaceitem.collection_id;
If the "handle" column corresponds to the handle of the collection you're trying to delete, check the submitter ID for that item. If the login as feature is enabled, you can login as that user (their IDs are listed in the "People" admin menu together with their names and emails), go to his / her submissions page, and cancel the submission. If not, you may have to contact that user to do it himself / herself.
If none of these approaches are possible, I assume it would be possible to delete the item directly from the database, but I would advise you against that approach (or at least make sure that you also remove all dependencies from all tables in the database).
Cheers,
Benoît | |
d10909 | The answer to this problem is to update Angular libraries versions (in my case from 5.1.0 to 5.1.1). | |
d10910 | The question here would be are you dead set on creating a 'model' or an automation works for you?
I would suggest ordering the dataframe by probability of picking the call every hour (so you can give the more probable leads first) and then further sorting them by number of calls on that day.
Something along the lines of:
require(dplyr)
todaysCall = df %>%
dplyr::group_by(propertyID) %>%
dplyr::summarise(noOfCalls = n())
hourlyCalls = df %>%
dplyr::filter(hour == format(Sys.time(),"%H")) %>%
dplyr::left_join(todaysCall) %>%
dplyr::arrange(desc(Prodprobability),noOfCalls)
Essentially, getting the probability of pickups are what models are all about and you already seem to have that information.
Alternate solution
Get top 5 calling times for each propertyID
top5Times = df %>%
dplyr::filter(Prodprobability != 0) %>%
dplyr::group_by(propertyID) %>%
dplyr::arrange(desc(Prodprobability)) %>%
dplyr::slice(1:5L) %>%
dplyr::ungroup()
Get alternate calling time for cases with zero Prodprobability:
zeroProb = df %>%
dplyr::filter(Prodprobability == 0)
alternateTimes = df %>%
dplyr::filter(propertyID %in% zeroProb$propertyID) %>%
dplyr::filter(Prodprobability != 0) %>%
dplyr::arrange(propertyID,desc(Prodprobability))
Best calling hour for cases with zero probability at given time:
#Identifies the zero prob cases; can be by hour or at a particular instant
zeroProb = df %>%
dplyr::filter(Prodprobability == 0)
#Gets the highest calling probability and corresponding closest hour if probability is same for more than one timeslot
bestTimeForZero = df %>%
dplyr::filter(propertyID %in% zeroProb$propertyID) %>%
dplyr::filter(Prodprobability != 0) %>%
dplyr::group_by(propertyID) %>%
dplyr::arrange(desc(Prodprobability),hour) %>%
dplyr::slice(1L) %>%
dplyr::ungroup()
Returning number of records as per original df:
zeroProb = df %>%
dplyr::filter(Prodprobability == 0) %>%
dplyr::group_by(propertyID) %>%
dplyr::summarise(total = n())
bestTimesList = lapply(1:nrow(zeroProb),function(i){
limit = zeroProb$total[i]
bestTime = df %>%
dplyr::filter(propertyID == zeroProb$propertyID[i]) %>%
dplyr::arrange(desc(Prodprobability)) %>%
dplyr::slice(1:limit)
return(bestTime)
})
bestTimeDf = bind_rows(bestTimesList)
Note: You can combine the filter statements; I have written them separate to highlight what each step does. | |
d10911 | Disregard, found out during the CurrentItem: Quantity lookup i had set the part name to string instead of lookup value. | |
d10912 | You should do something as shown below:
#include <string>
struct Input_Interface {
struct command_output {
std::string command;
void (*output_function)();
};
static void Clear();
static void Quit_loop();
};
int main() {
Input_Interface::command_output t = {"CLEAR", Input_Interface::Clear};
return 0;
}
Live example here
Although I would suggest using a functor object over function pointer. | |
d10913 | ARBCreateSubscriptionRequest has parameter "startDate" where you can set date the subscription begins.
If first price should be different from monthly payments you can also set parameter "trialAmount" for first payment
All information you can find here
http://www.authorize.net/support/ARB_guide.pdf
A: You should always charge the first subscription payment using the AIM API. The AIM API will process immediately and act as a verification for the credit card. You will know immediately if a card is invalid and before you create the subscription. If you schedule a payment to process the same day the subscription is created it does not process immediately. That process later that night. If the credit card is invalid you lose the opportunity to have the user correct it because they are no longer present at your website. | |
d10914 | You don't necessarily know that id2 is the third argument; it's the last argument. You can gather all the intervening arguments into a single tuple using extended iterable unpacking. Once you have the tuple of middle arguments, you can join them back together.
id1, *names, id2 = input_valores.split()
list_a["id1"] = int(id1)
list_a["name"] = " ".join(names)
list_a["id2"] = int(id2)
This is somewhat lossy, as it contracts arbitrary whitespace in the name down to a single space; you get the same result of 1, "foo bar", and 2 from "1 foo bar 2" and "1 foo bar 2", for instance. If that matters, you can use split twice:
# This is the technique alluded to in Ignacio Vazquez-Abrams' comment.
id1, rest = input_valores.split(None, 1)
name, id2 = rest.rsplit(None, 1)
rsplit is like split, but starts at the other end. In both cases, the None argument specifies the default splitting behavior (arbitrary whitespace), and the argument 1 limits the result to a single split. As a result, on the first and last space is used for splitting; the intermediate spaces are preserved.
A: You can use slicing.
args = input('Enter ID, name, and second ID').split()
id1 = int(args[0])
id2 = int(args[-1])
name = " ".join(args[1:-1])
A: you could use python's slicing notation for this
input_values = input("Press {}, o {} e o {}".format("id1", "name", "id2"))
listSplit = input_values.split()
id1 = listSplit[0]
name = join(listSplit[1:-1])
id2 = listSplit[-1]
def join(arr):
newStr = ""
for i in arr:
newStr += i + " "
return newStr[:-1]
where id1 is the first word, name is everything between the first index and the last which has been joined into one string and the third argument which is actually the last word.
Hope that helps.
A: this will work:
split = input_values.split()
id1 = int(split[0])
id2 = int(split[-1])
name = " ".join(split[1:-1]) | |
d10915 | Some phones include the rotation information, some phone don't, but the best way to know on videos that include this information is with mediainfo:
mediainfo --Inform="Video;%Rotation%" | |
d10916 | Use:
sum(*/*/*[. >=0])
and
sum(*/*/*[not(. >=0)])
Here is a complete transformation that uses these two relative XPath expressions:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="Statement_Details">
Statement <xsl:value-of select="position()"/>
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="Invoice_Details">
Invoice <xsl:value-of select="position()"/>
Positive: <xsl:value-of select="sum(*/*[. >=0])"/>
Negative: <xsl:value-of select="sum(*/*[not(. >=0)])"/>
</xsl:template>
</xsl:stylesheet>
When this transformation is applied on the following XML document (having the wanted structure):
<Billing_Statements>
<Statement_Details>
<Invoice_Details>
<Meter_Details>
<Consumption>-3</Consumption>
</Meter_Details>
<Meter_Details>
<Consumption>5</Consumption>
</Meter_Details>
</Invoice_Details>
<Invoice_Details>
<Meter_Details>
<Consumption>8</Consumption>
</Meter_Details>
<Meter_Details>
<Consumption>-12</Consumption>
</Meter_Details>
</Invoice_Details>
<Invoice_Details>
<Meter_Details>
<Consumption>22</Consumption>
</Meter_Details>
<Meter_Details>
<Consumption>3</Consumption>
</Meter_Details>
</Invoice_Details>
<Invoice_Details>
<Meter_Details>
<Consumption>4</Consumption>
</Meter_Details>
<Meter_Details>
<Consumption>-5</Consumption>
</Meter_Details>
</Invoice_Details>
</Statement_Details>
<Statement_Details>
<Invoice_Details>
<Meter_Details>
<Consumption>-13</Consumption>
</Meter_Details>
<Meter_Details>
<Consumption>25</Consumption>
</Meter_Details>
</Invoice_Details>
<Invoice_Details>
<Meter_Details>
<Consumption>77</Consumption>
</Meter_Details>
<Meter_Details>
<Consumption>-15</Consumption>
</Meter_Details>
</Invoice_Details>
<Invoice_Details>
<Meter_Details>
<Consumption>31</Consumption>
</Meter_Details>
<Meter_Details>
<Consumption>-3</Consumption>
</Meter_Details>
</Invoice_Details>
<Invoice_Details>
<Meter_Details>
<Consumption>-87</Consumption>
</Meter_Details>
<Meter_Details>
<Consumption>54</Consumption>
</Meter_Details>
</Invoice_Details>
</Statement_Details>
</Billing_Statements>
the wanted, correct result is produced:
Statement 1
Invoice 1
Positive: 5
Negative: -3
Invoice 2
Positive: 8
Negative: -12
Invoice 3
Positive: 25
Negative: 0
Invoice 4
Positive: 4
Negative: -5
Statement 2
Invoice 1
Positive: 25
Negative: -13
Invoice 2
Positive: 77
Negative: -15
Invoice 3
Positive: 31
Negative: -3
Invoice 4
Positive: 54
Negative: -87 | |
d10917 | Now site is working but showing nothing is here I think at that time server has got to many requests that's why it cannot be reached . | |
d10918 | Using reformulate will be helpful.
reformulate(names(tbest$model)[-1], 'encounter')
If the list of variable names are in x :
reformulate(x, 'encounter')
encounter ~ open_shrubland + Appalachian_Mountains + Boreal_Hardwood_Transition +
Central_Hardwoods + Piedmont + wetland + Badlands_And_Prairies +
Peninsular_Florida + Central_Mixed_Grass_Prairie + water +
New_England_Mid_Atlantic_Coast + grassland + mixed_forest +
cropland + Oaks_And_Prairies + Eastern_Tallgrass_Prairie +
evergreen_needleleaf + year + pland_change + evergreen_broadleaf +
Southeastern_Coastal_Plain + Prairie_Potholes + Shortgrass_Prairie +
urban + Prairie_Hardwood_Transition + Lower_Great_Lakes_St.Lawrence_Plain +
mosaic + Mississippi_Alluvial_Valley + deciduous_broadleaf +
deciduous_needleleaf + barren
A: We can create a formula with paste
as.formula(paste('encounter~', paste(names(tbtest$model)[-1], collapse = "+"))) | |
d10919 | while (c > 0){
...
c++;
}
This is going to cause an infinite loop. The segmentation fault is from reading symbols[4], which is an access violation.
I strongly recommend learning how to step through code in a debugger if you want to use this language. Good luck! | |
d10920 | You have infinite loop at while (filled == false) { ... }, because filled_f always sets filled to false (and the else if branch of the condition inside this loop as well does so). It's because you most likely missed figure brackets when writing else if block in filled_f. Your indentation hints that you wanted 2 statements to be in that block, but as of now, only the first is executed conditionally, and the second (filled = false;) is executed after the branch. In other words, with intuitive indentation this function looks like this:
bool filled_f() { //check if the spot is filled
if (out[x] != 'X' and out[x] != 'O') {
filled = true;
out[x] = player_out; //fill the input into the spot
}
else if (out[x] == 'X' or out[x] == 'O')
cout << "The square has already been used!\n";
filled = false;
return filled;
}
It sets filled = false; in any case, since if/else execute (depending on condition) the statement immediately following one of them (see here), and indentation is ignored (unlike in, e.g., Python, where indentation alone determines boundaries of conditions, loops, function etc), so only cout << ... is conditionally executed. To do what you want put figure brackets around appropriate statements the same way you already did for the first if branch to create compound statement (block) from them, which is a statement itself and does what you want - groups several other statements within it, executed in sequence:
bool filled_f() { //check if the spot is filled
if (out[x] != 'X' and out[x] != 'O') {
filled = true;
out[x] = player_out; //fill the input into the spot
}
else if (out[x] == 'X' or out[x] == 'O') {
cout << "The square has already been used!\n";
filled = false;
}
return filled;
}
Additional remarks
Note that logically it's not needed to have if condition in else since if the first if condition is dissatisfied, else if condition is definitely satisfied (look De Morgan's Laws) and you can just write else:
// ...
else {
cout << "The square has already been used!\n";
filled = false;
}
// ...
Also in your main loop, you use this:
if (x > 0 && x < 10){ //check if input is in range 1-9
filled_f(); //check if the spot is occupied
}
else if(x < 0 && x > 10) { //if input is out of range
cout << "Invalid! Enter again!\n";
filled = false; //repeat the asking input circle (the while)
}
to test whether x is within range, but your condition in else if is wrong (should be x <= 0 || x >= 10 instead of x < 0 && x > 10) and can be omitted altogether (again see De Morgan's Laws) by using just else. | |
d10921 | Thanks for all of your opinion.
I have tried use another way from Combine columns in matrix having same column name.
I think it's more suitable for my case, and don't take lot of time to execute.
nms <- colnames(tf_mat)
tf_mat_bind <- sapply(unique(nms), function(i)rowSums(tf_mat[, nms==i, drop=FALSE])) | |
d10922 | Use on to bing all your div scrollbar, including the dynamically created div.
$(document).on('scroll','.divClass', someFunction);
The .divClass must be present on all your container where you want to execute the someFunction function. | |
d10923 | For performance is better foreach cycle.
Visit this site with some benchmark of php and see which cycle is better for you:
http://www.phpbench.com/
A: If you're getting timeout (infinite loops) errors, neither while or foreach will do. You're better off looking at limiting how much your array is processed, and do it step by step (Pagination..?).
for ($i = 0; $i < 100; $i++)
{
//Do your thing. Don't use for each, use $array[$i]
}
if it's not numeric, use a while with two statements:
while ($test = current($array) && $i < 50)
{
//xxxx
next($array);
$i++;
} | |
d10924 | Well one method would be to set up replication from each of them to a single database. But that seems pretty time intensive. I think you might have to write a program to do it (either .net or SQL) because how would it know which record to take if you have two records with the same primary key?
If you know that there will never be any duplicates, you could just write sql statements to do it. But that's a pretty big if.
You might try something like http://www.red-gate.com/products/sql-development/sql-data-compare/ which will synchronize data and I believe it will also figure out what to do when there are two records. I've had very good luck with Red-Gate products. | |
d10925 | The issue is that the path for the log file is hard coded in the source code, as can be seen on github. The path C:\\tmp does however not exist per default in windows.
Simplest solution is just to create a tmp folder on your C drive | |
d10926 | Hm. Gallery1.Selected represents the entire record in the Sharepoint List. Can you add another . to Selected to get to the actual field you want to write?
Gallery1.Selected.Attendee (or the like)
A: Got it:
Patch('Child List',
Defaults('Child List'),
{
Title:"test",
ParentItem:
{
Id:Gallery1.Selected.ID,
Value:Gallery1.Selected.Title
}
}
) | |
d10927 | I just found out the answer to that. In useStyles (styles in my code) I added marginRight: 700, to root class. Then the stepper stretched.
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
marginRight: 700,
},
Now it's look like this. | |
d10928 | I was able to solve my problem. After pouring through the issues in Zurb's Github, I found a semi-related issue that was fixed in a recent pull request.
On a whim I merged it into my code, and it fixed the issue.
See here: https://github.com/seantimm/foundation/commit/7af78ddbcc5a516eafed588e7c17d90bee115567 | |
d10929 | You can try like this:
insert into mytable(Translation)
(select to_char(Translation) from sometable);
or like
insert into mytable(Translation)
(select to_char('yourValue') from dual); | |
d10930 | This got solved by upgrading Composer version to 2.
Jfrog throwing error when there is composer version 1.x while pulling Artifact.
Sometime an OS doesn't easily upgrade to Composer 2 due to missing CA certificates.
Can follow below steps:
*
*cd /etc/pki/tls/certs
*check ca-bundle.crt file is there or not: file /etc/pki/tls/certs/ca-bundle.crt
*sudo curl https://curl.se/ca/cacert.pem -o /etc/pki/tls/certs/ca-bundle.crt -k run this command to download the CA certificates extracted from Mozilla.
*upgrade composer using following this page https://getcomposer.org/download/ :
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === '55ce33d7678c5a611085589f1f3ddf8b3c52d662cd01d4ba75c0ee0459970c2200a51f492d557530c71c15d8dba01eae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"
(always take the latest version from the download page as it changes from time to time) | |
d10931 | Your host probably has error reporting turned off, try turning on error reporting with
ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);
at the top of your file, or check for a file called error_log in the directory of your script. | |
d10932 | "(aaa)bb\\1". You need to escape the backslash.
A: Both C++ and the regex use \ as an escape character. When you use it in your string C++ is interpreting it as octal character constant 1. You'll need to double escape the 1: std::string regx="(aaa)bb\\1";
A: In addition to needing to escape your backslash:
Boost::regex sets the extended-syntax specific no_bk_refs flag by default. If you want to use back-references with extended syntax you'll have to unset it yourself:
flags = boost::regex::extended & ~boost::regex::no_bk_refs;
A: I fix this problem by chaning this row
boost::regex_constants::syntax_option_type flags = boost::regex::extended;
to
boost::regex_constants::syntax_option_type flags = boost::regex::bk_vbar;
and ofcourse use \\
and this work for me.
thanks | |
d10933 | You have provide only a pseudo-code. You should have provide your actual code so that I may have guided you better. Anyhow you may use the following short form for your long swith statement.
var cases = {
1: doX,
2: doY,
3: doN
//......................cases from 4 to 19
20: doZ
};
if (cases[something]) {
cases[something]();
}
Hope it helps.
A: You can if there are some cases for which task is same. For example: if for both case 1 and case 10 same method doX() happens, you could do this:
switch (something) {
case 1:
case 10:
doX();
break;
//...
}
Furthermore, if you have a common task that you would be done for many cases like for case - 12, 13, 14, 15 and 16, doA() will be executed. Let it be for default case. It will lessen writing many cases.
switch (something) {
// for case 12, 13, 14, 15, 16
default:
doA();
break;
}
A: You might use ES6 Map functionality to create a map of your functions then you just need to call it with the dynamic key value.
var myMap = new Map(),
doX = n => console.log(n),
doY = n => console.log(n*2),
doN = n => console.log(n/2),
something = 2;
myMap.set(1,doX)
.set(2,doY)
.set(3,doN);
myMap.get(something)(4);
The same could be implemented by an ordinary object as well like
var myMap = {},
doX = n => console.log(n),
doY = n => console.log(n*2),
doN = n => console.log(n/2),
something = 3;
myMap[1] = doX;
myMap[2] = doY;
myMap[3] = doN;
myMap[something](4); | |
d10934 | #include <stdio.h>
int main()
{
int result, i, n;
printf("Input n: ");
scanf("%d", &n);
for(int i = 1; i <= n; i++)
{
result = i*i;
printf("%-3d", result);
}
}
OUTPUT: 1 4 9 16... n^2
Probably, you want this.
You should scan the value of n before the loop. Otherwise, the behavior of your program would be unpredictable. Second, it is wise to avoid floating-point calculations when possible and here you want to print the series of square of integers. i.e. 1,4,9,... so you shouldn't use
double pow(double a, double b)
function. Also as Fred said, "Calculate result before you print it." | |
d10935 | You can learn the criteria in SET DEADLOCK_PRIORITY (Transact-SQL):
Which session is chosen as the deadlock victim depends on each
session's deadlock priority:
*
*If both sessions have the same deadlock priority, the instance of SQL Server chooses the session that is less expensive to roll back as
the deadlock victim. For example, if both sessions have set their
deadlock priority to HIGH, the instance will choose as a victim the
session it estimates is less costly to roll back.
*If the sessions have different deadlock priorities, the session with the lowest deadlock priority is chosen as the deadlock victim.
For your case, A should be considered by DBMS the less expensive transaction to roll back.
A: There's no way to know just be looking at the queries. Basically, so far as I understand things, the engine considers all transactions involved in the deadlock and tries to work out which one will be the "cheepest" to roll back.
So, if, say, there are 2 rows in your Customers table, and 9000000 rows in your Orders table, it will be considerably cheeper to rollback the UPDATE applied to Customers than the one that was applied to Orders. | |
d10936 | I have managed to partly work this out.
One of the problems was with the program behaving nondeterministically. This is just because (1) OpenMP performs reductions in thread-completion order, which is non-deterministic, and (2) floating-point addition is non-associative. I assumed that the reductions would be performed in thread-number order, but this is not the case. So any OpenMP for construct that reduces using floating-point operations will be potentially non-deterministic even if the number of threads is the same from one run to the next, so long as the number of threads is greater than 2. Some relevant StackOverflow questions on this matter are here and here.
The other problem was that the program occasionally hangs. I have not been able to resolve this issue. Running gdb on the hung process always yields __psynch_cvwait () at the top of the stack trace. It hangs around every 10^8 executions of the parallelised for loop.
Hope this helps a little. | |
d10937 | You can construct a MultiIndex object from the year and month and assign it to the data frame's index:
import pandas as pd
d.index = pd.MultiIndex.from_arrays([d.index.year, d.index.month])
d.index
# MultiIndex(levels=[[1970, 1971], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]],
# labels=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]])
d.head()
# 0
#1970 1 0.657130
# 2 0.047241
# 3 0.984799
# 4 0.868508
# 5 0.678536
A: d.index = pd.MultiIndex.from_tuples(d.reset_index()['index'].\
apply(lambda x:(x.year,x.month))) | |
d10938 | Jus a note, in 2016 Parse has closed (it's now open source and you run it on Heroku or whatever). There are many other "baas" such as Firebase etc.
Since there seems to be some confusion,
(a) your current service has no API. it is, thus, unfortunately essentially useless so your most absolutely time saving step from here would be just scrap it and use parse (or another baas) as the backend. you can have parse up and running in minutes. what previously took server developers man-years is now just like "a consumer product", just make a few clicks to add column-names
(b) your current service has no API. assuming yo DO WANT TO continue to use it, you will have to somehow add an API, using php or whatever. there's no way to avoid this. IF you do that, then you could (if you wanted) make a "basic" API that parse can get the info from, and then use parse to actually connect to the ios/android builds (since that is so easy)
TBC, here's literally how you do that in Parse,
https://parse.com/docs/cloud_code_guide#networking
"Cloud Code allows sending HTTP requests to any HTTP Server" it's that simple.
As I mention above, it's far easier just to scratch your current backend and change to a bAAs (such as Parse). you have to "go with the times" you know?
Note that the development and testing of an API on a service is incedibly time consuming, it is a huge job for a team.
Here on this question you seem to be asking about bAAs and how they fit in the formula. the answers are:
(1) if you simply scrap your current service, do everything on a baas: it is trivial. what used to take literally man-years is now a few clicks
(2) in terms of "helping you ADD AN API to that service". bAAs cannot help you with that in any way and is irrelevant
(3) if you DO have a service with an API, yes it is relatively easy to have bAAs "link in" to that. (i include literally the doco from pare on doing that above)
Hope it helps!!! | |
d10939 | There isn't really a relationship type in Laravel for your specific use case. The easiest thing you can do in this case is create a separate hasMany relationship for each of your post types, and then write a function that returns a combination of all the results.
So you'd end up with something like this in your User class:
public function videoPosts()
{
return $this->hasMany(App\VideoPost::class);
}
public function textPosts()
{
return $this->hasMany(App\TextPost::class);
}
public function getPosts()
{
return $this->textPosts->concat($this->videoPosts);
}
You can then just keep chaining concat calls for every other post type you may want to add. | |
d10940 | Qt is, among other things, a great framework for developing applications with GUIs. The only way to know if it is appropriate is to try it out. I suggest going through this Qt tutorial, which involves creating a simple game.
A: To begin with Qt is an excellent idea. Qt is already simpler.
You should begin with these official tutorials: http://doc.qt.nokia.com/4.7-snapshot/tutorials.html
A: GUI program is a big change from a console app - the difference is that you don't know when things are going to happen and in what order.
But Qt is a very good place to start, the signal/slot mechanism is much clearer (IMHO) than the hidden macros of MFC or some other gui toolkits. | |
d10941 | The SDR or SVR channel will always open the transmission queue for exclusive use. If the .Net client is getting an error because of this then it is asking for input rights as well as inquire. You can verify this by using WMQ Explorer to inquire on the queue and you will see that it has no problem getting queue attributes, depths, etc. So open for inquire but not browse or get and you should be fine. | |
d10942 | The most likely reason for this is because the process hasn't spun up yet. You need to hit an ASP page first before IIS spins up the DLLHOST.exe in which it runs an application if you have that application set to have high isolation (recommended for debugging purposes).
Hence debugging bia attachment requires the you use the browser to ping an ASP page in your site first, then open the Attach to process list.
A: I had the same problem. I fixed it out installing Service Pack 1 for my Visual Studio 2008. And now I attach to "inetinfo.exe" process instead of "dllhost.exe".
A: The following steps might help you:
*
*Host the site is IIS and make sure it's running
*Change the Application Configuration to enable debugging
*Then Attach the debugger to w3wp (IIS worker process) | |
d10943 | Go with "the sum of something".
I don't see it is a problem.
If you really dislike it, just write your own function to do it.
As you already know, it is not hard.
Detail
Box2D is not an architectural library.
As far as I know, there is no such function.
In 3D Physics and Graphics, I also faced a little inconvenience like this.
There are 2 choices for me :-
*
*hard code "the sum of something" (I start to love this phrase.)
*encapsulate such library (e.g. Box2D) / code a utility function
I usually pick one of the choices, depends on situation.
Because it is only little inconvenience, I believe the first is suitable for your situation.
By the way, there are reserved margin between colliding fixtures, so I think you can't set the exact position.
there is always a small margin of space added around the fixture by default.
A: An explanation of what's going on...
For static and kinematic bodies, where you place them is where they'll be. In other words, if you call b2Body::SetTransform with a position of pos and then call b2Body::GetPosition, the returned value should equal pos. This should hold true even if these bodies overlap each other. They won't move unless you tell them to.
Dynamic bodies behave differently however. They behave more like we'd expect solid bodies to behave in the real world. But we can do things to them still that couldn't practically be done to real solid objects. For instance, we can call b2Body::SetTransform on one dynamic body to place it (or part of it) within another body. Now the physics engine works to figure out where to move the dynamic body so that it's not within the other body anymore (and in a way that's intended to appear reasonable enough given what the initial overlap may look like).
More precisely, the 2.3.2 Box2D library will resolve the overlap of two bodies (where one or both are dynamic) as much as b2_maxLinearCorrection for each position iteration until minSeparation >= -3.0f * b2_linearSlop where minSeparation is the distance separating the closest vertices (of both shapes) in the separating plane minus the sum of the vertex radiuses (of both shapes). The "sequential solver" does this via impulses but without influencing the body velocity values so that neither body acts as if it had any additional momentum.
You can take a look at the code involved in the b2ContactSolver::SolvePositionConstraints method of the b2ContactSolver.cpp file.
So in a sense, the Box2D world step "calculates the position" for you. Note however the following caveats:
*
*This position resolution doesn't always complete in one step. I.e. users may watch as the box moves out from the wall till it appears entirely out.
*If you place the box too far into the wall, it will appear on the opposite side of the wall.
*You may want to factor in to your expectations the total of the vertex radiuses - i.e. sum the values of the shapes' m_radius values. This is referred to as the reserved margin of space. For two polygons, this will be 4.0f * b2_linearSlop or 0.02f (2 centimeters).
Insofar as placing an object beside another precisely then:
*
*You can place non-dynamic bodies beside each other as precisely as floating-point values allow.
*You can place a dynamic body beside another body only as close as position resolution allows (and only as precisely as floating-point values allow). Any closer, and the "sequential solver" will move it back out. | |
d10944 | So I've found out that one of my entity class extends ViewModel. Removing it solved the problem. Just check your entity class.
Thanks. | |
d10945 | Have a look at SpecFlow Assist Helpers. There are a few helpful methods, you can try to use table.CreateInstance<T> method to convert row in your table to object for future use. You can also specify the custom mapping using TableAliases attribute, see Working Effectively with SpecFlow Tables article for details | |
d10946 | You can use a two pointer approach + counting the frequencies.
static int countSub(String str)
{
int n = (int)str.length();
// Stores the count of
// subStrings
int ans = 0;
// Stores the frequency
// of characters
int []cnt = new int[26];
// Initialised both pointers
// to beginning of the String
int i = 0, j = 0;
while (i < n)
{
// If all characters in
// subString from index i
// to j are distinct
if (j < n &&
(cnt[str.charAt(j) - 'a'] == 0))
{
// Increment count of j-th
// character
cnt[str.charAt(j) - 'a']++;
// Add all subString ending
// at j and starting at any
// index between i and j
// to the answer
ans += (j - i + 1);
// Increment 2nd pointer
j++;
}
// If some characters are repeated
// or j pointer has reached to end
else
{
// Decrement count of j-th
// character
cnt[str.charAt(i) - 'a']--;
// Increment first pointer
i++;
}
}
// Return the final
// count of subStrings
return ans;
}
Here it considered only lower case letters. You can refer here | |
d10947 | You can't link a Credential asset directly to Key Vault, however it should be possible to write a script that connects to Key Vault and updates the appropriate Automation Credentials from there.
This could either be fired on a schedule, a webhook, or by picking up Key Vault events from the new Event Grid (presuming they are currently wired up) | |
d10948 | You can format the axis using axis.POSIXct as seen below:
axis.POSIXct(1,station_171$datetime, format = '%Y-%m-%d %H:%S')
One should also make sure to include the xaxt='n' in the plot function to avoid double printing the x-axis labels. | |
d10949 | Resize using JavaScript Client-Side-Processing
We're using JavaScript resizing, which uses clients device processing power to resize the image, and works GREAT, saving us space and money, saving the netwrok unnecesary bandwidth, and saving the client a bunch of time and also money in most mobile cases.
The original script we are using came from here, and the procedure to use it is as simple as this:
<input type="file" id="select">
<img id="preview">
<script>
document.getElementById('select').onchange = function(evt) {
ImageTools.resize(this.files[0], {
width: 320, // maximum width
height: 240 // maximum height
}, function(blob, didItResize) {
// didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob')
document.getElementById('preview').src = window.URL.createObjectURL(blob);
// you can also now upload this blob using an XHR.
});
};
</script>
I believe that guy (dcollien) deserves a LOT of merit, so I would recommend you to vote his answer up.
A: You can also use Firebase Storage + Google Cloud Functions to upload an image, resize the image (using ImageMagick or similar), and write it back to Firebase Storage.
I have an example using these together here (though I trigger the Cloud Vision API, rather than an image resizer).
A quick side note: Firebase Storage doesn't have a Node.js client, instead we recommend using the GCloud-Node library.
A: You could also use Firebase Storage + the official Firebase Resize Image extension:
https://firebase.google.com/products/extensions/firebase-storage-resize-images. The downside here is that "To install an extension, your project must be on the Blaze (pay as you go) plan". Bc basically what it will do is spin up a Firebase Function App for you, and it'll get triggered every time you upload a file to the path you specify. You can configure things like the desired size as well as the format or if you want to keep a copy of the original file or not. Good thing you won't need to worry about the underlying implementation. | |
d10950 | In your situation, you do not need a reset_var function, simply do:
i=50
j=40
unset i j
That is said, a possible reset_var function would be:
reset_var() {
while [ "${#}" -ge 1 ] ; do
unset "${1}"
shift
done
}
A: You have an infinite loop when passing some arguments. Your reset function should look something like this:
reset_var() {
for arg
do
unset ${arg}
done
} | |
d10951 | From the boost page on iterator_facade, the template arguments are: derived iterator, value_type, category, reference type, difference_type. Ergo, merely tell it that references are not references
class my_iterator
: public boost::iterator_facade<
my_iterator,
my_obj,
boost::forward_traversal_tag,
my_obj> //dereference returns "my_obj" not "my_obj&"
See it working here: http://coliru.stacked-crooked.com/a/4b09ddc37068368b | |
d10952 | From the official site
title "Types of Vehicles Produced Worldwide (Details)";
proc gchart data=sashelp.cars;
pie type / detail=drivetrain
detail_percent=best
detail_value=none
detail_slice=best
detail_threshold=2
legend
;
run;
quit;
This graph uses the data set entitled CARS found in the SASHELP
library. The DETAIL= option produces an inner pie overlay showing the
percentage that each DRIVETRAIN contributes toward each type of
vehicle. The DETAIL_PERCENT= option and the DETAIL_SLICE= option
control the positioning of the detail slice labels. The DETAIL_VALUE=
option turns off the display of the number of DRIVETRAINS for each
detail slice. The DETAIL_THRESHOLD= option shows all detail slices
that contribute more than 2% of the entire pie. The LEGEND option
displays a legend for the slice names and their midpoint values,
instead of printing them beside the slices. | |
d10953 | This should work. You wouldn't want to use a group_by here, you would do that if you were trying to go from more to less, we're going the other way.
You're combining the different versions with the corresponding severity. Here's how you could do that.
map(.fields | (.versions[] | { id, name }) + { value: .severity.value }) | |
d10954 | To get the authentication token, you need to pass the redirect URI to the call to WL.init:
WL.init({
redirect_uri: "<< INSERT REDIRECT DOMAIN HERE >>"
});
Where the redirect domain must be the same as the one in your Live Connect application. | |
d10955 | In another technology, I found it easier to have your date sent as ISO format (YYYY-MM-DD), unless you specifically need to have day, month and year received as parameters
A: Fixed by changed
params.orderDate = day + "/" + month + "/" + d.getFullYear();
to:
params.orderDate = moment().format('MM/DD/YYYY');
Since the HTTP docs applies application/x-www-form-urlencoded to the request params, and the two above expressions console.log(d) the same value, that leaves me guessing that the javascript compiler does not treat the output of both expressions the same, maybe in their data types.
If this is the case, how can this issue be best handled when it comes to sending other non alphanumeric characters collected from the client via jQuery..serializeArray() and ends up in the HTTP POST request params to a remote server? | |
d10956 | You'll have to update the version of g++ to 4.6.3 (or later) if you want to use c++11 features. See this question and it's answers on how to do it for deb linux.
Then you'll have to pass --std=c++0x to the compiler in options. You should be able to easily find them in codeblocks.
what is the difference between C++ 0x and C++11??
c++0x is a synonym for c++11.
A: The command:
g++ --version
gives you the version of your g++ or mingw compiler. Since you got g++ TDM-2 mingw32 4.4.1 then your version is 4.4.1. If you want to use version 4.6.3 as in that web site, then you would have to update.
It wouldn't hurt to use a newer than 4.6.3 version of mingw, so please see here for the latest version. This page offers an windows installer for mingw.
After installation, you would have to configure CodeBlocks to use the newly installed compiler by looking into Compiler and debugger settings -> Toolchain executables tab and setting the paths for the compiler-related executables to the new ones.
Hope this helps.
EDIT:
Here is a small tutorial/example of what the CodeBlocks settings look like. | |
d10957 | I've found the solution to the problem by some hit & trial.
It is because when we make getJSON() call on cross domain then response should be wrapped inside a function name. This function is our callback handler for the response in the script.eg
html file :
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js'></script>
<script type='text/javascript'>
$(function(){
$.getJSON("localhost:8080/test.jsp?callback=?");
}
function test(data){
alert(data.feed);
}
And the jsp test.jsp
<%@ page language="java" contentType="text/json; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%
response.setContentType("application/x-javascript");
out.write("test({\"feed\": \"test\"})");
%>
hope if anybody has the same problemm this will help.you can pass the callback function name as a parameter and make jsp at the server such that it uses that name to wrap the response.
A: I have encountered the same issue which was actually because of the some issue with json or ajax call. In your json call it should be {"test":"test"} instead of {test:"test"}.
Try it should work if this is the issue. | |
d10958 | Your code has non-standard characters in some of the white space, including right after K; | |
d10959 | You can do it like this as well? You can change your onclick events as follows:
Change onlick functions to this: onclick ="myFunction(this)"
And Update your javascript function to be like the following:
function myFunction(obj) {
if (obj.value == "Connected")
obj.value = "Connect";
else
obj.value = "Connected";
}
A: You cant use same Id for multiple elements. Simply you can use class instead of Id. Then your code will look like that :
$(".toggle").click(function(){}
$(this).text("Whatever");
}) | |
d10960 | I have spent more than 3 hours on this nonsense. It turned out to be a straightforward problem. I hope I can help somebody with this answer.
First, you must realize that you need 2 JavaScript functions.
1- A one that is executed after the submit button is pressed. In this function, always use:
event.preventDefault() to avoid form submission! You don't want to submit your form yet.
grecaptcha.execute() to initiate the reCAPTCHA.
You can execute this function with the submit button (onClick property).
2- A one that is executed after the reCAPTCHA is solved successfully. For this function, you only need:
document.getElementById("form").submit() to submit your form.
To execute this function, use data-callback property in your reCAPTCHA div element. As you can see in the docs, data-callback property is defined as
The name of your callback function, executed when the user submits a
successful response. The g-recaptcha-response token is passed to your
callback.
That's all you need. Make sure that your form only gets submitted with the second function you created, nothing else.
A: The following code does this:
*
*The <button class="g-recaptcha"... is the Automatically bind the challenge to a button. It will automatically trigger the invisible recaptcha when the button is clicked.
*Once the recaptcha is completed it will add a hidden field named g-recaptcha-response which contains the token and then run the onSubmit callback which submits the form.
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
function onSubmit() {
document.getElementById("formV").submit();
}
</script>
</head>
<body>
<a class="button"></a>
<div class="topBar">
</div>
<div class="underTopBar">
<form class="flex-itemform form" method="POST" id="formV">
<table>
<tr>
<td>
<div>
<button
class="g-recaptcha buttonDesign"
data-sitekey="..."
data-callback="onSubmit"
data-size="invisible">Senden</button>
</div>
</td>
<tr>
</table>
</form>
</div>
Important: You still need to verify the token g-recaptcha-response server side. See Verifying the user's response. Without verifying the token, adding the recaptcha to the frontend doesn't stop anyone from submitting the form. | |
d10961 | Probably because the function is not marked as a fixture. Try after decorating the function with @pytest.fixture. For example,
@pytest.fixture(scope="session")
def client():
api=create_app()
c = testing.TestClient(api)
yield c
remove_db() | |
d10962 | The golang specification says, "float64 is the set of all IEEE-754 64-bit floating-point numbers." which is commonly known as double precision numbers,
http://en.wikipedia.org/wiki/Double-precision_floating-point_format
You can read all of its glory details if interested, but to answer your question, quote,
"...next range, from 253 to 254, everything is multiplied by 2..."
So if you want to use it as counters, i.e. positive integers, you won't have problem until 253=9,007,199,254,740,992.
A: Yes, float64 has 52 bits to store your counter. You should be accurate until 253.
(Side note: the entire JavaScript language uses only Floating Point.) | |
d10963 | The problem is that the HestonModelHelper expects the type of the spot and the strike to be a float.
For it to work with minimal change, use:
helper = ql.HestonModelHelper(
p,
calendar,
spot.value(),
s,
ql.QuoteHandle(ql.SimpleQuote(vols)),
yield_ts,
dividend_ts
) | |
d10964 | The problem was that you'd have to use .text and not .textContent for ie8, because the textContent property doesn't exist in ie.
You can see in MDN that textContent is available only for ie 9+ | |
d10965 | Yes, you can. This is a "for each" loop. ch will have the value of each successive character in the string s.
A: This is named Range for loop and is a new syntax introduced in C++11. | |
d10966 | Tables for the win! fiddle
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#container { display: table; width: 100% }
#left, #right { display: table-cell; width: 50%; background: #ffd }
#content { display: table-cell }
</style>
</head>
<body>
<div id="container">
<div id="left"></div>
<div id="content">
<div style="white-space: nowrap" onclick="this.firstChild.nodeValue += ' blah'">blah</div>
</div>
<div id="right"></div>
</div>
</body>
</html>
A: Give the header a fixed width if you can. Then use jQuery to calculate the widths and set them accordingly.
Here is a working demo: http://jsfiddle.net/rniestroj/fsnuh/135/
html:
<div>
<h3 class="headline2">
<div class="spanl"></div>
<div class="center">Kontakt 11111111111 22222</div>
<div class="spanr"></div>
</h3>
</div>
css:
*{
padding: 0;
margin: 0;
}
h3{
width: 600px;
overflow: auto;
}
.spanr, .spanl {
background: url("../img/headline2.png") no-repeat scroll right center gold;
float: left;
height: 33px;
position: relative;
width: 33%;
}
.center {
background: none repeat scroll 0 0 #E6B043;
float: left;
height: 33px;
line-height: 33px;
padding: 0 10px;
position: relative;
text-transform: uppercase;
width: auto;
}
js:
var h3Width = $("h3").width();
var centerWidth = $(".center").width();
var asideWidth = 0;
asideWidth = ((h3Width - centerWidth) / 2) - 12;
$(".spanl").width(asideWidth );
$(".spanr").width(asideWidth );
A: Try this CSS only solution:
jsFiddle Example.
HTML:
<div id="headlines">
<h3 class="headline2">
<span>Kontakt</span>
</h3>
</div>
CSS:
#headlines {
background-image: url('../img/headline2.png'), url('../img/headline2.png');
background-repeat: no-repeat;
background-position: left center, right center
}
.headline2, .headline2 > span {
height: 33px;
text-align: center;
text-transform: uppercase;
line-height: 33px
}
.headline2 > span {
background-color: #E6B043;
display: inline-block;
padding: 0 10px
} | |
d10967 | FYI: indeed has discontinued their API.
I am posting this here because their website still lists it as active but when one tries to get a publisher id one gets redirected to an unrelated page without any explanation. After some time I called indeed and they told me it was discontinued.
Hopefully this saves other people time from trying to figure out what they are doing wrong in trying to get a publisher id.
A: when we try to do advance serch in indeed, like for company "facebook" than on result page we get in search box some thing like "company:Facebook".
So using this format in q parameter we can search that and to add other parameter also simple add space and that parameter in advance search.
like for company and title it will be like this
q="company:facebook title:Executive Assistant"
This will work for advance search, don't use url parameter like as_cmp and all it is not working.
A: I can't comment yet, so posting here. In case it is of use, here is the helpful reply I received from Indeed support. Thank you Indeed!
Hello,
Thank you for your interest in Indeed.
You can utilize our Advanced Search to create a targeted q value for your API calls. You can do this here: http://www.indeed.com/advanced_search? Add your criteria, press search then add the q value located in the 'What" box to your API calls. Please note, the more targeted search the less results.
For example: Here, I entered the "with these words in the title" junior developer and "company" IBM and received 3 results:
http://api.indeed.com/ads/apisearch?publisher=yourpublishernumber&q=title:(Junior%20Developer)%20company:IBM&l=&sort=&radius=&st=&jt=&start=&limit=&fromage=&filter=&latlong=1&co=us&chnl=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2
In this example, I used the selection "With all of these words" with junior developer and company "IBM" and received 28 results:
http://api.indeed.com/ads/apisearch?publisher=yourpublishernumber&q=Junior%20Developer%20company:IBM&l=&sort=&radius=&st=&jt=&start=&limit=&fromage=&filter=&latlong=1&co=us&chnl=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2
Please give this a try and let me know if it doesn't meet your needs.
Thank you,
Indeed Support Team
Indeed - How the World Works.™ | |
d10968 | LINQtoCSV only takes a StreamReader, not a stream. Try this:
using (MemoryStream mStream = new MemoryStream(System.Text.ASCIIEncoding.Default.GetBytes(data)))
using (StreamReader reader = new StreamReader(mStream))
{
IEnumerable<Data> datas = cc.Read<Data>(reader, inputFileDescription);
} | |
d10969 | You will need to process the Documentation of the test to see if it has a JIRA issue number, if so, then add a Tag (for example TagName) to it. When launching tests with robotframework version 4.0, you call them by passing the option --skiponfailure TagName. You will have those tests marked as SKIPPED.
The parsing of Documentation would be needed to parse before running the actual tests (in a helper test run). | |
d10970 | Solved
I wasn't able to get the Nico's solution to work for me, since I still needed to somehow bind within NutriDetailsControl.xaml to MyBasketItem, and no permutation I tried seemed to work.
After reading the Data Binding in Depth, I thought maybe I should forget about this whole custom control thing situation, and just go with a blank user control, called NutriControl.
I created a DependencyProperty in NutriControl.idl (blank user control) by adding
static Windows.UI.Xaml.DependencyProperty MyBasketItemProperty{ get; };
BasketItem MyBasketItem;
(Note that MyBasketItemProperty and MyBasketItem; must be the same). A DependencyProperty of a user control, "exposed" through the NutriControl.idl file, is basically like a box that you can put data into from other Xaml files (like MainPage.xaml). The data can be text, class objects (including your viewmodels), etc.
// Mainpage.Xaml
<local:NutriControl MyBasketItem="{x:Bind}"/>
"x:Bind" binds to the local DataContext (DataType??), which was a BasketItem here, so I didn't need to specify anything else.
// NutriControl.h
...other stuff...
struct NutriControl : NutriControlT<NutriControl>
{
NutriControl();
NutritionBasket::BasketItem MyBasketItem()
{
return winrt::unbox_value<NutritionBasket::MyBasketItem>(GetValue(m_myBasketItemProperty));
}
void MyBasketItem(NutritionBasket::MyBasketItem const& value)
{
SetValue(m_myBasketItemProperty, winrt::box_value(value));
}
static Windows::UI::Xaml::DependencyProperty MyBasketItemProperty() { return m_myBasketItemProperty; }
static void OnMyBasketItemChanged(Windows::UI::Xaml::DependencyObject const&, Windows::UI::Xaml::DependencyPropertyChangedEventArgs const&);
private:
static Windows::UI::Xaml::DependencyProperty m_myBasketItemProperty;
};
}
...other stuff...
// NutriControl.c
NutriControl::NutriControl() {
InitializeComponent();
}
Windows::UI::Xaml::DependencyProperty NutriControl::m_myBasketItemProperty =
Windows::UI::Xaml::DependencyProperty::Register(
L"MyBasketItem",
winrt::xaml_typename<NutritionBasket::BasketItem>(),
winrt::xaml_typename<NutritionBasket::NutriControl>(),
Windows::UI::Xaml::PropertyMetadata{ winrt::box_value(L"default label"), Windows::UI::Xaml::PropertyChangedCallback{ &NutriControl::OnMyBasketItemChanged } }
);
void NutriControl::OnMyBasketItemChanged(Windows::UI::Xaml::DependencyObject const& d, Windows::UI::Xaml::DependencyPropertyChangedEventArgs const& /* e */)
{
// still unimplemented
}
// NutriControl.Xaml
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button HorizontalAlignment="Right" VerticalAlignment="Center" Content=">">
<Button.Flyout>
<Flyout>
<Flyout.FlyoutPresenterStyle>
<Style TargetType="FlyoutPresenter">
<Setter Property="ScrollViewer.HorizontalScrollMode" Value="Disabled"/>
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
<Setter Property="IsTabStop" Value="True"/>
<Setter Property="TabNavigation" Value="Cycle"/>
</Style>
</Flyout.FlyoutPresenterStyle>
<StackPanel>
see here--------> <TextBlock Text="{x:Bind MyBasketItem.Nutrition.Amount, Mode=OneWay}"></TextBlock>
and here--------> <ListBox ItemsSource="{x:Bind MyBasketItem.Nutrition.Elems}">
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="local:BasketItemNutriElem">
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="{x:Bind Nutrient, Mode=OneWay}"/>
<TextBlock VerticalAlignment="Center" Text="{x:Bind Amount, Mode=OneWay}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
</StackPanel>
</Flyout>
</Button.Flyout>
</Button>
</StackPanel>
This worked. MyBasketItem (-> Nutrition) and (->Elems->BasketItemNutriElem) are both sub-viewmodels of type BasketItem, so I've successfully passed local instances of viewmodels from MainPage.Xaml to a user control.
A:
So I need to figure out a way to either pass in BasketItem, or BasketItemNutri, from the MainPage into custom user control.
You has placed NutriDetailsControl in the DataTemplate, so you can't use x:Bind to bind property in the code behind directly. For this scenario, the better way is that use bind element name then find it's DataContext
MyBasketItem="{Binding ElementName=ItemList,Path=DataContext.MyBasketItem}"
Please note, you need specific current page as page's DataContext.
public MainPage()
{
this.InitializeComponent();
DataContext = this;
}
For more detail please refer this case reply . | |
d10971 | What about Anonymous Types? Something like this:
return Ok(new { Zones, userZones });
A: I think that the best way to go is to creat a list, add the object to your list, and return the list. This way is also easyer if you need to work with these object.
To create a list, first we need to code a propper class:
public class Item {
public int Id { get; set; }
public Object MyObj { get; set; }
}
Now we can create and populate the list:
List<Item> items = new List<Item>()
{
new Item{ Id=1, MyObj= Zones},
new Item{ Id=2, MyObj= userZones}
}
Now you can return your list using: return items
A: You could also use anout parameter, like:
public Zones GetZones(..., out Zones userZones)
{
uzerZones = _ZoneService.GetUserZones(user);
return _ZoneService.GetZones();
} | |
d10972 | You don't feed a source URL to drawImage; it wants the image itself. This can be read from a DOM element or by constructing an Image object in code, as shown here:
var canvas = document.querySelector('Canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext('2d');
function drawImagesToCanvas() {
var imageArray = new Array();
imageArray[0] = "https://placehold.it/220x150";
// ...
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 20, 80, 220, 150);
};
img.src = imageArray[0];
}
drawImagesToCanvas();
<canvas></canvas> | |
d10973 | This code section here ,
return snapshot.hasData
? PostListView()
: Center(child: CircularProgressIndicator());
Add PostListView(posts:snapshot.data)
Tell me if it works. | |
d10974 | Not sure if this it what you want but here is code for finding the last (bottom) filled in cell in a column. Call it as lastRow = findLastRow(yoursheetname, yourcolumnname (like "F:F" or a named column) ):
Option Explicit
Function findLastRow(Sheetname As String, ColumnName As String)
Dim lastRow As Integer
Dim r As Range
Dim WS As Worksheet
Set WS = Worksheets(Sheetname)
lastRow = WS.UsedRange.Rows.Count
'*
'* Search backwards till we find a cell that is not empty
'*
Set r = WS.Range(ColumnName).Rows(lastRow)
While r.Value = ""
Set r = r.Offset(-1, 0)
Wend
lastRow = r.Row
Set WS = Nothing
findLastRow = lastRow
End Function
A: There are 2 easy ways to deal with this.
*
*Formatted Tables
*Named Range using an Offset()
Just put you list(s) on another admin/config/list sheet to get it out of the way.
Here are a few good sites explaining how to do it, if you search Excel dynamic validation list
http://excelsemipro.com/2011/05/a-dynamic-dependent-drop-down-list-in-excel/
http://www.contextures.com/xlDataVal02.html
https://www.extendoffice.com/documents/excel/4021-excel-data-validation-dynamic-range.html
https://chandoo.org/wp/2010/09/13/dynamic-data-validation-excel/
http://www.techrepublic.com/article/pro-tip-create-a-dynamic-validation-control-in-excel/ | |
d10975 | This tutorial is the best for me http://www.raywenderlich.com/44640/integrating-facebook-and-parse-tutorial-part-1
A: Why third party? What's wrong with Facebooks documentation? It's perfectly clear
https://developers.facebook.com/docs/ios/getting-started | |
d10976 | I don't know how this is done in C#, but you have also tagged this question WinAPI so I can help there. In WinAPI, it can be done like so:
#include <stdio.h>
#include <Windows.h>
#include <Psapi.h>
#pragma comment(lib, "Psapi.lib")
int main(void)
{
/* Hacky loop for proof of concept */
while(TRUE) {
Sleep(100);
if(GetAsyncKeyState(VK_F12)) {
break;
}
if(GetAsyncKeyState(VK_LBUTTON)) {
HWND hwndPt;
POINT pt;
if(!GetCursorPos(&pt)) {
wprintf(L"GetCursorPos failed with %d\n", GetLastError());
break;
}
if((hwndPt = WindowFromPoint(pt)) != NULL) {
DWORD dwPID;
HANDLE hProcess;
GetWindowThreadProcessId(hwndPt, &dwPID);
hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, dwPID);
if(hProcess == NULL) {
wprintf(L"OpenProcess failed with error: %d\n", GetLastError());
} else {
wchar_t lpFileName[MAX_PATH];
DWORD dwSize = _countof(lpFileName);
QueryFullProcessImageName(hProcess, 0, lpFileName, &dwSize);
wprintf(L"%s\n", lpFileName);
CloseHandle(hProcess);
}
}
}
}
return EXIT_SUCCESS;
}
Example result:
In this case, I am simply polling to get the mouse click. A more proper way would be to use some sort of windows hook.
A: As Mike Kwan said, you'll be better of writing a hook though both approaches have their own drawbacks, but bjarneds already did a good work on this. Have a look @ DotNET Object Spy. It's written in C# and will serve for your needs and more.
You should also note that using hooks are becoming redundant by the day. Depending on what you want to do, other winapis like GetForegroundWindow might serve better. | |
d10977 | Two solutions:
*
*You could paginate your results
*You could hydrate your results into arrays
You could do something like this
$query = $this->cert_repository
->createQueryBuilder('p')
->select(array('p'))
->where('p.isTemplate = :isTemplate')->setParameter('isTemplate', true)
->andWhere('p.policies = :policies')->setParameter('policies', $pol->getId())
->getQuery()
->setFirstResult($offset)
->setMaxResults($limit);
return $query->getArrayResult();
Basically, when Doctrine hydrates objects, it keeps reference of the object's data into memory and using the function unset will not free the memory, however hydrating the objects into arrays lets you use the function unset. | |
d10978 | Try this:
<Extension()> _
Public Function ToList(Of TItem, TList As {New, List(Of TItem)})(ByVal item As TItem) As TList
Dim tList As New TList
tList.Add(item)
Return tList
End Function
Basically your return type was a generic (declared as List (of T)). The function decaration here does it so that the return type is a list of the type that is being extended.
A: Try this.
<Extension()>
Public Function ToList(Of T)(ByVal Item As Object) As List(Of T)
Dim tlist1 As New List(Of T)
tlist1.Add(Item)
Return tlist1
End Function | |
d10979 | If I understand correctly, the challenge is that your library needs to know how to parse ValueField (and perhaps KeyField) but the library itself does not know their types; only the caller of the library does.
The way to solve this is to have the caller pass in a "prototype" instance of their message type, from which you can spawn additional instances:
map<string, Message*> parse(string data, const Message& prototype) {
map<string, Message*> result;
MapProto proto;
proto.ParseFromString(data);
for (int i = 0; i < proto.entry_size(); i++) {
Message* value = prototype->New();
value->ParseFromString(proto.entry(i).value());
result[proto.entry(i).key()] = value;
}
return result;
}
The caller would call this function like:
map<string, Message*> items = parse(data, MyValueType::default_instance());
Then, each message in the returned map will be an instance of MyValueType (the caller can use static_cast to cast the pointer to that type). The trick is that we had the caller pass in the default instance of their type, and we called its New() method to construct additional instances of the same type. | |
d10980 | You can compress XM, S3M, IT and MOD files to MO3.
There is no way to convert MP3, WAV, OGG or FLAC to MO3, because the way of saving the audio is fundamentally different. It's like giving your computer a cd and asking it to write out the notes for all instruments, the lyrics and special effects.
Maybe this can help you, as somebody finds some hackings... http://www.un4seen.com/forum/?topic=1953.0 | |
d10981 | I would use forkJoin in the following fashion:
ngOnInit() {
forkJoin([
this.habitService.fetchAllById(this.authService.userId),
this.status$ = this.statusService.fetchAll()
]).subscribe(([habits, statuses]) => {
this.joined = habits.map(habit => ({
...statuses.find(t => t.habitId === habit.habitId),
...habit
}));
});
}
see simple demo | |
d10982 | <script>
function myFunction($i) {
alert(x);
<?php
$_SESSION["id"] = $i;
?>
}
</script>
You are trying to include php code in javascript thinking you will change php global variable at client end when a click event happens. This is not the right way.
Sessions are for saving session variables. You are using sessions for passing GET params to server. Session variables can't be updated from client end since they are not exposed to client.
Sessions in PHP :
The contents of the SESSION superglobal cannot be changed. This lives on the server and the client has no way to access this.
However, a session id is passed to the client so that when the client contacts the server the server knows which session to use. This value could be changed which would allow a user to use someone else's session.
A: As brute_force already mentioned, the problem is
<?php
$_SESSION["id"] = $i;
?>
This code is executed server-side, before the page is sent to the user. That's the difference between PHP and javascript: javascript is executed at runtime, while the page is loaded, but the PHP in the page is executed in order to load the page, so the SESSION["id"] is set to 10 in your while-loop, and then, in the mentioned piece of code, put into the SESSION variable.
In order to get the variable in the session at runtime, you must create a request to a PHP script on the server, which in turn puts it in the SESSION. Have a look at (jQuery) ajax, that's the easiest solution in this case.
A: but what you are trying to do? php is server side language and javascript is client side. you must do a ajax call to pass the value ID.
A: You can not execute server side codes on client through JS . Coming to your problem you can send it to php via string query
** BEST SOLUTION FOR THIS PROBLEM IS STRING QUERY**
while($query_row = mysql_fetch_assoc($query)) {
echo "<tr><td><a
href='page.php?id='.$i>".$query_row['title']."</a></td><td>$i</td>";
$i = $i + 1;
}
page2.php
<?php
id=$_REQUEST['id'];
echo $id;
?>
Or if rigid to session use ajax. A cheat solution with iframe(without ajax) is below
<?php
echo "<table>";
$con = mysql_connect("localhost","root","") or die ("problem");
mysql_query("SET NAMES 'utf8'", $con);
mysql_select_db("dedomena");
$query = mysql_query("SELECT * FROM posts");
$i = 1;
while($query_row = mysql_fetch_assoc($query)) {
echo "<tr><td onclick='myFunction(i)'><a
href='page.php'>".$query_row['title']."</a></td><td>$i</td>";
$i = $i + 1;
}
echo "</table>";
?>
function myFunction(i) {
alert(i);
var html='';
html +='<div id="fakeDiv">';
html +='<form action="setSession.php" method="post" id="fakefrm" target="ifk">';
html +='<input type="hidden" name="jsvar" id="jsvar" value="'+val+'"/>';
html +='</form>';
html +='</div>';
html +='<iframe name='ifk'style='display:none;></iframe>';
var c=document.createElement('div');
document.body.innerHTML += html;
document.getElementById('fakefrm').submit();
document.body.removeChild(document.getElementById('fakeDiv'));
}
setSession.php
<?php
session_start();
$_SESSION['id']=$_POST['jsvar'];
?>
Add setSession.php in your project..
NOTE - In fact , if i see this answer in quick , i caste downvote this , but this answer is an instant relief for a guy who is unaware the name "ajax" | |
d10983 | your problem is that you shouldn't use property <param name="actionName">AdminIndex</param>, here is the solution:
<result name="success" type="redirectAction">
<param name="actionName">AdminIndex</param>
</result>
regarding to the doc Struts2 Redirect Action Result Type, you should use redirectAction instead redirect
Answer to your questions:
*
*please give us more detail.
*try this (assuming that your namespace config is correct):
<action name="ConfigurerDureeStockageSave" class="fr.si2m.occ.web.actions.admin.ConfigurerDureeStockageAction" method="savePeriod">
<result name="success" type="redirect">
<param name="location">adminIndex.action</param >
</result>
</action>
or
<action name="ConfigurerDureeStockageSave" class="fr.si2m.occ.web.actions.admin.ConfigurerDureeStockageAction" method="savePeriod">
<result name="success">
<param name="location">adminIndex.jsp</param >
</result>
</action>
*because result type redirect doesn't have property actionName, you should use redirectAction result type, which has this property | |
d10984 | How about
%p= item.price + " dollars".html_safe
A: This answer is for a slightly different question but I found this question searching for it...
If you have a submit tag %input{ :type => "submit", :value => " dollars", :name => "very_contrived" } even if you throw an html_safe on the :value it will not evaluate the html.
The solution is to use the rails helper... duh
= submit_tag " dollars".html_safe
this is pretty obvious but it tripped me up. Legacy code + rails upgrade = this kind of stuff :P
A: Use != instead of =
See "Unescaping HTML" in the haml reference: http://haml.info/docs/yardoc/file.REFERENCE.html#unescaping_html
A: The interpolation option:
%p= "#{item.price} dollars".html_safe
A: I tried using html_safe in different ways, but none worked. Using \xa0 as suggested by ngn didn't work, either, but it got me to try the Unicode escape of the non-breaking space, which did work:
"FOO\u00a0BAR"
and .html_safe isn't even needed (unless something else in the string needs that, of course).
The Ruby Programming Language, first edition, says: "In Ruby 1.9, double-quoted strings can include arbitrary Unicode escape characters with \u escapes. In its simplest form, \u is followed by exactly four hexadecimal digits ..."
A: You could use \xa0 in the string instead of . 0xa0 is the ASCII code of the non-breaking space.
A: I prefer using the character itself with the escaped HTML method with most symbols other than the whitespace characters. That way i don't have to remember all the html codes. As for the whitespace characters i prefer to use CSS, this is a much cleaner way.
%p&= "#{item.price} $%&#*@" | |
d10985 | Ok, so firstly your initialisation is completely wrong! Secondly where is your declaration for your struct instance? Thirdly you are missing several semi-colons to close off statements, next you are accessing your arrays wrong, please look at my code ad work from that.
struct gridblock
{
bool occ;
double col[3];
double trans[3];
}grid[10][19];
void initgrid(gridblock& grid[10][19])
{
grid[0][0].trans[0] = 3.3;
grid[0][0].trans[1] = 5.1;
grid[0][0].trans[2] = 7.0;
grid[0][0].occ = false;
....
}
int main(int argc, char **argv)
{
gridblock grid;
initgrid(grid);
return 0;
}
I would also recommend going through a beginner C++ book to learn these fundamental concepts, I get the feeling you have jumped ahead to structs way to fast!
A: The problem is that you have not enabled the C++11 compiler switch. That capability is new. The warning you is telling you to enable the switch. Changing the code won't help. You have to change the configuration of your compiler. | |
d10986 | HTML is not JSON, and it can not be parsed into JSONObjects. The top answer for org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject is pretty good at explaining this further. | |
d10987 | you can use strncmp() function from string.h
strncmp(str1, str2, size_of_your_string);
Here you can manually give the size of string(or the number of characters that you want to compare). strlen() may not work to get the length of your string because your strings are not terminated with the NUL character.
UPDATE:
see the code for comparison of unsigned char array
#include<stdio.h>
#include<string.h>
main()
{
unsigned char str[]="gangadhar", str1[]="ganga";
if(!strncmp(str,str1,5))
printf("first five charcters of str and str1 are same\n");
else
printf("Not same\n");
}
A: Since you know the size of the array, you could use strncmp():
int strncmp (char *string1, char *string2, int n)
with n being the number of characters to compare.
Deets: http://www.tutorialspoint.com/ansi_c/c_strncmp.htm
A: two years later, but...
I believe ‘memcmp‘ is the function you want to use, since ‘strncmp‘ may stop if it found a zero byte inside the compression string. | |
d10988 | NSArray is a single-dimensioned array, but you're trying to use it as a two-dimensional array. I can't see how this would ever compile.
You need to translate into Swift types immediately so you can continue programming in Swift, not go adrift in a sea of force-unwrapped Optionals.
How about:
if let ar = sender.draggingPasteboard().propertyListForType("ABLinkedPeopleUIDsPboardType") as? [[String]] {
// I'm assuming you're expecting to get back a two-dimensional array of Strings, or in the Obj-C realm, an NSArray of NSArrays of NSStrings
let uniqueID = ar[0][0]
}
else {
print("Property List for ABLinkedetc. is not a 2D String Array!")
}
Hayden's link is the correct general discussion but if you're new to bridging Obj C to Swift it may be difficult to apply in your particular case. | |
d10989 | I figured out how to do it without breaking existing functionality. Unfortunately I have to add code to every Plan I have but it is quite small change any way.
First define intent.
object AllowAllOrigin extends unfiltered.kit.Prepend {
def intent = Cycle.Intent {
case _ ⇒ ResponseHeader("Access-Control-Allow-Origin", Set("*"))
}
}
Then add it to intent in plans, if got two things you want to do before Plan specific stuff just add more.
def intent = AllowAllOrigin { Authentication(config) {
case _ => Ok // or perhaps something more clever here :)
}} | |
d10990 | I don't know if i got your question right, but normally, if you set up an new menu-module you can set the Menu you want to use and the Base-Item (Home) where all the Sub Items are placed.
So if you want to only display the Sub-Items of home you normally should then set start-level to "1" (Since your base item is already "Home" and you want to display down all items from home... so if you choose "3" it would start displaying menus that are the third sublevel of "home") and end-level to "all" (or the maximal depth you choose), assign the right position for the Module and give it a go. | |
d10991 | This is not possible. It is possible to copy all text from a textbox but there are no viable options to only copy selected text to clipboard.
How can I click a button in VB and highlight a text box and copies conent to clipboard? | |
d10992 | public static void main(String[] args){
if (c == 1){
//...
double area1 = Integration.Areaf(lower, upper);
double area2 = Integration.Areag(lower, upper);
sum = area1 - area2;//sum and minus used?
System.out.println("Area between the two curves = " + sum);
}
}
Also you used inheritance incorrectly cause all your methods in base class (Integration) are static. You can simply delete extends clause from sub class or adjust it in correct way. | |
d10993 | aws-cdk has a library of testing utilities that are useful for asserting against stacks. The cdk repo uses it itself for a lot of its own unit tests.
https://www.npmjs.com/package/@aws-cdk/assert
This allows you to do something like
// jest
test('configurable retention period cannot exceed 14 days', () => {
const stack = new MyStack();
expect(stack).to(haveResource('AWS::SomeService::SomeResource', {
SomePropertyOnResource: 'some-value-it-should-have'
}));
});
This is only supported for CDK apps written in typescript as of now, but the plan is to eventually support all languages cdk supports.
Whether or not you should do this usually is similar to asking whether you should unit test any codebase. If you have a lot of complex business logic happening that does things like conditionally creating resources or otherwise changing your apps behavior, its probably worth getting some coverage in those places. If your app is essentially a bunch of static declarations without conditionals, loops, etc, maybe you can get by with just running cdk diff when making changes and manually verifying your expected changes.
If you're writing custom constructs for reusing in different cdk apps, unit testing those is probably a good idea.
Some relevant docs
https://docs.aws.amazon.com/cdk/latest/guide/testing.html
A: An approach that I use, is to create a different project delegated to use the resources that i expect that have been created.
So, from the cdk-init-cluster project, i simply create all the necessary resources using cdk library. Than, after the DEPLOY phase, i run the cdk-init-cluster-test module that is delegated to populate/query/use the resources previously created from the cdk-init-cluster project.
This approach, can only help with few type of resources such as:
*
*S3 bucket
*Lambda
*AppSync
*DynamoDB table
The test project is in charge to:
*
*Populate the DynamoDB table and retrieve the data.
*Call the Lambda function with dummy data
*Call the lambda function with correct data for verify permission behaviour
*Call appsync (that wrap all the resources above) and verify the result
Then, i remove the data inserted for test. If no exceptions occurs, the test is passed. | |
d10994 | There is no built-in way to invert image colors within the framework.
Instead, because of the overhead of doing this on the phone, you should create both versions of the image at design/build time and then choose which version to display from your code by detecting Theme Visibility and Opacity.
A: I must add that what i did in the end was a continuation of what Matt wrote.
*
*create two different images that have different versions of the image (dark and light) and place them in the exact same position
*set their visibility based on the theme resource
the code looks like this:
<Image Height="30" HorizontalAlignment="Center" Margin="0,0,0,220" Name="imgDark" Stretch="Fill" Visibility="{StaticResource PhoneLightThemeVisibility}" VerticalAlignment="Center" Width="30" Source="/MyApplication;component/imageDarkTheme.png" />
<Image Height="30" HorizontalAlignment="Center" Margin="0,0,0,220" Name="imgLoading" Stretch="Fill" Visibility="{StaticResource PhoneDarkThemeVisibility}" VerticalAlignment="Center" Width="30" Source="/MyApplication;component/imageLightTheme.png" />
A: This Question is 1.5 years old now. But here is the easiest way to do what you want. The example given there is very simple like
<Button>
<Image Stretch="None" Source="{Binding Converter={StaticResource ThemedImageConverter}, ConverterParameter={StaticResource PhoneBackgroundColor} }"
DataContext="/WP7SampleProject4;component/Images/{0}/appbar.feature.camera.rest.png" />
</Button> | |
d10995 | Regex support improved between gcc 4.8.2 and 4.9.2. For example, the regex =[A-Z]{3} was failing for me with:
Regex error
After upgrading to gcc 4.9.2, it works as expected.
A: Update: <regex> is now implemented and released in GCC 4.9.0
Old answer:
ECMAScript syntax accepts [0-9], \s, \w, etc, see ECMA-262 (15.10). Here's an example with boost::regex that also uses the ECMAScript syntax by default:
#include <boost/regex.hpp>
int main(int argc, char* argv[]) {
using namespace boost;
regex e("[0-9]");
return argc > 1 ? !regex_match(argv[1], e) : 2;
}
It works:
$ g++ -std=c++0x *.cc -lboost_regex && ./a.out 1
According to the C++11 standard (28.8.2) basic_regex() uses regex_constants::ECMAScript flag by default so it must understand this syntax.
Is this C++11 regex error me or the compiler?
gcc-4.6.1 doesn't support c++11 regular expressions (28.13).
A: The error is because creating a regex by default uses ECMAScript syntax for the expression, which doesn't support brackets. You should declare the expression with the basic or extended flag:
std::regex r4("[0-9]", std::regex_constants::basic);
Edit Seems like libstdc++ (part of GCC, and the library that handles all C++ stuff) doesn't fully implement regular expressions yet. In their status document they say that Modified ECMAScript regular expression grammar is not implemented yet. | |
d10996 | I'd say there aren't that many places really using FxCop. We have it turned on, but most of the dev staff ignores the warnings produced.
Also, Dev Management here hasn't been interested in really pushing cleaning up the warnings, in part because FxCop really dislikes the conventions (variable names, etc) that management wants us to follow...
On projects where I've been the lead, I've mandated its use because I think it helps us be better programmers. But you have to have by in at the top in order to get all the dev's to follow it.
A: Note that FxCop is very customisable with regards to the rules you wish to apply. You may find it works best by incrementally introducing it; only for a certain set of rules for a certain set of files, or even excluding all legacy files initially.
There are bound to be rules that you may never activate because they just do not suit your problem domain. And remember that if a piece of code 'breaks a rule' for a specific purpose, there is an attribute to mark such code as acceptable, although I would instate a rule that all such overrides must use the Justification property on the attribute to indicate why.
Finally, as much as the built-in rules will help a lot with improving code quality, the really big wins are to be had in custom rules that will allow you to check for company conventions. If you do not automate your 'peer review' in this fashion, then you cannot really guarantee compliance.
I use FxCop as an integrated part of the build system at work, and our common libraries currently get released with all rules enabled with minimal attribute overrides, and it has been worthwhile in more than a few places. | |
d10997 | Hi you will need to store more information in state. Instead of boolean true false you should store something that can be used as ID, unique to all buttons.
For example
const [selected, setSelected] = useState()
And then toggleText could become toggleSelected and needs to take the id of the element that was selected as an argument.
const toggleText = (id) => setSelected(id)
Then in the code for one of the buttons it becomes
//assuming we call this one with id favorite
<div className="inline-flex justify-center items-center">
<Button className=" border-none bg-white" onClick={()=>toggleText("favorite")}>
<IconHeart size={30} stroke={1} />
</Button>
{selected==="favorite" && (
<Text className="flex justify-center items-center align-text-top">
favorites
</Text>
)}
</div>
You can then make similar changes for the rest of the buttons giving whatever ids you want.
If using typescript you can ensure the state is correct assigned an expected value with something like
type Option = "favorite" | "membership" | "total" | "notification"
...
const [selected,setSelected] = useState<Option>()
...
const toggleText = (id:Option) => setSelected(id)
This will work and keep the structure as it is. Then eventually what you would probably want is to create a component for that and remove some repetition for the logic.
Best
A: All of your button/text is using the same set of function setter and state, so it will behave the same way when you click on one.
The easiest way is just to extract them into a component like this
//TextWithButton.jsx (multiple codes r removed)
const [showText, setShowText] = useState(false)
const toggleText = () => setShowText((text) => !text)
<div className="inline-flex justify-center items-center">
<Button className=" border-none bg-white" onClick={toggleText}>
<IconUsers size={30} stroke={1} />
</Button>
{showText && (
<Text className=" inline-flex justify-center items-center align-text-top ">
devenir member
</Text>
)}
</div>
// parent.tsx (multiple codes r removed)
<TextWithButton />
<TextWithButton />
<TextWithButton />
<TextWithButton />
However, I feel like you are missing an understanding of the concept of components in React. I would recommend you to read this article through :) | |
d10998 | You can use .Except() to get the difference between two sets:
var difference = accessories.Except(foo);
// difference is now a collection containing elements in accessories that are not in foo
If you then want to add those items to foo:
foo = foo.Concat(difference).ToList();
A: Use List.Except:
foo.AddRange(accessories.Except(foo));
From MSDN:
Except Produces the set difference of two sequences.
A: There's a LINQ method to do this for you, it looks like this; accessories.Except(foo);
A: You can combine Concat and Distinct to do this:
foo = foo.Concat(accessories).Distinct().ToList();
Edit: Or Except as others have pointed out, which seems to be the superior choice for this case.
A: If you just want foo to be the distinct combination of all elements in foo and accessories (i.e., the union of the two lists),
List<string> foo = foo.Union(accessories).ToList(); | |
d10999 | In a Vue CLI project, the src/assets directory normally contains files that are processed by Webpack (for minification, etc.), and static assets are stored in the public directory. So, you could move your src/assets/others to public/others, where they'll automatically be copied to dist during the build.
On the other hand, if you'd rather the src/assets directory also contain static assets for some reason, you could configure the WebpackCopyPlugin (already included in Vue CLI) to copy src/assets/others to dist/others at build time:
// vue.config.js
const path = require('path')
module.exports = {
chainWebpack: config => {
config.plugin('copy')
.tap(args => {
args[0].push({
from: path.resolve(__dirname, 'src/assets/others'),
to: path.resolve(__dirname, 'dist/others'),
toType: 'dir',
ignore: ['.DS_Store']
})
return args
})
}
}
A: With webpack 5 and vue-cli 5 this changed to:
// vue.config.js
const path = require('path')
module.exports = {
chainWebpack: (config) => {
config.plugin('copy').tap((entries) => {
entries[0].patterns.push({
from: path.resolve(__dirname, 'src/assets/others'),
to: path.resolve(__dirname, 'dist/others'),
toType: 'dir',
noErrorOnMissing: true,
globOptions: { ignore: ['.DS_Store'] },
})
return entries
})
},
} | |
d11000 | I figured it out. This is how I added it:
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AdalService } from 'ng2-adal/dist/core';
@Injectable()
export class RouteGuard implements CanActivate {
constructor(private router: Router, private adalService: AdalService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.adalService.userInfo.isAuthenticated) {
return true;
} else {
this.adalService.acquireToken(this.adalService.config.clientId).toPromise().then((data) => {
console.log('Generating a new authentication token.');
return true;
},
(error) => {
console.log('No user logged in.');
this.router.navigate(['/user-login']);
return false;
}
}
}
}
A: I had the same issue and my fix worked.
In app.component.ts, add this code to ngOnit().
this.adalService.handleWindowCallback();
this.adalService.acquireToken(this.adalService.config.loginResource).subscribe(token => {
this.adalService.userInfo.token = token;
if (this.adalService.userInfo.authenticated === false) {
this.adalService.userInfo.authenticated = true;
this.adalService.userInfo.error = '';
}
}, error => {
this.adalService.userInfo.authenticated = false;
this.adalService.userInfo.error = error;
this.adalService.login();
});
When token expires, app component gets called, and acquire token refreshes the token silently. But the this.adalService.userInfo.authenticated is still false leading to redirection or again calling login method. So manually setting it to true fixes the redirection error. this.adalService.config.loginResource this is automactically set by adal-angular itself with the resource that we need token for.
Also add expireOffsetSeconds: 320, to adal configuration data settings along with
tenant: configData.adalConfig.tenant,
clientId: configData.adalConfig.clientId,
redirectUri: window.location.origin,
expireoffsetseconds invalidates the token based on the time that we specify before its actual expiry. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.