_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d9601 | train | Use the json module to convert the string to a set of nested dict objects, make your changes, and then dump the dictionary back to a json string.
import json
jstr = '''{
"EZMessage":{
"action":"account.cash",
"data":{
"authToken":"123456",
"account":"#ACCOUNTID#",
"portfolio":"true",
"historical":"true"
}
}
}'''
j = json.loads(jstr)
j['EZMessage']['data']['authToken'] = 654321
jstr = json.dumps(j)
For how to read-from/write-to a file see the fine tutorial.
A: Convert the JSON object to a Python object, then change the value just like any other Python object. | unknown | |
d9602 | train | You have to fade out before that, you can add fadeOut before changing the elememt's background and then add fadeIn when the background has changed
A: The steps will be
*
*Show an image.
*Fade out the current image.
*After finished fading out, change the url to a new image.
*Fade in to show the new image.
Working solution:
$(function () {
var i = 0;
document.getElementById("homeImage").src = images[i];
setInterval(function () {
if (i == images.length - 1) {
i = 0;
}
else {
$('#homeImage').fadeOut("slow", function() {
document.getElementById("homeImage").src = images[i];
$('#homeImage').fadeIn("slow");
});
i++;
}
}, 3000);
});
A: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - Williams Marketing Studio</title>
<link rel="stylesheet" href="~/Content/newstyle.css">
@RenderSection("metatags", required: false)
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<header>
<nav>
<div class="nav-bar">
<span><a href="/Home/Index"><img src="~/Content/Images/nav-image.png" class="img-nav" title="Williams Marketing Studio" aria-label="Company Logo" /></a></span>
<ul class="nav-links">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Services", "Index", "Services")</li>
<li>@Html.ActionLink("Categories", "Index", "Categories")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
@using (Html.BeginForm("Index", "Services", FormMethod.Get, new { @class = "navbar-form navbar-left" }))
{
<div class="flex-row">
@Html.TextBox("Search", null, new { @class = "form-input", @placeHolder = "Search Services" })
<button type="submit" class="button">Search</button>
</div>
}
</div>
</nav>
</header>
<section>
<div>
<p><img id="homeImage" src="~/Content/Images/home-image2.jpg" class="header-image" padding="0px" title="Homepage Image" aria-label="Colourful Laptop Screen"></p>
</div>
<div class="container body-content">
@RenderBody()
<hr />
</section>
<footer>
<div class="footer">
<section class="footer-column">
Copyright ©@DateTime.Now.Year<br>
<a href="mailto:[email protected]" title="Email Us">Williams Marketing Studio</a>
<a href="https://validator.w3.org/docs/users.html#Calling" title="HTML Validator" style="color: #87edaa;">W3C Validator API</a>
<a href="https://jigsaw.w3.org/css-validator/manual.html" title="CSS Validator" style="color: #87edaa;">CSS Validator</a>
</section>
<section class="footer-column">
<span><a href="/Home/Index" title="HOME" aria-label="HOME"><img src="~/Content/Images/nav-image.png" alt="footer logo" height="100px"></a></span>
</section>
<section class="footer-column">
<ul class="footer-links">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Services", "Index", "Services")</li>
<li>@Html.ActionLink("Categories", "Index", "Categories")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</section>
</div>
</footer>
<!--<footer>
<address>
Written by <a href="mailto:[email protected]">Williams Marketing Studio</a><br>
</address>
<p>© @DateTime.Now.Year </p>
</footer>-->
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html> | unknown | |
d9603 | train | Check the following libraries:
https://github.com/PhilJay/MPAndroidChart
https://github.com/diogobernardino/WilliamChart
https://github.com/lecho/hellocharts-android
They are beautiful and maybe they have what you need. | unknown | |
d9604 | train | Try ^ and $:
RedirectMatch 301 ^/\d{4}/\d{2}/([^/]+)(/?)(.*)$ http://domainname.com/$1
A: You should probably stick with using mod_rewrite instead of mod_alias because it'll interfere with wordpress' mod_rewrite rules. Both mod_rewrite and mod_alias affect the same request URI at different points in the URL-file processing pipeline, so you could end up getting redirected and rewritten at the same time.
RewriteCond %{REQUEST_URI} !\.(jpeg|gif|png)$ [NC]
RewriteRule ^\d{4}/\d{2}/([^/]+?)(/?)(.*)$ http://domainname.com/$1 [L,R=301] | unknown | |
d9605 | train | I will give an example of how I do it:
import tensorflow as tf
batch_size = 50
task_index = 2
num_workers = 10
input_pattern = "gs://backet/dir/part-00*"
get all names of files in the bucket that correspond to input_pattern
files_names = tf.train.match_filenames_once(
input_pattern, name = "myFiles")
select names for worker task_index. tf.strided_slice is like slice for lists: a[::,task_index] (select every task_indexth file for worker task_index)
to_process = tf.strided_slice(files_names, [task_index],
[999999999], strides=[num_workers])
filename_queue = tf.train.string_input_producer(to_process,
shuffle=True, #shufle files
num_epochs=num_epochs)
reader = tf.TextLineReader()
_ , value = reader.read(filename_queue)
col1,col2 = tf.decode_csv(value,
record_defaults=[[1],[1]], field_delim="\t")
train_inputs, train_labels = tf.train.shuffle_batch([col1,[col2]],
batch_size=batch_size,
capacity=50*batch_size,
num_threads=10,
min_after_dequeue = 10*batch_size,
allow_smaller_final_batch = True)
loss = f(...,train_inputs, train_labels)
optimizer = ...
with tf.train.MonitoredTrainingSession(...) as mon_sess:
coord = tf.train.Coordinator()
with coord.stop_on_exception():
_ = tf.train.start_queue_runners(sess = mon_sess, coord=coord)
while not coord.should_stop() and not mon_sess.should_stop():
optimizer.run()
I'm not sure my method is the best way to implement input pipeline in case of distributed TensorFlow implementation because each worker reads names of all files in the bucket
Good lecture about input pipeline in TensorFlow: http://web.stanford.edu/class/cs20si/lectures/notes_09.pdf | unknown | |
d9606 | train | As simple as that :
$(".my-item").remove();
(if I understood your question correctly)
A: I have found some things which could be improved.
First of all. An id is unique, so whenever you start to clone elements, the id is cloned as well.
I made a few adjustments and this is how it works:
HTML
<div class="my-item">
<div class="item-header">
<h2 id="toggle">Click Me!</h2>
<div class="item-body">My Text!
</div>
</div>
<button class="divButton">Click!</button>
<button class="deleteButton">Delete!</button>
</div>
CSS (still the same)
.my-item {
width: 250px;
heigth: 180px;
margin: 10px;
padding: 20px;
background: green;
border: 2px solid black;
}
.item-header {
width: 150px;
heigth: 120px;
margin: 5px;
padding: 10px;
background: yellow;
border: 1px solid black;
}
.item-body {
width: 70px;
heigth: 50px;
margin: 3px;
padding: 5px;
background: purple;
border: 1px solid black;
}
jQuery
function addEvents() {
$(".divButton").unbind("click").click(function() {
$(this).parent().clone().appendTo($("body"));
addEvents();
});
$(".deleteButton").unbind("click").click(function() {
$(this).parent().remove();
});
}
addEvents();
The reason why I put both click events in a separate function, is when the element is cloned, the events are not cloned. Therefor, you will have to rebind them. This doesn't have to happen when you delete an element.
I hope this solves your question
FIDDLE
A: Guess you mean something like this:
$("#deleteButton").click(function(){
$(this).nextAll(".my-item").remove();
});
This will remove all .my-item after the delete button and not your template.
Just a notice, when you're cloning your .my-item element, you'll get multiple "toggle" IDs in the DOM, which is not good.
A: I recommend to use single instead of the double quotation marks for js:
$('selector');
The following line is wrong:
$(".my-item").append(".my-item"+ "button class="deleteButton">Delete</button>");
Correct is:
$(".my-item").append("<button class=\"deleteButton\">Delete</button>");
or
$('.my-item').append('<button class="deleteButton">Delete</button>');
Your code will not produce new elements by clicking on button "Click!" and adding new delete buttons by clicking on the "Delete"-Button.
I guess what you want to archive is to duplicate an Item and add a delete button to the item itself.
Just clone your element without appending and save it to a var.
( var newElement = $.('selectpr').clone(); )
Then append the delete button to the newElement object and append the object to the target.
Another approach would be appending the clone to a container and then selecting it by looking for the last element in the container. Then bind a click event to the delete button.
Please check jQuery and CSS manual for correct selectors.
A: Ok, here's a different solution for you with cached element and no duplicate IDs.
<script>
$(document).ready(function() {
var $myItem = $(".my-item");
var $deleteBtn = $("<button/>",{"class":"deleteButton"}).text('Delete').on({
click: function() {
$(this).closest('.my-item').remove(); // delete item
}
});
// enable toggle of item body
$(".toggle").click(function() {
$(this).next(".item-body").slideToggle("normal");
});
// Add new item
$("#divButton").click(function(){
var $newItem = $myItem.clone(true);
$("body").append($newItem.append($deleteBtn.clone(true)));
});
});
</script>
And here is your HTML body part:
<body>
<div class="my-item">
<div class="item-header">
<h2 class="toggle">Click Me!</h2>
<div class="item-body">My Text!</div>
</div>
</div>
<button id="divButton">Click!</button>
</body> | unknown | |
d9607 | train | If you include the Microsoft.Bcl.Async assembly and build with a compatible IDE (VS2012+), you can use async/await with .NET 4. Then you can await Task.WhenAll, e.g.
var myTask = await requiredTask;
var otherTasks = from item in otherObjects select item.DoSomethingAsync();
await Task.WhenAll(otherTasks);
// do my real work
Since Task.WhenAll was added in .NET 4.5, not in the Microsoft.Bcl.Async assembly, this is how you'd do it in .NET 4:
var myTask = await requiredTask;
var otherTasks = (from item in otherObjects select item.DoSomethingAsync()).ToList();
foreach (var otherTask in otherTasks)
await otherTask;
I also threw in a ToList() so that if you use otherTasks later (e.g. to get results), the expression will not be reevaluated. | unknown | |
d9608 | train | I'm not sure if I've interpreted the question correctly, but if you're trying to access another DOM element on the page - I was able to use a jquery selector.
For example, given html of
<input type="textfield" id="initials" value=" ">
and a simple meteor template of
<template name="demo">
<input type="button" div id="s0">
</template>
I can successfully access the initials field when the s0 button is clicked as follows
Template.demo.events({
'click .cell': function(event, template) {
if ($('#initials').val().trim().length > 0) {
console.log($('#initials').val().trim() + ' - you clicked button '+$(event.target).attr('id'));
}
}, | unknown | |
d9609 | train | Solved (May 18, 2020)
I changed my approach and go for a custom runtime and it worked out.
Here is the configuration I used if anyone encounter this problem in the future.
Change the runtime to custom in the App.yaml
<!-- language: lang-html -->
env: flex
runtime: custom
And include a Dockerfile with a nginx.conf for the runtime management
Dockerfile:
FROM node:8-alpine as react-build
WORKDIR /app
COPY . ./
RUN npm install
RUN npm run build
# server environment
FROM nginx:alpine
COPY nginx.conf /etc/nginx/conf.d/configfile.template
ENV PORT 8080
ENV HOST 0.0.0.0
RUN sh -c "envsubst '\$PORT' < /etc/nginx/conf.d/configfile.template > /etc/nginx/conf.d/default.conf"
COPY --from=react-build /app/build /usr/share/nginx/html
EXPOSE 8080
CMD ["nginx", "-g", "daemon off;"]
nginx.conf
server {
listen $PORT;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri /index.html;
}
gzip on;
gzip_vary on;
gzip_min_length 10240;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml;
gzip_disable "MSIE [1-6]\.";
}
This configuration appears in one of the tutorials here: https://cloud.google.com/community/tutorials/deploy-react-nginx-cloud-run
Thank you to @Nibrass H for suggesting some possible solutions. | unknown | |
d9610 | train | These errors occur if the .aspx page or the Global.asax page contains a reference to a code-behind module and if the application has not been built.
You could try the below method to build the application:
Use the C# command-line compiler (CSC.exe) to run the following command:
csc /t:library /r:System.web.dll /out:mydll.dll myfile.cs
OR
In Microsoft Visual Studio .NET, click Build on the Build menu.
Also try changing CodeBehind="index.aspx.cs" to CodeFile="index.aspx.cs". This change is required when you change project type from website to webapplication or vice versa.
make sure you install the .ne framework feature of iis.
A: I actually created a brand new web that used a Virtual Directory for it's codebase that is the same code as the other webs.
Index.aspx resides in the /lmw/main directory. I had created an Application on that folder when I was creating the other applications in the web. So, I removed the "Application" from /lmw/main and it worked. | unknown | |
d9611 | train | I know this isn't very secure, but I'd personally create an ASP.NET app on your target Windows Server, or a different Server on the domain. Create web services exposed, and make an iOS app with UIWebView. You can do RPC calls from the web service that do WMI/ADSI/File System manipulation. You can prompt for domain credentials, and do remote calls essentially is the gist.
You could expose the web app so that your app can access it from local network, or URL. If you were to access it from outside I'd suggest using some secure credentials in Windows/IIS.
Some years ago I created a "mobile-friendly" web app that allowed me to manage servers, perform RPC, and do basic Active Directory queries. Also allowed file listing and deletion/moving/copying with some creative scripting. It was essentially a ASP.NET/C# web app that loaded in a iPhone app. UIWebView in iOS was a able to load it, used AJAX and some other client side scripting that looked decent. You'd essentially have to make sure that your web app renders properly in Safari/UIWebView (which is bastardized safari).
Here's a link to a demo of what I created:
https://www.youtube.com/watch?v=czXmubijHwQ&t=12s
I ran it in a browser, but it'd run from my PSP, Android test devices, iPod Touch, Blackberry, etc. | unknown | |
d9612 | train | Make sure your tableGen() returns JSX, without quote.
return <h3>Hello World</h3>;
Then, your MainTable function should have return keyword:
MainTable() {
return MainTable.tableGen();
}
And, invoke the function when referencing it in JSX:
{this.MainTable()} | unknown | |
d9613 | train | You must enclose the variable names in exclamation points to cause them to be expanded, as in !part3!. This must be done every place you want the value of a variable. The exclamation points are used for delayed expansion within a FOR loop. You can use percents for normal expansion, but not within a loop that also sets the value.
Also, your inner FOR /F loop must use double quotes within the IN() clause. As currently written, it is attempting to open a file with the name of your folder.
But there is a simpler way in your case:
@echo off
for /d %%F in (c:\users\*-*-*-*) do for /f "tokens=2* delims=-" %%A in ("%%~nxF") do ren "%%F" "%%B" | unknown | |
d9614 | train | Not every folder under C:\Users will have a AppData\Local\Microsoft\Outlook subdirectory (there are typically hidden directories there that you may not see in Windows Explorer that don't correspond to a real user, and have never run Outlook, so they don't have that folder at all, but will be found by os.listdir); when you call os.listdir on such a directory, it dies with the exception you're seeing. Skip the directories that don't have it. The simplest way to do so is to have the glob module do the work for you (which avoids the need for your first loop entirely):
import glob
import os
for folder in glob.glob(r"c:\users\*\AppData\Local\Microsoft\Outlook"):
for file in os.listdir(folder):
if file.endswith(".txt"):
print(os.path.join(folder, file))
You can simplify it even further by pushing all the work to glob:
for txtfile in glob.glob(r"c:\users\*\AppData\Local\Microsoft\Outlook\*.txt"):
print(txtfile)
Or do the more modern OO-style pathlib alternative:
for txtfile in pathlib.Path(r'C:\Users').glob(r'*\AppData\Local\Microsoft\Outlook\*.txt'):
print(txtfile) | unknown | |
d9615 | train | select om.MemberID as mem
Use th AS keyword. This is called aliasing.
A: Try this:
p.*,
om.EmailAddress,
om.FirstName,
om.LastName
You should never use * though. Always specifying the columns you actually need makes it easier to find out what happens.
A: You are dreaming in your implementation.
Also, as a best practice, select * is something that is typically frowned upon by DBA's.
If you want to limit the results or change anything you must explicitly name the results, as a potential "stop gap you could do something like this.
SELECT p.*, om.MemberId, etc..
But this ONLY works if you want ALL columns from the first table, and then selected items.
A:
But this creates a very long sequence
of select p.a, p.b, p.c, p.d, ... etc
... which I am trying to avoid.
Don't avoid it. Embrace it!
There are lots of reasons why it's best practice to explicity list the desired columns.
*
*It's easier to do searches for where a particular column is being used.
*The behavior of the query is more obvious to someone who is trying to maintain it.
*Adding a column to the table won't automatically change the behavior of your query.
*Removing a column from the table will break your query earlier, making bugs appear closer to the source, and easier to find and fix.
And anything that uses the query is going to have to list all the columns anyway, so there's no point being lazy about it! | unknown | |
d9616 | train | You can use Serializable for passing a object like ->
class Shop(
val name: String,
val details: String?,
val id: Int,
):Serializable
now pass this Shop class like
var shop = Shop("name","details",1)
val intent = Intent(this, AnotherActivity::class.java).putExtra(
"SHOP",
shop
)
startActivity(intent)
now receive this shop class from another activity
val shope = intent.getSerializableExtra("SHOP") as Shop
you can also use Parcelable instead of Serializable | unknown | |
d9617 | train | Just complementing the answer, you can deploy directly on Jboss with a cli command and/or see the deployment status/content using the following commands:
#deployment-info
NAME RUNTIME-NAME PERSISTENT ENABLED STATUS
hibernate.war hibernate.war false true OK
#deployment=hibernate.war:read-attribute(name=content)
{
"outcome" => "success",
"result" => [{"hash" => bytes {
0x29, 0x93, 0x46, 0x13, 0xdd, 0x74, 0xff, 0x1d,
0xb7, 0x6e, 0xa6, 0xde, 0x60, 0xb3, 0x85, 0xf6,
0xae, 0x72, 0xc9, 0x0f
}}]
}
Q: Where can i check the .war which has deployed using puppet in Jboss server
A: You don't need another tool. | unknown | |
d9618 | train | The solution was to increase tmax of
t = np.linspace(0,1.76,2400)
i.e. 1.76. FFT makes bins the size of 1/tmax and the small tmax is, the bigger the bins are leading to less resolution. | unknown | |
d9619 | train | I agree with everything said above.
Yes, you can only change the family instance dimension parameter values after the instance has been placed.
Yes, you could define different types for different values, and then place the type.
You could create those types on the fly immediately before placing the instance.
In Revit 2015, you can define which family type is placed by PromptForFamilyInstancePlacement.
Where do the width and height etc. come from?
Can you determine them immediately before the call to PromptForFamilyInstancePlacement?
If so, then you could create a new family type with those dimensions on the fly and set that to be the active type right before the call to PromptForFamilyInstancePlacement.
Cheers, Jeremy.
A: I believe the only solution to resizing the element before placement would be to create different family types for each size you need. Depending on your needs, this may or may not be a practical solution.
The rest of my answer is focused on manipulating the elements after placement.
Do you need your users to be able to select the location of the placement? If not, then you can use the NewFamilyInstance method to place the element (there is no preview, and you must provide a location point).
This function returns the element that was just placed, so you would be able to modify it after placement.
You may be able to use the Selection.PickPoint method to allow the user to pick a point for placement which you can pass to NewFamilyInstance, but I'm not sure how this works with elevations.
The alternative is to use a FilteredElementCollector after the element has been placed. You could use a FamilyInstanceFilter to find all of the instances of the FamilySymbol you are using.
Since Revit ElementId's increase as new elements are placed (with some exceptions due to worksharing/synchronizing that aren't relevant here), you could retrieve the element with the highest ElementId and safely assume that it's the one you just placed.
Another suggestion would be to run the FilteredElementCollector before you place your elements, and then run it again after. The difference would be the element/s that you just placed.
A: Doesn't the familySymbol object have the get_Parameter() method?
I think you can use it to achieve your goal. | unknown | |
d9620 | train | It's not:
<form action="/upload/submit/" method="POST" encrypt="multipart/form-data">
it's
<form action="/upload/submit/" method="POST" enctype="multipart/form-data">
i.e. enctype not encrypt
As an aside, you should use a Form or ModelForm to do this, it will make your life much easier. | unknown | |
d9621 | train | Yes, it's highly possible and I did it like this:
*
*Create page template in Wordpress
*Connect to remote database and check from backend first
*Write UI code + server code + Mysql queries to grab the data in template
*Create UI in page which will grab data from DB/server | unknown | |
d9622 | train | Use jQuery selectors to get it:
$("input[type='checkbox']:checked").first().val()
or
$("input[type='checkbox']:checked:first").val()
JSFIDDLE
A: $('input[type=checkbox]:checked').first()
A: $('#rooms input:checked:first').val() | unknown | |
d9623 | train | The traditional format is the same. It just appears in the HTTP request body instead of as part of the URI. Whatever library you use to parse the query string should handle x-www-form-urlencoded data just as easily.
POST / HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
a=3&b=2&c=1
A: You should use either form method = POST or ajax.
Jquery ajax is easier. Just google it. (if you want it that way).
P.s. You can't send post parameters via url.
A: The most common way to send POST data is from an html form:
<FORM action="http://somesite.com/somescript.php" method="post">
<P>
<LABEL for="firstname">First name: </LABEL>
<INPUT type="text" id="firstname"><BR>
<LABEL for="lastname">Last name: </LABEL>
<INPUT type="text" id="lastname"><BR>
<LABEL for="email">email: </LABEL>
<INPUT type="text" id="email"><BR>
<INPUT type="radio" name="sex" value="Male"> Male<BR>
<INPUT type="radio" name="sex" value="Female"> Female<BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</P>
</FORM>
Then process the $_POST vars similar to how you would with $_GET vars in PHP. | unknown | |
d9624 | train | I found a solution with ReSharper.
You can open and disassemble the references with the extension ReSharper and set break points. | unknown | |
d9625 | train | Not sure if this is what you are looking for, but I believe that you'll find better than this
You may try this when the MouseDown is called
private void richTextBox1_MouseDown(object sender, MouseEventArgs e)
{
// Continue if the Right mouse button was clicked
if (e.Button == MouseButtons.Right)
{
// Check if the selected item starts with http://
if (richTextBox1.SelectedText.IndexOf("http://") > -1)
{
// Avoid popping the menu if the value contains spaces
if (richTextBox1.SelectedText.Contains(' '))
{
// Show the menu
contextMenuStrip1.Show(Cursor.Position.X, Cursor.Position.Y);
}
}
}
}
Or this when a Link is Clicked, but this won't apply for Mouse Right-Click
private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
{
contextMenuStrip1.Show(Cursor.Position.X, Cursor.Position.Y);
}
Thanks,
I hope this helps :) | unknown | |
d9626 | train | I suspect that the error is in how you are building the regex pattern to be used here. I suggest concatenating the input list together by space to form a single input string, and then using the following regex pattern with re.findall:
\b(lasko[A-Z0-9]+)\b
The word boundaries are appropriate here, because the train value should be bounded on the left by a tab, and on the right by a space.
xbsfindupdates_output_list = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko']
train = 'lasko'
inp = ' '.join(xbsfindupdates_output_list)
pattern = r'\b(' + train + r'[A-Z0-9]+)\b'
matches = re.findall(pattern, inp)
print(matches)
This prints:
['lasko17A565']
Edit:
If you just want to find out if there is a match, then try:
xbsfindupdates_output_list = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko']
train = 'lasko'
inp = ' '.join(xbsfindupdates_output_list)
pattern = r'\b' + train + r'[A-Z0-9]+\b'
if re.search(pattern, inp):
print("MATCH")
else:
print("NO MATCH")
A: Try this:
for SDK in xbsfindupdates_output_list:
print(SDK,re.search("%s[0-9A-Z]+"%train,SDK))
if re.match("%s[0-9A-Z]+"%train,SDK.strip()):
print("FOUND")
found_new_SDK = True
print (found_new_SDK)
re.match is returning True iff both strings are same. Try re.search, which would search in string the required pattern
A: Match objects are always true, and None is returned if there is no match. Just test for trueness. So instead of match, i used re.search here:
xbsfindupdates_output_list = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko']
train = 'lasko'
found_new_SDK = False
for SDK in xbsfindupdates_output_list:
if re.search(r'\b' + train + r'[\d\S]+', SDK):
found_new_SDK = True
print found_new_SDK
O/p:
True | unknown | |
d9627 | train | Initially I thought it only works in SQL 2016 but I realized that you either need to import the module: SqlServer or Install-Module SqlServer. Either 2 ways, it should work. Thanks for your help guys. Powershell is taking over the world. | unknown | |
d9628 | train | You are looking for a memberOf attribute which it seems is not present. If you are using openLDAP, memberof attribute is hidden by default. Check that setting once. Also make sure that anonymous access is allowed for this attribute. | unknown | |
d9629 | train | The error "where was called on null" implies, that players are null by the time you call it. I am assuming PlayerLab.get().players returns a Future so you should add the "await" keyword before the call:
initState() async {
List<Player> players = await PlayerLab.get().players
....
} | unknown | |
d9630 | train | when(firstService.getOne(any(), any())).thenReturn(CompletableFuture.completedFuture(mockOne));
solved my problem | unknown | |
d9631 | train | Telegram has intoduced levels of access for Channel admins in the version 4.1.
If you are creator of the channel, you can do everything with your channel, otherwise tell the creator of the channel to give you the required permissions. In your case, the title of permission is: "can add admins" | unknown | |
d9632 | train | You can consider using select operator with your selector getAccessToken, and "chain" observables.
No need to subscribe if you use first() or take(1) operators. Observable will automatically complete after one value.
Your code for HttpInterceptor could looks like below:
export class ServerInterceptor implements HttpInterceptor {
constructor(
private store: Store<AuthenticationState>
) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.store.pipe(
select(getAccessToken),
first(),
mergeMap(accessToken => {
const authReq = !!accessToken ? request.clone({
headers: request.headers.set('Authorization', `Bearer ${accessToken}`)
}) : request;
return next.handle(authReq);
})
);
}
}
Some resources on the subject :
*
*Using NgRx Store Auth Token with Angular HttpInterceptor by Antony Derham
*Add JWT Token to Angular HTTP Requests Using NGRX by WASi | unknown | |
d9633 | train | Buffering
Case your PHP scripts are causing a slow load you must put' em in buffer. So, when the load is finished you can free this buffer.
This isn't so hard to implement.
See the PHP output buffering control documentation for this:
PHP Output Buffering Control
Finished the loading of the buffer
You can make like this:
http://jsfiddle.net/S9uR9/
$(window).load(function () {
//hideLoading();
});
hideLoading = function() {
$('.loading').fadeOut(2000, function() {
$(".content").fadeIn(1000);
});
};
hideLoading();
In your page, try to remove the commented line in $(window).load() function and comment the last line hideLoading();.
Detecting browser’s activity
I've noticed that some browsers show a loading icon in the place of the favicon whenever the page is loading (or, at least, Google Chrome does). Is it be possible to know when the browser loading icon is active and display a page loading icon concurrently?
You can try another alternative. You can detect the network activity. This is more complex to implement, however more interesting, principally if you want a mobile approach.
See this article, can help. | unknown | |
d9634 | train | {id: "1", name: "vivek", fname: "modi", mobile: "9024555623", photo: "http://localhost/axios1/uploaded/student/rhinoslider-sprite.png"}
fname: "modi"
id: "1"
mobile: "9024555623"
name: "vivek"
photo: "http://localhost/axios1/uploaded/student/rhinoslider-sprite.png"
<input defaultValue={this.state.data.name} />
Just use name from state
as if the object you mentioned is state then you can directly access state keys from state
like
this.state.name || this.state.mobile
A: You need to show your code in order to get better help but
If you have a correct state you can change values like this:
<input type="text" name="fname" value={this.state.data.name}>
But your state is null and the code you showed has problem, you need to fill your state correctly, in your class you can write:
State={name:"test"}
And it will work fine. Hope this can help you
update now write this:
{this.state.data && this.state.data.name
&& ( < input defaultValue={this.state.data.name} /> )}
A: You can set like call your axios request through
componentDidMount(){
axios.post("http://localhost/axios1/index.php",data)
.then(res=>this.setState({data:res.data},
()=>console.log(this.state.data)))
}
Suppose you are getting this in your state
state={
data:{
id: "1",
name: "vivek",
fname: "modi",
mobile: "9024555623",
photo: "http://localhost/axios1/uploaded/student/rhinoslider-sprite.png"
}
}
and then render it as
render(){
const {name,fname} = this.state.data?this.state.data:"";
return(
<div>
<input defaultValue={this.state.name} />
<input defaultValue={this.state.fname} />
</div>
);
}
A: Change this in your code, line no 31
this.setState({res.data},()=>console.log(this.state)) | unknown | |
d9635 | train | following your example, if you don't want to use promises, you can simply pass a callback from the caller and invoke the callback when you have the result since the call to mongo is asynchronous.
fetchId = (name, clb) => {
User.findOne({name: name}, (err, user) => {
clb(user._id);
});
};
fetchId("John", id => console.log(id));
Otherwise you can use the promise based mechanism omitting the first callback and return the promise to the caller.
fetchId = name => {
return User.findOne({name: name}).then(user => user.id);
};
fetchId("John")
.then(id => console.log(id));
A: A third way is a variation of suggestion #2 in @Karim's (perfectly good) answer. If the OP wants to code it as if results are being assigned from async code, an improvement would be to declare fetchId as async and await its result...
fetchId = async (name) => {
return User.findOne({name: name}).then(user => user.id);
};
let someId = await fetchId("John");
console.log(id)
edit
For any method on an object -- including a property getter -- that works asynchronously, the calling code needs to be aware and act accordingly.
This tends to spread upward in your system to anything that depends on caller's callers, and so on. We can't avoid this, and there's no syntactic fix (syntax is what the compiler sees). It's physics: things that take longer, just take longer. We can use syntax to partially conceal the complexity, but we're stuck with the extra complexity.
Applying this to your question, say we have an object representing a User which is stored remotely by mongo. The simplest approach is to think of the in-memory user object as unready until an async fetch (findOne) operation has completed.
Under this approach, the caller has just one extra thing to remember: tell the unready user to get ready before using it. The code below employs async/await style syntax which is the the most modern and does the most to conceal -- but not eliminate :-( -- the async complexity...
class MyMongoUser {
// after new, this in-memory user is not ready
constructor(name) {
this.name = name;
this.mongoUser = null; // optional, see how we're not ready?
}
// callers must understand: before using, tell it to get ready!
async getReady() {
this.mongoUser = await myAsyncMongoGetter();
// if there are other properties that are computed asynchronously, do those here, too
}
async myAsyncMongoGetter() {
// call mongo
const self = this;
return User.findOne({name: self.name}).then(result => {
// grab the whole remote object. see below
self.mongoUser = result;
});
}
// the remaining methods can be synchronous, but callers must
// understand that these won't work until the object is ready
mongoId() {
return (this.mongoUser)? this.mongoUser._id : null;
}
posts() {
return [ { creator_id: this.mongoId() } ];
}
}
Notice, instead of just grabbing the mongo _id from the user, we put away the whole mongo object. Unless this is a huge memory hog, we might as well have it hanging around so we can get any of the remotely stored properties.
Here's what the caller looks like...
let joe = new MyMongoUser('joe');
console.log(joe.posts()) // isn't ready, so this logs [ { creator_id: null } ];
await joe.getReady();
console.log(joe.posts()) // logs [ { creator_id: 'the mongo id' } ]; | unknown | |
d9636 | train | You can clear elements with:
window.FindElement(key).Update('')
Have you tried this? | unknown | |
d9637 | train | Simply use the The $_ automatic variable in your Where-Object to reference the property names:
Get-PnpDevice | Sort-Object -Property Name | Where-Object{
( $_.ConfigurationFlags -NotLike '*DISABLED*') -and
( $_.FriendlyName -like '*touch screen*' ) }| ft Name, InstanceId -AutoSize
A: You can pipe 'Where' clauses together... it's simpler syntax and easier to read
Get-PnpDevice | Sort-Object -Property Name | Where ConfigurationFlags -NotLike '*DISABLED*' | Where FriendlyName -like '*touch screen*' | ft Name, InstanceId -AutoSize | unknown | |
d9638 | train | You have to build your data string before you pass it in the ajax call. This is one way you can do:
var dynData = new Object();
dynData.api = <value>;
dynData.address = <value>;
Looks static as of now. Now based on your 'state', you can add properties to the javascript object on the fly using the following:
dynData["newProperty"] = <value>;
Now using JSON and json2.js, you can create your JSON string using:
data:JSON.stringify(dynData);
Mark as answer if this worked :) | unknown | |
d9639 | train | I suggest you use some kind of delimiter, like a ; to pass in multiple roles.
'before' => 'role:administrator;moderator'
And change the filter:
Route::filter('role', function($route, $request, $value)
{
if(Auth::check()){
$user = Auth::user();
$roles = explode(';', $value);
foreach($roles as $role){
if($user->hasRole($role)){
return;
}
}
}
return Response::make('Unauthorized', 403);
}); | unknown | |
d9640 | train | If your dataframe looks like:
>>> df
March 29 March 30 March 31 April 1 April 2 April 3 April 4
0 9 5 4 7 4 4 2
1 6 7 7 2 7 3 6
2 3 5 8 9 8 2 2
3 9 1 8 3 5 9 3
4 9 1 1 3 9 2 9
First, build list of month groups by splitting column names in two parts:
*
*[0] → month name
*[1] → day
months = [month for month, _ in df.columns.str.split()]
>>> months
['March', 'March', 'March', 'April', 'April', 'April', 'April']
Then, group and sum for each month along columns axis:
out = df.groupby(months, axis="columns").sum()
>>> out
April March
0 17 18
1 18 20
2 21 16
3 20 18
4 23 11
Edit: column names as datetime (like 2021-01-01 00:00:00)
>>> df
2020-03-29 2020-03-30 2020-03-31 2020-04-01 2020-04-02 2020-04-03 2020-04-04
0 9 5 4 7 4 4 2
1 6 7 7 2 7 3 6
2 3 5 8 9 8 2 2
3 9 1 8 3 5 9 3
4 9 1 1 3 9 2 9
Convert your columns name from string to datetime (if needed):
df.columns = pd.to_datetime(df.columns)
The rest remains unchanged:
months = df.columns.strftime("%B")
out = df.groupby(months, axis="columns").sum()
>>> out
April March
0 17 18
1 18 20
2 21 16
3 20 18
4 23 11 | unknown | |
d9641 | train | You can know if a token has expired if the token does not exist when you try to get it.
token = cookies['token'].value #this will not exist
The browser deletes the cookie and everything related to that when the expiration date passes.
This way in many implementations you can even delete cookies or for example log-out a user just but setting the expiration date of the user_id cookie to something in the past( eg a negative number).
Now as I understand you need a policy to detect expired tokens server side and that can be accomplished by double validation. Eg try to store an unique identifier for each token and server side when you read the token try to check if it has expired. It's also possible for the user to manipulate his cookies so never blindly trust cookies to store significant data or make any user_id simple validation.
I hope I helped.
EDIT
From rfc2109
Max-Age=delta-seconds
Optional. The Max-Age attribute defines the lifetime of the
cookie, in seconds. The delta-seconds value is a decimal non-
negative integer. After delta-seconds seconds elapse, the client
should discard the cookie. A value of zero means the cookie
should be discarded immediately.
And from wiki http cookies
The Expires directive tells the browser when to delete the cookie.
Derived from the format used in RFC 1123, the date is specified in the
form of “Wdy, DD Mon YYYY HH:MM:SS GMT”,[29] indicating the exact
date/time this cookie will expire. As an alternative to setting cookie
expiration as an absolute date/time, RFC 6265 allows the use of the
Max-Age attribute to set the cookie’s expiration as an interval of
seconds in the future, relative to the time the browser received the
cookie.
I would recommend to use max-age because saves some trouble from setting dates etc. You just calculate an interval.
Reading a bit more I found that max-age is not supported by IE < 9 and that means that expires is preferred
Max-Age vs Expires
That should help ;-) | unknown | |
d9642 | train | when i === 3 you will have problems
if (i > id.length) {
should become
if (i >= id.length) {
UPDATE: http://jsfiddle.net/HgNuc/ | unknown | |
d9643 | train | If the apache and php are configured correctly, so that .php files go through the php interpreter, the thing I would check is whether the php files are using short open tags "<?"
instead of standard "<?php" open tags. By default newer php versions are configured to not accept short tags as this feature is deprecated now. If this is the case, look for "short_open_tag" line in php.ini and set it to "on" or, preferrably and if time allows, change the tags in the code. Although the second option is better in the long run, it can be time consumming and error-prone if done manually.
I have done such a thing in the past with a site-wide find/replace operation and the general way is this.
*
*Find all "<?=" and replace with "~|~|~|~|" or some other unusual string that is extremely unlikely to turn up in real code.
*Find all "<?php" and replace with "$#$#$#"
*Find all "<?" in the site and replace with "$#$#$#"
*Find all "$#$#$#" and replace with "<?php " The trailing space is advised
*Find all "~|~|~|~|" and replace with "<?php echo " The trailing space is neccessary | unknown | |
d9644 | train | There appears to be some kind of bug with default arguments, overloaded operators, and template function parameter overload resolution.
These are all complex, so sort of understandable.
The good news is that you shouldn't be taking just any iomanip there -- you should be taking a specific one.
You can either hard code it, or deduce it like so:
// Get the nth type from a template instance:
template<class...>struct types{using type=types;};
template<class T, size_t N>
struct nth{};
template<class T, size_t N>
using nth_t=typename nth<T,N>::type;
template<template<class...>class Z, class T0, class...Ts, size_t N>
struct nth<Z<T0,Ts...>,N>:nth<types<Ts...>,N-1>{};
template<template<class...>class Z, class T0, class...Ts>
struct nth<Z<T0,Ts...>,0>{using type=T0;};
// From a String type, produce a compatible basic_stream type:
template<class String>
using compat_stream = std::basic_ostream<nth_t<String,0>, nth_t<String,1>>;
// From a type T, produce a signature of a function pointer that
// pass-through manipulates it:
template<class T>
using manip_f = T&(*)(T&);
// From a String type, produce a compatible io-manipulator:
template<class String>
using io_manip_f = manip_f< compat_stream<String> >;
// The return of foobar:
struct foobar {
std::stringstream s_;
// the type of manipulators that is compatible with s_:
using manip_f = io_manip_f<std::stringstream> manip;
// a Koenig operator<<:
friend foobar& operator<<( foobar& self, manip_f manip ) {
self.s_ << manip;
return self;
}
}; | unknown | |
d9645 | train | I think probably the best way to do this is to use a framework that can operate through a browser. There are several options, but the most pythonic is windmill http://www.getwindmill.com/
I've found it useful on a number of projects. | unknown | |
d9646 | train | I don`t know why this function is not called. I also confuse for this, because official documents of DHMTLX Gantt (as you mentioned, api_date) say it should works.
However I found that if you override xml_date it will work as you want. Although it is named xml_date but it works for json data also.
So could use following snippet:
gantt.templates.xml_date = function(date){
// Your customized code.
// return a Date object.
};
A: api_date template and config are no longer used. We will update the information in the documentation. Please use xml_date as hadi.mansouri suggested. | unknown | |
d9647 | train | You can expose your ADF Business Components as REST webservice
(https://blogs.oracle.com/shay/entry/rest_based_crud_with_oracle)
and consume them from javascript. | unknown | |
d9648 | train | Actually, I'm not sure about Delphi 2009, but MSDN says:
Note that DEFAULT_CHARSET is not a real charset; rather, it is a constant akin to NULL that means "show characters in whatever charsets are available."
So my guess is that you just need to remove all the code that you mentioned, and it should work.
A: Not a really answer to this question, but 'small' note on possible memory corruption with this code under D2009+. Function GetLocaleInfo "MSDN: Returns the number of characters retrieved in the locale data buffer..." not BYTES, so under D2009+ you MUST allocate 2 bytes for each characters. Best way to do this is write:
GetMem(Buffer, iSize * SizeOf(Char)); //This will be safe for all delphi versions
Without this you can lead to unpredicted AVs (D2009+), function GetLocaleInfo can overwrite your memory, because you have allocated too small buffer.
Also I don't understant why you're trying change charset to user locale one, I think that you should change charset to your destination translation (like, your program is set to be translated to Russian language, but running on English OS, then you need change charset to RUSSIAN_CHARSET, not ANSI_CHARSET). And under D2009+ I not sure if this is needed, but I might be wrong. | unknown | |
d9649 | train | As rightly suggested by @sweenish, You must do the constructor delegation in the initialization section. Something like this:
#include <iostream>
#include <cstring>
using namespace std;
class student
{
private:
char name[10];
int id;
int fee;
public:
student(char name[10],int id)
{
strcpy(this->name,name); //string copy
this->id=id;
fee=0;
}
student(char name[10],int id,int fee): student(name, id) // constructor delegation
{
this->fee=fee;
}
void show() //print function
{
cout<<"Name:"<<name<<endl;
cout<<"id:"<<id<<endl;
cout<<"fee:"<<fee<<endl<<endl;
}
};
int main()
{
student s1("DAVID",123);
student s2("WILLIAM",124,5000);
s1.show();
s2.show();
return 0;
}
Also, an advice for you. You may define the more specialized constructor and delegate the responsibility of less specialized constructors to more specialized ones.
#include <iostream>
#include <cstring>
using namespace std;
class student
{
private:
char name[10];
int id;
int fee;
public:
student(char name[10],int id, int fee): id{id}, fee{fee} // more specialized
{
strcpy(this->name,name); //string copy
}
student(char name[10],int id): student(name, id, 0) { } // less specialized calling the more specialized constructor
void show() //print function
{
cout<<"Name:"<<name<<endl;
cout<<"id:"<<id<<endl;
cout<<"fee:"<<fee<<endl<<endl;
}
};
int main()
{
student s1("DAVID",123);
student s2("WILLIAM",124,5000);
s1.show();
s2.show();
return 0;
}
A: Here's your code with changes made to get it compiling; I marked the changes with comments.
#include <iostream>
// #include <cstring> // CHANGED: Prefer C++ ways when writing C++
#include <string> // CHANGED: The C++ way
// using namespace std; // CHANGED: Bad practice
class student {
private:
std::string name{}; // CHANGED: Move from C-string to std::string
int id = 0; // CHANGED: Default member initialization
int fee = 0;
public:
// CHANGED: Move from C-string to std::string
student(std::string name, int id)
: name(name),
id(id)
// CHANGED: ^^ Utilize initialization section
{
// CHANGED: Not needed anymore
// strcpy(this->name,name); //string copy
// this->id=id;
// fee=0;
}
student(std::string name, int id, int fee) : student(name, id) {
// CHANGED: Not needed anymore
// student::student(name,id); //calling a constructor of one class
// // within a constructor of same class
// NOTE: Inconsistency with other ctor w.r.t. this->
this->fee = fee;
}
void show() // print function
{
std::cout << "Name:" << name << '\n';
std::cout << "id:" << id << '\n';
std::cout << "fee:" << fee << "\n\n";
}
};
int main() {
student s1("DAVID", 123);
student s2("WILLIAM", 124, 5000);
s1.show();
s2.show();
return 0;
}
Here is the same code, but with the stuff I commented out removed to make it easier to read.
#include <iostream>
#include <string>
class student {
private:
std::string name{};
int id = 0;
int fee = 0;
public:
student(std::string name, int id) : name(name), id(id) {}
student(std::string name, int id, int fee) : student(name, id) {
this->fee = fee;
}
void show()
{
std::cout << "Name:" << name << '\n';
std::cout << "id:" << id << '\n';
std::cout << "fee:" << fee << "\n\n";
}
};
int main() {
student s1("DAVID", 123);
student s2("WILLIAM", 124, 5000);
s1.show();
s2.show();
return 0;
}
The initialization section follows the parameter list and is marked with :. You then initialize each member, in the order they are declared.
In the case of the constructor doing the delegating, you are unable to initialize fee in the initialization section. The error I receive is a delegating constructor cannot have other mem-initializers.
I don't like splitting my initialization like that, and if you insist on delegating constructor calls for this class, implement the most specific constructor and delegate to it with your less specific constructors. I prefer default member initialization as I think it leads to less confusion and written code overall.
The code then compiles and you get the expected output:
Name:DAVID
id:123
fee:0
Name:WILLIAM
id:124
fee:5000 | unknown | |
d9650 | train | Try to use ASP.NET Web API.
Check my sample code but I consume it by Web Pages:
Server Side
[HttpPost]
[Route("api/PostMaterialRequest")]
public IHttpActionResult PostMaterialRequest(List<ItemDto> items)
{
try
{
foreach (var i in items)
{
_context.Items.Add(new Item()
{
MaterialId = i.MaterialId,
Description = i.Description,
Unit = i.Unit,
Quantity = i.Quantity,
MaterialRequestId = i.MaterialRequestId
});
_context.SaveChanges();
}
return Ok();
}
catch (Exception)
{
return BadRequest();
}
}
Client-Side
function postItem(materials) {
$.ajax({
contentType: 'application/json',
type: 'POST',
url: '/api/PostMaterialRequest',
data: JSON.stringify(materials),
success: function (data) {
console.log("do something with " + data);
},
failure: function (response) {
console.log('Failed to save.');
}
});
}
Sample of Web API consume by Mobile
I hope, I point you to right direction. | unknown | |
d9651 | train | There are different ways of doing this. One way, you could set bool value to true when the button is pressed then in updateCountdown check to the boolean.
For example:
func updateCountdown() {
self.countdown--
if self.countdown == 0 && YOUR_BUTTON_BOOL {
self.timer.invalidate()
self.timer = nil
}
let texts: NSArray = ["Test", "Testing"]
let range: UInt32 = UInt32(texts.count)
let randomNumber = Int(arc4random_uniform(range))
let textstring = texts.objectAtIndex(randomNumber)
self.ColorText.text = textstring as? String
}
However, using NSTimer in this fashion where you have it trigger in a short period of time like 1.5 seconds can become inaccurate. After the timer triggers 20 times the time past will be greater than 30 seconds. If accuracy is important you might be better off setting a second timer for 30 seconds. If the button is pressed it invalidates the 30 second timer if the 30 second timer fires it invalidates the 1.5 second timer. | unknown | |
d9652 | train | I created a free-form-text field on PO to store image file url in it. And then printed that image this way in the advanced pdf :
<img src= "${record.imgfieldname}"/>
A: Use <@filecabinet nstype="image" src="${entity.custbody_signature}">.
You won't need to use "available without login"
A: The best way to get the image url from image field in NetSuite is to do something like this
<img src= "${record.custbody_signature@Url}"/> | unknown | |
d9653 | train | Try this:
DateTime dt;
DateTime.TryParseExact(Updated_Value, "d-M-yyyy", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
var newdate = dt.ToString("d-MMM-yyyy"); | unknown | |
d9654 | train | There's no need to set the ADBannerView's size. Your ADBannerView will know which device it is on and set the dimensions of itself correctly. All you need to do is set the ADBannerView's position. Check this implementation for an example.
If you're using Auto Layout and wanted the ADBannerView to be at the bottom of the screen then pin it to the bottom of the screen with Bottom Space to: Bottom Layout Guide and align it to Align Center X to: Superview. Be sure you do not set any height, width, trailing, or leading constraints
A: OK. I still have no idea about resizing, but I figured out initial sizing.
Since iOS 6, ADBannerViews have an adType property. This property can be either ADAdTypeBanner or ADAdTypeMediumRectangle. The documentation gives the sizes for both kinds:
The banner height varies with device type and orientation as follows:
UI Idiom and Orientation | Ad Height
--------------------------------------
phone, portrait | 50 points
phone, landscape | 32 points
pad, portrait or landscape | 66 points
As for resizing, I can only assume that the banner view automatically takes the width of the screen by observing orientation change notifications. | unknown | |
d9655 | train | From your example, I'm assuming that your surplus characters must appear at the right side of the string. This means that the previous characters must alternate. This gives you only two possible solutions for the final string. In the case you give, these would be
10101000
01010100
Your entire algorithm is simple: produce both of these sequences (k 0's alternating with k 1's) and append the n-k extras. Compare each with the original to see which of the two has the smaller quantity of displaced characters. Identify those pairs and swap. For instance, using the above:
10100100 original
10101000 candidate
--------
....!!.. two differences, one swap
10100100 original
01010100 candidate
--------
!!!!.... four differences, two swaps
You use the first candidate, with locations 4 and 5 already identified.
A: Convert String to collection of Ints:
("10100100".toList).map (_.toInt-'0')
= List(1, 0, 1, 0, 0, 1, 0, 0)
Zip it with index:
.zipWithIndex
List((1,0), (0,1), (1,2), (0,3), (0,4), (1,5), (0,6), (0,7))
with modulo, find for index (0,1,2...), which value we either expect, (010...) a is string value, b is possible, alternating value of 01, c is index in String
.map {case (a,b)=> (a, b%2, b)}
List((1,0,0), (0,1,1), (1,0,2), (0,1,3), (0,0,4), (1,1,5), (0,0,6), (0,1,7))
filter those who match expectation (do the same for those in opposite order, a!=b):
.filter {case (a,b,c) => a==b }
List((0,0,4), (1,1,5), (0,0,6))
group by alternating value for later counting:
.groupBy {case (a,b,c)=> b}
Map(1 -> List((1,1,5)), 0 -> List((0,0,4), (0,0,6)))
get the lenghts and count:
.map {case (a, b) => (a, b.length)}
Map(1 -> 1, 0 -> 2)
Ignore the 1 and 0 as identifier, just take the count:
.map (i => (i._2))
List(1, 2)
Since we can only perform swaps for 1 where we have a corresponding 0 and vice versa, take the minimum of both:
"10100100".toList).map (_.toInt-'0').zipWithIndex.map {case (a,b)=> (a, b%2, b)}.filter {case (a,b,c) => a==b }.groupBy {case (a,b,c)=> b}.map {case (a, b)=> (a, b.length)}.map (i => (i._2)).min
1
In the end, we didn't need the c-value, it was just useful for keeping track, what's happening. Here is the version without c, and which starts with 1, not 0:
("10100100".toList).map (_.toInt-'0').zipWithIndex.map {case (a,b)=> (a, b%2)}.filter {case (a,b) => a!=b }.groupBy {_._2}.map {case (a, b)=> (a, b.length)}.map (i => (i._2)).min
2
The minimum of those two values (1, 2) is the solution. | unknown | |
d9656 | train | synchronized (YourClass.class)
static synchronized
Are equivalent, this is what it means.
Or in other words:
public static synchronized void go(){
}
will acquire the monitor that is associated with a class, not with an instance, as opposed to :
public synchronized void go() {
}
that will acquire the monitor from an instance. | unknown | |
d9657 | train | Most likely this is because of -webkit-tap-highlight-color
You can try to make a transparent style:
a {
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
} | unknown | |
d9658 | train | No you cannot do that, because generics are assessed at compilation (and you are asking for dynamic generics). Can you provide some more context on the usage?
How are you getting your t parameter to pass to your desired example? If it's simply by typeof(int) as a parameter, then why not use the generic exmaple?
Consider this example:
Type t = GetTypeInfoBasedOnNameInAFile();
int a = GetValue(someSerializationInfo, "PropertyName", t);
How can the compiler know that Type t is going to be castable to int at runtime?
What you could do is have GetValue return an Object and then:
Type t = GetTypeInfoBasedOnNameInAFile();
int a = (int)GetValue(someSerializationInfo, "PropertyName", t);
But of course, if you are doing that it implies you know the expected types at compile time, so why not just use a generic parameter.
You can perhaps achieve what you are after (I'm not sure on the context/usage) by using dynamic variables.
A: The return type T in the first example does not refer to any valid type: T in that case is simply the name of a parameter passed to the method.
You either know the type at design time or you don't, and if you don't then your only choice is to return the type Object, or some other base type or interface.
A: You can do a runtime conversion to a type:
Convert.ChangeType(sourceObject, destinationType);
I believe that is the syntax. Of course, this will throw an exception if the cast is not possible. | unknown | |
d9659 | train | The potential problem is that Bootstrap uses jQuery for a lot of its UI functionality. Anything changed by jQuery is not reflected in Angular by itself - for instance checking a checkbox using "regular" javascript (or jquery) will not update its ng-model automatically in the way a user checking it would.
I'd say most bootstrap plugins can be made into directives, just like Angular-strap have done. But that can be a lot of work. Some common ones (like growl) are also available as stand-alone angular projects on Github. | unknown | |
d9660 | train | The bottom is just standard notation for representing hex values in the ascii space.
If you want the number 0, it is \x00, if you want 10, it would be \x0A, and 16 (hex's 10) is \x10 (15 would be \x0F) | unknown | |
d9661 | train | It is a bit difficult to guess what you can say without knowing anything about your design (i.e. how the classes cooperate between each other), and there are a lot of "OOP concepts out there".
The only thing I can suggest you, assuming that you didn't declare every function of the other classes static, is to say that you did not use inheritance because composition is often (but not always) better. You have a composition if one member of you class is a class itself:
class Player
{
private:
Weapon gun;
public:
Player(Weapon& pistol);
void shoot(){gun.bang();}
};
Gun is a composition: Player uses a Gun to shoot() and it is a perfectly legit use of a composition here. This is a case when you DON'T want to use a composition:
class MedievalFolk
{
private:
Knight arthur;
public:
Player(Knight& pistol);
void duel(){arthur.duel();}
};
If you did something like this be prepared to be turned down, because there is no difference between a Knight and a MedievalFolk and you will need a better reason than "composition is better" here since this argument won't hold. Also, if you declared everything static then the only thing I can advise you is to rework your code not to do so. You would have just a glorification of old-fashioned procedural code (regardless of using classes) where everything is a function which calls other functions and, if I would be teaching a course on OOP, I would fail this coursework
I don't know what you are studying OOP for, but if you plan to get into software development I would strongly advise you to defer the examination and do your coursework properly, you won't be able to fix it all in a few hours not even professional can ressurect bad code in few days of work. Also there isn't a single employer that wish to hire a developer which is not proficient in OOP those days, unless you plan to work on ancient stuff of the 70s (and probably it still won't be sufficient). There is nothing wrong with taking a bit longer time if this makes you better | unknown | |
d9662 | train | There is a backend - frontend way how to comunicate between client and server. I know it doesn't sound like what you want but it is.
How does it work:
Because backend get request from client and base on this request he do something (e.g. make SQL Select).
In your case your client will be another server. And request will not come from some .js but instead from another .php file. However it still works same way.
Very basic example:
This is server which send data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/server.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1");
// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
this is server which wait for request:
if(isset($_POST['postvar1'])) {
$data = $_POST['postvar1'];
// Here comes your logic..
}
A: Yes you can run a query without a user doing anything. You also don't want to use mysql_*. You might want to look at mysqli_* functions, or PDO. | unknown | |
d9663 | train | Your json isn't correctly declared in your POST function.
Try changing:
if(req_custname && req_type && req_recomment && repeatval)
{
$.ajax({
type: "POST",
url: BASE_URL+"/req/add",
dataType: "json",
data:
{
req_custname:req_custname,
req_type:req_type,
req_recomment:req_recomment,
repeatval:repeatval
},
});
};
to:
if(req_custname && req_type && req_recomment && repeatval)
{
var postData = { "req_custname":req_custname,
"req_type":req_type,
"req_comment":req_recomment,
"req_data":repeatval };
var json = JSON.stringify(postData);
$.ajax({
type: "POST",
url: BASE_URL+"/req/add",
dataType: "json",
data: json,
});
};
See https://codepen.io/verdant-spark/pen/mdyyoXG for a working PoC of the json string creation. | unknown | |
d9664 | train | You'll have to import the whole CSV into python, process it and saving it back to file.
Here's a simple snippet which opens the CSV, processes it asking what you want to delete, then saves it back again.
You can start from this code to get what you need.
import csv
try:
csvfile = open('testcsv.csv','rb')
table = [row for row in csv.reader(csvfile)] #further parameters such as delimiters on doc
whichdelete = whichdelete = input("What thing do you want to delete? ")
header = table.pop(0) #remove header and save it to header variable
res = [row for row in table if whichdelete not in row] #save result without the row you want to delete
csvfile.close()
except IOError:
print "File not found"
quit()
try:
resultFile = open('resultCSV.csv','wb+')
writer = csv.writer(resultFile)
writer.writerow(header)
for row in res:
writer.writerow(row)
resultFile.close()
except IOError:
print "Error creating result file"
quit() | unknown | |
d9665 | train | You can add a ToList before the Select to execute the query before transforming the result.
rd.SetDataSource(db.Visitor.ToList().Select(c => new Visitor()
{
// ...
})); | unknown | |
d9666 | train | It's been a long time, but in case anyone else runs into this problem, you can leverage a style to fix this.
it looks like the color of the arrow is controlled by android:textColorSecondary, so if you are programmatically generating a popup menu, you could do something like this (in Kotlin):
val contextThemeWrapper = ContextThemeWrapper(context, R.style.PopupMenuStyle)
val popupMenu = PopupMenu(contextThemeWrapper, view)
val menu = popupMenu.menu
menu.addSubMenu(groupId, itemId, order, groupTitle)
menu.add(groupId, itemId, order, title1)
menu.add(groupId, itemId, order, title2)
etc...
and define your PopupMenuStyle like this in your styles.xml:
<style name="PopupMenuStyle" parent="@style/<some.parent.style>">
<!--this makes an the arrow for a menu's submenu white-->
<item name="android:textColorSecondary">@android:color/white</item>
</style>
A: custom theme and set listMenuViewStyle
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
<item name="listMenuViewStyle">@style/listMenuViewStyle</item>
</style>
set subMenuArrow
<style name="listMenuViewStyle" parent="Base.Widget.AppCompat.ListMenuView">
<item name="subMenuArrow">@drawable/icon_sub_menu</item>
</style>
apply custom theme to activity
<activity android:name=".material.MyTopAppBarActivity"
android:theme="@style/AppTheme"/> | unknown | |
d9667 | train | The file name wildcard is specified with the FileName property
That doesn't work, only the Filter property can be used to filter files. Furthermore, a wildcard like foo*bar.xml does do what you hope it does, anything past the * is ignored. A wildcard doesn't behave like a regular expression at all. This goes way, way back to early operating systems that didn't have the horsepower to implement regex. Definitely at CP/M, probably as far back as RSX.
Options are very limited, you can specify multiple wildcards by separating them with a ; semicolon. Like "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*". But that's as far as you can push it. | unknown | |
d9668 | train | files is a HTML5 file api feature and works only on browsers that support it.
It's not supported in IE9 see: http://caniuse.com/#feat=fileapi
You can check if files is supported before use it, try (not tested):
if( ev.target.files ){
$scope.uploadedFile = element.files[0];
}else{
$scope.uploadedFile = ev.target.value;
} | unknown | |
d9669 | train | if(direction==RIGHT) {
if(rendedMap[initX][initY+1]==0) {
finished=true;
message = "Out of bounds, try again!";
return;
} else {
rendedMap[initX][initY+1]= rendedMap[initX][initY+1]+6;
rendedMap[initX][initY]=rendedMap[initX][initY]-6;
}
}
check your rendedMap array is been initialized because this can often lead to contextual errors, especially within the android IDE.
A: if(!holder.getSurface().isValid())
continue;
canvas = holder.lockCanvas();
if(runSolution && movements.size()>0){
executeSolution();
drawPuzzle(canvas, rendedMap);
if(finished){//checks if the execution finished
runSolution=false;
}
if(message.equals("No more actions") ||
message.equals("Out of bounds, try again!")){
System.out.println(message);
drawPuzzle(canvas, originalMap);
}
}else{
drawPuzzle(canvas, originalMap);
}
drawMovements(canvas);
recall your drawPuzzle beforte surface view is locked down as the else causes it may not be executed in that contextual loop, as I said befor it is a problem that is comon with our organization apps
hope this helps! do hesistate to ask for more assistence
sorry for english I am indian | unknown | |
d9670 | train | I think your best bet is to create a virtual environment.
Open your conda cli and write this command:
conda create -n legacy python=2.7 anaconda
where legacy is the name I've arbitrarily chosen for the virtual environment
After this runs, you can activate the virtual environment with conda activate legacy and you'll be running in python 2.7
running the command spyder should then open spyder in the legacy environment running 2.7
Python 2.7 is past end of life, if you're connecting to the internet I'd strongly consider deprecating this code asap python 2.7 does not reliably back port security updates. | unknown | |
d9671 | train | I would load all the data into a datatable as you said, then have a Series object:
class Series{
public string seriesname{get;set;}
public string renderas{get;set;}
public IList<SeriesValue> data{get;set;}
}
class SeriesValue{
public string value{get;set;}
}
and return an array of Series to the frontend, serialized as JSON. Then you have the dataset array already built and you don't need to do any other processing on it.
I expect the performance bottleneck to be in loading the data from the db and sending it to the client .. the actual conversion to json shouldn't matter in the grand scheme of things. | unknown | |
d9672 | train | Is there a need for me to marshall the thread comming from the Track.cs object to my viewmodel? Any example code would be very appreciated!
Yes. Unfortunately, while INotifyPropertyChanged will handle events from other threads, INotifyCollectionChanged does not (ie: ObservableCollection<T>). As such, you need to marshal back to the VM.
If the VM is being create from the View (View-First MVVM) or is known to be created on the UI thread, there's a good option using .NET 4 tasks:
TaskScheduler uiScheduler;
public MainWindowViewModel()
{
uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Track _Track = new Track();
_Track.OnResponseEvent += new Track.ResponseEventHandler(UpdateTrackResponseWindow);
}
Then, later, your event handler can do:
private void UpdateTrackResponseWindow(AbstractResponse message)
{
Task.Factory.StartNew(
() => TrackResponseMessage.Add(FormatMessageResponseToString(message)),
CancellationToken.None, TaskCreationOptions.None,
uiScheduler);
}
This has the nice advantage of not pulling WPF or Silverlight specific resources and types into your ViewModel class (ie: Dispatcher), while still providing all of the benefits. It also works, unchanged, in other routines with thread affinity (ie: WCF service work).
A: If the RaisePropertychanged is executed on a thread other than the UI thread AND the event handler for the event touches the UI you need to switch to the UI thread. | unknown | |
d9673 | train | The method can throw lots of exceptions like ArgumentException, NotSupportedException, or etc. However, if your inputs are correct, the most possible exceptions are StorageException for communications against Azure Storage service and IOException for reading the file from local disk. | unknown | |
d9674 | train | Unfortunately, the expression ORGID ≠ 'L1' or ORGID ≠ 'G1' or ORGID ≠ 'S1' is a tautology, i.e. it's true if ORGID is 'L1' and true if ORGID is not L1, so the whole expression is always true whatever the value of ORGID is.
What you want is this:
not( ORGID = 'L1' or ORGID = 'G1' or ORGID = 'S1' )
Note that you may also use the equivalent expression without not, by using the De Morgan's law, here you have to switch and/or and negate the conditions:
ORGID != 'L1' and ORGID != 'G1' and ORGID != 'S1'
NB: does ≠ really work? Shouldn't you use !=? | unknown | |
d9675 | train | It seems to me that this is what you're after - I don't know what all that other stuff is for...
SELECT major_desc, COUNT(*) cnt
FROM all_students
GROUP
BY major_desc;
A: Here we go. Thanks to my boy 3mHz.
SELECT a.major_desc,
(select count(a.username)) as test
FROM all_students AS a
WHERE EXISTS (select * from all_course_reg
inner join courses on courses.crn=all_course_reg.crn
where all_course_reg.username=a.username)
GROUP BY a.major_desc
So we now get the right count for each major if the course is offered within the set of program courses. | unknown | |
d9676 | train | Your car model must contain user_id or user_name or some property like that,
so that you can take that data and do your embedding on the back end.
You also need to make use of parse() method of your model.
You override it to parse your json response from the server,
and when you parse, you automatically create your User model in backbone
(or refer to it, if it is already created).
But I think that also you can do this while creating your car model,
in it's initialize() method.
That may be even better.
However, if what you are asking is how you will select the proper car based on the user, when you request data from the server, then this logic is on the server side.
You need to implement it server side.
If you want to embed a driving_person within a model on a client side just like in your json response, just define your driving_person property, and it will have json object as its value.
If you want a new Backbone.Model embedded within car model, you will need to deal with initialize() of the car model.
Or even maybe parse().
Edited:
If you want to embed a user model into car model after fetch, you need to override constructor method:
var Car = Backbone.Model.extend({
constructor: function(data, options){
this.driving_person = new User(data.driving_person);
delete data.driving_person;
Backbone.Model.prototype.constructor.call(this, data);
}
/// Your other model code like initialize, etc.
Edit 2:
If you want to avoid having a new driver model per each car (because maybe more cars will share same driver), then you should probably have a global variable (or even a collection),
that takes Driver models.
It needs to be a global collection defined earlier in the code.
Then, you add driver to that global collection within this constructor that I gave you.
Let's say that you defined a global DriverCollection earlier in the code
(you do this by:
window.DriverCollection = Backbone.Collection.extend({
model: Driver,
Then, you would make your car model like this:
var Car = Backbone.Model.extend({
constructor: function(data, options){
if (!window.DriverCollection.find(function(driver){return driver.name == data.driving_person.name;}))
{window.DriverCollection.add(driving_person);}
data.driving_person = data.driving_person.name;
Backbone.Model.prototype.constructor.call(this, data);
}
/// Your other Car model code like initialize etc.
This way, your Car constructor takes JSON data and adds to global DriverCollection the driver if it doesnt exist, and it sets your car's driving_person property to name property of the embedded json driver object.
You can of course also use other property to reference & seek your driver, like id or whatever.
This way you avoid duplication.
You need to have Driver model defined for this to work. | unknown | |
d9677 | train | The main challenge in the conversion here is the format of your datetime. Pass format="%Y-%m-%d %H:%M:%S-%Z" as an argument to pd.to_datetime and convert your column to datetime.
df['PublishDateTime'] = pd.to_datetime(df['PublishDateTime'],
format='%Y-%m-%d %H:%M:%S-%Z',
errors='coerce') | unknown | |
d9678 | train | Actions can increment or decrement the count by a number or by a proportion. So if you want a dynamic increment or decrement I think you will need to create a custom action. I think you could pull out the info you need from the IRuleEvaluationContext.
To change the instance count you will need to change the deployment configuration. See https://social.msdn.microsoft.com/forums/azure/en-US/dbbf14d1-fd40-4aa3-8c65-a2424702816b/few-question-regarding-changing-instance-count-programmatically?forum=windowsazuredevelopment&prof=required for some discussion.
You should be able to do that using the Azure Management Libraries for .NET and the ComputeManagementClient. Something like:
using (ComputeManagementClient client = new ComputeManagementClient(credentials))
{
var response = await client.Deployments.GetBySlotAsync(serviceName, slot);
XDocument config = XDocument.Parse(response.Configuration);
// Change the config
StringBuilder builder = new StringBuilder();
using (TextWriter writer = new StringWriter(builder))
{
config.Save(writer);
}
string newConfig = builder.ToString();
await client.Deployments.BeginChangingConfigurationBySlotAsync(serviceName, slot, new DeploymentChangeConfigurationParameters(newConfig));
} | unknown | |
d9679 | train | There is no "standard" method for custom widgets, but usually paintEvent overriding is required.
There are different issues in your example, I'll try and address to them.
Overlapping
If you want a widget to be "overlappable", it must not be added to a layout. Adding a widget to a layout will mean that it will have its "slot" within the layout, which in turn will try to compute its sizes (based on the widgets it contains); also, normally a layout has only one widget per "layout slot", making it almost impossible to make widget overlap; the QGridLayout is a special case which allows (by code only, not using Designer) to add more widget to the same slot(s), or make some overlap others. Finally, once a widget is part of a layout, it cannot be freely moved nor resized (unless you set a fixedSize).
The only real solution to this is to create the widget with a parent. This will make it possible to use move() and resize(), but only within the boundaries of the parent.
Hovering
While it's true that most widgets can use the :hover selector in the stylesheet, it only works for standard widgets, which do most of their painting by themself (through QStyle functions). About this, while it's possible to do some custom painting with stylesheets, it's generally used for very specific cases, and even in this case there is no easy way to access to the stylesheet properties.
In your case, there's no need to use stylesheets, but just override enterEvent and leaveEvent, set there any color you need for painting and then call self.update() at the end.
Painting
The reason you're getting those warnings is because you are calling begin after declaring the QPainter with the paint device as an argument: once it's created it automatically calls begin with the device argument. Also, it usually is not required to call end(), as it is automatically called when the QPainter is destroyed, which happens when the paintEvent returns since it's a local variable.
Example
I created a small example based on your question. It creates a window with a button and a label within a QGridLayout, and also uses a QFrame set under them (since it's been added first), showing the "overlapping" layout I wrote about before. Then there's your arrow widget, created with the main window as parent, and that can be moved around by clicking on it and dragging it.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class ArrowWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
# since the widget will not be added to a layout, ensure
# that it has a fixed size (otherwise it'll use QWidget default size)
self.setFixedSize(200, 200)
self.blurRadius = 20
self.xO = 0
self.yO = 20
shadow = QtWidgets.QGraphicsDropShadowEffect(blurRadius=self.blurRadius, xOffset=self.xO, yOffset=self.yO)
self.setGraphicsEffect(shadow)
# create pen and brush colors for painting
self.currentPen = self.normalPen = QtGui.QPen(QtCore.Qt.black)
self.hoverPen = QtGui.QPen(QtCore.Qt.darkGray)
self.currentBrush = self.normalBrush = QtGui.QColor(QtCore.Qt.transparent)
self.hoverBrush = QtGui.QColor(128, 192, 192, 128)
def mousePressEvent(self, event):
if event.buttons() == QtCore.Qt.LeftButton:
self.mousePos = event.pos()
def mouseMoveEvent(self, event):
# move the widget based on its position and "delta" of the coordinates
# where it was clicked. Be careful to use button*s* and not button
# within mouseMoveEvent
if event.buttons() == QtCore.Qt.LeftButton:
self.move(self.pos() + event.pos() - self.mousePos)
def enterEvent(self, event):
self.currentPen = self.hoverPen
self.currentBrush = self.hoverBrush
self.update()
def leaveEvent(self, event):
self.currentPen = self.normalPen
self.currentBrush = self.normalBrush
self.update()
def paintEvent(self, event):
qp = QtGui.QPainter(self)
qp.setRenderHints(qp.Antialiasing)
# painting is not based on "pixels", to get accurate results
# translation of .5 is required, expecially when using 1 pixel lines
qp.translate(.5, .5)
# painting rectangle is always 1px smaller than the actual size
rect = self.rect().adjusted(0, 0, -1, -1)
qp.setPen(self.currentPen)
qp.setBrush(self.currentBrush)
# draw an ellipse smaller than the widget
qp.drawEllipse(rect.adjusted(25, 25, -25, -25))
# draw arrow lines based on the center; since a QRect center is a QPoint
# we can add or subtract another QPoint to get the new positions for
# top-left, right and bottom left corners
qp.drawLine(rect.center() + QtCore.QPoint(-25, -50), rect.center() + QtCore.QPoint(25, 0))
qp.drawLine(rect.center() + QtCore.QPoint(25, 0), rect.center() + QtCore.QPoint(-25, 50))
class MainWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
layout = QtWidgets.QGridLayout()
self.setLayout(layout)
self.button = QtWidgets.QPushButton('button')
layout.addWidget(self.button, 0, 0)
self.label = QtWidgets.QLabel('label')
self.label.setAlignment(QtCore.Qt.AlignCenter)
layout.addWidget(self.label, 0, 1)
# create a frame that uses as much space as possible
self.frame = QtWidgets.QFrame()
self.frame.setFrameShape(self.frame.StyledPanel|self.frame.Raised)
self.frame.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
# add it to the layout, ensuring it spans all rows and columns
layout.addWidget(self.frame, 0, 0, layout.rowCount(), layout.columnCount())
# "lower" the frame to the bottom of the widget's stack, otherwise
# it will be "over" the other widgets, preventing them to receive
# mouse events
self.frame.lower()
self.resize(640, 480)
# finally, create your widget with a parent, *without* adding to a layout
self.arrowWidget = ArrowWidget(self)
# now you can place it wherever you want
self.arrowWidget.move(220, 140)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
testWidget = MainWidget()
testWidget.show()
sys.exit(app.exec_()) | unknown | |
d9680 | train | I have experienced the same problem with you before. I solve this problem with set the width and max-width for the drop down.
<select class="chzn-select" name="chznName" >
...
</select>
<style>
select, option {
width: 500px;
max-width: 500px;
}
</style>
Chosen will create the chosen dropdown with width from the actual dropdown that you create. | unknown | |
d9681 | train | Config needs to be modified to use this in the binding:
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic" proxyCredentialType="None" realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
EDIT
The reason it works is because that eventhough the UserName property is set in code the WCF service still needs to be configured to send the credentials. This is done in the B of the WCF ABC (http://msdn.microsoft.com/en-us/library/aa480190.aspx):
"A" stands for Address: Where is the service?
"B" stands for Binding: How do I talk to the service?
"C" stands for Contract: What can the service do for me?
The whole idea of WCF is that it should be configurable so that there is no need to redeploy the code if the service changes. | unknown | |
d9682 | train | The default buffer size can be seen in .Net's source code, here.
WriteThrough is not supported in .Net. You can use unmanaged Win API calls is you really want that functionality. I just spent a day experimenting with it, and there are no advantages to using it. This was not true 10+ years ago, where the caching had a noticeable effect on speed.
Out of interest, someone kindly wrote the whole library for doing the API calls, available here.
A: You could use your own factory method to construct the FileStream.
Other than that, you could hardwire the buffer size discovered using Reflector (0x1000). | unknown | |
d9683 | train | - name: "Add ssh keys"
authorized_key: user=admin key="{{ lookup('file', 'ssh_keys/id_rsa_{{ hostvars[item].server_name }}.pub') }}"
with_items: "{{ groups['web'] }}" | unknown | |
d9684 | train | If you can restrict id to some subset of all values you can add that constraints to route (i.e. numbers only) to let default handle the rest.
routes.MapRoute(
name: "Brochure",
url: "{id}",
defaults: new { controller = "brochure", action = "Brochure", id = "Index" },
namespaces: new[] { "Web.Areas.Brochure.Controllers" }
constraints : new { category = @"\d+"}
);
If you can't statically determine restrictions - automatically redirecting in your BrochureController similar to your current code would work. The only problem with sample in the question is it hits the same route again and goes into infinite redirect loop - redirect to Url that does not match first rule:
// may need to remove defaults from second route
return RedirectToRoute("HomeDefault", new { client = id, action = "index" });
If standard constraints do not work and you must keep single segment in url - use custom constraints - implement IRouteConstraint and use it in first route. See Creating custom constraints.
A: Two ways I could have solved this issue:
Way 1
I reviewed the redirect and just passed in an action in order to get a route that has 2 segments in the url. i.e. client/Index. The Index action now handles logins - going past a custom controller.
public class HomeController : CustomController
public ActionResult Brochure(string id, string action) {
if (ViewExists(id)) {
return View(id);
}
return RedirectToAction("Index", "Home", new { client = id, action = "Index" });
}
Way 2
(from @Alexei_Levenkov)
Create a custom Route constraint so the route will be ignored if the view cannot be found.
namespace Web.Contraints {
public class BrochureConstraint : IRouteConstraint {
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) {
//Create our 'fake' controllerContext as we cannot access ControllerContext here
HttpContextWrapper context = new HttpContextWrapper(HttpContext.Current);
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "brochure");
ControllerContext controllerContext = new ControllerContext(new RequestContext(context, routeData), new BrochureController());
//Check if our view exists in the folder -> if so the route is valid - return true
ViewEngineResult result = ViewEngines.Engines.FindView(controllerContext, "~/Areas/Brochure/Views/Brochure/" + values["id"] + ".cshtml", null);
return result.View != null;
}
}
}
namespace Web {
public class MvcApplication : System.Web.HttpApplication {
//If view doesnt exist then url is a client so use the 'HomeDefault' route below
routes.MapRoute(
name: "Brochure",
url: "{id}",
defaults: new { controller = "brochure", action = "Brochure", id = "Index" },
namespaces: new[] { "Web.Areas.Brochure.Controllers" },
constraints: new { isBrochure = new BrochureConstraint() }
);
//This is home page for client
routes.MapRoute(
name: "HomeDefault",
url: "{client}/{action}",
defaults: new { controller = "home", action = "index" },
namespaces: new string[] { "Web.Controllers" }
);
}
}
I hope this helps someone else out there.
A: There are several issues with your configuration. I can explain what is wrong with it, but I am not sure I can set you on the right track because you didn't provide the all of the URLs (at least not all of them from what I can tell).
Issues
*
*Your Brouchure route, which has 1 optional URL segment named {id}, will match any URL that is 0 or 1 segments (such as / and /client). The fact that it matches your home page (and you have another route that is named HomeDefault that will never be given the chance to match the home page) leads me to believe this wasn't intended. You can make the {id} value required by removing the default value id = "Index".
*The Brouchure route has a namespace that indicates it is probably in an Area. To properly register the area, you have to make the last line of that route ).DataTokens["area"] = "Brochure"; or alternatively put it into the /Areas/Brouchure/AreaRegistration.cs file, which will do that for you.
*The only way to get to the HomeDefault route is to supply a 2 segment URL (such as /client/Index, which will take you to the Index method on the HomeController). The example URLs you have provided have 3 segments. Neither of the routes you have provided will match a URL with 3 segments, so if these URLs are not getting 404 errors they are obviously matching a route that you haven't provided in your question. In other words, you are looking for the problem in the wrong place.
If you provide your entire route configuration including all Area routes and AttributeRouting routes (including the line that registers them), as well as a complete description of what URL should go to what action method, I am sure you will get more helpful answers.
So the question is:
How can I get the route to act properly?
Unknown. Until you describe what properly is.
Related: Why map special routes first before common routes in asp.net mvc? | unknown | |
d9685 | train | One idea is as follows:
You pick an initial random point, and for each dimension, find the exact value. How? For the sake of symmetry, suppose that you desire to find x of the target point. Increase by one the x, and compute the distance of the new point from the target point. If it goes further, it means that you should move in the opposite direction. Hence, you can run a binary search and get the distance to find the exact x of the target point. Otherwise, it means that you are going in the right direction along X-axis. So, do a binary search between all points with the same y and z such that their x values can change from x+1 to 100. A more formal solution comes in the following (just a pseudo-code).
You should also ask about the complexity of this solution. As the dimension of the point is constant (3) and checking these conditions take a constant time, the complexity of number of calling getDifference function is O(log(n)). What is n here? the length of valid range for coordinates (here is 100).
1. p: (x,y,z) <- Pick a random coordinate
2. dist: (dist_x, dist_y, dist_z) <- getDifference(p, TargetPoint)
3. For each dimension, do the following (i can be 0 (x), 1 (y), 2 (3)):
4. if(dist == 0):
5. isFound[i] <- p[i]
6. continue
7. new_i <- p[i] + 1
8. new_point <- p
9. new_point[i] <- new_i
10. new_dist <- getDifference(new_point, pointToFound)
11. if(new_dist == 0):
12. isFound[i] <- new_point[i];
13. continue
14. if(new_dist[i] > dist[i]):
15. isFound[i] <- binary_search for range [0, p[i]-1] to find the exact value of the pointToFound in dimension i
15. continue
16. else:
17. isFound[i] <- binary_search for range [p[i] + 1, 100] to find the exact value of the pointToFound in dimension i
18. continue
A: Following method will work for coordinates with positive or negative real values as well.
Let's say you are searching for the coordinates of point P. As the first query point, use origin O. Let the distance to the origin O be |PO|. At this point, you know that P is on the surface of sphere
(P.x)^2 + (P.y)^2 + (P.z)^2 = |PO|^2 (1)
As the second query point, use Q = (|PO|, 0, 0). Not likely but if you find the distance |PQ| zero, Q is the point you are looking for. Otherwise, you get another sphere equation, and you know that P is on the surface of this sphere as well:
(P.x - |PO|)^2 + (P.y)^2 + (P.z)^2 = |PQ|^2 (2)
Now, if you subtract (1) from (2), you get
(P.x - |PO|)^2 - (P.x)^2 = |PQ|^2 - |PO|^2 (3)
Since the only unknown in this equation is P.x you can get its value:
P.x = (((-|PQ|^2 + |PO|^2) / |PO|) + |PO|)/2)
Following similar steps, you can get P.y with R = (0, |PO|, 0) and P.z with S = (0, 0, |PO|). So, by using four query points O, Q, R, and S you can get the coordinates of P.
A: This can be done with at most 3 guesses and often with 2 guesses:
*
*Let the first guess be [0, 0, 0], and ask for the distance
*Find in the 100x100x100 cube all points that have that distance to [0, 0, 0]. There might be around 100-200 points that have that distance: consider all of these candidates.
*Take the first candidate as the second guess and ask for the distance
*Find among the other candidates the ones that have exactly that distance to the first candidate. Often there will be only one point that satisfies this condition. In that case we can return that candidate and only 2 guesses were necessary.
*Otherwise (when there is more than one candidate remaining) repeat the previous step which will now certainly lead to a single point.
Here is an implementation that provides a blackbox function which chooses the secret point in a local variable, and which returns two functions: f for the caller to submit a guess, and report for the caller to verify the result of the algorithm and report on the number of guesses. This is not part of the algorithm itself, which is provided in the findPoint function.
const rnd = () => Math.floor(Math.random() * 101);
const distance = (a, b) =>
a.reduce((acc, x, i) => acc + (x - b[i]) ** 2, 0) ** 0.5;
function findPoint(f) {
// First guess is always the zero-point
let guess = [0, 0, 0];
let dist = f(guess);
if (dist === 0) return guess; // Extremely lucky!
// Find the points in the cube that have this distance to [0,0,0]
let candidates = [];
const limit = Math.min(100, Math.round(dist));
for (let x = 0; x <= limit; x++) {
const p = [x, limit, 0];
// Follow circle in X=x plane
while (p[1] >= 0 && p[2] <= limit) {
const d = distance(p, guess);
const diff = d - dist;
if (Math.abs(diff) < 1e-7) candidates.push([...p]);
if (diff >= 0) p[1]--;
else p[2]++;
}
}
// As long there are multiple candidates, continue with a guess
while (candidates.length > 1) {
const candidates2 = [];
// These guesses are taking the first candidate as guess
guess = candidates[0];
dist = f(guess);
if (dist === 0) return guess; // lucky!
for (const p of candidates) {
let d = distance(p, guess);
let diff = d - dist;
if (Math.abs(diff) < 1e-7) candidates2.push(p);
}
candidates = candidates2;
}
return candidates[0]; // Don't call f as we are sure!
}
function blackbox() {
const secret = [rnd(), rnd(), rnd()];
console.log("Secret", JSON.stringify(secret));
let guessCount = 0;
const f = guess => {
guessCount++;
const dist = distance(secret, guess);
console.log("Submitted guess " + JSON.stringify(guess) + " is at distance " + dist);
return dist;
};
const report = (result) => {
console.log("Number of guesses: " + guessCount);
console.log("The provided result is " + (distance(secret, result) ? "not" : "") + "correct");
}
return {f, report};
}
// Example run
const {f, report} = blackbox();
const result = findPoint(f);
console.log("Algorithm says the secret point is: " + JSON.stringify(result));
report(result);
Each run will generate a new secret point. When running this thousands of times it turns out that there is 1/9 probability that the algorithm needs a third guess. In the other 8/9 cases, the algorithm needs two guesses. | unknown | |
d9686 | train | The core Java runtime does not offer a JSON parser (edit: technically, it does, see bottom of answer), so you will need a library. See Jackson, Gson, perhaps others.
Even with that, you will not get the dynamic features you want, because Java is statically typed. Example with Jackson:
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String, Object>>(){});
map.get("monday").get("1").get("subject");
^^^
This fails because the result of get("monday") is Object, not Map
The "right" approach in Java-land, would be to create a class (or set of classes) that represents your JSON model, and pass it to the JSON parser's "object mapper". But you said "dynamic" so I'm not exploring this here.
So you'll need to cast to Map when you know it's not primitive values:
((Map<String,Map<String,String>>)map.get("monday")).get("1").get("subject");
This works but with a warning about unchecked cast...
All in all, Java is not a dynamic language and I see no way to do exactly what you want (perhaps I'm missing approaches that are still slightly easier than what I have suggested).
Are you limited to Java-the-language or Java-the-platform? In the latter case you can use a dynamic language for the Java platform, such as Groovy, who has excellent features to parse JSON.
EDIT: a funny alternative is to use Java's own JavaScript implementation. This works and is easy and dynamic, but I don't know if it's "good":
String json = "{\"date\":\"07.05.2017 11:44\",\n" +
"\"monday\":{\"1\":{\"subject\":\"test\",\"room\":\"test\",\"status\":\"test\"}}}";
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.put("data", json);
System.out.println(engine.eval("JSON.parse(data)['monday']['1']['subject']"));
A: If you are sure about the value you want to get then you can do following as well :
String str = "{\"date\":\"07.05.2017 11:44\", \"monday\":{\"1\":{\"subject\":\"test\",\"room\":\"test\",\"status\":\"test\"}}}";
JSONObject results= new JSONObject(str);
String str1 = results.getJSONObject("monday").getJSONObject("1").getString("subject");
System.out.println(str1);
For array kind of results, we have to write logic for that. In this case org.json library is used.
A: You can use GCON library:
https://github.com/google/gson
Very good for parsing JSON objects. | unknown | |
d9687 | train | I just tried to clean up your code, as there was a Link outside a li element. This should work:
<nav>
<div class="nav-wrapper blue lighten-2">
<a class="brand-logo left">
<img src="/images/logo_small.png"></img>
</a>
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li>
<a href="teechrworks.html">How teechr works?</a>
</li>
<li>
<a href="aboutus.html">About us</a>
</li>
<li>
<Link to="/chooseachatbottype">Get started!</Link>
</li>
<li>
<Link style={navStyle} to="/createquiz1">
Create your quizbot!
</Link>
</li>
<li>
<a href="signin.html" a class="waves-effect waves-light btn">
Sign in
</a>
</li>
</ul>
</div>
</nav>
A: pass a prop of target="__blank" should work like in Standart HTML.
Create your Links in const and you have better overview.
Didn't add your Styles...
import React, { Fragment, useEffect } from 'react';
import { Link } from 'react-router-dom';
const Navbar = () => {
const links = (
<Fragment>
<li>
<Link className="link-item" to='/'>Home</Link>
</li>
<li>
<a className="link-item" href="https://www.google.com" target="__blank">External Website</a>
</li>
</Fragment>
)
return (
<Fragment>
<div className="nav-wrapper">
<ul>
{links}
</ul>
</div>
</Fragment>
)
}
export default Navbar;
Your typo:
<a class="brand-logo left">
<img scr="/images/logo_small.png"></img>
</a>
src not scr | unknown | |
d9688 | train | First and foremost, you can force IE not to display the Compatibility View button simply by adding this to your page head:
<meta http-equiv="X-UA-Compatible" content="IE=edge">
As for your other questions:
Why is the Compatibility View button appearing if there are no issues?
So what's the deal with this Compatibility View junk? Why is it there - on a website that does not have any issues?
It's there in case a site, typically one that was written many years ago, fails to work in a newer version of IE, to allow users to view or IE to display it in a legacy rendering mode where it will hopefully work better.
Additionally, it's there by default because legacy sites will not even have the meta tag above to begin with. In order for the button to display when viewing existing sites without having to update their code, it's only logical to make it an opt-out feature instead, by having the developer add it to new code to tell newer versions of IE to hide the button when it's not needed.
And, most importantly, is it important that I make sure my website works well while in Compatibility View even though it works perfectly when it's off and even though it works perfectly in all the major browsers - and then some?
Compatibility View is meant for websites that were specifically designed for legacy browsers, and as such, depend on legacy rendering quirks not present in more recent browsers which may cause "problems" in those more recent browsers.
Without seeing your site, we won't be able to determine why it works in IE7 and IE10 in IE7 mode but not Compatibility View, but if it works well in newer versions of IE, you do not need to ensure that it works well in Compatibility View. Using the meta tag above to hide the button when it's not necessary will suffice.
A: Can you provide us a link to your site? I always use
<!DOCTYPE html>
on the first line of the HTML document. This is a universal switch to the latest rendering mode in all modern browsers. Use BoltClock's solution to hide a compatible view button in IE's address bar. I would prefer a HTTP header rather than HTML meta tag, because the meta tag causes parser switch and reset. | unknown | |
d9689 | train | In your
const urlElemt = $('article.product-tile')
...
let urlTitle = $(urlElemt.find("h2.product-tile__title"))
find() function already returns a Cheerio object, hence you don't need to pass it to $ function. This will suffice:
let urlTitle = urlElemt.find("h2.product-tile__title")
thus you can do
console.log(urlTitle.text())
or
console.log(urlTitle.html())
to see the serialized versions of the dom nodes, which in your case should be a plain text string. (see the api docs) | unknown | |
d9690 | train | Immutability is an implementation technique. Among other things, it provides persistence, which is an interface. The persistence API is something like:
*
*version update(operation o, version v) performs operation o on version v, returning a new version. If the data structure is immutable, the new version is a new structure (that may share immutable parts of the old structure). If the data structure isn't immutable, the returned version might just be a version number. The version v remains a valid version, and it shouldn't change in any observe-able way because of this update - the update is only visible in the returned version, not in v.
*data observe(query q, version v) observes a data structure at version v without changing it or creating a new version.
For more about these differences, see:
*
*The chapter "Persistent data structures" by Haim Kaplan in Handbook on Data Structures and Applications
*"Making Data Structures Persistent" by Driscoll et al.
*The first lecture of the Spring 2012 incarnation of MIT's 6.851: Advanced Data Structures
A: Yes, there is a difference. An immutable data structure cannot be modified in any way after its creation. The only way to effective modify it would be to make a mutable copy or something similar (e.g. slightly modifying the parameters you pass to the constructor of the new one). A persistent data structure, on the other hand, is mutable in the sense that the exposed API appears to allow changes to the data structure. In truth, though, any changes will retain a pointer to the existing data structure (and therefore every preceding structure); they only seem to mutate the data structure because the exposed API returns a new pointer that may include pointers to a subset of the previous data structure (in trees, e.g., we will point at the node whose subtree hasn't changed as a result of the operation). | unknown | |
d9691 | train | Remember that Type Erasure is a thing in Kotlin, so the runtime does not know what the T in it as? T, and hence cannot check the cast for you. Therefore, the cast always succeeds (and something else will fail later down the line). See also this post. IntelliJ should have given you an "unchecked cast" warning here.
So rather than checking the type using T, you can check the type using the property argument:
class ColorDelegate<T> {
operator fun getValue(thisRef: Palette, property: KProperty<*>) =
// assuming such an item always exists
thisRef.colorCollection.list.first {
property.returnType.classifier == it::class
} as T
}
fun main() {
val palette = Palette()
println(palette.black) // prints "black"
println(palette.white) // prints "white"
}
Here, I've checked that the class of the returnType of the property (i.e. the property on which you are putting the delegate) is equal to the list element's runtime class. You can also e.g. be more lenient and check isSubclassOf.
Do note that this wouldn't find any element in the list if the property's type was another type parameter, rather than a class, e.g.
class Palette<T> {
...
val foo: T by ColorDelegate()
...
}
But alas, that's type erasure for you :(
A: This is due to type erasure with generics. Casting to a generic type always succeeds because generic types are not known at runtime. This can cause a runtime exception elsewhere if the value is assigned to a variable of a concrete mismatched type or a function it doesn't have is called on it.
Since casting to generic types is dangerous (it silently works, allowing for bugs that occur at a different place in code), there is a compiler warning when you do it like in your code. The warning says "unchecked cast" because the cast occurs without type-checking. When you cast to a concrete type, the runtime checks the type at the cast site and if there is a mismatch it immediately throws ClassCastException, or resolves to null in the case of a safe-cast as?.
Info about type erasure in the Kotlin documentation | unknown | |
d9692 | train | Are you trying to find out if another latitude and longitude is within a certain radius of your initial latitude and longitude? If so, check out this other StackOverflow post.
A: You will need more information than a point and a radius. You are also going to need the angle of the point in the circle.
Using the radius and the angle you have to apply trigonometric laws and draw and imaginary triangle with dimensions radius, height and width. The height and width will give you the distance from the current latitude and longitude.
For example:
for (int angle = 0; angle < 360; angle++){
double x = getDistanceX(radius, angle);
double y = getDistanceY(radius, angle);
if (angle > 180)
x *= -1;
if (angle > 90 && angle < 270)
y *= -1;
double newLatitude = getCalculateLatitude(latitude, x);
double newLongitude = getCalculateLatitude(longitude, y);
} | unknown | |
d9693 | train | here is something to start with:
@echo off
for /f %%i in (t.txt) do for /f %%a in ('type t.txt^|findstr /x "%%i"^|find /v /c "" ') do if %%a gtr 1 echo %%i
findstr can't count, so we have to use find /c as helper
see find /?, findstr /? and for /? for more information.
A: Stephan's answer works, but it prints out every replicate word as many times as it appears. It also fairly inefficient, reading the entire file once for every line in the file.
Here is a fairly simple pure batch solution that prints out each replicate word only once. The task is much simpler if you use SORT to group all the replicates together. However, the Windows SORT command ignores case, so the IF must also ignore case. This solution only reads the file twice, regardless of size, once for SORT, and once for FOR /F.
@echo off
setlocal enableDelayedExpansion
set "prev="
set "dup="
for /f "delims=" %%W in ('sort test.txt') do (
if /i %%W==!prev! (
if not defined dup echo(%%W
set dup=1
) else set "dup="
set "prev=%%W"
)
If you want the word comparison to be case sensitive, then the above algorithm requires a case sensitive SORT routine. I've written JSORT.BAT to do just that (among other things). It is pure script (hybrid JScript/batch) that runs natively on Windows.
But if you are willing to use a JScrpt/batch hybrid, then the solution becomes very simple if you add my JREPL.BAT regular expression find/replace utility. The /M option allows me to search for repeated words across newlines.
jsort test.txt | jrepl "^(.+)$(\r?\n\1$)+" $1 /jmatch /m
There is significant initialization time to fire up the JScript engine, so this solution is a bit slower than the pure batch solution if the file is small. But if the file is large, than this is much faster than the pure batch solution. | unknown | |
d9694 | train | How about this?
static String getTimeBetween(ZonedDateTime from, ZonedDateTime to) {
StringBuilder builder = new StringBuilder();
long epochA = from.toEpochSecond(), epochB = to.toEpochSecond();
long secs = Math.abs(epochB - epochA);
if (secs == 0) return "now";
Map<String, Integer> units = new LinkedHashMap<>();
units.put("day", 86400);
units.put("hour", 3600);
units.put("minute", 60);
units.put("second", 1);
boolean separator = false;
for (Map.Entry<String, Integer> unit : units.entrySet()) {
if (secs >= unit.getValue()) {
long count = secs / unit.getValue();
if (separator) builder.append(", ");
builder.append(count).append(' ').append(unit.getKey());
if (count != 1) builder.append('s');
secs %= unit.getValue();
separator = true;
}
}
return builder.append(epochA > epochB ? " ago" : " in the future").toString();
}
You could probably store the LinkedHashMap instead of instantiating it every method call, but this should work. | unknown | |
d9695 | train | You can try SUMPRODUCT:
=SUMPRODUCT(--(((A:A<=TODAY()-365)*(A:A<>"")+(A:A="")*(B:B<>"")*(B:B<=TODAY()-365))>=1))
Explanation:
Part (A:A<=TODAY()-365)*(A:A<>"") counts non empty cells in col A where date is less than year ago.
Part (A:A="")*(B:B<>"")*(B:B<=TODAY()-365))) counts non empty cells in col B where cell in col A is empty and date in col B is less than year ago.
By summing both parts we get total count of dates according to your conditions (I hope).
-- converts bool to int value so SUMPRODUCT can sum it, but you can ignore this part as formula works without it and >=1
=SUMPRODUCT(((A:A<=TODAY()-365)*(A:A<>"")+(A:A="")*(B:B<>"")*(B:B<=TODAY()-365))) | unknown | |
d9696 | train | If you want to visit your website without having to specify the port, you need to make sure it's running on the default port.
The default secured HTTP (https://) port is 443.
The default unsecured HTTP (http://) port is 80. | unknown | |
d9697 | train | Plunker did not work for me, lastX variable is undefined when I click the button. But I copy pasted code and I put values manually and seem that it works, so I think the problem is that you should check if variable is defined before store them.
Also, you need init lines in localStorage before setting its default value, or will throw an error later trying to store in an undefined value.
http://embed.plnkr.co/kbrRd2fYlL3oW07iI8Hm/
A: setup you variables at scope
app.controller('app', function($scope, $http, $localStorage) {
// Set a default
$scope.$storage = $localStorage.$default({
"lines": []
});
$scope.cloneItem = function() {
$scope.$storage.lines.push({
"lastX": $scope.lastX,
"lastY": $scope.lastY,
"currentX": $scope.currentX,
"currentY": $scope.currentY
});
alert('$scope.lastX11111 -' + $scope.lastX)
}
});
to
app.directive("drawing", function() {
return {
restrict: "A",
link: function(scope, element) {
var ctx = element[0].getContext('2d');
// variable that decides if something should be drawn on mousemove
var drawing = false;
element.bind('mousedown', function(event) {
if (event.offsetX !== undefined) {
scope.lastX = event.offsetX;
scope.lastY = event.offsetY;
} else {
scope.lastX = event.layerX - event.currentTarget.offsetLeft;
scope.lastY = event.layerY - event.currentTarget.offsetTop;
}
// begins new line
ctx.beginPath();
drawing = true;
});
element.bind('mousemove', function(event) {
if (drawing) {
// get current mouse position
if (event.offsetX !== undefined) {
scope.currentX = event.offsetX;
scope.currentY = event.offsetY;
} else {
scope.currentX = event.layerX - event.currentTarget.offsetLeft;
scope.currentY = event.layerY - event.currentTarget.offsetTop;
}
draw(scope.lastX, scope.lastY, scope.currentX, scope.currentY);
// console.log(lastX, lastY, currentX, currentY);
// set current coordinates to last one
scope.lastX = scope.currentX;
// console.log(lastX, lastY, currentX, currentY);
scope.lastY = scope.currentY;
}
});
element.bind('mouseup', function(event) {
// stop drawing
drawing = false;
});
// canvas reset
function reset() {
element[0].width = element[0].width;
}
function draw(lX, lY, cX, cY) {
// line from
ctx.moveTo(lX, lY);
// to
ctx.lineTo(cX, cY);
// color
ctx.strokeStyle = "#4bf";
// draw it
ctx.stroke();
}
}
};
});
http://plnkr.co/edit/Qcqua0gjoAfya6xkQFiX?p=preview | unknown | |
d9698 | train | You can use setTimeout
$(document).ready(function(){
$( ".leftbar" ).mouseenter(function() {
window.setTimeout(function(){
$( "body" ).addClass( "myclass" );
}, 300);
});
}):
See https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setTimeout
A: Use a setTimeout, being sure to clear it when the cursor leaves.
Minor error, but myclass != myclass1.
$(document).ready(function(){
var barTimeout = 0;
$( ".leftbar" ).on({
mouseenter: function(){
barTimeout = setTimeout(function(){
$( "body" ).addClass( "myclass" );
}, 300);
},
mouseleave: function(){
if( typeof barTimeout !== 'undefined' ) clearTimeout( barTimeout );
$( "body" ).removeClass( "myclass" );
}
});
});
JSFiddle
A: You could take a look at the jQuery UI method addClass which allows you to pass in some animation parameters into it. View the example and documentation here http://api.jqueryui.com/addClass/
For your use, it should be as simple as adding in the delay to addClass()
Add a reference to the jQuery Library, then change your code to;
$("body").addClass("myclass", 300);
A: You can do it like this:
$(document).ready(function () {
$(".leftbar").hover( function () {
$(this).delay(300).queue(function(next){
$(this).addClass("myclass");
next();
});
}, function(){
$(this).delay(300).queue(function(next){
$(this).removeClass("myclass");
next();
});
});
});
Check it out here: JSFiddle | unknown | |
d9699 | train | You have to encode the query string as it appears in the request URL.
To do so you need:
urllib.parse.urlencode()
Here's a working example:
import json
import urllib.parse
import requests
link = 'https://www.zillow.com/search/GetSearchPageState.htm?'
params = {
'searchQueryState': {
"pagination": {},
"usersSearchTerm": "Vista, CA",
"mapBounds": {
"west": -117.44051346728516,
"east": -116.99488053271484,
"south": 33.126944633035116,
"north": 33.27919773006566
},
"regionSelection": [{"regionId": 41517, "regionType": 6}],
"isMapVisible": True,
"filterState": {
"doz": {"value": "6m"}, "isForSaleByAgent": {"value": False},
"isForSaleByOwner": {"value": False}, "isNewConstruction": {"value": False},
"isForSaleForeclosure": {"value": False}, "isComingSoon": {"value": False},
"isAuction": {"value": False}, "isPreMarketForeclosure": {"value": False},
"isPreMarketPreForeclosure": {"value": False},
"isRecentlySold": {"value": True}, "isAllHomes": {"value": True},
"hasPool": {"value": True}, "hasAirConditioning": {"value": True},
"isApartmentOrCondo": {"value": False}
},
"isListVisible": True,
"mapZoom": 11
},
'wants': {"cat1": ["listResults"]},
'requestId': 2
}
with requests.Session() as s:
s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'
s.headers["x-requested-session"] = "BE6D8DA620E60010D84B55EB18DC9DC8"
s.headers["cookie"] = f"JSESSIONID={s.headers['x-requested-session']}"
data = json.dumps(
json.loads(s.get(f"{link}{urllib.parse.urlencode(params)}").content),
indent=2
)
print(data)
Output:
{
"user": {
"isLoggedIn": false,
"hasHousingConnectorPermission": false,
"savedSearchCount": 0,
"savedHomesCount": 0,
"personalizedSearchGaDataTag": null,
"personalizedSearchTraceID": "607a9ecb5aabe489c361c1d91f368b37",
"searchPageRenderedCount": 0,
"guid": "33b7add3-bfd3-4d85-a88a-d9d99256d2a2",
"zuid": "",
"isBot": false,
"userSpecializedSEORegion": false
},
"mapState": {
"customRegionPolygonWkt": null,
"schoolPolygonWkt": null,
"isCurrentLocationSearch": false,
"userPosition": {
"lat": null,
"lon": null
},
"regionBounds": {
"north": 33.275284,
"east": -117.145153,
"south": 33.130865,
"west": -117.290241
}
},
and much much more ...
Note: Go easy on that site as they have a pretty sensitive anti-bot measures and if you keep requesting the data too quickly, they'll throw a CAPTCHA at you. | unknown | |
d9700 | train | I believe that the problem lies in your global variable, lis_. You manipulate this through all of the lis entries. You return the list reference for each element of your comprehension, but continue to update the list on later parsing.
What you get is a list of identical pointers (each one is the reference to lis_), each of which contains all of the processing.
To fix this, use proper encapsulated programming practices. Use local variables, clean them on each call, and return only the value needed in the calling program.
Does that get you moving?
A: Would this be helpful?
lis = ['hi how are you',
'pretty good',
'the quick brown fox',
'the is quick brown fox play',
'play the quick brown fox']
def requ(text):
# This mimics the request
output = []
for word in text.split():
# This just mimics getting some ID for each word
xyz = "".join(str([ord(x) for x in word])).replace(", ", "")
# This mimics the word root part
if word in ["are", "is"]:
output.append((word, "be", xyz))
else:
output.append((word, word, xyz))
return output
new_lis = [requ(w) for w in lis]
print(new_lis)
Output:
[[('hi', 'hi', '[104105]'), ('how', 'how', '[104111119]'), ('are', 'be', '[97114101]'), ('you', 'you', '[121111117]')], [('pretty', 'pretty', '[112114101116116121]'), ('good', 'good', '[103111111100]')], [('the', 'the', '[116104101]'), ('quick', 'quick', '[11311710599107]'), ('brown', 'brown', '[98114111119110]'), ('fox', 'fox', '[102111120]')], [('the', 'the', '[116104101]'), ('is', 'be', '[105115]'), ('quick', 'quick', '[11311710599107]'), ('brown', 'brown', '[98114111119110]'), ('fox', 'fox', '[102111120]'), ('play', 'play', '[11210897121]')], [('play', 'play', '[11210897121]'), ('the', 'the', '[116104101]'), ('quick', 'quick', '[11311710599107]'), ('brown', 'brown', '[98114111119110]'), ('fox', 'fox', '[102111120]')]]
A: Your list comprehension is fine, the reason you get strange output looks to be that the request function always returns a reference to the global variable lis_, which you keep appending things to. You should create lis_ as a local variable inside convert(). | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.