_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d16401 | val | You can try with postMessage:
http://en.wikipedia.org/wiki/Cross-document_messaging
https://developer.mozilla.org/en-US/docs/DOM/window.postMessage
You should send a command from search.html to the main page and let the main page handle the event of a received message.
You'll find what you need in the links above
Example (Parent page):
window.onmessage = function(e){
//Here is the data that you receive from search.html
var DataReceived = e.data;
var OriginUrl = e.origin;
//Do what you want when the message is received
};
Example (search.html):
function buttonClick() {
var curDomain = location.protocol + '//' + location.host; //This will be received as e.origin (see above)
var commandString = "Hello parent page!"; //This will be received as e.data
parent.postMessage(commandString,curDomain); //Sends message to parent frame
}
The windows.onmessage in the parent page should be 'launched' on page load. The 'buttonClick()' function could be called when and where you want to send a message to the parent page that will execute some stuff (in this case your stuff with accordion)
EDIT:
to close the modal try this way:
Parent:
window.onmessage = function(e){
//Here is the data that you receive from search.html
var DataReceived = e.data;
var OriginUrl = e.origin;
if (e.data == 'close') {
$(this).modal('hide'); //Example code, you can run what you want
}
};
Search:
function buttonClick() {
var curDomain = location.protocol + '//' + location.host; //This will be received as e.origin (see above)
var commandString = "close"; //This will be received as e.data
parent.postMessage(commandString,curDomain); //Sends message to parent frame
}
In this case you send the message 'close' to the parent frame. When parent receive the message he check if it's "close" and then run the code you want (in this case you close your modal with $(".modal").dialog('close')) | unknown | |
d16402 | val | I found a fix in this thread: JavaWeb java.lang.NoClassDefFoundError: sun/security/ssl/HelloExtension
"Had basically the same problem, eventually solved it with this solution here.
In your glassfish folder go to glassfish5/glassfish/modules/endorsed/ and open the grizzly-npn-bootstrap.jar file with winrar or your preferred unzipper.
Delete the sun folder and try running your program again."
I've been stuck with this for over a week and finally found this fix. Now using the post-function works! | unknown | |
d16403 | val | It seems as though py2app had some issues with the 32/64-bit install of python 2.7 I was using (the official one from python.org).
I downloaded a 32-bit only version of 2.7 and it works now.
On a related note, on another build I was using wxPython and to get it to work without the -A switch I had to import the package explicitly in my setup.py file.
DATA_FILES = []
OPTIONS = {'argv_emulation': True,
'packages' : ['wx', 'pubsub'],
}
A: I've read that you need to leave the 'argv_emulation': True setting out of the options for a 64bit build. Hope this helps. | unknown | |
d16404 | val | I did not find a solution.
We ended up in coercing the date into the desired text string in Excel itself (in a different cell, and ignoring the date cell when reading the sheet in Java). | unknown | |
d16405 | val | I solve my problem a bit, now the wav file is working correctly because I add the extension of wav file in the google colab file which created after the compilation of my files (Buildozer.spec) but the problem with jpg is still there and for mp3 also | unknown | |
d16406 | val | According to this, it is happening when the addition operator is being used on $num_words.
You could cast $num_words to an integer to avoid this warning.
$words_array = preg_split( "/[\n\r\t ]+/", $text, (int)$num_words + 1, PREG_SPLIT_NO_EMPTY );
I would suggest identifying why $num_words isn't an integer first though. | unknown | |
d16407 | val | First of all iText developers often have stressed that in onStartPage one MUST NOT add content to the PDF. The reason is that under certain circumstances unused pages are created and onStartPage is called for them but they then are dropped. If you add content to them in onStartPage, though, they are not dropped but remain in your document.
Thus, always use onEndPage to add any content to a page.
In your use case there is yet another reason for using onEndPage: Usually it only becomes clear that a given page is the last page when the last bit of content has been added to the document. This usually occurs after onStartPage has been called for the page but before onEndPage has.
Thus, after you've added the last bit of regular page content to the document, you can simply set a flag in the page event listener that the current page is the final document page. Now the following onEndPage call knows it processes the final page and can add content differently.
So the page event listener would look like this
class MyPageEventListener extends PdfPageEventHelper {
public boolean lastPage = false;
@Override
public void onEndPage(PdfWriter writer, Document output) {
if (!lastPage) {
[add extra content for page before the last one]
} else {
[add extra content for last page]
}
}
...
}
and be used like this
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, TARGET);
MyPageEventListener pageEventListener = new MyPageEventListener();
writer.setPageEvent(pageEventListener);
document.open();
[add all regular content to the document]
pageEventListener.lastPage = true;
document.close(); | unknown | |
d16408 | val | *
*Find all input using querySelectorAll.
*Loop over all input and addEventListener
*check if the elment is checked or not using e.target.checked, If it is checked change its parent e.target.parentElement background style.
I've used red, you can select color on your own.
const allInputs = document.querySelectorAll("input");
allInputs.forEach(input => {
input.addEventListener("click", e => {
if (e.target.checked) {
e.target.parentElement.style.background = "#ff0000";
} else {
e.target.parentElement.style.background = "#E8EBF0";
}
})
})
.checkbox-container {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: nowrap;
background: #E8EBF0;
border: 1px solid #E8EBF0;
transition: background .3s ease-in-out;
margin-bottom: 8px;
border-radius: 4px;
}
<div class="dimensional-container checkbox-container">
<input type="checkbox" name="snapchat" class="checkbox-container__snapchat" id="snapchat">
<label for="snapchat">snapchat</label>
</div>
<div class="dimensional-container checkbox-container">
<input type="checkbox" name="facebook" class="checkbox-container__facebook" id="facebook">
<label for="facebook">Facebook</label>
</div>
<div class="dimensional-container checkbox-container">
<input type="checkbox" name="hangouts" class="checkbox-container__hangouts" id="hangouts">
<label for="hangouts">hangouts</label>
</div> | unknown | |
d16409 | val | Add the below property before your select statement!
set hive.resultset.use.unique.column.names=false
Then hive doesn't printout the tablename as part of column names. | unknown | |
d16410 | val | Cloud Foundry applications on IBM Bluemix can use Bluemix's Object Storage service for shared storage between applications.
Cloud Foundry does not support sharing volumes across instances and discourages users from writing the the filesystem as storage.
Using Object Storage, you have an API to access and share files between applications. | unknown | |
d16411 | val | No, they are just different multipliers. The actual code is using a raw number of bytes under the hood. | unknown | |
d16412 | val | I just assumed your requirement from the website you provided,i think this is what you need
DEMO
.shadow-effect {
position:relative;
-webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
-moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
}
.shadow-effect:before, .shadow-effect:after {
content:"";
position:absolute;
z-index:-1;
-webkit-box-shadow:0 0 10px rgba(0,0,0,0.8);
-moz-box-shadow:0 0 10px rgba(0,0,0,0.8);
box-shadow:0 0 10px rgba(0,0,0,0.8);
top:20%;
bottom:0;
left:50px;
right:50px;
-moz-border-radius:100px / 10px;
border-radius:100px / 10px;
}
.box h3{
text-align:center;
position:relative;
top:80px;
}
.box {
width:70%;
height:100px;
background:#FFF;
margin:40px auto;
}
.effect6
{
position:relative;
-webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
-moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
}
.effect6:before, .effect6:after
{
content:"";
position:absolute;
z-index:-1;
-webkit-box-shadow:0 0 20px rgba(0,0,0,0.8);
-moz-box-shadow:0 0 20px rgba(0,0,0,0.8);
box-shadow:0 0 20px rgba(0,0,0,0.8);
top:50%;
bottom:0;
left:10px;
right:10px;
-moz-border-radius:100px / 10px;
border-radius:100px / 10px;
} | unknown | |
d16413 | val | My advice is reduce the problem down. Have only a single point, slow the interval down, step through to see what's happening. The mouse doesn't appear to be doing anything. Commenting out the line grid.ApplyDirectedForce(new Vector3(0, 0, 5000), new Vector3(mouseX, mouseY, 0), 50); doesn't change the output. It goes wrong in grid.Update(), for some reason grid.Update() does something even if there's no force applied, maybe that means the spring code has a bug. The bottom right point doesn't move frame one maybe that means something. The debugger is your friend. Add a breakpoint to grid.Update() and see what the code is actually doing. I know this isn't a direct answer but I hope this guides you in the right direction.
I also want to point out that usually the whole point of Magnitude Squared is so that you can compare vectors or distances without having to do a square root operation. That is, in your Magnitude function you do a Square root operation and then in your Magnitude Squared function you square it. This is is the same as simply going x^2 + y^2 + z^2
frame 1:
frame 2: | unknown | |
d16414 | val | My intent would be to receive some sound file and plot it on a graph
Neither library does this by default. The libraries are used to plot a graph given a set of data points. Getting the data points from the sound file is up to you.
So, for this purpose which library would be better.
Either library should be fine once you get the data points.
Also I wanna know, where I can see the complete implementation or definitions of these libraries i.e. the structure and code for the API's used in the above libraries.
Check out the sources for GraphView and AndroidPlot.
A: I have used Achartengine some times and it works great. I modified it without difficulties.
A: If You are drawing simple Line Graph using canvas to draw the graph.
A: Use AndroidPlot. This code draw the content of Vector(in this case filled of zeros). You only have to pass the info of the wav file to the vector. And you can check this thread for the reading issue.
Android: Reading wav file and displaying its values
plot = (XYPlot) findViewById(R.id.Grafica);
plot.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 0.5);
plot.setRangeStep(XYStepMode.INCREMENT_BY_VAL, 1);
plot.getGraphWidget().getGridBackgroundPaint().setColor(Color.rgb(255, 255, 255));
plot.getGraphWidget().getDomainGridLinePaint().setColor(Color.rgb(255, 255, 255));
plot.getGraphWidget().getRangeGridLinePaint().setColor(Color.rgb(255, 255, 255));
plot.getGraphWidget().setDomainLabelPaint(null);
plot.getGraphWidget().setRangeLabelPaint(null);
plot.getGraphWidget().setDomainOriginLabelPaint(null);
plot.getGraphWidget().setRangeOriginLabelPaint(null);
plot.setBorderStyle(BorderStyle.NONE, null, null);
plot.getLayoutManager().remove(plot.getLegendWidget());
plot.getLayoutManager().remove(plot.getDomainLabelWidget());
plot.getLayoutManager().remove(plot.getRangeLabelWidget());
plot.getLayoutManager().remove(plot.getTitleWidget());
//plot.getBackgroundPaint().setColor(Color.WHITE);
//plot.getGraphWidget().getBackgroundPaint().setColor(Color.WHITE);
plot.setRangeBoundaries(-25, 25, BoundaryMode.FIXED);// check that, these //boundaries wasn't for audio files
InicializarLasVariables();
for(int i=0; i<min/11;i++){
DatoY=0;
Vector.add(DatoY);
}
XYSeries series = new SimpleXYSeries(Vector, SimpleXYSeries.ArrayFormat.Y_VALS_ONLY,"");
LineAndPointFormatter seriesFormat = new LineAndPointFormatter(Color.rgb(0, 0, 0), 0x000000, 0x000000, null);
plot.clear();
plot.addSeries(series, seriesFormat); | unknown | |
d16415 | val | ICollection isn't anywhere near as useful now as it was with .NET 1.1 when there was no ICollection<T> offering greater type safety. There's very little one can usefully do with ICollection that one can't do with ICollection<T>, often with greater efficiency and/or type safety, especially if one writes generic methods for those cases where one might want to do something with collections of different element types.
This though begs the question of why the likes of List<T> did implement ICollection. But when List<T> was introduced with .NET 2.0 all legacy code was using ICollection and ArrayList, not ICollection<T> and List<T>. Upgrading code to use List<T> rather than ArrayList can be a pain, especially if it means having to either immediately change all uses of ICollection it would hit to use ICollection<T> or, even worse, double up because a method was being hit with the List<T> that was also being hit with other non-generic collections and so versions of the method would be needed for each. Implementing ICollection eased the upgrade path by allowing people to be more piecemeal in how they took advantage of generic collections.
When HashSet<T> came out generics had been in use for three years already, and there was not a previous non-generic hash-set type provided by the framework, so there was less of an upgrade pain, and hence less of a motivation for supporting ICollection. | unknown | |
d16416 | val | The following first asserts there is sufficient stock, if not, alert caller else update the stock. This assumes no other users are working with the same item.
Note the use of delegates and that the database does not match your database but the same will work for your code with adjustments.
public class DataOperations
{
private const string ConnectionString
= "Data Source=.\\sqlexpress;Initial Catalog=NorthWind2020;Integrated Security=True";
public delegate void OnProcessing(string text);
public static event OnProcessing Processed;
public static void UpdateProductStockCount(int id, int amount)
{
using (var cn = new SqlConnection(ConnectionString))
{
using (var cmd = new SqlCommand() { Connection = cn })
{
cmd.CommandText = "SELECT UnitsInStock FROM dbo.Products WHERE ProductID = @Id";
cmd.Parameters.Add("@Id", SqlDbType.Int).Value = id;
cn.Open();
var currentCount = (short)cmd.ExecuteScalar();
if (currentCount - amount <0)
{
Processed?.Invoke("Insufficient stock");
}
else
{
cmd.CommandText = "UPDATE dbo.Products SET UnitsInStock = @InStock WHERE ProductID = @Id";
cmd.Parameters.Add("@InStock", SqlDbType.Int).Value = currentCount - amount;
cmd.ExecuteNonQuery();
Processed?.Invoke("Processed");
}
}
}
}
}
Form code
public partial class StackoverflowForm : Form
{
public StackoverflowForm()
{
InitializeComponent();
DataOperations.Processed += DataOperationsOnProcessed;
}
private void DataOperationsOnProcessed(string text)
{
if (text == "Insufficient stock")
{
MessageBox.Show($"Sorry {text} ");
}
else
{
MessageBox.Show(text);
}
}
private void updateButton_Click(object sender, EventArgs e)
{
DataOperations.UpdateProductStockCount(21,1);
}
}
A: As @BagusTesa suggested, a simple if could do the trick:
private void updateQty()
{
try
{
int newqty = stock - Convert.ToInt32(txtnumberofunit.Text);
if (newqty >= 0) // proceed
{
con.Open();
SqlCommand cmd = new SqlCommand("Update medic Set quantity=@q where id=@Xkey ", con);
cmd.Parameters.AddWithValue("@q", newqty);
cmd.Parameters.AddWithValue("@Xkey", key);
cmd.ExecuteNonQuery();
MessageBox.Show("Medicine updated!!");
con.Close();
}
else // cancel purchase
{
MessageBox.Show("New quantity is below 0, purchase cancelled");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
} | unknown | |
d16417 | val | Well, I cannot think of a "one-step solution".
Your entities are inherently linked to a table. So, one solution could be to define a secondary entity class linked to your secondary table.
This secondary class could inherit from the first one to ensure compatibility, and you could provide a copy constructor that receives an instance of the parent and copies all attributes every time you want to move a record. Then you could delete the original record from the original table by deleting the original entity. | unknown | |
d16418 | val | running "sudo npm install live-server -g" worked for me | unknown | |
d16419 | val | To use late binding use the FileDialog() function from the Excel.Application Object. Excel.Application.FileDialog() Is a function that returns a FileDialog Object for an open Workbook. If you declare a variable as a specific object such as Office.FileDialog it will create the object of the version that is used in the VBA reference the code was written with and at runtime on a different pc will ignore other version references and look for the specific version that the variable was declared with.
You can use the reference to the active workbook but is not explicitly needed in Excel
Dim strategyFileDialog As Object
Set strategyFileDialog = ActiveWorkbook.Application.FileDialog(3)
'Filedialog Enumerations:
'msoFileDialogFilePicker = 3 File picker dialog box.
'msoFileDialogFolderPicker = 4 Folder picker dialog box.
'msoFileDialogOpen = 1 Open dialog box.
'msoFileDialogSaveAs = 2 Save As dialog box | unknown | |
d16420 | val | Try:
c = np.concatenate((b,a), axis=1)
This assumes that a.shape = (6,1). If a.shape = (6,) then you can do:
c = np.concatenate((b,a.reshape((6,1))), axis=1) | unknown | |
d16421 | val | The events are all fired in order. If your event handlers are asynchronous, which seems to be the case, then the code firing the events is going to continue executing as soon as it starts the event handlers, not when they complete.
If the code firing the events needs to not continue on until all of the handlers have finished, then you need to restructure this class such that the event handlers have some means of indicating to this class when they're done. There are any number of ways to do this, from passing a parameter in the event that allows handlers to tell it when they're done, or to having the signature of the event handlers return a Task rather than being void (you'll need to await those tasks when firing the event). | unknown | |
d16422 | val | It might be related to file permissions or something like that.
There is no need to use VPS. I manage my website on a shared server and I've tested WordPress on free hosting services too.
A: This is probably due to incorrect permissions either on the file structure or the mySQL DB user or something like that. Take a look at this article on the WP codex about file permissions.
Big services like Hostgater usually have an "auto-install" feature for common software like Wordpress (via Softaculous or something similar). I don't know how you migrated your site from your local version to the server but it may be worth installing a fresh Wordpress instance through Hostgator and then simply loading in the wp-content folder and your development database on top of that. | unknown | |
d16423 | val | The best explanation is that the http://en.wikipedia.org/wiki/RGB_color_model is somewhat unintuitive for us humans.
And following is pretty well worked.
NewColor.R = Color1.R - (Color1.R - Color2.R)/2
NewColor.G = Color1.G - (Color1.G - Color2.G)/2
NewColor.B = Color1.B - (Color1.B - Color2.B)/2
https://github.com/benjholla/ColorMixer also will help you. | unknown | |
d16424 | val | Something like:
dta_transformed <- dta[,.(rn = .I, phase = unlist(phase)), by = setdiff(names(dta), 'phase')][
, shifted_max := shift(max_val), by = phase][
shifted_max < end_val, `:=` (cor_start = shifted_max, cor_end = end_val), by = phase][
shifted_max > end_val, `:=` (cor_start = end_val, cor_end = end_val), by = phase][
is.na(cor_start), `:=` (cor_start = start_val, cor_end = max_val), by = phase][
, phase := paste(phase, collapse = ","), by = rn][!duplicated(rn),][
, c("rn", "shifted_max") := NULL]
However, the output I get is:
criteria phase start_val end_val max_val cor_start cor_end
1: A block3 12 15 13.0 12.0 13
2: A block1,block2 1 11 8.0 1.0 8
3: B block2 7 11 9.5 8.0 11
4: A block2 7 11 11.0 9.5 11
5: A block3 12 15 15.0 13.0 15
6: B block1 1 6 6.0 6.0 6
Could it be that in row number 3 the cor_end should be 11 in your desired output? As the previous matching row (2) has lower max_val, therefore the current end_val (11) should be taken?
Also the tidyverse approach, slightly more readable:
library(tidyverse)
dta %>% mutate(rn = row_number()) %>%
unnest(phase) %>%
group_by(phase) %>%
mutate(
cor_start = case_when(
lag(max_val) < end_val ~ lag(max_val),
lag(max_val) > end_val ~ end_val,
TRUE ~ start_val
),
cor_end = if_else(!is.na(lag(max_val)), end_val, max_val)
) %>% group_by(rn) %>%
mutate(
phase = paste(phase, collapse = ",")
) %>% ungroup() %>% select(-rn) %>% distinct()
A: Here is a different approach which uses pmin() instead of ifelse() and utilises the fill parameter of the shift() function. Furthermore, it reduces the number of grouping operations:
library(data.table)
dta[, rn := .I]
dta[dta[, .(phase2 = unlist(phase)), by = rn], on = "rn"][
, `:=`(cor_start = pmin(shift(max_val, fill = start_val[1]), end_val),
cor_end = max_val), by = phase2][
, .SD[1], by = rn][
, c("rn", "phase2") := NULL][]
criteria phase start_val end_val max_val cor_start cor_end
1: A block3 12 15 13.0 12.0 13.0
2: A block1,block2 1 11 8.0 1.0 8.0
3: B block2 7 11 9.5 8.0 9.5
4: A block2 7 11 11.0 9.5 11.0
5: A block3 12 15 15.0 13.0 15.0
6: B block1 1 6 6.0 6.0 6.0 | unknown | |
d16425 | val | To avoid this problem you must use RecyclerView. There are a lot of tutorials on youtube on how to implement it. | unknown | |
d16426 | val | /files/sample.pdf
You can always use
href="{{asset('files/sample.pdf')}}"
It will be easier
A: You should apply url function instead of paste the directory directly.
<a href="{{url('/files/sample.pdf'}}">Download</a>
A: If you're really looking for a download response when clicking the link, you should have the URL link to a controller method.
<a href="{{ url('route/to/method') }}">
Now in the controller method
return response()->download(public_path('files/sample.pdf'));
Laravel responses | unknown | |
d16427 | val | $("span.runId").each(function(){
var runId = $(this).text(),
processname = $(this).next("span.processName").text();
});
A: Functional programming to the rescue:
var data = $td.children('span.runId').map(function() {
return {runId: $(this).text(), processName: $(this).next().text()};
}).get();
Structure the data how ever you want to.
A: To be honest, I would suggest that if they have that type of correlation that they are wrapped together in another tag, or better yet combined as they are not even displayed. This, of course, does not apply to parsing code you do not have write/modify access to.
Suggested html:
<table>
<tr>
<td style="display:none;">
<span data-runid='4' class="processName">Get End-Of-Day Reuters Feed Rates</span>
<span data-runid='130' class="processName">Get End-Of-Day Bloomberg Feed Rates</span>
<span data-runid='133' class="processName">CapVolsCalibration AllCurrencies EOD</span>
<span data-runid='228' class="processName">GBP Basis Adjustment</span>
</td>
</tr>
</table>
jQuery:
$("td span.processName").each(function() {
var runid, processName, $this = $(this);
runid = $this.data('runid');
processName = $this.text();
});
I'm not exactly sure what your needs are, but I'd even get rid of the class processName as well. Since the data isn't displayed, it's not really needed at this level assuming you don't need to access this for other purposes. This minimizes down to:
html:
<table id='someId'>
<tr>
<td style="display:none;">
<span data-runid='4'>Get End-Of-Day Reuters Feed Rates</span>
<span data-runid='130'>Get End-Of-Day Bloomberg Feed Rates</span>
<span data-runid='133'>CapVolsCalibration AllCurrencies EOD</span>
<span data-runid='228'>GBP Basis Adjustment</span>
</td>
</tr>
</table>
jQuery:
$("#someId").find('td span').each(function() {
var runid, processName, $this = $(this);
runId = $this.data('runid');
processName = $this.text();
});
Technically, you can't have a span outside of a td in a table, so it could be reduced further:
$("#someId").find('span').each(function() {
var runid, processName, $this = $(this);
runId = $this.data('runid');
processName = $this.text();
});
A: So many ways to do things with jQuery:
$('td > span:nth-child(2n-1)').text(function(i,txt) {
alert(txt + $(this).next().text());
});
Example: http://jsfiddle.net/vqs38/ | unknown | |
d16428 | val | I made a Plunker with your example and it does fill the space.
https://plnkr.co/edit/QMiHzA89NZrDkpsrCefF
HTML
<header>
<div class="site-header">
<%= link_to full_title(yield(:title)), root_path, class: "logo" %>
<nav>
<% if user_signed_in? %>
<%= link_to "Sell", new_item_path %>
<%= link_to "FAQ", pages_faq_path %>
<%= link_to "Settings", edit_user_registration_path %>
<%= link_to "Log out", destroy_user_session_path %>
<% end %>
</nav>
<div class="log-in">
<% if !user_signed_in? %>
<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
<div class="form">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true, class: 'peach' %>
</div>
<div class="form">
<%= f.label :password %><br />
<%= f.password_field :password, autocomplete: "off", class: 'peach' %>
<%= f.submit "LOG IN", class: 'button-functional' %><br>
<%= render "devise/shared/forgotpass" %>
</div>
<% end %>
<% end %>
</div>
</div>
</header>
CSS
header {
background-color: white;
top: 0;
left: 0;
right: 0;
z-index: 0;
border-bottom: 1px dashed black;
.site-header {
margin: 0 2em;
padding: 1em 0;
height: auto;
nav {
float: right;
a {
margin-right: 2em;
}
a:last-child {
margin-right: 0;
}
}
.log-in {
float: right;
.form {
float: left;
}
input {
margin-right: 1em;
}
}
}
}
Maybe you have some other CSS messing around. | unknown | |
d16429 | val | Try this:
Enrollments: Student ID, Course No
Score: Assignment No, Student ID, Course No.
Note: Some designers frown on composite primary keys. Not me. | unknown | |
d16430 | val | Your current query is very close, you are missing a few columns in your GROUP BY clause. I'd also suggest a shorter way to get the date without time.
SELECT
Name,
AVG(cast(Availability as decimal(10, 2))),
CAST([Date] as date) AS Expr1,
ItemID
FROM dbo.ServiceAvailability
GROUP BY Name, CAST([Date] as date), ItemID
See Demo. Since you are using SQL Server 2014, you can just cast your datetime column as a date - which drops the time portion. I'd also suggest casting your Availability column to something other than an int so you get a decimal.
Since you are using an aggregate function any columns in the SELECT list that aren't being aggregated need to be included in the GROUP BY clause, so you need to include Name and ItemID. | unknown | |
d16431 | val | For some options, setterm works by sending a sequence of characters to stdout. Normally, when you are on the console these are therefore read by the console driver and interpreted. Other options do ioctls on stdin similarly.
If you use these commands from cron or a systemd unit, you would need to redirect the output or input to/from the console. For example, from cron, as root, try
setterm -term linux -blank 0 >/dev/console
Or for something using ioctl, set the stdin
setterm -term linux -powersave on </dev/console
If you use the bash shell in cron you can say <>/dev/console to open for in and out. | unknown | |
d16432 | val | I have the answer to my own question. I am not sure if this is the "jinja" way of doing things.
{% set ldsk = [] %}
{% for disk in ldisks %}
{{ ldsk.append( "\"|a"+ disk +"[145]|\"") }}
{% endfor %}
filter = [ {{ ldsk | join(", ") }}, "a|/dev/mapper/3500.*part1|", "r|.*|" ] | unknown | |
d16433 | val | Even better - when the user uploads the file, include the user_ID for the file. Then, when you try to retrieve the file, make sure it belongs to the user.
So therefore even if they guess another file - it wont matter!
You need to use readfile:
function user_files($file_name = "")
{
// Check user is logged in
if ($user->logged_in())
{
// Check file_name is valid and only contains valid chars
if ((preg_match('^[A-Za-z0-9]{1,32}+[.]{1}[A-Za-z]{3,4}$^', $file_name))
{
// Now check file belongs to user - PSUEDOCODE
if ($filename == $user->records)
{
header('Content-Type: '.get_mime_by_extension(YOUR_PATH.$file_name)));
readfile(YOUR_PATH.$file_name);
} else {
echo 'You do not have access to this file';
}
}
}
}
There is some issues around directory traversal etc - so you'll need to check the $file_name first like I have using the preg_match | unknown | |
d16434 | val | I ran a test and here is what I found:
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`age` int(11) NOT NULL,
`email` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
From the console:
INSERT INTO `test` () VALUES ();
// Result:
1 row(s) affected, 2 warning(s):
1364 Field 'name' doesn't have a default value
1364 Field 'email' doesn't have a default value
Then a select:
mysql> select * from test;
+----+------+-------+
| id | name | email |
+----+------+-------+
| 1 | 0 | |
+----+------+-------+
1 row in set (0.00 sec)
Another insert test:
mysql> INSERT INTO `test` () VALUES(NULL, NULL, NULL);
ERROR 1048 (23000): Column 'name' cannot be null
So it appears that if you bind no parameters and set no values, for some reason MySQL does not treal the missing values as NULL. It's interesting that the data still gets inserted even though no default values were set (so the defaults become specific to the column type).
Some PHP code to further illustrate the point:
$pdo = new PDO('mysql:host=10.1.1.37;dbname=testing', 'user', 'pw');
$query = $pdo->prepare("INSERT INTO `test` () VALUES ()");
$result = $query->execute();
var_dump("Result: ", $result);
var_dump("Affected: ", $query->rowCount());
var_dump("Warnings: ", $query->errorInfo());
/*
string(8) "Result: "
bool(true)
string(10) "Affected: "
int(1)
string(10) "Warnings: "
array(3) {
[0]=>
string(5) "00000"
[1]=>
NULL
[2]=>
NULL
}
*/
So, the reason you are getting a successful result from execute() is because I would guess the data is getting inserted into your table. Are you sure you weren't seeing anything in there? Hope that helps clear things up. | unknown | |
d16435 | val | One of my first projects was similar to this. I believe your asking for help in getting the text file lines as an array.
To open the file for reading:
file = open("/path/to/file", "r")
I would then split on spaces so:
for line in file:
print line.split(' ')
this would give you an array of words from each line in the txt file.
Then use the csv module in python to input into a csv file.
References:
*
*Python the Hard Way - Opening and Closting Files
*split() function
*CSV Module | unknown | |
d16436 | val | This may help.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class DenyRegularUser : AuthorizeAttribute
{
public DenyRegularUser() :
base()
{
}
protected override bool IsAuthorized (System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (AuthorizeRequest(actionContext))
{
return true;
}
return false;
}
protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
//Code to handle unauthorized request
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.TemporaryRedirect);
actionContext.Response.Headers.Add("Location", "~/Index/Subscribe");
}
private bool AuthorizeRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
//Write your code here to perform authorization
}
}
I believe the IsAuthorized method is the correct way to override the AuthorizeAttribute. | unknown | |
d16437 | val | Your session object is a dict, not a list of tuple. Try this code in template:
Nom : {{request.session.nom}}
Prix : {{request.session.prix}}
But, you have already set the vars in context, so you can do:
Nom : {{nom}}
Prix : {{prix}}
# And your views.py
def cart_add(request, code):
dico={'produits':[{'code':'2BG12','nom':'banane sucré','prix':1500},
{'code':'MLO23','nom':'pomme de terre','prix':1800}]}
mes_produits=dico['produits']
selected_product = next((item for item in mes_produits if item["code"] == code), None)
if selected_product != None:
context={
'nom':selected_product.get('nom'),
'prix':selected_product.get('prix')
}
else:
context = {}
return render(request, 'cart/cart_detail.html',context)
Maybe you do not understand session usage?
https://docs.djangoproject.com/en/4.1/topics/http/sessions/ | unknown | |
d16438 | val | The following code should help you.
const formattedData = Object.values(this.currenciesList).map(({ name, symbol }) => ({ name, symbol }))
console.log(formattedData)
A: Here is one approach:
const data = {
"USD": {
"symbol": "$",
"name": "US Dollar",
"symbol_native": "$",
"decimal_digits": 2,
"rounding": 0,
"code": "USD",
"name_plural": "US dollars"
},
"CAD": {
"symbol": "CA$",
"name": "Canadian Dollar",
"symbol_native": "$",
"decimal_digits": 2,
"rounding": 0,
"code": "CAD",
"name_plural": "Canadian dollars"
},
}
const result = Object.values(data).map(({
name,
symbol
}) => ({
name,
symbol
}))
console.log(result)
A: loadCurrencies() {
this.http.get('assets/data/currencies.json').subscribe((response) => {
this.currenciesList = Object.values(response).map(obj =>
return {
name: obj.name,
symbol: obj.symbol
});
console.log(this.currenciesList);
});
} | unknown | |
d16439 | val | My team uses a monorepo with different cdk-pipelines for each product/service that we offer. It does trigger each pipeline when we push to the develop branch, but if there are no changes in 'ProductService' or 'OrderService' then technically I don't think there's no harm letting it update all of them.
But if you do want separate triggers, you would have to use separate branches that trigger each microservice. You are allowed to specify a branch for 'GitHubSourceActionProps.Branch'. For example, the pipeline construct for 'UserService' could look like this: (C#)
var pipeline = new Amazon.CDK.Pipelines.CdkPipeline(this, "My-Cdk-Pipeline", new CdkPipelineProps()
{
SourceAction = new GitHubSourceAction(new GitHubSourceActionProps()
{
ActionName = "GitHubSourceAction",
Branch = user-service,
Repo = "my-cool-repo",
Trigger = GitHubTrigger.WEBHOOK,
}),
};
aws cdk api reference githubsourceactionprops | unknown | |
d16440 | val | I tried your yaml and it works for me with following yaml.
Entrypoint.yaml:
parameters:
- name: RunChangeLogic
displayName: Run change logic
type: boolean
default: false
steps:
- script: echo ${{ parameters.RunChangeLogic }}
Azure_pipeline.yaml:
trigger: none
pool:
vmImage: 'ubuntu-latest'
extends:
template: "YamlTemplates/Stage/Entrypoint.yaml"
parameters:
RunChangeLogic: 'true'
For more info please refer the official Doc Template types & usage.
Edit:
From your comment, I understand that you have a multi stage azure pipeline. Please refer to this stages.template definition.
You can define a set of stages in one file and use it multiple times in other files.
Here is my test yaml files for stages template.
Entrypoint.yaml:
parameters:
- name: RunChangeLogic
displayName: Run change logic
type: boolean
default: false
stages:
- stage: Teststage1
jobs:
- job: ${{ parameters.RunChangeLogic }}_testjob1
steps:
- script: echo ${{ parameters.RunChangeLogic }}
- stage: Teststage2
jobs:
- job: ${{ parameters.RunChangeLogic }}_testjob2
steps:
- script: echo ${{ parameters.RunChangeLogic }}
Azure_pipeline.yaml:
trigger: none
pool:
vmImage: 'ubuntu-latest'
stages:
- template: "YamlTemplates/Stage/Entrypoint.yaml"
parameters:
RunChangeLogic: 'true' | unknown | |
d16441 | val | You must leave the stack and non-volatile registers as you found them. The calling function has no clue what you might have done with them otherwise - the calling function will simply continue to its next instruction after ret. Only ret after you're done cleaning up.
ret will always look to the top of the stack for its return address and will pop it into EIP. If the ret is a "far" return then it will also pop the code segment into the CS register (which would also have been pushed by call for a "far" call). Since these are the first things pushed by call, they must be the last things popped by ret. Otherwise you'll end up reting somewhere undefined.
A: The CPU has no idea what is function/etc... The ret instruction will fetch value from memory pointed to by esp a jump there. For example you can do things like (to illustrate the CPU is not interested into how you structurally organize your source code):
; slow alternative to "jmp continue_there_address"
push continue_there_address
ret
continue_there_address:
...
Also you don't need to restore the registers from stack, (not even restore them to the original registers), as long as esp points to the return address when ret is executed, it will be used:
call SomeFunction
...
SomeFunction:
push eax
push ebx
push ecx
add esp,8 ; forget about last 2 push
pop ecx ; ecx = original eax
ret ; returns back after call
If your function should be interoperable from other parts of code, you may still want to store/restore the registers as required by the calling convention of the platform you are programming for, so from the caller point of view you will not modify some register value which should be preserved, etc... but none of that bothers CPU and executing instruction ret, the CPU just loads value from stack ([esp]), and jumps there.
Also when the return address is stored to stack, it does not differ from other values pushed to stack in any way, all of them are just values written in memory, so the ret has no chance to somehow find "return address" in stack and skip "values", for CPU the values in memory look the same, each 32 bit value is that, 32 bit value. Whether it was stored by call, push, mov, or something else, doesn't matter, that information (origin of value) is not stored, only value.
If that's the case, can't we just use push and pop instead of call and ret?
You can certainly push preferred return address into stack (my first example). But you can't do pop eip, there's no such instruction. Actually that's what ret does, so pop eip is effectively the same thing, but no x86 assembly programmer use such mnemonics, and the opcode differs from other pop instructions. You can of course pop the return address into different register, like eax, and then do jmp eax, to have slow ret alternative (modifying also eax).
That said, the complex modern x86 CPUs do keep some track of call/ret pairings (to predict where the next ret will return, so it can prefetch the code ahead quickly), so if you will use one of those alternative non-standard ways, at some point the CPU will realize it's prediction system for return address is off the real state, and it will have to drop all those caches/preloads and re-fetch everything from real eip value, so you may pay performance penalty for confusing it.
A: In the example code, if the return was done before pop %ebp, it would attempt to return to the "address" that was in ebp at the start of the function, which would be the wrong address to return to. | unknown | |
d16442 | val | The type guard will affect the quality field, not the product variable. Type-guards only impact the field that owns the discriminating field; it does not affect the owner.
So this works:
type Product = GoodProduct | BadProduct;
let product!: Product;
if (product.quality.type == GoodBad.Good) {
let goodQuality: GoodQuality = product.quality; // Ok
let badQuality: BadQuality = product.quality; // Err
let goodProduct: GoodProduct = product; // Err, product not affected
let badProduct: BadProduct = product; // Err, product not affected
}
Your solution of adding an extra field is a good one, another would be to create a custom type guard:
function isGoodProduct(p: Product) : p is GoodProduct {
return p.quality.type === GoodBad.Good
}
if (isGoodProduct(product)) {
let goodProduct: GoodProduct = product; // OK
let badProduct: BadProduct = product; // Err
} | unknown | |
d16443 | val | You normally use FormEditor rather than MultiPageEditorPart when using FormPage (FormEditor extends MultiPageEditorPart).
FormEditor has an addPage that accepts a FormPage. | unknown | |
d16444 | val | Type must be 'string', 'number', 'boolean', 'json' or 'ref' like error say.
So u need set type to 'ref' (object or array), and u can use custom function for validate.
inputs: {
fields: {
type: 'ref',
custom: function (data) {
// some logic
// example
if (typeof data.body !== "string") {
return false;
// or u can use trow Error('Body is not a string')
}
return true;
},
required: true,
description: 'All keys are not required, but at least one is'
}
Now input is type object and in custom function return false or trow Error('Some problem') break validation.
If u use schema type, just remove ? from your example:
inputs: {
fields: {
type: {
body: 'string',
rruleSetStr: 'string'
},
required: true,
description: 'All keys are not required, but at least one is'
}
This is Runtime (recursive) type-checking for JavaScript., please check documentation for writing rules. | unknown | |
d16445 | val | SFTP has nothing to do with FTP, except inasmuch as both are for transferring files. Firefox out of the box doesn't speak SFTP, last i heard.
In order to download something via SFTP, you'll need an SFTP client, like WinSCP. or PSFTP (part of PuTTY). Both are free. Or, apparently, there's a FF addon called FireFTP. | unknown | |
d16446 | val | Assuming that you are working with DataTables, here is what you can do:
private async void btnSearch_Click(object sender, EventArgs e) // async is important
{
DataTable dt = await Task.Run(() => // await is important (avoids the UI freeze)
{
return GetData(); // Fetch your data from DB
});
// Fill your listbox with the data in dt
} | unknown | |
d16447 | val | Ok. Let me explain how this work.
First things first. Your CSS has a bug.
top:-50;
This wont do anything. It has to be something like
top:-50px;
But my question is why do you want negative margins? it will only hide you image by 50 pixels on the top side.
Ok, now coming to the real issue. You say you have no problems when your Image is 150X150 pixels. Thats because the parent <div> is 150x150. But if you have a different image size like 300x200 you have a problem.
This happens because in your CSS you have only mentioned width: 100% for the image.From here on its plain math.
The width=300 & height =200
Since you have mentioned width:100% the image automatically gets adjusted to the new width
300(original width)/150(new width)=2
So taking the same factor of 2
200(original height)/2=100(new height)
Hence you rendered image will have height of 100px.
if you want the rendered image to have same height of div just add this line to img CSS
height: 100%;
Working fiddle
A: from the code you have pasted, it's working properly. Are you able to link to the site where this is live and not working? Cache issue?
See jsfiddle: http://jsfiddle.net/FNQZn/
.feature-image {
width:150px;
height:150px;
display:block;
position:relative;
overflow:hidden;
}
.feature-image img {
position:absolute;
top:-50;
left:0;
width:100%;
} | unknown | |
d16448 | val | Hiding functionality in methods is good practice, Code Complete explains quite well, why that's the case.
If you ever want to change the filterInt, e.g. add upper and lower bounds, you are way better off if you have encapsulated it.
*
*less code lines to be changed
*easier to test against
*..
A: For only one method like your example, it does not make much sense.
It start to make sense if you use it to group all your filter function here, you could have Filter::filterDeliveryAdress and then, anytime you have to filter something you might remember that you already have a function for this. So if you filter function is for exsample not accurate enough, you can fix it in the class to get it fixed in all your code.
Of course here a static function would be better, it's even easier to use.
If, as I think, it's only for grouping related function and your using PHP >= 5.3, namespace would be more appropriate. | unknown | |
d16449 | val | It is possible to do such an assertion. But you'll need to write your custom ResultMatcher for that. I don't think it is a good idea to convert XML (nodes) to Java objects just to do a simple comparison in a unit test.
You may run into problems with XML namespace resolution or the Java hashCode equals contract if not implemented right.
Instead, you should use libraries that lets you focus on your unit tests and not on the details of a technology or a programming language.
I recommend you to use XMLUnit in your test. XMLUnit is a Java library for XML comparison.
The example below depicts how easy it is to compare a XML document with XMLUnit and a custom ResultMatcher.
import org.hamcrest.Matcher;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xmlunit.builder.Input;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
@RunWith(SpringRunner.class)
@WebMvcTest(XmlUnitDemoTests.XmlUnitDemo.class)
public class XmlUnitDemoTests {
static final String XML_CONTENT = "<node1><node2 id=\"1\">text</node2></node1>";
@Autowired
MockMvc mockMvc;
@Test
public void xmlUnit() throws Exception {
mockMvc.perform(get("/xml"))
.andExpect(xml(XML_CONTENT));
}
static ResultMatcher xml(String bodyValue) {
return MockMvcResultMatchers.content().source(equalXml(bodyValue));
}
static Matcher equalXml(String value) {
return isSimilarTo(Input.fromString(value).build());
}
@SpringBootApplication
@RestController
static class XmlUnitDemo {
@RequestMapping(value = "xml", produces = "text/xml")
String xml() {
return XML_CONTENT;
}
}
}
Of course, you may load big XML files from classpath or select a node with XPatch before doing a comparison. Take a look at the XMLUnit documentation for more information on that. | unknown | |
d16450 | val | Marking it here as an answer, since the comment worked. The color css attribute controls font-colors, including those for glyphicons. So the fix is to change the corresponding table elements and glyphicons to use color: #000 or color: black.
Adding !important simply ensures no other CSS files change the color (unless they use !important too and have priority, through either more specific selectors, or the same selectors but appearing after this rule - which was apparently not the case here).
.calendar-table, .glyphicon-calendar {color: #000 !important;} | unknown | |
d16451 | val | On server side please add this code ,
print_r($_FILES);
then check for array parameter 'error' then check error code from here
http://php.net/manual/en/features.file-upload.errors.php
if you want the file upload code for android then please tell me i can post here
i hope this will help you.
Thank you.
A: move_uploaded_file($_FILES['image']['temp'],$name); replace this line with
move_uploaded_file($_FILES['image']['tmp_name'],$name);
The file's temporary file name is in "tmp_name", as i can see from your log output. | unknown | |
d16452 | val | Copy system.serviceModel section from the app.config in your library project and put it in your web.config and refresh service reference. See also this answer. Could not find default endpoint element
A: Add "WSHttpBinding" end point in your WCF service web.config file like below
<endpoint address="web" behaviorConfiguration="jsonBehavior" binding="webHttpBinding" bindingConfiguration="webHttpBindingWithJsonP" contract="DataService.IDataService"/>
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsHttpBinding" contract="DataService.IDataService" />
and in your app.config file write code like below
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IDataService" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
<security mode="None" />
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost/pricedataservice/DataService.svc" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IDataService" contract="DataService.IDataService"
name="WSHttpBinding_IDataService" />
</client>
I am sure this will fix your problem and below blog will help you to understand different type of binding in WCF service
http://www.dotnet-tricks.com/Tutorial/wcf/VE8a200713-Understanding-various-types-of-WCF-bindings.html
A: Add client definition in your client web.config file like below;
<system.serviceModel>
/////
<client>
<endpoint address="referencedurl"
binding="webHttpBinding" bindingConfiguration=""
contract="MemberService.IMemberService"
name="MemberServiceEndPoint"
behaviorConfiguration="Web">
</endpoint>
</client>
////
</system.serviceModel>
AND Service Reference Name must same as the Interfaces prefix. contract="ReferenceName.IMemberService" | unknown | |
d16453 | val | I assume your code looks like
interface TestRepository extends JpaRepository<Test, Long>
So TestRepository is an interface and interfaces can extend other interfaces not implement interfaces.
The TestRepository will be implemented from Spring Data JPA during runtime based on the SimpleJpaRepository
https://github.com/spring-projects/spring-data-jpa/blob/master/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java
A: In Java
*
*Class extends Class
class Test Extends Thread
*interface Extend interface
public interface TestI extends Runtime
*class implements interface
public class Test implements Runnable | unknown | |
d16454 | val | Very recent kernels (5.1 and later - not yet released at the time of writing - see commit b303c6df80c9 ("kbuild: compute false-positive -Wmaybe-uninitialized cases in Kconfig")) have a separate config option CONFIG_CC_DISABLE_WARN_MAYBE_UNINITIALIZED to disable the warning. Those kernels define the option by default for GCC version 4.7 (which introduced the warning) and GCC version 4.8, but the option can be configured manually.
For your kernel and compiler version, it should be safe to modify the Makefile to add $(call cc-disable-warning,maybe-uninitialized,) globally. Alternatively, you could consider using GCC 4.9 or later. | unknown | |
d16455 | val | Try this out:
=ARRAYFORMULA(IF(ISNA(E:E),,SCAN(,E:E,LAMBDA(a,c,a+NOT(ISNA(c))))))
Update
=ARRAYFORMULA(IFNA(IF(D:D="",,SCAN(,D:D,LAMBDA(a,c,a+(IFNA(c)<>""))))))
A: You may try:
=index(if(H:H="",,scan(,H:H,lambda(a,c,if(c="",a,a+1))))) | unknown | |
d16456 | val | I have same need just like you.The way I deal with it is that I delete the module directly.In my program I delete the NLP and NL module and it works normally. | unknown | |
d16457 | val | The problem with your code was that you were checking to see if the dragging div had child divs rather than the drop div. The check should be in the allowDrop which will set ev.preventDefault() if it will accept drops. There are much better examples out there for drag and drops but here is an example based on your scenario:
HTML
<div id="drop1" class="dropDiv" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
<div id="drop2" class="dropDiv" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
<div id="draggable1" draggable="true" class="dragDiv" ondragstart="drag(event)">
Drag me #1
</div>
<div id="draggable2" draggable="true" class="dragDiv" ondragstart="drag(event)">
Drag me #2
</div>
JS
function drop(ev) {
var id = ev.dataTransfer.getData("text");
$('#' + id).appendTo(ev.target);
}
function allowDrop(ev) {
// Only check the parent div with id starting with drop and not the child div
if(ev.target.id.indexOf('drop') == 0) {
var count = $('#' + ev.target.id + ' > div').length;
if(count < 1) {
//allow the drop
ev.preventDefault();
}
else
{
// NOPE
}
}
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
https://jsfiddle.net/astynax777/dq3emchj/23/ | unknown | |
d16458 | val | Objects in Java are polymorphic: You can simply declare an array of a common base type and have objects of all kinds of derived classes in it.
To go with Radiodef's example, this is valid code:
Number[] foo = {new Integer(0), new Double(1), new Long(2), ...};
What Java does not have is a mechanism that defines an array restricted to one particular derived type of some known base class, where the particular derived type is only known at runtime.
So, if you mean public void foo(int someOtherStuff, <? extends T>... optionalArray) to check whether the objects in optionalArray are all of the same derived type, then the answer is that this can not be done automatically. You can however use
public void foo(int someOtherStuff, T... optionalArray)
to get the guarantee that all objects in the array are derived of the same class T. They may be of different derived types, though.
A: By the way.. I found the answer to the initial question, maybe somebody needs it one day:
public class MyClass<T> {
public <R extends T> void foo(int someOtherStuff, R... optionalArray){
//some code
}
}
Found it by mistake by looking at the implementation of Arrays.asList(T[] a). In knew I've seen that syntax somewhere just didn't remember where.
A:
You're completely right Radiodef and Felix
Thanks a lot for your detailed explaination!
I just thought I have to declare it like that because something didn't work and I thought that was the problem. But something different was really the problem. Just want to mention it quickly:
I have following generic class:
public class MyClass<T> {
public void foo1(List<Object> someList){ //wrong
//some code
}
public void foo1(Object... someArray){
//some code
}
public void foo2(List<? extends T> someList){
foo1(someList);
//some code
}
}
I wanted that foo2 would invoke foo1(List<Object> someList) but instead it invoked foo1(Object... someArray) even though T will always extend Object (or not?)
However, to make that work, foo1(List<Object> someList) needs to be declared like this:
public void foo1(List<? extends Object> someList){ //correct
//some code
}
then foo2 will invoke this rather than foo1(Object... someArray). | unknown | |
d16459 | val | You should store the output from cat into ID instead of using >>. The way you are doing that you always add to a file named '0'. To store the output of cat use:
ID=$( cat 'usernum.txt' )
I have also removed the 'pwd' as you do not need it and also it gets escaped by the single quotes.
EDIT: here is a complete working example. Note that if there is no usernum.txt file this will print some errors(cat and rm fail) but still will work(i.e. will print 1 in the file). You should perform a check to see if the file exists to avoid these errors:
ID=$( cat 'usernum.txt' )
count1=1
IDB=$(($ID+$count1))
rm "usernum.txt"
touch "usernum.txt"
echo $IDB >> usernum.txt | unknown | |
d16460 | val | @Echo off&SetLocal EnableExtensions EnableDelayedExpansion
CD /D "X:\path\to\pdfs"
For %%A in (*.pdf) Do (
Set "Filename=%%~nA"
If !FileName:~5,1! lss 5 (
Set Folder=!FileName:~0,5!0000
) Else (
Set Folder=!FileName:~0,5!5000
)
If not Exist "%Folder%" MkDir "%Folder%"
Move %%A "%Folder%"
)
Edit substring position is zero based, had to change offset.
A: Similar to LotPings answer:
@Echo Off
Set "SrcDir=C:\Users\AName\Documents"
Set "DstDir=C:\Users\AName\Documents\PDFs"
If Not Exist "%SrcDir%\*.pdf" Exit/B
For %%A In ("%SrcDir%\*.pdf") Do (Set "FName=%%~nA"
SetLocal EnableDelayedExpansion
If !FName:~-4! Lss 5000 (Set DstNum=0000) Else Set "DstNum=5000"
If Not Exist "%DstDir%\!FName:~,-4!!DstNum!\" (
MD "%DstDir%\!FName:~,-4!!DstNum!")
Move "%%~A" "%DstDir%\!FName:~,-4!!DstNum!"
EndLocal)
A: I'm going to try and give this a crack, though I do not generally work with batch, but I can at least get you going...
for %%f in (*.pdf) do {
set TEMP = %f:5%
if exists <your path>/%TEMP% <do nothing>
if not exists <your path>/%TEMP% mkdir <your path>/%TEMP%
<move file to this new directory
}
This isn't entirely working/correct, but it should give you a good idea of what to do. | unknown | |
d16461 | val | This will work for you
document.getElementsByName('my_field')[0].value
A: You may try this:
document.getElementsByName('my_field')[0].value
A: You can also do
document.getElementsByName("my_field")[0].type = "text"
Which will make the password field cleartext.
But the shortest way is to this is: Right click to the password field, click Inspect Element, find the type="password" and make it type="text"
Last one requires minimum time and typing, but the rest works too | unknown | |
d16462 | val | You probably forgot to click the "mines" button. Don't forget the .click() at the end of your code, like this:
driver.find_element_by_xpath('/html/body/div[1]/main/div[1]/div[4]/div[2]/div[1]/div/div/div[4]/div[1]/div/div[3]/div/a').click()
And you also might want to give the site some time to load by importing time and using time.sleep(x) which sleeps the code for x seconds.
import time
time.sleep(2) # Use this between the .click() lines to give the site time to load after clicking a button | unknown | |
d16463 | val | In Javascript:
*
*Floor Round a number downward to its nearest integer.
*Ceil Round a number upward to its nearest integer.
*Round Round a number to the nearest integer.
function ceil() {
var d = Math.ceil(5.1);
var x = d + "<br>";
document.getElementById("ceil").innerHTML = x;
}
function floor() {
var d = Math.floor(5.1);
var x = d + "<br>";
document.getElementById("floor").innerHTML = x;
}
function round() {
var d = Math.round(5.1);
var x = d + "<br>";
document.getElementById("round").innerHTML = x;
}
<!DOCTYPE html>
<html>
<body>
<p>Click the different buttons to understand the concept of Ceil, Floor and Round</p>
<button onclick="ceil()">Ceil 5.1</button>
<p id="ceil"></p>
<button onclick="floor()">Floor 5.1</button>
<p id="floor"></p>
<button onclick="round()">Round 5.1</button>
<p id="round"></p>
</body>
</html>
A: I realise this post is old, but an important distinction is being overlooked.
The function round() rounds towards or away from zero, while the functions ceil() and floor() round toward positive infinity and negative infinity;
This is important if dealing with both positive and negative numbers. i.e.
round(4.900000) = 5.000000
ceil(4.900000) = 5.000000
floor(4.900000) = 4.000000
round(4.100000) = 4.000000
ceil(4.100000) = 5.000000
floor(4.100000) = 4.000000
round(-4.100000) = -4.000000
ceil(-4.100000) = -4.000000
floor(-4.100000) = -5.000000
round(-4.900000) = -5.000000
ceil(-4.900000) = -4.000000
floor(-4.900000) = -5.000000
A: min() and max() return the smaller or larger of 2 values, some might do more than 2 values, as in
min(3, 5); returns 3.
floor() and ceiling() truncate a double into an integer as in
floor(5.3); returns 5.
A: Not sure I understand your question, see for example:
a = 1.7
b = 2.8
min(a,b) = 1.7 (returns the minimum of a and b)
max(a,b) = 2.8 (returns the maximum of a and b)
floor(a) = 1 (rounds towards 0)
floor(b) = 2 (rounds towards 0)
ceil(a) = 2 (rounds up)
ceil(b) = 3 (rounds up)
A: This is apples vs. oranges. In most languages/APIs, min/max take two (or more) inputs, and return the smallest/biggest. floor/ceil take one argument, and round it down or up to the nearest integer.
A: To my knowledge max and min are used on a collection, say an array of numbers. Floor and ceiling are used for single numbers. For example:
min(1, 2, 3, 4) => 1
max(1, 2, 3, 4) => 4
floor(3.5) => 3
ceiling(3.5) => 4
A: min(1, 2) == 1
max(1, 2) == 2
floor(3.9) == 3
round(3.9) == 4
ceil(3.1) == 4
round(3.1) == 3
trunc, as in (int)(3.xxx) = 3 (no matter what xxx is)
On the definition:
floor is the greatest integer less than n.
ceil is the smallest integer greater than n.
A: Please consider below for difference between Math.floor(), Math.round() and Math.ceil() in javascript:
1- Math.floor(x) /if x=0.99 convert to = x=0/ (Returns x rounded down to its nearest integer)
2- Math.ceil(x) /if x<0.1 convert to x=1/(Returns x rounded up to its nearest integer)
3-1- Mathh.round(x) / if x<0.5 convert to x=0/
3-2- Mathh.round(x) / if 0.5<=x<1 convert to x=1/
(Returns x rounded to its nearest integer) | unknown | |
d16464 | val | Need to use defineComponent wrapper
export default defineComponent({
...
}); | unknown | |
d16465 | val | Just a quick example of what one could do. It is, however, probably better to use fuzzy matching for your cities.
# City codes (all city codes can be found at https://www.allareacodes.com/)
my_city_codes <- data.frame(code = c(201:206),
cities = c("Jersey City, NJ", "District of Columbia", "Bridgeport, CT", "Manitoba", "Birmingham, AL", "Seattle, WA"),
stringsAsFactors = FALSE)
# Function for checking if city/city-code matches those in the registries
adress_checker <- function(adress, citycodes) {
# Finding real city
real_city <- my_city_codes$cities[which(adress$code == my_city_codes$code)]
# Checking if cities are the same
if(real_city == adress$city) {
return("Correct city")
} else {
return("Incorrect city")
}
}
# Adresses to check
right_city <- data.frame(code = 205, city = c("Birmingham, AL"), stringsAsFactors = FALSE)
wrong_city <- data.frame(code = 205, city = c("Las Vegas"), stringsAsFactors = FALSE)
# Testing function
adress_checker(right_city, my_city_codes)
[1] "Correct city"
adress_checker(wrong_city, my_city_codes)
[1] "Incorrect city" | unknown | |
d16466 | val | The layout you're showing is not a form layout, it could be a grid layout, but it actually seems more like a QTableView (or QTableWidget) or even a QTreeView (if those small arrows on the left are used to expand elements). Using nested layouts in this case might not be a good solution, as each layout would be independent from the others, with the result that the widgets might not be properly aligned. This small arrows for expand element in that case a QTreeView with a QStandardItemModel or a QTreeWidget might help, then use setItemWidget() to add buttons. –
musicamante | unknown | |
d16467 | val | There are probably more efficient variations, but the following should do:
xor eax, eax ; total = 0
L1:
mov esi, [ebx] ; X[i]
add ebx, 4 ; or: lea ebx, [ebx + 4]
test esi, esi
js L2 ; jump if sign (most significant) bit set.
add eax, esi ; total += X[i]
L2:
loop L1
This may not be the best way to structure the loop - and it assumes that: length (ecx) != 0 | unknown | |
d16468 | val | If you use Querydsl SQL this should work
Expression<String> dateExpr = Expressions.stringTemplate("convert(varchar, {0}, 103)", table.feLecutra);
Expression<String> timeExpr = Expressions.stringTemplate("convert(varchar, {0}, 108)", table.feLectura);
List<Tuple> results = query.from(table).list(dateExpr, timeExpr);
And to access the columns from a Tuple instance
String date = tuple.get(dateExpr);
String time = tuple.get(timeExpr); | unknown | |
d16469 | val | I've tried to simply add this Width="Auto" into the first DataGridTextColumn and it worked for me.
Code:
<DataGrid IsReadOnly="True" CanUserResizeColumns="False" AutoGenerateColumns="False"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<DataGrid.ItemsSource>
<x:Array Type="{x:Type sys:DateTime}">
<sys:DateTime/>
</x:Array>
</DataGrid.ItemsSource>
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Padding" Value="10,2"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Border Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">
<ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.CellStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="Some short header" Width="Auto" Binding="{Binding Path=., StringFormat=dddd MMMM yyyy HH:mm:ss}"/>
<DataGridTextColumn Header="Stretching" Binding="{Binding}" Width="*"/>
</DataGrid.Columns>
</DataGrid>
Result: | unknown | |
d16470 | val | Look at this example to pass a variable using jQuery.load() :
var siteName='example.com';
$("#result").load(sitename+"/site/pax_dropdown/2", {"variableName": variable});
A: Try this:
$(function(){
var url = $("#url").val();
var val = $("#value").val();
$("#result").load(url, {id: val});
});
function pax_dropdown()
{
$data['id'] = $this->input->post('id');
$this->load->vars($data);
$this->load->view("site/pax_dropdown");
}
And
<ul id="result" class="dropdown-menu">
<?php //$this->load->view("site/pax_dropdown"); comment out this line ?>
</ul>
A: Don't you have a default ID? If so, set this to the $id. If you don't want any default number, just wrap it into an if statement (if (isset($id)) and don't use the $id if it isn't set and logically shouldn't be set.
Maybe the logic behind the code would help as well for finding a solution. | unknown | |
d16471 | val | While you're using CPT UI, I thought use of another plugin to extend the functionality is a better solution in your case.
Use Custom Post Type Permalinks and configure the permalink option as:
/%custom-taxonomy-slug%/%postname%/ | unknown | |
d16472 | val | This code corrects the problem pointed out with the second use of query() and uses the $prg as the context for the next search. But I've also added the . to the start of the query to ensure it reads only the contents of this node.
As this extracts the <a> tags inside this element, it picks out only the data from the 1st and 3rd links. It then looks as the colorSwatch classed elements, not sure what you wanted to do with them, so it just outputs the content...
$doc = new DOMDocument();
$doc->loadHTML($dataop);
$xpath = new DomXPath($doc);
$nodeList = $xpath->query("//div[@class='product4Col']");
foreach($nodeList as $prg){
echo "<br>------------------<br>";
$nodeListnx = $xpath->query(".//div[@class='fluidprodCol']//a", $prg);
echo $nodeListnx[0]->attributes['href']->textContent . " " . $nodeListnx[0]->textContent . "<br /";
echo $nodeListnx[2]->attributes['href']->textContent . " " . $nodeListnx[2]->textContent. "<br /";
$colorSwatchs = $xpath->query(".//div[@class='colorSwatch']", $prg);
foreach ( $colorSwatchs as $colorSwatch ) {
echo $colorSwatch->textContent . "<br />";
}
echo "<br>------------------<br>";
} | unknown | |
d16473 | val | You can use a rotated pseudo element. Make it 1px wide and make the lines with top/bottom borders :
body {
padding: 0;
margin: 0;
background-image: url('https://farm7.staticflickr.com/6083/6055581292_d94c2d90e3.jpg');
background-size: cover;
}
div {
position: relative;
width: 150px;
margin: 130px auto;
padding: 10px 0;
}
div:before {
content: '';
position: absolute;
top: -120px;
left: 50%;
width: 1px;
height: 100%;
border-top: 120px solid #000;
border-bottom: 120px solid #000;
-webkit-transform: rotate(8deg);
-ms-transform: rotate(8deg);
transform: rotate(8deg);
}
<div>
<h1>Title</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec luctus condimentum mi sit amet iaculis. Aliquam erat volutpat. Maecenas eleifend commodo rutrum.</p>
</div>
A: I think you are looking for this-
body{background: url('http://i.imgur.com/Kv22GCi.png');}
div {
position: relative;
width: 120px;
margin: 100px auto;
padding: 5px 0;
}
div:before {
content: '';
position: absolute;
top: -100px; left: 45%;
width: 1px; height: 100%;
border-top: 120px solid #000;
border-bottom: 120px solid #000;
-webkit-transform: rotate(8deg);
-ms-transform: rotate(8deg);
transform: rotate(8deg);
}
<div>
<h2>dsfsd jf fkljdsfjdsj</h2>
<p>Loream ipsum dolor shit amet</p>
</div>
I hope this will help you.
A: You can do using pseudo selectors :after or :before
Download this png image for background http://i.imgur.com/Kv22GCi.png
.container {
position: relative;
width: 300px;
height: 548px;
border: 1px solid #ccc;
background-image: url(http://i.imgur.com/Kv22GCi.png);
padding: 50px;
-moz-box-sizing: border-box;
box-sizing: border-box;
font-family: sans-serif
}
/*For the diagonal line*/
.container:after {
content: "";
position: absolute;
height: 100%;
border: 1px solid #000;
top: 0;
left: 70px;
z-index: -1;
-moz-transform: rotate(10deg);
-ms-transform: rotate(10deg);
-o-transform: rotate(10deg);
-webkit-transform: rotate(10deg);
transform: rotate(10deg)
}
h1 {
font-size: 50px
}
p {
font-size: 22px
}
<div class="container">
<h1>About Us.</h1>
<p>"Lorem ipsum sit amet.Lorem ipsum sit amet.Lorem ipsum sit amet.Lorem ipsum sit amet.Lorem ipsum sit amet.Lorem ipsum sit amet.Lorem ipsum sit amet."
<p/>
</div> | unknown | |
d16474 | val | I can give you advice both from the sysadmin's side and the developers side.
Sysadmin
Setting up node.js is not a big task. Setting up a MongoDB correctly is. But that is not your business as an application vendor, especially not when you are a one man show FOSS project, as I assume. It is an administrators task to set up a database, so let him do it. Just tell them what you need, maybe point out security concerns and any capable sysadmin will do his job and set up the environment.
There are some things you underestimate, however.
Applications, especially useful ones, tend to get used. MongoDB has many benefits, but being polite about resources isn't exactly one of them. So running on a surplus PC may work in a software development company or visual effects company, where every workstation has big mem, but in an accountant company your application will lack resources quite fast. Do not make promises like "will run on your surplus desktop" until you are absolutely, positively sure about it because you did extensive load tests to make sure you are right. Any sensible sysadmin will monitor the application anyway and scale resources up when necessary. But when you make such promises and you break them, you loose the single most important factor for software: the users trust. Once you loose it, it is very hard to get it back.
Developer
You really have to decide whether MongoDB is the right tool for the job. As soon as you have relations between your documents, in which the change of of document has to be reflected in others, you have to be really careful. Ask yourself if your decision is based on a rational, educated basis. I have seen some projects been implemented with NoSQL databases which would have been way better of with a relational database, just because NoSQL is some sort of everybody's darling.
It is a FAR way from node.js to Java EE. The concepts of Java EE are not necessarily easy to grasp, especially if you have little experience in application development in general and Java.
The Problem
Without knowing anything about the application, it is very hard to make a suggestion or give you advice. Why exactly has the mongodb to be local? Can't it be done with a VPC? Is it a webapp, desktop app or server app? Can the source ode be disclosed or not? How many concurrent users per installation can be expected? Do you want a modular or monolithic app? What are your communication needs? What is your experience in programming languages? It is all about what you want to accomplish and which services you want to provide with the app.
A: Simple and to the point: Chef (chef solo for vagrant) + Vagrant.
Vagrant provides a uniform environment that can be as closed to production as you want and Chef provides provisioning for those environments.
This repository is very close to what you want: https://github.com/TryGhost/Ghost-Vagrant
There are hundreds of thousands of chef recipes to install and configure pretty much anything in the market. | unknown | |
d16475 | val | One way would be an If statement control inside the loop.
Sub printS()
Dim sht As Worksheet
For Each sht In ThisWorkbook.Worksheets
With sht
If .name <> sheets("THAT SHEET NAME HERE").name then 'this control will exclude your button sheet
If Not IsError(Application.Match("Person1", .Range("C:C"), 0)) And .Index > 3 And Not IsEmpty(.Cells(13, 1)) Then
sht.Tab.ColorIndex = 7
sht.Select (False)
End If
End if 'close block if
End With
Next
ActiveWindow.SelectedSheets.PrintOut
End Sub | unknown | |
d16476 | val | 1) you cannot use a class variable in a static method so accessing ofd in this line:
PdfReader reader = new PdfReader(ofd.FileName);
should result in an compiler error message that
for the non-static field 'ofd' an object instance is required.
2) It seems that you are not calling your method. You need to call it and pass the filename as parameter into it
private void button1_Click(object sender, EventArgs e)
{
ofd.Filter = "PDF|*.pdf";
if (ofd.ShowDialog() == DialogResult.OK)
{
richTextBox1..Text = pdfText(ofd.SafeFileName);
}
}
Then you need to use the method parameter inside the method:
public static string pdfText(string path)
{
//this is the error, I cannot get the path of the File I chose from the OpenFileDialog
PdfReader reader = new PdfReader(path); // Here use path
Now the returned string should appear in your richTextBox1 | unknown | |
d16477 | val | I reported this bug but it's closed as won't fix: https://github.com/nunit/nunit/issues/1209
So you can either use NUnit 3.x or accept that it's just broken in NUnit 2.6.x.
A: Althoug either a and bare of type Int32[2][] that does not mean they are equal as Equals returns true if the references of your arrays are identical which they are not. What you want is to echeck if their content is the same using a.SequenceEquals(b). | unknown | |
d16478 | val | You can get the date by passing the date argument when declaring a variable:
var=$(date '+%d/%m/%Y %H:%M:%S');
And as pointed out by @Cyrus, you can also not use date via:
printf -v var "%(%d/%m/%Y %H:%M:%S)T\n" -1 | unknown | |
d16479 | val | Since I used display: flex in my solution I used margin-left: auto instead of float: right and I assumed the max-width: 160px. You can use your own value.
.wrapper{
max-width: 160px;
}
.inner{
display: flex;
}
.right{
margin-left: auto;
}
.left{
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
<div class='wrapper'>
<div class='inner'>
<span class='left'>Name</span>
<span class='right'>Value</span>
</div>
<div class='inner'>
<span class='left'>id:</span>
<span class='right'>123456789012345678</span>
</div>
<div class='inner'>
<span class='left'>occupancy_timeout</span>
<span class='right'>10000</span>
</div>
<div class='inner'>
<span class='left'>led_indication</span>
<span class='right'>true</span>
</div>
</div> | unknown | |
d16480 | val | Run the JVCL installer and uninstall. Then open the JVCL root folder in the command line and type "clean.bat all" and that should take care of the rest of it.
A: There is no automatic way to nicely uninstall Jedi.
To uninstall Jedi and restore the functionality of previous GIF library do this:
*
*Close Delphi
*Run the JCL uninstaller
*Run the JVCL uninstaller
*Run the cleaning utility as explained by Mason Wheeler (in both folders)
*Manually delete JCL folders
*Manually delete JVCL folders
*Start Delphi. Reinstall TGifImage component
Note: To start the uninstallers run the "install.bat". | unknown | |
d16481 | val | You can make your loop simpler (in case you use C# 6 or higher):
foreach(var o in objects)
{
o.Update(time);
(o as Portal)?.Interact(ref player, player.Interact);
(o as Enemy)?.Update(time, player);
}
For C# 5 or lower you should use:
foreach(var o in objects)
{
o.Update(time);
if (o is Portal)
{
((Portal)o).Interact(ref player, player.Interact);
}
else if(o is Enemy)
{
((Enemy)o).Update(time, player);
}
}
In this case you have less lines of code but you cast two times.
You can cast only one time:
foreach(var o in objects)
{
o.Update(time);
var e = o is Portal;
if (e != null)
{
e.Interact(ref player, player.Interact);
}
else
{
((Enemy)o).Update(time, player);
}
}
A: Try this:
((Enemy)o).Update(time, player);
Remember about possible Null Reference Exception if you didn't check a type of this object. In your code everything is fine.
A: You can replace those two lines with a single line as follows:
else if(o is Enemy)
{
((Enemy)o).Update(time, player);
}
A: You call the function in that way:
var a = ((Portal)o).Interact(ref player, player.Interact);
so the type of a will be the returned type of Interact, but in context of your code it won't matter much.
A: To go further than other response, you could use the visitor pattern.
First create a IVisitorClient and a IVisitor interface.
interface IVisitorClient
{
Accept(IVisitor visitor);
}
interface IVisitor
{
Visit(SceneObject o); // here the types of your objects
Visit(Enemy e);
Visit(Portal p);
}
Make your different object implement IVisitorClient.
abstract class SceneObject : IVisitorClient
{
public virtual void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
}
class Portal : SceneObject
{
...
public override void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
...
}
class Enemy: SceneObject
{
...
public override void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
...
}
Then build an updater that implement IVisitor :
class UpdaterVisitor : IVisitor
{
readonly Player player;
readonly Time time;
public UpdaterVisitor(Player player, Time time)
{
this.player = player;
this.time = time;
}
public void Visit(SceneObject o)
{
e.Update(time);
}
public void Visit(Enemy e)
{
e.Update(time, player);
}
public void Visit(Portal p)
{
p.Interact(ref player, player.Interact);
}
}
Finally, to update the object, the code will look like this.
var updateVisitor = new UpdaterVisitor(player, time);
foreach(var o in objects)
{
o.Accept(updateVisitor);
}
A: Or do it this way to avoid the double cast...
foreach(var o in objects)
{
o.Update(time);
Portal p = o as Portal;
if(p != null)
{
p.Interact(ref player, player.Interact);
}
else
{
Enemy e = o as Enemy;
if (e != null)
{
e.Update(time, player);
}
}
} | unknown | |
d16482 | val | In your script tags instead of export default use:
module.exports = {
data() {
return { counter: 1 }
}
}
This should work for you
A: Call the component inside your template
Vue.component('example', {
template: `<div class="profile">{{ name }}</div>`,
data () {
return {
name: 'John Doe'
}
}
})
const app = new Vue({
el: '#app'
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app"><example></example></div>
A: The problem is that you are trying to load the component 'example' from that file but you didn't give a name to it. You should use:
<script>
export default {
name: 'example',
data() {
return {
name: 'John Doe'
}
}
}
</script>
Or load the component the following way (not sure if extension .vue is needed):
require('./exmaple').default();
If you are using Babel you can also load the components without giving them a name using this syntax:
import Example from ./example
Also checkout this post to get some more info in case you use Babel | unknown | |
d16483 | val | One workaround to your situation uses string operations to obtain the numerical subject code and use it for sorting.
SELECT
subject_code
FROM yourTable
ORDER BY
CAST(SUBSTR(subject_code,
INSTR(subject_code, ' ') + 1) AS UNSIGNED)
However, you should really be storing the text and numerical code in separate columns.
Output:
Demo here:
Rextester | unknown | |
d16484 | val | It would be really helpful to see your Kubernetes configuration, but overall you can use ConfigMaps for this purpose - as it is standard Kubernetes resource for storing configuration data. It is described in more details here.
Below is the example of ConfigMap, where MySQL connector jar file is mounted to the pod:
containers:
- name: container
volumeMounts:
- name: config
mountPath: /usr/local/mysql-connector-java.jar
volumes:
- name: config
configMap:
name: config-map
items:
- key: mysql-connector-java.jar
path: mysql-connector-java.jar
But ConfigMap will work for you only if you are storing the connector jar file, which size is not exceeding 1 MiB.
Otherwise, there is one more option - mounting a persistent volume with a MySQL connector jar file - as described here and here. The jar file will be copied to the pod once persistent volume is mounted into it - and it can be re-mounted to the pod after its restart/re-creation. | unknown | |
d16485 | val | The problem was resolved after delete /Users/currentuser/Library/Caches/Homebrew/downloads/922ce7b351cec833f9bd2641f27d8ac011005f8b1f7e1119b8271cfb4c0d3cd7--brotli-1.0.9.bottle_manifest.json
and run brew install curl again
A: It might be using the installed curl instead of system curl.
From man brew
set HOMEBREW_FORCE_BREWED_CURL
A: I have also this problem with brew install php
the problem persists even after deleting all the files from
/Users/currentuser/Library/Caches/Homebrew/downloads/
and
brew install php again
i have also tried
HOMEBREW_FORCE_BREWED_CURL=1 brew install openssl
A: This command fixed the issue for me:
brew cleanup
A: same for brew install python
but I deleted folder under my username, don't know and searched right now whether or not exist Users/currentuser folder but result is ok
homebrew says ;
[email protected]
Python has been installed as
/usr/local/bin/python3 | unknown | |
d16486 | val | Maybe using replace with that kind of RegEx :
https://regex101.com/r/MRmZ00/3
(.*[?&]lang=)[A-Z]{2}(.*)
Output : '$1' + newlang + '$2'
Working if it's your only parameter or your first one ?lang=ES or anywhere else in the url &lang=ES.
A:
URI.js is a javascript library for working with URLs. It offers a "jQuery-style" API (Fluent Interface, Method Chaining) to read and write all regular components and a number of convenience methods like .directory() and .authority().
Here is link
Here is example :
URI(location.href).addQuery("lang", languageName); | unknown | |
d16487 | val | The DECODE() Oracle function is available as part of the Oracle UDF Library on the Teradata Developer Exchange Downloads section. Otherwise, you are using the DECODE function in your example in the same manner in which the ANSI COALESCE() function behaves:
COALESCE(t.satisfaction, 'Not Evaluated')
It should be noted that the data types of the COALESCE() function must be implicitly compatible or you will receive an error. Therefore, t.satisfaction would need to be at least CHAR(13) or VARCHAR(13) in order for the COALESCE() to evaluate. If it is not, you can explicitly cast the operand(s).
COALESCE(CAST(t.satisfaction AS VARCHAR(13)), 'Not Evaluated')
If your use of DECODE() includes more evaluations than what is in your example I would suggest implementing the UDF or replacing it with a more standard evaluated CASE statement. That being said, with Teradata 14 (or 14.1) you will find that many of the Oracle functions that are missing from Teradata will be made available as standard functions to help ease the migration path from Oracle to Teradata. | unknown | |
d16488 | val | I am really surprised at how obscure this is, because I had exactly the same problem and could not find a definitive answer. One would think the ZF2 documentation would say something about this. Anyhow, using trial and error, I came across this extremely simple answer:
Inside controller functions:
$config = $this->getServiceLocator()->get('Config');
Inside Module class functions (the Module.php file):
$config = $e->getApplication()->getServiceManager()->get('Config');
whereas $e is an instance of Zend\Mvc\MvcEvent
In general, the config is accessible from anywhere you have access to the global service manager since the config array is registered as a service named Config. (Note the uppercase C.)
This returns an array of the union of application.config.php (global and local) and your module.config.php. You can then access the array elements as you need to.
Even though the OP is quite old now, I hope this saves someone the hour or more it took me to get to this answer.
A: What exactly do you want to do in your controller with the module configuration? Is it something that can't be done by having the DI container inject a fully configured object into your controller instead?
For example, Rob Allen's Getting Started with Zend Framework 2 gives this example of injecting a configured Zend\Db\Table instance into a controller:
return array(
'di' => array(
'instance' => array(
'alias' => array(
'album' => 'Album\Controller\AlbumController',
),
'Album\Controller\AlbumController' => array(
'parameters' => array(
'albumTable' => 'Album\Model\AlbumTable',
),
),
'Album\Model\AlbumTable' => array(
'parameters' => array(
'config' => 'Zend\Db\Adapter\Mysqli',
)),
'Zend\Db\Adapter\Mysqli' => array(
'parameters' => array(
'config' => array(
'host' => 'localhost',
'username' => 'rob',
'password' => '123456',
'dbname' => 'zf2tutorial',
),
),
),
...
If you need to do additional initialization after the application has been fully bootstrapped, you could attach an init method to the bootstrap event, in your Module class. A blog post by Matthew Weier O'Phinney gives this example:
use Zend\EventManager\StaticEventManager,
Zend\Module\Manager as ModuleManager
class Module
{
public function init(ModuleManager $manager)
{
$events = StaticEventManager::getInstance();
$events->attach('bootstrap', 'bootstrap', array($this, 'doMoarInit'));
}
public function doMoarInit($e)
{
$application = $e->getParam('application');
$modules = $e->getParam('modules');
$locator = $application->getLocator();
$router = $application->getRouter();
$config = $modules->getMergedConfig();
// do something with the above!
}
}
Would either of these approaches do the trick?
A: for Beta5, you can add function like this in Module.php
public function init(ModuleManager $moduleManager)
{
$sharedEvents = $moduleManager->getEventManager()->getSharedManager();
$sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
$config = $e->getApplication()->getConfiguration();
$controller = $e->getTarget();
$controller->config = $config;
});
}
in controller, you can get config :
print_r($this->config);
A: To read module-only config your module should just implement LocatorRegisteredInterface
Before:
namespace Application;
class Module
{
// ...
}
After:
namespace Application;
use Zend\ModuleManager\Feature\LocatorRegisteredInterface;
class Module implements LocatorRegisteredInterface
{
// ...
}
That implementation says LocatorRegistrationListener to save module intance in service locator as namespace\Module
Then anywhere you can get access to your module:
class IndexController extends AbstractActionController
{
public function indexAction()
{
/** @var \Application\Module $module */
$module = $this->getServiceLocator()->get('Application\Module');
$moduleOnlyConfig = $module->getConfig();
// ...
}
}
A: There is a pull request ready now which pulls the module class (so the modules/foo/Module.php Foo\Module class) from the DI container. This gives several advantages, but you are also able to grab that module instance another time if you have access to the Zend\Di\Locator.
If your action controller extends the Zend\Mvc\Controller\ActionController, then your controller is LocatorAware. Meaning, upon instantiation your controller is injected with the locator knowing about modules. So, you can pull the module class from the DIC in your controller. Now, when your module consumes a config file and stores this inside the module class instance, you can create a getter to access that config data from any class with a locator. You probably have already an accessor with your module Foo\Module::getConfig()
While ZF2 is heavily under development and perhaps this code will change later on, this feature is currently covered by this test, with this the most relevant part:
$sharedInstance = $locator->instanceManager()->getSharedInstance('ListenerTestModule\Module');
$this->assertInstanceOf('ListenerTestModule\Module', $sharedInstance);
So with $sharedInstance your module class, you can access the config from there. I expect a shorthand for this feature soon, but this can only be done after PR #786 has been merged in ZF2 master.
A: You need to implements ServiceLocatorAwareInterface from your model. And then you can set setServiceLocator() and getServiceLocator() which give you direct access to the service manager. Take a look at this code sample https://gist.github.com/ppeiris/7308289
A: I created the module with controller plugin and view helper for reading a config in controllers and views. GitHub link __ Composer link
Install it via composer
composer require tasmaniski/zf2-config-helper
Register new module "ConfigHelper" in your config/application.config.php file
'modules' => array(
'...',
'ConfigHelper'
),
Use it in controller and view files
echo $this->configHelp('key_from_config'); // read specific key from config
$config = $this->configHelp(); // return config object Zend\Config\Config
echo $config->key_from_config;
A: you can also access any config value anywhere by this hack/tricks
$configReader = new ConfigReader();
$configData = $configReader->fromFile('./config.ini');
$config = new Config($configData, true); | unknown | |
d16489 | val | This should be able to set more than one column to maxheight. Just specify the selectors just like you would if you wanted to select all your elements with jQuery.
function matchColHeights(selector){
var maxHeight=0;
$(selector).each(function(){
var height = $(this).height();
if (height > maxHeight){
maxHeight = height;
}
});
$(selector).height(maxHeight);
};
$(document).ready(function() {
matchColHeights('#leftPanel, #rightPanel, #middlePanel');
});
A: one line alternative
$(".column").height(Math.max($(col1).height(), $(col2).height()));
Check out this fiddle: http://jsfiddle.net/c4urself/dESx6/
It seems to work fine for me?
javascript
function matchColHeights(col1, col2) {
var col1Height = $(col1).height();
console.log(col1Height);
var col2Height = $(col2).height();
console.log(col2Height);
if (col1Height < col2Height) {
$(col1).height(col2Height);
} else {
$(col2).height(col1Height);
}
}
$(document).ready(function() {
matchColHeights('#leftPanel', '#rightPanel');
});
css
.column {
width: 48%;
float: left;
border: 1px solid red;
}
html
<div class="column" id="leftPanel">Lorem ipsum...</div>
<div class="column" id="rightPanel"></div>
A: When I load your site in Chrome, #leftPanel has a height of 1155px and #rightPanel has a height of 1037px. The height of #rightPanel is then set, by your matchColHeights method, to 1155px.
However, if I allow the page to load, then use the Chrome Developer Tools console to remove the style attribute that sets an explicit height on #rightPanel, its height becomes 1473px. So, your code is correctly setting the shorter of the two columns to the height of the taller at the time the code runs. But subsequent formatting of the page would have made the other column taller.
A: The best tut on this subject could be found here:
http://css-tricks.com/equal-height-blocks-in-rows/ | unknown | |
d16490 | val | In case this can help anybody in the future - this issue was caused by me performing a placement-new in a block of memory that wasn't big enough to hold the object, no doubt overwriting some memory belonging to bullet physics. | unknown | |
d16491 | val | The mapreduce.tasktracker.map.tasks.maximum (defaulted to 2) controls the maximum number of map tasks that are run simultaneously by a TaskTracker. Set this value to 1.
Each map task is launched is a seperate JVM. Also set the mapreduce.job.jvm.numtasks to -1 to reuse the JVM.
The above settings will enable all the map tasks to run in single JVM sequentially. Now, SomeClass has to be made a singleton class.
This is not a best practice as the node is not efficiently utilized because of the lower number of map tasks that can run in parallel. Also, with JVM reuse there is no isolation between the tasks, so if there is any memory leak it will be carried on till the jvm crashes. | unknown | |
d16492 | val | Nutch stores its data in the f column family as BytesType. The column names are stored as UTF8Type.
If you want to get the data as a String you have to convert it first. A row is completely stored in the ByteBuffer. In your example you convert the whole byte buffer to String what gives you the whole row. When you select one row, you get the current position an limit of that row. So you have to read from begin:buffer current pointer position to buffer limit. For example to get the websites content in the "cnt" field:
// This is the byte buffer you get from selecting column "cnt"
ByteBuffer buffer;
int length = buffer.limit() - buffer.position();
byte[] cellValue = new byte[length];
buffer.get(cellValue, 0, length);
return new String(cellValue, Charset.forName("UTF-8")); | unknown | |
d16493 | val | XPath is designed for locating information in existing documents, not for constructing new documents. You want XSLT or XQuery for that job.
A: The problem, as Michael has pointed out, is that XPath, the language, is just not sufficiently expressive to perform the task you need. (It would I think be possible in XPath 3 but only awkwardly, and I think you are not running XPath 3 here).
On the bright side, this task is easily performed e.g. in XSLT, simply by embedding your existing XPath into a very simple XSLT stylesheet
<joblist xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<job>
<xsl:copy-of select="
/joblist/job/*[
self::uuid or self::group or self::name or self::description or self::tags
]
"/>
</job>
</joblist>
See section 2.3 "Literal Result Element as Stylesheet" of the XSLT spec for the details of how this works. | unknown | |
d16494 | val | You're right. This behavior is a feature not a bug.
In iOS 11 you can use compassVisibility.
let compass = MKCompassButton(mapView: mapView)
compass.compassVisibility = .visible
https://developer.apple.com/documentation/mapkit/mkcompassbutton/2890262-compassvisibility | unknown | |
d16495 | val | If your team site is a classic team site then no, you can't have a megamenu unless you make a custom one.
IF your team site is a modern team site then you inherit the megamenu from a hub site I believe.
I have a feeling you have a classic team site with modern pages in it. | unknown | |
d16496 | val | I think it means that if you look at the parents of the object they all have the same scale.
Just to be clear, the two entities below would not work right
<a-entity scale="1 2 1">
<a-entity scale="2 2 2">
</a-entity>
</a-entity>
https://aframe.io/docs/1.0.0/components/scale.html#sidebar | unknown | |
d16497 | val | You can always filter your dataset to include only two levels.
Where var3 ne 'C';
Usually you would use an ANOVA instead when you have 3 levels and then you could do pairwise comparisons but you need to correct for multiple testing. PROC ANOVA incorporates options for this type of analysis. | unknown | |
d16498 | val | The exception is thrown since some properties of entity executes new query while a previous reader has not been closed yet. You cannot execute more than one query on the data context at the same time.
As a workaround you can "visit" the properties you access in ProcessEntity() and make the SQL run prior to the thread.
For example:
var repo = new Repository();
var entities = repo.GetAllEntities();
foreach (var entity in entities)
{
var localEntity = entity; // Verify the callback uses the correct instance
var entityCustomers = localEntity.Customers;
var entityOrders = localEntity.Orders;
var invoices = entityOrders.Invoices;
ThreadPool.QueueUserWorkItem(
delegate
{
try
{
ProcessEntity(localEntity);
}
catch (Exception)
{
throw;
}
});
}
This workaround will execute the SQL only on the main thread and the processing will be done in other threads. You loose here some of the efficiency since all the queries are done in the single thread. This solution is good if you have a lot of logic in ProcessEntity() and the queries are not very heavy.
A: Try creating the Repository inside the new thread instead of passing it in.
A: Be aware that a SqlConnection instance is NOT thread safe. Whether you still have an open reader or not. In general, the access of a SqlConnection instance from multiple threads will cause you unpredictable intermittent problems.
See: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx
A: The solution for me was LightSpeed Persistence framework, which is free until 8 entities. Per thread create the unitwork.
http://www.mindscapehq.com/products/LightSpeed/default.aspx | unknown | |
d16499 | val | Results is expecting id and text nodes in the json, you can either tell your JSON to ouput the results using these node names or specify which to use in the JS:
Example from site:
query: function (query) {
var data = {results: []}, i, j, s;
for (i = 1; i < 5; i++) {
s = "";
for (j = 0; j < i; j++) {s = s + query.term;}
data.results.push({id: query.term + i, text: s});
}
query.callback(data);
}
A: Put debugger before if ($(data).filter(function () and check what you have got in $(data)
A: I found the issue. I needed to call the data.data (in my example) in the results ajax function.
Example:
results: function (data, page) {
return {
results: data.data
};
} | unknown | |
d16500 | val | try this one
it('if I have 3 zeros or more in decimals only display max of 2 zeros in decimals', function() {
// using $filter
expect($filter('customCurrency')(1.000, '$', 2)).toEqual('$1<span class="decimals">.00</span>');
});
A: Not sure this will work out for you in the long run as I'm sure there is a better way to go about this, but if you want a quick and dirty fix try this:
DEMO
app.filter('customCurrency',function ($filter) {
return function (amount, currencySymbol, fractionSize) {
var currency = $filter('currency');
if (amount < 0) {
return currency(amount, currencySymbol).replace('(', '-').replace(')', '');
}
debugger;
if (fractionSize !== undefined) {
amount = currency(amount, currencySymbol, fractionSize);
} else {
amount = currency(amount, currencySymbol)
}
debugger;
var amounts = amount.split("."),
fractionalPart = amounts[1],
decimals = fractionalPart.length,
zerosFromRight = countZerosFromRight(fractionalPart);
if(zerosFromRight > 2){
return amounts[0] + '<span class="decimals">.00</span>';
}
return amounts[0] + '<span class="decimals">.' + amounts[1] + '</span>';
///////////////////////////////////
function countZerosFromRight(str){
var len = str.length,
count = 0;
while(len--){
if(str[len] === '0'){
count++;
continue;
}
break;
}
return count
}
};
});
EDIT
Had a rethink and think this way is better:
I've added this test and maybe you don't need this functionality but I think this is a bit more robust.
DEMO2
it('should only remove the zeros up to the last non-zero number', function() {
expect($filter('customCurrency')(1.004000, '$', 6)).toEqual('$1<span class="decimals">.004</span>');
expect($filter('customCurrency')(1.4066000, '$', 6)).toEqual('$1<span class="decimals">.4066</span>');
});
app.js
var app = angular.module('plunker', ['ngRoute']);
'use strict';
var app = angular.module('plunker');
app.filter('customCurrency',function ($filter) {
return function (amount, currencySymbol, fractionSize) {
var currency = $filter('currency');
if (amount < 0) {
return currency(amount, currencySymbol).replace('(', '-').replace(')', '');
}
debugger;
var rounded = round(amount, fractionSize),
currencyString = currency(rounded, currencySymbol, fractionSize),
amounts = currencyString.split("."),
integerPart = amounts[0],
fractionalPart = amounts[1] || false,
indexLastNonZero = indexLastNonZero(fractionalPart);
// if only zeros after decimal then remove all but 2
if(indexLastNonZero === -1){
return integerPart + '<span class="decimals">.00</span>';
}
// if zeros and other numbers after decimal remove all trailing zeros
if(indexLastNonZero > 1){
return integerPart + '<span class="decimals">.' + fractionalPart.slice(0, indexLastNonZero + 1) + '</span>';
}
return integerPart;
/////////////////////////////////////////////
function round(str, decimals){
var num = +str;
return num.toFixed(decimals);
}
function indexLastNonZero(str){
var len = str.length;
while(len--){
if(str[len] !== '0'){
return len;
}
}
return -1;
}
};
}); | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.