text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
Objective-C: Float addition error when returning to view
I've got an NSDictionary made up of titles and floats (although they're stored as strings, for what it's worth), along the lines of "Paid for Dinner":"15.00". Right now, those entries are (15, 25.25, 25.75, 15), which should add up to 81. (And I've checked in the debugger, those are the correct values being stored, so it isn't a data source problem.)
I want to get the sum of all the entries programmatically, so I've got a fairly simple bit of code to do that:
float currentTotal;
for(id key in thisSet) {
currentTotal = currentTotal + [[thisSet objectForKey:key] floatValue];
}
By the end of the function, currentTotal is correctly set at 81.
Thing is, when I leave that ViewController and then return back to it, (by going from the MasterView, where I was, to the DetailView and then back, if it matters), the same function with the same values will return 81.006.
The values didn't change (I checked the debugger again, it's still precisely (15, 25.25, 25.75, 15)) and the code didn't change, so why would simply moving from to another View and back change the result?
NOTE: I know about floating point addition errors and such from other answers like this and this. I'm not looking for why floating point operations can be imprecise, I'm wondering why a change in View would affect the results.
PS I changed all the "float" references to "double" and it fixed the problem, but I'd still love to know why the same function would return one thing on launch, then change to a different thing upon returning to the same ViewController and stay with the second result from then on?
In your code currentTotal is not initialized to zero. Is that actually missing or did you just not show it? Could that be the reason for different results?
That was actually missing, but either way it should be the same every time it executes, right? Whatever it does the first time should be the same thing it does the second time, it seems like. So why would it change upon returning to the View?
When a variable is deallocated the memory isn't cleaned, so if you push a variable into the stack and you don't assign it, you get old values. But you can't know what was on the stack before calling the function, so it's undefined behavior.
The local variable currentTotal must be assigned a value (zero in your case) before
it is used, otherwise its contents is
undefined and may be different on each invocation of the function.
(The Static Analyzer should warn you about this.)
| common-pile/stackexchange_filtered |
Opening Youtube e-mail attachments
How do I open You Tube video from link in Thunderbird e-mail attachment?
Try Ctrl+click, or double click
You can find the settings here:
Open TB
Click 'Edit'
Click 'Preferences'
Click 'Attachments' tab
You will see 'Content Type' listed (mine shows 'http' and 'https')
Under 'Action' select 'Use Other'
Locate the browser you want to use (usually in /usr/lib/)
Repeat for both 'Content Types'
'Action' should now read 'Use [your browsername]'
Close. You're all set.
| common-pile/stackexchange_filtered |
Sitemap of SharePoint Online portal and all related content needed
I've got a legal request for a list of ALL the SharePoint sites AND all the links/content listing from the SharePoint sites. The site export from the Admin portal is not adequate. Is it possible within the Admin realm of SharePoint Online? If not, is there a tool that can be recommended that will do this for me? Thanks!
Are you hoping to find information on all site sets including sub-sites of each site set?
If so, you can use PowerShell to export these sites information.
For the first method, you can download the PnP module and then refer to the PowerShell command in this article: Get All Sites and Sub Sites in SharePoint Online using PnP PowerShell.
Second method, We can create a SharePoint Site Collections and Subsites Inventory Report.
I hope this will help you.
| common-pile/stackexchange_filtered |
Drawing path without overlaying existing shapes?
Help needed..
I have a organization layout which have rectangular shapes not in an ordered grid. If it was a grid, I would have used A- star code. So, How to connect two nodes (i.e. two rectangles) without interfering in between nodes(rectangles).
I just want the algorithm to find coordinates that will draw the path so that I can use that in generating SVG file.
Algorithm which I followed-
Store coordinates of edges of all Rectangles namely edge left,
right, top, bottom as four datasets.
Follow the path from a point on RectangleA to a point on RectangleB.
Find the first edge that intersect with the path( Skew edges that are impossible to intersect the path are found based on calculations using coordinates and they are eliminated while finding intersecting edges).
After finding the first intersection, path from PointA to PointB is changed to PointA to Point of intersection and the path generated along the edge that intersect and from there to Point B.
Points 3 n 4 are repeated till path to PointB is complete without intersecting any edge.
I implemented this algorithm even though this is not giving an exact shortest path. This gives great output. I would like to share the java code if anyone requests since I find it difficult to explain how I implemented by above points.
to get shortiest path you should build a graph which nodes will be Rectangle's edges. Then connect nodes that are in visible range of each other and store the length for each connecting line. After adding starting and destination points to this graph you can run A* code on it.
| common-pile/stackexchange_filtered |
Firebase Storage in android eclipse project
I have an android project on Eclipse and I want to use Firebase 'Cloud Storage' within it.
using Android Studio, I add Firebase to my app by using the Firebase Assistant and Connect to Firebase, then I add the dependencies for Cloud Storage to my build.gradle file [compile 'com.google.firebase:firebase-storage:11.4.2'] and it works fine.
while the android project on Eclipse hasn't build.gradle file. So how can I install firebase Cloud Storage for eclipse and add it to my project?
You can add Gradle to your Eclipse install, or you can import Eclipse project to Android Studio. Other options are much more difficult
Eclipse isn't really supported by Play services or Firebase. You should seriously consider switching to gradle and Android Studio.
You can try to
use gradle with eclipse or
download the firebase jar and add it to your libs folder
I don't know how far you'll get with 2. because you might need to apply the google services gradle plugin to get everything running.
If you're thinking about going with option 1., you'd probably be better off converting the project into an Android Studio project anyways, which I'd strongly recommend, because Eclipse is not supported anymore since june 2015.
| common-pile/stackexchange_filtered |
JS multidimentional array inside for loop
so, I have following js:
var INFO = [];
var newMap = {};
function user_info(id,name,url,img){
newMap[id] = [name, url, img];
return newMap ;
}
...
for (var j = 0; j < 2; j++) {
INFO.push(user_info(a,b,c,d));
}
alert(JSON.stringify(INFO, null, 4));
Then, I get the following result:
I know why it is happening. Because newMap does not get emptied out before the second and third for loop run, and gets added multiple times.
Could someone help me with how to clean this or fix this issue so that there is only multiarray like below:
I tried to do the following:
var INFO = [];
function user_info(id,name,url,img){
var newMap = {};
newMap[id] = [name, url, img];
return newMap ;
}
But getting the following result which is not what I am looking for:
Issue here is that all the actual arrays are inside of its own 2nd layer.
Instead of adding image, add the actual string, it's easy to add text than image.
What is a, b, c, d? Add complete code, also add live demo if possible.
It's "user_info(id,name,url,img)" like shown in the function. I am not sure if this is relevant as the element in the array is not the question, but adding the array via for loop. Thanks though.
Okay, try `function user_info(data) {
for (loopoverdatahere) {
newMap[id] = [name, url, img];
}
return newMap;
}
INFO.push(user_info(completeData));`. Send complete data to the function, it'll loop over all the data, add individual arrays inside object and return result.
Seems like all you really need is to get rid of the INFO.push() call inside the loop, and move it after the loop. The user_info doesn't need to return anything. https://jsfiddle.net/72ogoat5/
@squint Unfortunately there is a condition inside the loop which if true, calls the function.
@Tushar I am not fully understanding what this loopoeverdatahere and completeData is. I will try it again though. Thanks
@RyanPicard Now you understand why complete code is necessary to add in question. :). It is the data that you're looping over using for loop.
What's the point of the array if you are just wrapping one object?
like that:
function user_info(map, id,name,url,img){
map[id] = [name, url, img];
}
var INFO = [];
var newMap = {};
for (var j = 0; j < 2; j++) {
user_info(newMap, a,b,c,d)
}
INFO.push(newMap);
alert(JSON.stringify(INFO, null, 4));
I think this is all you need, although it's hard to test without access to what your j, a, b, c, d variables in your example:
var INFO = [],
data = {};
for (var j = 0; j < 2; j++) {
data[a] = [b, c, d];
}
INFO.push(data);
alert(JSON.stringify(INFO, null, 4));
| common-pile/stackexchange_filtered |
Is it possible to create a start up disk for 14.04 LTS via Windows 7? My Ubuntu o/s has crashed
I have "messed up" my system and when I boot up I get a blank screen which asks for my keyring login password. When I enter the password the screen goes completely blank and nothing further happens. I can only get out by switching off my laptop.
You can burn a Live CD from any OS -- the real question is most likely whether that can let you solve your problem, short of installing fresh.
... and if you need a startup USB, try Rufus.
Sure you can
Download PowerIso
Run the program as administrator and click on the following:
A box will appear and here you can choose what image file to "burn" onto a USB drive. It'll make it bootable.
However another option is clicking Ctrl+Alt+F1
This will allow you to browse your system, all you have to do is login.
Goodluck!
Can I reinstall Ubuntu and will it sense that I already have an installed version(which has crashed)? Will this solve my problem?
If you reinstall the system, then it's good as new. If you choose to accept this as your answer, then please check it :P
| common-pile/stackexchange_filtered |
remote desktop access
I have my work system on the ip range 172.16.xx.yy, and I have my personal system on the ip range 172.16.aa.bb. Both of them, however, are on the same network of my University, but on different LANs/VLANs (i hope i used the right word here).
How can I remotely connect to my work system from my PC, given that both use private IP addresses?
If such a thing is not possible with current set up, what minimal changes are required for it?
You need to define a static route to 172.16.xx.yy on the router of the 172.16.aa.bb subnet. This router should be connected to 172.16.xx.yy subnet and you define its IP on 172.16.xx.yy as the gateway.
is your solution feasible in a situation where my personal system is configured for dynamic IP?
Yes if the main subnet 176.16.xx.yy is not changed (and I don't believe it changes). Even if you personal subnet changes, it should work as the route only needs the main subnet IP. (obs: the reverse route (from the main network to your machine) couldn't be as easily configured with your IP dynamic but this is not what you want anyway).
If you do not have access to the routers then you will need to use an application like Teamviewer. You would need the full version on the personal computer and the unattended host application on your work computer. It is free for personal usage.
This is not a home network. This is at a university, do you think he has access and control of the routers/firewall? Maybe the network admin is his best friend... otherwise what choice does he have?
@Radoo & Logman- eh...the network admin's assistant does happen to be my friend. But he says that the only way he knows how to do this is to create a separate VLAN for these two systems of mine. I am looking for a solution involving lesser hassles with the authorities. And of course, Teamviewer is a good application but it won't let me utilize the high speed LAN available to me.
same ip range now... didnt see the change until after this post
dynamic IPs, you know... :)
Dynamic ip range that cross IP classes? odd
| common-pile/stackexchange_filtered |
Json Deserialize Issue with EF and RIA Services
I have an odd problem. I use WCF RIA with Entity Framework. I've implemented a generic search functionality, which relies on sending back the resulting entities as byte[] (enter Json.Net) and I'm able to get around all sorts of limitations of strong typedness of RIA. But when I'm deserializing back in the client, my object is not properly assembled. Now what do I mean by that?
The json, technically a string, converted to byte[] by me and back on the client, contains the related entity information I need. So let's suppose the entity is called Account and it has a related Person object. The json string , even the deserialized jobject, has this Person object and it's details. However, when I deserialize like JsonConvert.DeserializeObject<Account>(jdata, settings) - Person is null with no errors.
The settings I'm trying are here:
settings = new JsonSerializerSettings()
{
//CheckAdditionalContent = true,
PreserveReferencesHandling = PreserveReferencesHandling.All,
//ReferenceLoopHandling = ReferenceLoopHandling.Serialize
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore,
ObjectCreationHandling = ObjectCreationHandling.Replace,
TypeNameHandling = TypeNameHandling.Auto
};
Any ideas?
Ok, figured it out - so before deserializing I attached the below resolver to my settings like settings.ContractResolver = new DynamicContractResolver();
public class DynamicContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(System.Reflection.MemberInfo member, MemberSerialization memberSerialization)
{
var r = base.CreateProperty(member, memberSerialization);
r.Ignored = false;
return r;
}
}
Now everything that's in the Json deserializes in to the object fully. I don't know why this isn't the default behavior.
| common-pile/stackexchange_filtered |
QListWidgetItem objects are unhashable, it is a bug or there's a reason?
I stumbled upon this (it is, obviously, an extract from a bigger application):
import sys
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
if __name__ == '__main__':
app = QApplication(sys.argv)
d = {}
widget = QWidget()
d[widget] = 'hashable'
item = QListWidgetItem('abc')
d[item] = 'unhashable'
If you run this, on the last line you get:
TypeError: unhashable type: 'PySide2.QtWidgets.QListWidgetItem'
As far as I can tell any Qt object can be used as dict keys, just like any user-defined class instances.
I'm running PySide2 5.13.0, Python 3.6.4 on Windows 7. I get the same error on Ubuntu 18.04, Python 3.6.9, PySide 5.9.0a1.
Thanks for any hint.
I don't think it's a bug, it seems that you expecting QListWidgetItem to be hashhable but it seems that it wasn't designed for that. Why do you need a QListWidgetItem to be the key of a dictionary?
Because I want to associate informations to a set of QListWidgetItem in a dictionary, and easily retrieve these informations when I get a specific QListWidgetItem through a slot o via QListView.currentItem(). I already do this with QPushButtons and a lot of other Qt objects.
You are applying a pythonic solution to a framework that does not use the bases of python design so many python solutions will not work in Qt, Qt is a library that can work by itself, so it has alternatives for what you want as I propose in my answer .
QListWidgetItem (similar to QTableWidgetItem and QTreeWidgetItem) is not hashtable since a QListWidgetItem associated with a row can change without notification unlike QObjects such as QWidget, QPushButton, etc.
If your goal is to associate information with a QListWidgetItem then you can use the setData() and data() methods.
import sys
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QApplication, QListWidget, QListWidgetItem, QWidget
if __name__ == "__main__":
app = QApplication(sys.argv)
w = QListWidget()
for i in range(10):
it = QListWidgetItem("abc-{}".format(i))
it.setData(Qt.UserRole, "data-{}".format(i))
w.addItem(it)
def on_currentItemChanged():
current = w.currentItem()
print(current.data(Qt.UserRole))
w.currentItemChanged.connect(on_currentItemChanged)
w.show()
sys.exit(app.exec_())
| common-pile/stackexchange_filtered |
Android making a call with a predefined call duration
I am building an Android application that will automatically make calls and send SMSes to some telephone numbers.
The problem is I need to specify the duration (how long the call will last for) of all the calls.
Is there any way to specify the call duration from Java code? Or how do I cut the present outgoing call?
You may work on Java Runnables and then merge it with call and telephony API.
| common-pile/stackexchange_filtered |
Jar file and resource file returning null
I have a simple program that reads a text file (test.txt) line by line and prints each line to the console. In intellij it works just fine.
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
public class testing {
public static void main(String[] args) {
testing main= new testing();
main.handleData("test.txt");
// handleData();
//System.out.println("hello world");
}
public void handleData(String fileName) {
System.out.println("Testing");
File file= new File(getClass().getResource(fileName).getPath());
try {
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I am trying to build it with gradle and when i run the jar command java -jar out/artifacts/helloTestingWorld_jar/helloTestingWorld.jar I get an error saying the path is null
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.net.URL.getPath()" because the return value of "java.lang.Class.getResource(String)" is null
at testing.handleData(testing.java:22)
at testing.main(testing.java:12)
My build.gradle file looks like this
plugins {
id 'java'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}
jar {
manifest {
attributes "Main-Class": "src.main.java.testing"
}
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
}
test {
useJUnitPlatform()
}
My resource folder is marked as the resource root and my java folder that contains my main class is marked as the source root. I am thinking that I might have to add the text file as a dependency in the jar file?
I have had a look at all of the other suggestions on here and the all lead to the same result. I have tried rebuilding the project from scratch and still the same result.
I have also tried using InputStream instead of File
InputStream in = getClass().getResourceAsStream(fileName);
When I use InputStream I get this error
Exception in thread "main" java.lang.NullPointerException
at java.base/java.io.Reader.<init>(Reader.java:168)
at java.base/java.io.InputStreamReader.<init>(InputStreamReader.java:76)
at java.base/java.util.Scanner.<init>(Scanner.java:566)
at testing.handleData(test.java:23)
at testing.main(test.java:10)
Does this answer your question? Avoiding NullPointerException in Java
Does this answer your question? Loading files from Resource folder using java jar
You are not showing your jar file. It looks more like the build tool configuration file.
| common-pile/stackexchange_filtered |
Can't disable jqueryui button with knockoutjs in chrome
I have the following very simple code:
html
<a data-bind="enable: selected()" href="http://www.google.com">Click Me</a>
javascript
function pageViewModel() {
var self = this;
self.selected = ko.observable();
}
$(document).ready(function() {
$("a").button();
ko.applyBindings(new pageViewModel());
});
This works in IE9 but not in Chrome (i.e. the anchor tag is made to look like a disabled button in IE9 but in Chrome the tag looks like/IS an enabled button). I've also tried disabling the buttons by directly manipulating the css with the following binding:
<a data-bind="css: {ui-button-disabled: !selected(), ui-state-disabled: !selected()}">Click Me</a>
But apparently knockoutjs doesn't like the fact that the classes I'm using have the - in them.
So now I'm stuck. Does anyone have any ideas on how I can get this to work for both browsers using jqueryui and knockoutjs?
Thanks.
Issue was logged for knockout here: https://github.com/SteveSanderson/knockout/issues/692
You can enclose the class name in quotes:
<a data-bind="css: {'ui-button-disabled': !selected(), 'ui-state-disabled': !selected()}">Click Me</a>
A better approach, though, would be to use a custom binding that sets the button's disabled option:
ko.bindingHandlers.button = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
$(element).button();
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = ko.utils.unwrapObservable(valueAccessor()),
disabled = ko.utils.unwrapObservable(value.disabled);
$(element).button("option", "disabled", disabled);
}
};
You can then bind it like:
<a data-bind="button: { disabled: !selected() }">Click Me</a>
Thanks a MILLION! I haven't really explored custom bindings but I'll sure be looking into them after this! Awesome!
You're welcome. I recommend going to Ryan Niemeyer's site at http://www.knockmeout.net/ and reading his articles on custom bindings.
Instead of
<a data-bind="enable: selected()" href="http://www.google.com">Click Me</a>
try
<a data-bind="enable: selected" href="http://www.google.com">Click Me</a>
| common-pile/stackexchange_filtered |
Rails Form: Link to a named route rather than a url with query parameters
I have the following form:
<form action="<%= jobs_path %>" method="get" >
<%= label_tag 'l', "I'm looking for a job in"%>
<%= select_tag 'l',
options_for_select(Job.areas.keys.map {|area| area.humanize.titlecase}, :selected => params[:l]),
include_blank: "All Cities"
%>
and I'm interested in
<%= text_field_tag 'q', nil, :placeholder => "Major or Interest...", :value => params[:q] || "" , :class =>"query" %>
<%= submit_tag "Find Jobs", :name => nil, :class => "cta"%>
</form>
When you submit, this form currently creates links that look like http://localhost:3000/jobs?l=Boston&q=assistant.
But, I want the links to output like this:
http://localhost:3000/jobs/l-Boston-q-assistant
Right now, my routes.rb looks like this:
get "jobs/l-:l-q-:q", to: "jobs#index"
get "jobs/l-:l", to: "jobs#index"
get "jobs/q-:q", to: "jobs#index"
resources :jobs
This makes it so that links like http://localhost:3000/jobs/l-Boston-q-assistant do properly query, but if people use the search form on the page, it creates the query params version of the links.
How do I make it so that searches created with the form generate links like http://localhost:3000/jobs/l-Boston-q-assistant?
That seems very, em, unconventional.
U probably want onsubmit function build string l-Boston-q-assistant from submited form elements and have route something
get 'jobs/:params', to: 'photos#show', params: /[a-zA-Z-]*/
then set location to jobs/generated string
then on controller u can split params into corresponding values
| common-pile/stackexchange_filtered |
The diophantine equation $z^2=a^2+bx^2+cy^2$
Is there a way to obtain (enumerate) the integer solutions $(x,y,z)$ of the following quadratic Diophantine equation
$z^2=a^2+bx^2+cy^2$
where $a$ is an integer and $b, c$ are positive integers?
I have checked the literature on Diophantine equations but could not find anything useful. Any help or suggestions would be greatly appreciated.
Did you see Legendre's theorem
Of course you can solve it. The only cumbersome formula. And decisions are determined by Pell equations. For example for some simple cases, you can write. http://math.stackexchange.com/questions/351491/integral-solutions-of-hyperboloid-x2y2-z2-1/709219#709219 http://math.stackexchange.com/questions/298053/quadratic-diophantine-equations/710766#710766 http://math.stackexchange.com/questions/74931/integral-solutions-of-x2y21-z2/789972#789972
I think you can at first solve the well known equation $w^{2} + a^{2} = z^{2}$ for convenient values of a and go after to the equation $w^2 = bx^2 + cy^2$ which is solved in the book of L. J. Mordell “Diophantine Equations” (Academic Press. London and New York, 1969 page 44).
We have at least two, $(0,0,a)$ and $(0,0,-a).$
We have infinitely many solutions to
$$ b x^2 + c y^2 - z^2 = -a^2. $$
It is possible, however, that no solutions need be primitive: under some choices of $a$ it may be that all solutions have $x,y,z$ all divisible by $a.$ An early example of this (not quite the pattern your form takes) is due to C. L. Siegel, see pages 168 and 253 in CASSELS.
Actually, an easy example is given by
$$ 3 x^2 + 3 y^2 - z^2 = -9. $$
We see immediately that $z^2$ is divisible by $3,$ therefore $z$ is divisible by $3.$ As a result, $3x^2 + 3 y^2$ is divisible by $9,$ so that $x^2 + y^2$ is divisible by $3.$ Since Legendre symbol $(-1|3) = -1,$ we see that $x,y$ are also both divisible by $3.$
Find a solution ( the smallest one with $u,v > 0$ is best) to $u^2 - b v^2 = 1.$
We can now replace any of the solutions we have found so far with
$$(x,y,z) \mapsto (ux+vz,y, bvx+uz). $$
Find a solution ( the smallest one with $p,q > 0$ is best) to $p^2 - c q^2 = 1.$
We can replace any of the solutions we have found so far with
$$(x,y,z) \mapsto (x,py+qz, cqy+pz). $$
| common-pile/stackexchange_filtered |
Laravel Dompdf two column Layout
I am not getting pdf content in column wise. What i want is to show the content in two column layout using dompdf laravel.The HTML which i am using is working fine in first page only not on all pages.
Please add your html and any css files to your question, it's not possible to help without them. Please read the help section on How to create a Minimal, Reproducible Example
Without seeing your HTML and CSS it's hard to diagnose the problem, but it might be if your column has a row which spans a page break.
In the [Limitations][1] section of the readme it says
Table cells are not pageable, meaning a table row must fit on a single
page.
Make sure your table cells are on one page.
Hello thanks, That problem is solved. Actually problem was column count was not working with pdf so Column tag help me.
Use this for pdf
.row{ clear: both; }
.col-lg-1 {width:8%; float:left;}
.col-lg-2 {width:16%; float:left;}
.col-lg-3 {width:25%; float:left;}
.col-lg-4 {width:33%; float:left;}
.col-lg-5 {width:42%; float:left;}
.col-lg-6 {width:50%; float:left;}
.col-lg-7 {width:58%; float:left;}
.col-lg-8 {width:66%; float:left;}
.col-lg-9 {width:75%; float:left;}
.col-lg-10{width:83%; float:left;}
.col-lg-11{width:92%; float:left;}
.col-lg-12{width:100%; float:left;}
| common-pile/stackexchange_filtered |
UnauthorizedAccessException: Access to the path when saving unity data to a file
I have a inventory system which is saved in a file and loaded from the same file when its needed. The problem is that the loading system works perfectly on start but when i press the save and exit button, which is supposed to save the inventory and load the main menu scene, it throws a UnauthorizedAccessException: Access to the path exception, even though the file is not set to read-only and the savePath is the same for both loading and saving:
public void Load()
{
if (File.Exists(string.Concat(Application.persistentDataPath, savePath)))
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(string.Concat(Application.persistentDataPath, savePath), FileMode.Open, FileAccess.Read);
Inventory newContainer = (Inventory)formatter.Deserialize(stream);
for (int i = 0; i < container.items.Length; i++)
{
container.items[i].UpdateSlot(newContainer.items[i].item, newContainer.items[i].amount);
}
stream.Close();
}
}
The start function:
private void Start()
{
LoadInventory();
}
private void LoadInventory()
{
inventory.Load();
equipment.Load();
}
The save funtion:
public void Save()
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(string.Concat(Application.persistentDataPath, savePath), FileMode.Create, FileAccess.Write);
formatter.Serialize(stream, container);
stream.Close();
}
And where the save function is called. When building the game the SceneManager.LoadScene(0); line doesn't run:
public void SaveAndExit()
{
Time.timeScale = prevTimeScale;
SaveInventory();
SceneManager.LoadScene(0);
}
private void SaveInventory()
{
inventory.Save();
equipment.Save();
}
The savePath value in the inspector
And the strange thing is that if i build the game the inventory loads correctly from file and if i try to save and exit, the game throws an error however the data is still saved correctly on the file. I feel like i am missing something here that is quite obvious. If you need anymore info please feel free to ask.
What is savePaths value?
I will edit it into the post
Does this answer your question? Why is access to the path denied?
Thanks for the answer, however it doesn't appear to solve the problem. At first I searched the error on google and this popped up.
Can you call File.WriteAllText with a dummy "Hello world" text at that path? And can you try a save path without leading path separator char?
In general you should use Path.Combine and remove that / .. Path.Combine will automatically fill in the correct path separator used by the according file system
@derHugo I tried using Path.Combine however it throws the same error and i removed the / in the inspector.
Btw i should metion that the error occurs in the save() function at the Stream stream line
@yasirkula it does work to write at the save path with and without the /
Oh in general STOP using BinaryFormatter at all! .. and then what is your target platform?
@derHugo my target is windows pc, what should i use insted of the binaryFormatter, sorry i am new to the c# IO System. Currently i am just trying to store my container variable which is a Inventory class instance which has a array of inventorySlots. This is the setup which i followed in the tutorial.
If File.WriteAllText did work, then File.WriteAllBytes will probably work, too. I'd recommend you to compare your Stream with File.WriteAllBytes' stream: https://github.com/microsoft/referencesource/blob/5697c29004a34d80acdaf5742d7e699022c64ecd/mscorlib/system/io/file.cs#L978-L982 P.S. I use BinaryFormatter for my save files on Android/iOS and haven't encountered any issues. But if syncing save file with a server is a necessity, then BinaryFormatter may not be preferable for security reasons.
| common-pile/stackexchange_filtered |
IBM Bluemix push notification through PHP code
I am new with IBM Bluemix and I want to add PHP code for sending push notifications on both iOS and Android devices.
My app is built with the Xamarin platform for both type of mobile devices.
The backend is created in PHP with the Codeigneter framework.
I see in the Dashboard there is direct user interface for sending a push in Bluemix, but I want to send a Push on run-time for example: some user sending a friend request and the other user automatically receiving a push notification.
There is not a PHP SDK library, but you could accomplish your behavior by checking out the Push Notifications Swagger documentation:
https://mobile.ng.bluemix.net/imfpushrestapidocs/
First you would register your mobile app so it receives push notifications (using the Android or iOS Client SDKs available here). Then you could have your backend send the push notification to a specific device on the event that a friend request is sent by using the REST API (as outlined in the Swagger docs).
I don t understand your answer please tell me there is any php code or library for sending push notification or not.
You can use any HTTP request library to send a Push Notification in PHP.
After you register the device for Push Notifications using the Client SDK, try sending a Push Notification from the Swagger Docs. If this works, convert this POST request into PHP code, and then your PHP backend will be able to send the notification.
| common-pile/stackexchange_filtered |
Why do I continuously get errors when trying to use quiver using data from a NetCDF file?
I have been trying different methods found online, and even made a ton of alters but I cannot get quiver to work correctly. This is leading to lots of different errors that I am having a hard time solving. I used the following data: https://downloads.psl.noaa.gov/Datasets/NARR/monolevel/ and downloaded uwnd.10m.2016.nc and vwnd.10m.2016.nc to create the quivers.
Here is one of the methods I tried and the image I get is attached:
uwnd = xr.open_dataset('uwnd.10m.2015.nc').sel(time='2016-09-18')
vwnd = xr.open_dataset('vwnd.10m.2015.nc').sel(time='2016-09-18')
X = uwnd.x; Y = uwnd.y
U = uwnd.uwnd; V = vwnd, vwnd
ax = plt.axes(projection=ccrs.PlateCarree())
ax.quiver(X[::3],Y[::3],U[::3],V[::3], color='green')
ax.set_extent([-125, -70, 20,55])
ax.coastlines()
ax.add_feature(cartopy.feature.BORDERS, linestyle='-', alpha=1)
ax.add_feature(cfeature.STATES.with_scale('50m'))
ax.add_feature(cfeature.RIVERS)
plt.show()
Quiver Map after adding code
| common-pile/stackexchange_filtered |
Why Is My Github Pages Custom Domain Constantly Reset?
I go into the page in Github (https://github.com/user/repo/settings/pages) and set a custom domain. It works great!
However, every time I deploy (using the gh-pages npm package) it resets the domain back to
https://user.github.io/repo
This is incredibly frustrating... how can I tell it to use my custom domain permanently?
It looks like there are reports about this in the repo for gh-pages npm package. See #347, #236, #370, #213.
There is even a still opened merged pull-request that tackles the issue through documentation.
Basically, it says:
Modify the deployment line to your deploy script if you use custom domain. This will prevent deployment to remove the domain from settings in github.
echo 'your_cutom_domain.online' > ./build/CNAME && gh-pages -d build"
Edit: there are other options as well, some people directly change their deployment call and add a custom domain to their deployment scritpt:
var ghpages = require('gh-pages');
var fs = require('fs');
fs.writeFile('dist/CNAME', "your-custom-domain.com", function(err) {});
ghpages.publish('dist', function(err) {});
others just follow the advice for putting CNAME to your publishing folder.
I got confused with the quotation mark around the domain name. Actually, it was not required.
"deploy": "echo domain.com > ./build/CNAME && gh-pages -d build"
For my React static site I have to add below scripts to the package.json to add the CNAME file with the custom domain to the build/ dir before each deployment.
"scripts": {
"build": "react-scripts build",
"add-domain": "echo \"myAwesomeDomain.org\" > build/CNAME",
"deploy": "npm run add-domain && gh-pages -d build",
"bd": "npm run build && npm run deploy",
},
I had to remove the quotes around my domain name for this to work correctly for me. Thanks for the scripts though. They were quite helpful
For those of you using the GitHub Action crazy-max/ghaction-github-pages there is a setting called fqdn that you're looking for. Set that with the custom domain and it stop breaking every deploy.
See documentation here.
Thanks, I just checked and the action I use - peaceiris/actions-gh-pages@v3 - has an analogous cname setting.
I was having the same problem for a gatsby site, I needed to install the gatsby-plugin-cname package and add the following to the gatsby-config.js
module.exports = {
siteMetadata: {
siteUrl: 'http://custom-domain.com/'
},
plugins: [
'gatsby-plugin-cname'
],
}
https://www.gatsbyjs.com/plugins/gatsby-plugin-cname/
If you are using "npm run deploy" or any npm deployment scripts
Add a CNAME.txt file in public your Directory
In the 1st line enter your custom domain name in it. e.g. (acbd.com)
else
Create and Add the same in you static Directory
Deploy and check
| common-pile/stackexchange_filtered |
Storage on a dual Mac and Windows system
If I have Windows 10 on my MacBook Air. I have 60 GB left on my Windows volume, and I have 100 GB on my Mac volume. Could I use an external hard drive to extend my Windows-accessible storage?
You can certainly mount an external hard drive when running Windows, but "extending" your Windows volume is only possible by re-partitioning your existing drive and reallocating space from the Mac portion.
Alternately, you could install a larger drive within your MacBook Air, partition to your liking then copy your data back.
| common-pile/stackexchange_filtered |
CyberArk with Azure DevOps to Use Secrets in YAML Pipelines: High-level steps for beginners
I'm new to CyberArk and have a requirement to integrate it with Azure DevOps for securely managing and accessing secrets in my CI/CD pipelines. I am familiar with Azure DevOps, but not with CyberArk, so I'm looking for high-level guidance on how to start and complete this integration.
Here are my questions:
What are the initial steps required in CyberArk to prepare it for integration with Azure DevOps? For example, how do I define and load policies to authenticate Azure DevOps as a trusted workload?
Access Management: How should I grant specific Azure DevOps tasks or pipelines access to CyberArk secrets? Are there recommended policies or roles that I need to configure in CyberArk for this purpose?
Pipeline Configuration: Once CyberArk is configured, what are the best practices for accessing secrets from CyberArk within an Azure DevOps YAML pipeline? Are there specific tasks, scripts, or API calls that can be used to fetch secrets at runtime?
Parameterization: I understand that parameters like safeName and accountName might need to be referenced in the pipeline configuration. How can I ensure these are securely managed and referenced in my YAML files?
End-to-end flow: could you provide a high-level overview of the entire flow—from configuring CyberArk to retrieving secrets in Azure DevOps pipelines?
We have option of using CyberArk extension in Azure DevOps
I have gone through this document but not much clear on where to start as they have not provided any detail about extension usage.
Please provide the high level steps so that I can integrate CyberArk with Azure Devops.
note:
we use safe method to fetch secrets not conjur service connector method
About the Parameterization question, you can use Azure DevOps secret variables or secure files to manage parameters like safeName and accountName. By the way, you can visit the CyberArk Technical Community to get more support about CyberArk.
Looks like i can not use CyberArk tech forum with gmail credentials as a learner
Hi @kumar, yes, it seems that when we registered as a Learner, allowing read-only access. If you have a customer account, you can participate in the community.
| common-pile/stackexchange_filtered |
How do I add a custom dll to an azure dev ops pipeline from a private repository?
I'm new to Azure Dev Ops and I'm trying to create a pipeline for my project. The project is originally in subversion and relies on a few custom downloadable libraries that my company maintains. I'm trying to add these custom dlls to the build process so the nuget restore command will be successful. The dlls are located in a "packages" repository in the source repo. How can I add these dlls to the build pipeline? Any help would be appreciated!
How do I add a custom dll to an azure dev ops pipeline from a private
repository?
There's several directions for your requirement. According to your description, these are dlls instead of nuget packages. Here're two ways I like:
1.If you're familiar with nuget, you can create nuget packages for those dlls. Then publish the nuget package to the Azure Devops nuget feed. After that you can use Nuget Restore Task easily to restore those packages:
Prerequisite: Your project should use nuget package way to manage the dlls, it means you need to edit the project's project file. Your project should reference the nuget packages in csproj instead of referencing the dlls directly using hintpath ...
Advantage: Nuget is common tool to manage dlls when you're working in .net core. And azure devops Feed supports private feed, so no one can access your feed until you grant access to them.
Disadvantage: You have to do some jobs about packing/publishing dlls and editing the project file (xx.xxproj).
2.If your team insists on using single dlls instead packing them into nuget packages, then you don't need to worry about nuget restore step. All you need to make sure is the build step can find the missing assemblies.
For example, in local machine my project relies on one assembly in windows desktop. Then its xx.csproj has:
<Reference Include="ClassLibrary1">
<HintPath>..\..\..\..\Desktop\ClassLibrary1.dll</HintPath>
</Reference>
It's obvious that it would fail if I deploy it to Azure Devops, cause the pipeline won't find the same path. For this issue, my idea is to create an empty Dlls folder in project directory, add the folder into source control. Also, edit the HintPath in project file to be <HintPath>Dlls\ClassLibrary1.dll</HintPath>
Now in devops pipeline, I can add a git task or cmd task that runs git commands to download your assemblies from private repos. Then a command-line task to copy the assemblies to the Dlls folder under System.DefaultWorkingDirectory. Finally, the build process can also succeed.
I just shows two directions for your scenario, there actually exists other directions. Among them, I strongly recommend nuget packages+Azure Devops Feed way cause it's more convenient after configuring them well. Hope all above helps.
I too have a similar requirement where I wish to add a custom dll into Azure devops pipeline and I use Azure repository only but despite creating a dll folder in project directory and editing the HintPath as you mentioned still the build fails saying the type or namespace couldn't be found
If you are saying that your repository contains some dll's needed to build the app, you have an issue not with nuget restore. Nuget restore simply download linked nuget packages. And in your case you need to get dll's to build the app. You can use multi repo approach and get your subversion repo alongside with new one. Or you can use script step and there call directly svn command line to get just specific folders (and files needed for your build). Since both windows and ubuntu host agents have svn installed you are half way home. Please keep in mind that you need to get your dll's to proper folder so MSBuild can find them at build.
Another approach is to create nuget packages for those dll's and then keep them in Azure Feed. Then change references in your projects so they will be dependent on nuget package and not dll files directly.
| common-pile/stackexchange_filtered |
Redis 10x more memory usage than data
I am trying to store a wordlist in redis. The performance is great.
My approach is of making a set called "words" and adding each new word via 'sadd'.
When adding a file thats 15.9 MB and contains about a million words, the redis-server process consumes 160 MB of ram. How come I am using 10x the memory, is there any better way of approaching this problem?
Well this is expected of any efficient data storage: the words have to be indexed in memory in a dynamic data structure of cells linked by pointers. Size of the structure metadata, pointers and memory allocator internal fragmentation is the reason why the data take much more memory than a corresponding flat file.
A Redis set is implemented as a hash table. This includes:
an array of pointers growing geometrically (powers of two)
a second array may be required when incremental rehashing is active
single-linked list cells representing the entries in the hash table (3 pointers, 24 bytes per entry)
Redis object wrappers (one per value) (16 bytes per entry)
actual data themselves (each of them prefixed by 8 bytes for size and capacity)
All the above sizes are given for the 64 bits implementation. Accounting for the memory allocator overhead, it results in Redis taking at least 64 bytes per set item (on top of the data) for a recent version of Redis using the jemalloc allocator (>= 2.4)
Redis provides memory optimizations for some data types, but they do not cover sets of strings. If you really need to optimize memory consumption of sets, there are tricks you can use though. I would not do this for just 160 MB of RAM, but should you have larger data, here is what you can do.
If you do not need the union, intersection, difference capabilities of sets, then you may store your words in hash objects. The benefit is hash objects can be optimized automatically by Redis using zipmap if they are small enough. The zipmap mechanism has been replaced by ziplist in Redis >= 2.6, but the idea is the same: using a serialized data structure which can fit in the CPU caches to get both performance and a compact memory footprint.
To guarantee the hash objects are small enough, the data could be distributed according to some hashing mechanism. Assuming you need to store 1M items, adding a word could be implemented in the following way:
hash it modulo 10000 (done on client side)
HMSET words:[hashnum] [word] 1
Instead of storing:
words => set{ hi, hello, greetings, howdy, bonjour, salut, ... }
you can store:
words:H1 => map{ hi:1, greetings:1, bonjour:1, ... }
words:H2 => map{ hello:1, howdy:1, salut:1, ... }
...
To retrieve or check the existence of a word, it is the same (hash it and use HGET or HEXISTS).
With this strategy, significant memory saving can be done provided the modulo of the hash is
chosen according to the zipmap configuration (or ziplist for Redis >= 2.6):
# Hashes are encoded in a special way (much more memory efficient) when they
# have at max a given number of elements, and the biggest element does not
# exceed a given threshold. You can configure this limits with the following
# configuration directives.
hash-max-zipmap-entries 512
hash-max-zipmap-value 64
Beware: the name of these parameters have changed with Redis >= 2.6.
Here, modulo 10000 for 1M items means 100 items per hash objects, which will guarantee that all of them are stored as zipmaps/ziplists.
Fascinating and detailed answer; I didn't know that. Thanks @Didier !
Alright thanks a lot i am pretty positive that this will solve my problems. And yeah for 160mb its fine but i am expecting to work with up to 1gb of plain word data and didn't want that to spike to 10gb. Thanks a lot again, appreciate the detailed answer.
@Didier - Great answer! Couple of corrections though a) Hashtable entries are a single linked list, not double, 24 bytes overhead is correct though b) Redis object wrapper does not apply to each set/hash entries. It only applies to the top level key/value pair - so that overhead is constant c) You may want to indicate that zipmap is deprecated in 2.6/unstable, and that ziplist does the equivalent thing.
@SripathiKrishnan - thanks, I have updated my answer. I still think that robj usage applies to all set keys though. I refer to the setDictType structure in redis.c and the corresponding functions, which define this behavior.
@DidierSpezia - re. robj usage : yes, you are right. Dunno how I overlooked that wrapper!
One caveat/correction "Here, modulo 10000 for 1M items means 100 items per hash objects, which will guarantee that all of them are stored as zipmaps/ziplists." ... Yet above that you give an example of hashing the words, the modulo them by 10000. It won't evenly generate 100 items per hash bucket. Basically, some hashes, under some keys, will easily have more than 100 entries in them, due to how random hash codes distribute. Best to set hash-max-zipmap-entries well above 100.
Instead of storing:
words => set{ hi, hello, greetings, howdy, bonjour, salut, ... }
you can store:
words:H1 => map{ hi:1, greetings:1, bonjour:1, ... }
words:H2 => map{ hello:1, howdy:1, salut:1, ... }
Cloud you explain more detail how to you do that?. Thank you so much @DidierSpezia
As for my experiments, It is better to store your data inside a hash table/dictionary . the best ever case I reached after a lot of benchmarking is to store inside your hashtable data entries that are not exceeding 500 keys.
I tried standard string set/get, for 1 million keys/values, the size was 79 MB. It is very huge in case if you have big numbers like 100 millions which will use around 8 GB.
I tried hashes to store the same data, for the same million keys/values, the size was increasingly small 16 MB.
Have a try in case if anybody needs the benchmarking code, drop me a mail
How did you perform those measurements? Thanks
Did you try persisting the database (BGSAVE for example), shutting the server down and getting it back up? Due to fragmentation behavior, when it comes back up and populates its data from the saved RDB file, it might take less memory.
Also: What version of Redis to you work with? Have a look at this blog post - it says that fragmentation has partially solved as of version 2.4.
| common-pile/stackexchange_filtered |
What case follows "fond of"?
What case is "I am fond of her"? Dative or possessive? My thought is that this form comes from the Anglo-Saxon, which is still heard in German, for example "ich bin derren bewusst" (I am hers aware) or "ihret wegen" (hers because).
Wouldn't grammatical case be associated with the 'noun' (noun/pronoun/etc) rather than the verb?
When I Google Dative or possessive all I get is a shedload of results about German. I don't think this is a meaningful concept in English today.
There's no case here. "Of" is not a genitive case marker, thus "of her" is simply a complement of the verb. It's no different to "I am fond of fish".
My fingers won't stop... If you're too possessive, you may not get another dative, however fond of her you are.
English nouns do not have case. Only a few English personal pronouns. In any event, (be) fond (of) is a (transitive) predicate adjective, not a noun.
I think it is the "of her" that the OP is asking about.
Modern English doesn't have any morphological distinction between a "dative"-case form and the "accusative"-case form. Because of this, the concept of a particular construction or preposition governing the "dative" case (as opposed to the accusative case) doesn't make sense in English the way it does in German. (The word "dative" is sometimes used when talking about English syntax or semantics: e.g. the term "dative alternation" or "dative shift".)
"I am fond of her" clearly does not contain the possessive pronoun "her" that is found in a phrase like "her book", because we don't say things like "She is fond of my" or "I am fond of his": we would say "She is fond of me" and "I am fond of him".
It's accusative case.
You don't say "I am fond of she" (nominative) or "I am fond of hers" (possessive)
I am fond of her
is like
We are angry at them.
or
You are unsure about us.
following the pattern 'NounPhrase ToBE ADJ PrepositionalPhrase'. Not all adjectives work, and each adjective has it's own idiosyncratic preposition, but whatever the preposition, if the object is a pronoun, it will be in accusative case.
Prepositions in English take accusative case and this only really shows up in pronouns. 'above me', 'next to him' , 'among us', 'of her'. English doesn't have a dative case. Old English (or Old Anglo-Saxon) had a lot more cases, very similar to Old German which did not lose its cases. In older Germanic languages, some prepositions took accusative, mostly dative, and a few genitive (what is called possessive in English).
| common-pile/stackexchange_filtered |
How to specify a fixed job name for jobs submitted by qsub
I use -N option to specify the name for the job when submitting through qsub. The qsub, however, adds some numeric string after thejob name as described in the man page:
By default the file name for standard output has the
form job_name.ojob_id and job_name.ojob_id.task_id for
array job tasks (see -t option below).
Therefore, whenever I submit a new job with same job name, a new suffix .ojob_id is added to the job name and a new output file is created.
What I trying to achieve is to have same output file each time a job is submitted through qsub. How can I do that? I have to run a job several time and I want the output from a run to overwrite the output file generated in the previous run. How can I achieve that?
See the example below:
First time command is given to run script hello_world to output in log_hello_world:
qsub -cwd -N log_hello_world hello_world.sh
It creates two output files:
log_hello_world.e7584345
log_hello_world.o7584345
Second time the same command is given: It creates two more output files
log_hello_world.e7584366
log_hello_world.o7584366
What can I do to get the output in just one file log_hello_world.
I was able to resolve this issue by using options -o and -e to save the log and the error files respectively. With these options, the log and the errors from the job are written into same file every time from this command.
qsub -cwd -N job_hello_world -o log.hello_world -e error.hello_world hello_world.sh
You should append a file with a fixed name. This is done in the code which you run. You create a file in your directory, and then append it with the new results each time you run your code. So in your code (not in the qsub line), explicitly add a line of code which asks the results to be written to a file in your directory, in Mathematica this would be
str = OpenAppend["/home/my_name/Scratch/results.dat"];
Write[str,results];
Close[str];
Where results is a variable which contains the results of your computation. Then just run the job using qsub -N log_hello_world hello_world.sh. This will write the results to the same file every time you run the job without changing the name of the file.
(If you're looking to write both -o and -e files to the same file, you can just add -j y to the qsub after having specified the file path for the error file)
| common-pile/stackexchange_filtered |
C: Fifo between threads, writing and reading strings
Hello once more dear internet,
I am writing a small program that, among other things, writes to a log file all of the commands it received.
To do that, I want to use a thread that will only attempt to read from a pipe, while the main thread will write into that pipe whenever it should.
Since I don't know the length of each string command, I thought about writing and reading the pointer to the char buf[MAX_MESSAGE_LEN].
Since what I’ve tried so far doesn't work, I’ll post my best effort :P
char str[] = "hello log thread 123456789 10 11 12 13 14 15 16 17 18 19\n";
if (pipe(pipe_fd) != 0)
return -1;
pthread_t log_thread;
pthread_create(&log_thread,NULL, log_thread_start, argv[2]);
success_write = 0;
do {
write(pipe_fd[1],(void*)&str,sizeof(char*));
} while (success_write < sizeof(char*));
and the thread does this:
char buffer[MAX_MSGLEN];
int success_read;
success_read = 0;
//while(1) {
do {
success_read += read(pipe_fd[0],(void*)&buffer, sizeof(char*));
} while (success_read < sizeof(char*));
//}
printf("%s",buffer);
(Sorry if this doesn't indent, I can't seem to figure out this editor...)
oh, and pipe_fd[2] is a global parameter.
So, any help with this, either by the way I thought of, or another way I could read strings without knowing the length, would be much appreciated.
On a side note, I’m working on Eclipse IDE C/C++, version 1.2.1 and I can't seem to set up the compiler so it will link the pthread library to my project. I've resorted to writing my own Makefile to make it (pun intended :P) work. Anyone knows how to fix the link issue? I’ve looked online, but all I find are solutions that are probably good on an older version because the tabs and option keys are different.
Anyways, Thanks a bunch internet!
Yonatan
fixed your indention, use the code button while highlighting larger blocks of code. the `` syntax is for inline code.
Seems to me like if you just happened to read or write a little too much, then your code would terminate. You should have, while success_read < MAX_MSGLEN or sizeof(str).
You are not updating success_write in the loop.
Why do you read and write data by chunks of sizeof(char*) bytes that is 4 or 8 bytes? You are not forced to read and write by the same number of bytes!
If your problem is that you do not receive data in the reading thread, you should think about syncing after the write, using sync().
No, fflush() is for flushing stdio buffers. He's using read() and write() directly, which bypass stdio.
Do you really need an extra thread for this? As you're finding, adding threads increases complexity a lot... in this case, writing to the pipe is not likely to be much faster than writing to the file - and in fact, it may well end up being slower in practice, since write() doesn't have the buffering that fprintf() and friends do. The best solution may be simply to write to the logfile directly...
Have you tried socketpair(AF_UNIX,SOCK_DGRAM)? It is reliable by its nature and also would delimit messages for you.
In your case, you have to make sure that MAX_MESSAGE_LEN is less than PIPE_BUF, the platform's limit for pipe()'s internal buffer.
And obviously, change sending/recving of pointer into sending of the actual string, e.g.:
- char str[] = "hello log thread 123456789 10 11 12 13 14 15 16 17 18 19\n";
+ char str[MAX_MESSAGE_LEN] = "hello log thread 123456789 10 11 12 13 14 15 16 17 18 19\n";
- write(pipe_fd[1],(void*)&str,sizeof(char*));
+ write(pipe_fd[1],(void*)&str,MAX_MESSAGE_LEN);
So, any help with this, either by the way i thought of, or another way i could read strings without knowing the length, would be much appreciated.
You could create a simple protocol to communicate over the FIFO/pipe. The writer thread writes a single byte to the FIFO to indicate the message length and then writes the variable length message. The reader will read a single byte to learn the length of the message and then issue a subsequent read command for the specified message length.
You may want to check out this answer to a similar question on FIFOs for more details.
| common-pile/stackexchange_filtered |
Show that the polynomial $x^{8}-x^{7}+x^{2}-x+15$ has no real root.
Show that the polynomial $$x^{8}-x^{7}+x^{2}-x+15$$ has no real root.
Source
As I have learnt from my previous post,
using Descarte's Sign rule I am getting $4$ positive and $0$ negative roots.
So no of nonreal roots are $N-(p+q) = 8-(4+0)= 4$.So rest $4$ roots must be real! It is violating the question's condition.Can anybody help me out! I am not understanding the derivative concept regarding this!
Descarte's rule of signs does not tell you there are $4$ positive roots. It only says there are an even number of positive roots, and there are at most $4$. As the answers show, your objective here is rather to show that this function cannot be zero for real $x$.
https://math.stackexchange.com/questions/2487480/show-that-the-polynomial-x8-x7x2-x15-has-no-real-root?rq=1 I guess this helps!
Does this answer your question? Show that the polynomial $x^8 -x^7+x^2-x+15$ has no real root
If $x<0$ every term is positive, hence the polynomial is $>0$.
If $x>1$ , then $x^2-x>0$ , $x^8 - x^7 >0$ , $15>0$ hence the function is $>0$.
If $0<x<1$, then $1-x>0$ , $x^2 - x^6>0$, $14+x^8>0$ hence the function is $>0$
Hence for every real $x$ the function is $>0$ , hence no real root.
One suggestion for this post (and possibly others): try to implement different phrases. In this post alone, you’ve used the word “hence” 5 times in 4 sentences. Just a tip to keep in mind while writing :)
@Clayton, on the contrary. In mathematical writing similar content is better expressed in similar form. See for instance https://books.google.com/books?id=EYHFObaUIdIC&pg=PA52&lpg=PA52&dq=mathematical+writing+parallel+phrases&source=bl&ots=i0OQfW3lg2&sig=ACfU3U3VfRrkDUJAgjU8OwzEJJQBmUIc_w&hl=en&sa=X&redir_esc=y#v=onepage&q=mathematical%20writing%20parallel%20phrases&f=false
Descarte's Sign rule is saying that you can have $4$,$2$ or $0$ positive real roots. The change of sign is giving the upper limit to the number of real roots not the exact value.
So it is not really helpful in deciding if there are no real roots at all. You would still have to argue that the polynomial has no negative evaluation at all.
So, it is very easy to see that this polynomial is always positive. For $|x|>1$ it is always $x^{2n}-x^{n} > 0$, because it is the same as $x^{2n} > x^{n}$, and this covers two parts of it. For $|x| \leq 1$, the sum $|x^{8}-x^{7}+x^{2}-x^{1}|$ cannot exceed $15$ as it is $4$ at worst.
The polynomial is then positive all the time.
$f(x)=x^8-x^7+x^2-x+15$ has atmost $4$ positive real roots due to $4$ sign changes in its coefficients.
$f(-x)=x^8+x^7+x^2+x+15$ has no sign changes so no negative real root.
(using Descartes rule of signs)
Further, $f(x)=(x-1)(x^7+x)+15$ and observe that $f(x)>0$ for all $x>0$ so there will be no positive root in $(0,\infty)$.
| common-pile/stackexchange_filtered |
Is the site for cubical sets with connections equivalent to a full subcategory of posets?
Cubical sets with connection form a presheaf category on some category $C$. Is $C$ just the full subcategory of the category of posets whose objects are products of the interval $\Delta[1]$?
No. Cubical sets with or without connections do not have diagonals. That is, there is no map $\square^1 \to \square^2$ which maps $0$ to $(0,0)$ and $1$ to $(1,1)$.
| common-pile/stackexchange_filtered |
How to use Criteria all in querying mongoDb in java?
I am using MongoDB for my spring-boot application. I need to find the list of documents corresponding to list of IDs.
I have a Role collection and a list called roleIdList. This list (roleIdList) contains all the role ids whose documents needs to be fetched.
Below is my query:
// My roleIdList is of type List<ObjectId>. I also tried with List<String>
Query query = Query.query(where("_id").all(roleIdList));
List<RolesEntity> rolesEntityList = mongoOperations.find(query, RolesEntity.class);
But with the above query, I am getting empty rolesEntityList. Can anyone please help me.
Thanks in advance!
Use in instead of all
Query query = Query.query(where("_id").in(roleIdList));
See:
https://docs.mongodb.com/manual/reference/operator/query/all/
https://docs.mongodb.com/manual/reference/operator/query/in/
you can also use: List<RolesEntity> findByRole_IdIn(List<String> roleIdList)
| common-pile/stackexchange_filtered |
EF mapping question
Lets say I have the following classes:
public class User
{
public int UserId { get;set;}
public string Firstname { get;set;}
public Interests Interests { get;set;}
}
public class Interests
{
public IList<Team> FavoriteTeams { get;set;}
public IList<Food> FavoriteFoods { get;set;}
}
public class Team{
public int TeamId { get;set;}
public string City {get;set;}
public string Name { get;;set;}
}
public class Food{
public int FoodId { get;set;}
public string FoodName { get;set;}
}
At the database level I would like to have the following tables:
Users
Teams
Foods
UserTeams
UserFoods
Basically I would like to have the Interests property of the user entity but not have a seperate table for it.
I am using EF 4.1 code first POCO classes. I know the easiest thing to do is put the Teams and Food collection as a property on the User, which is ok, but from the object model point of view I would like it be be its own property. Any idea of how I would acheive this type of mapping?
I would say: The mapping you are looking for is not possible, because:
If you don't want the class Interests to be mapped to a table, it must not be an entity and the Interests property in your User class must not be a navigation property. To avoid that EF interprets the Interests property as a navigation property, you would only have two options:
Mark it as NotMapped -> Does not help because you would lose the relationship from User to Team and Food completely
Mark the Interests class as ComplexType -> Not possible in your example because complex types are not allowed to contain navigation properties.
That's just from my level of understanding. It's not unlikely that I overlooked another option.
It's too bad that EF doesn't support navigation properties on complex types, something competing frameworks have supported since the beginning of time. I wish I could say I'm surprised...
| common-pile/stackexchange_filtered |
PDF files come up blank in Document Viewer
When I try to open PDF files mostly they just come up blank. This is in the thumbnails and in the document viewer. Some will show the documents first page, but not the rest of the pages. Running 14.04 LTS Thanks.
Please edit your question to include a download link for one of these blank PDF files so we can make sure this is not a problem with the PDF file itself.
| common-pile/stackexchange_filtered |
How to write the date of an event that lasts a few days
What is the correct way to write, in American English, that something will happen over a date range?
The event will take place through July 1-10, 2011?
The event will take place from July 1 to July 10, 2011?
The event will take place starting on July 1 through July 10, 2011?
Any other suggestions are welcome.
1 no, 2 yes, 3 no.
Number 3 also sort of works though.
To add a contending opinion, I find this perfectly fine:
The event will take place July 1-10, 2011
I would pronounce the relevant portion "July 1st through 10th" or "July 1st through the 10th."
I like this version, it's more succinct.
I was going to offer my own version, but realized we're talking about writing the date range, in which case this is what I'd use.
I would prefer this:
The event will take place on July 1 to July 10, 2011.
The event will take place on July 1 through July 10, 2011.
The choice of the second preposition here is debatable, but I judge that both of them are correct.
However, your second example is also acceptable:
The event will take place from July 1 to July 10, 2011.
Here only to works as the second preposition. The first and third options that you gave sound very unnatural.
| common-pile/stackexchange_filtered |
Ratio test implies Raabe's test
I want to prove the ratio test
$$\lim \sup \left| \frac{a_{n+1}}{a_n} \right|<1$$
implies the Raabe's test
$$\lim \sup \left| \frac{a_{n}}{a_{n+1}} \right|>1 + \frac{C}{n}$$
for $C>1$
I am doing the following:
$$\lim \sup \left( \left| \frac{a_{n}}{a_{n+1}} \right|-1\right)n>C$$
$$ \left(\left| \frac{a_{n}}{a_{n+1}}\right|-1\right)n >p+\frac{p(p-1)}{2n} + \dots$$
$$\left| \frac{a_{n}}{a_{n+1}}\right| > 1 + \frac{p}{n}+\frac{p(p-1)}{2n^2} + \dots$$
$$\left| \frac{a_{n}}{a_{n+1}}\right| > \left( \frac{n+1}{n} \right)^p >1$$
since $\sum \frac{1}{n^p}$ converges if $p>1$ then by the ratio test it will converge if the fraction is $>1$. Therefore the Raabe's test gives convergence.
Is this correct?
What you have given as Raabe's test is not correct. Raabe's direct test states that defining
$C_n = n(a_n/a_{n+1}-1)$
Then $\liminf C_n>1$ implies convergence and $\limsup C_n<1$ implies divergence.
| common-pile/stackexchange_filtered |
Don't rebuild webpack bundle if entry files didn't change
Consider we have a webpack config like this:
entry: {
app: './main.js',
lib: './vendor.js',
}
The vendor.js file only consists of a bunch of requires to libraries from node_modules. 99% of the time I build the bundle(s) the output lib.js bundle is exactly the same.
Can I somehow tell webpack that if the vendor.js file didn't change (or preferrably some other custom condition like checking the modification date of lib.js and package.json to detect if I possibly have new versions of modules in node_modules) I do not want to rebuild the lib.js bundle? It takes a substantial amount of time on my CI server because of typescript transpliations etc.
As far as I am aware Webpack only really knows if a file will be the same once it has already built it because so many factors can change the file contents. The modified date of a file really does not provide enough information to determine that it should not be built again so I'd advise against it or you'll probably end up breaking your builds at some point and leaving people confused.
However if you did feel the need to do this though you could if you wanted make your Webpack config dynamic and use fs.stat to read vendor.js and then only add it as an entry if its changed. Something roughly like this:
var fs = require('fs');
var config = {
entry: {
app: './main.js'
}
...
};
var stats = fs.statSync('./vendor.js');
if (new Date(stats.mtime).getTime() > process.env.LAST_VENDOR_BUILD_TIMESTAMP) {
config.lib = './vendor.js';
// Then save new Date().getTime() somewhere like a DB and
// pass it in as LAST_VENDOR_BUILD_TIMESTAMP on next build.
}
module.exports = config;
As you can see the only way to solve your problem is that each and every build needs to have knowledge about previous builds to achieve this. This is undesired as your builds should be discrete and not care about previous build results.
Alternatively you should also try excluding some node_modules from the build if it is taking a really long time. I've not built typescript projects before but I exclude all of node_modules and my builds run much faster. Other than that, you shouldn't really mind your CI server being a little slow, at least it will be robust.
| common-pile/stackexchange_filtered |
Multiplexed 1 Gbps Ethernet?
Is it possible to multiplex two (or more) 1Gbps Ethernet into a single logical connection? Is it common place? Advisable? Stupid? Other considerations?
I ask because my hosting partner's network infrastructure is 1Gbps, but I have the need for more. 10Gbps networking kit is still on the pricey side, especially in the context of a high-availability Internet-facing data center. So, I'm exploring other options.
As many have indicated, teaming (LACP) is the common method. One thing to clarify though is that the method of teaming (MAC/IP addresses, etc) can limit the throughput of an individual connection to 1Gbps. For example, if you are teaming NICs on a server and mounting drives from an iSCSI target, you will only get 1Gbps to that server because the team will use the IP address combination to determine the path. There are round-robin schemes, but both sides of the connection have to support it. This "feature" of LACP can often trip you up the first time you use it.
@Kevin Kuphal: Thanks for this tip. The problem is actually easier to run into than I had imagined: We ran into the 'single path' problem with an HP ProCurve 2510G-24, which does its hash based on source & destinations MAC addresses--and no IP in the mix. That ment our properly LACP'd Linux server (distributing Tx packets over all links) faced a bottle neck getting off the switch and to the GW. Bonded ports apparently present only on MAC address!
Yes, it's called a variety of things such as 'teaming', 'etherchannel', 'DMP', 'MPIO', 'bonding' etc. but it happens all the time and is supported by most modern operating systems straight out of the box.
It's a very advisable thing to do if you have the spare ports on the server/pc and the switch - firstly because it allows you machine to carry on if a port or cable breaks and secondly because they can in many circumstances aggregate your traffic down both links to effectively give you 2Gbps.
Feel free to ask any more detailed questions around this area.
Thanks! Failures: I'd probably go with an additional 4-port NIC in the servers. We also have a hot standby fail over server. MORE: I need to know more about the network infrastructure issues...between my server, through the switch, through the packet filter and onto the Internet. (Time to go research those new terms! Thanks again.)
Oh it's worth knowing that often you can use more than two ports if needed, although I've personally never seen more than 4 links being used at once.
So, it's taken a bloody year but I'm going forward with this at a new colo providing a 2Gbps LACP link. We'll be moving upwards to 4x as needed. Thanks again.
So-called 'smart switches' employ a thing called Link Aggregation Control Protocol which allows you to bundle multiple ports together and use them as if they were one wide link... I'm not completely clear as to your precise need, but this maybe another term worth researching.
"Precise need"? I need a >1Gbps connection to the Internet for my Server, but find 10Gbps network infrastructure pricey.
"A single logical connection" to where, exactly? Your colo's gateway? Another colo's gateway? Please forgive me for trying to help...
@adamvs - I think what Stu is saying is that his hosting provider wants y for gigabit and 10 time y for 10G. I think Stu wants to know if he can buy 2 1Gb ports and team them together.
Switches usually support some (~64) aggregated links with up to 8 ports each. But before adding a Quad-NIC to a single server you should think putting about a load balancer with 4 GigE ports in front of your servers.
When using LACP, it's important to know which load balancing algorithm is used by the trunk. Normally you can (and should) choose between MAC- and/or IP-addresses and/or TCP/UDP-Ports as a source for load balancing.
Failover is really fast with LACP, you lose just a little more than the packets on the wire.
Clarification: I've two servers, 'live' and 'hot standby'. I need the multiple GigE on the individual servers.
| common-pile/stackexchange_filtered |
Computing the density for each layer with lidR
I am trying to perform a 3D profile index as a function. For this, I need to slice the layers and calculate the point density for each sliced layer. I write a for loop;
The problem is
density=grid_density(subset,res=0.1)
and
pt<-as.raster(pt)
parts gives always an error. When I run as.raster I always get this error:
Error in UseMethod("as.raster") :
no applicable method for 'as.raster' (applied to an object of class "c ('LAS', 'Spatial')")
I tried raster() instead of as.raster() it works but I don't know what is the main difference.
I filter the points with filter_poi() . In this filter I specified z value, the points must be calculated lower than the next sliced layer and higher than the layer itself. Then I want to calculate the grid_density() it gives this error:
Error in validityMethod (object): invalid extent: xmin> = xmax
Additionally: Warning messages:
1: In min (x @ data $ X): No missing arguments for min; Returning inf
2: In max (x @ data $ X):
No complete arguments for max; Returning inf
3: In min (x @ data $ Y): No missing arguments for min; Returning inf
4: In max (x @ data $ Y):
No missing arguments for max; Returning inf
library(lidR)
library(raster)
library(sp)
library(rgdal)
library(gridExtra)
#set the parameters
sz=0.05 #slice size in meters
s=seq(0,2,sz) #number of layer
k=seq(-1, 2.00,0.05) #correction factor (k)
las <- readLAS(x)
pt=grid_density(las,res=0.1) #pt is the total LiDAR points for all layers
pt<-as.raster(pt) #convert to raster
crs(pt) <- "+proj=utm +zone=31 +datum=WGS84 +units=m +no_defs"
# #make base layer, used to maintain the extent of the Pi raster layers
base_layer<-pt
values(base_layer)<-0
density_rasters=c()
for (i in s){
subset=filter_poi(las, Z>=i & Z<(i+sz))
if (!is.null(subset)){
density=grid_density(subset,res=0.1)
ras=as.raster(density)
setExtent(ras, ext=extent(base_layer),keepres = TRUE, snap = TRUE) # set extent to baselayer, otherwise the extent will be to small to be able to stack the rasters
ras=merge(ras,base_layer)
density_rasters=c(density_rasters,ras)
}
else { #used to insert empty raster if no points are within a given pi layer
density_rasters=c(density_rasters,base_layer)
}
density=0
ras=0
subset=0
}
I don't understand you problem because it is unclear and your question is messy. Why are you using as.raster on an object that is already a RasterLayer? Where the errors occurred? Which data did you used? So, I made an example that seems to be what you are looking for but without any explanation because I don't know what your problem is:
library(lidR)
LASfile <- system.file("extdata", "Megaplot.laz", package="lidR")
las = readLAS(LASfile)
sz = 2 # slice size in meters
s = seq(0, 20, sz) # number of layer
layout = grid_density(las, res = 4)
layout[] <- 0
density_rasters = vector("list", length(s))
for (i in seq_along(s))
{
subset = filter_poi(las, Z >= s[i] & Z < (s[i]+sz))
if (!is.empty(subset))
density_rasters[[i]] = grid_density(subset, res = layout)
else
density_rasters[[i]] = layout
}
density_rasters <- lapply(density_rasters, function(x) { extend(x, extent(layout))})
density_rasters <- stack(density_rasters)
names(density_rasters) <- paste0("Layer ", s)
plot(density_rasters)
I am sorry but I am pretty new in r even programming. Why are you using as.raster on an object that is already a RasterLayer? -because I wanted to create a base layer to use in the calculation. Where the errors occurred? -creating as.raster and applying grid density in function gives error which is written above. Which data did you used? I used las data which is already ground classified. @JRR
Please marked the question as answered (click on the checkmark) if it is the case. If not please edit your question to clarify where you are still struggled.
This code works without any problem! Just want to be sure, when I change the input to my las file, all the output rasters have min and max values as zero. Is that because of the input or should I tune anything?
I can't know. It depends on your data. If you used 5 cm slices on a 2-3 pt/m2 point cloud I'd say yes many slices are likely to be empty. But you can't ask if the output is correct without describing the input.
| common-pile/stackexchange_filtered |
How to speed up connection with a server in China
I have a EC2 server in China using Amazon AWS China.
It's a server with : Apache 2 and PHP The database is a RDS instance running MySQL (also in china)
The problem: Access from out of China is very slow. (tested from australia, france and Canada). Yes, the server has to stay in China :)
From inside China, access time is perfect.
I also have to refine this problem a bit more: what is slow ? The Bandwidth china <> china is what AWS advertise. The bandwidth outside-china <> china is very very bad. Can go down to as low as 2ko/sc. It can also work fine... it's very random.
Just to be clear, i even tried a realy big server just in case it made difference to the network... to no avail.
The latency (let's ping) is also very slow for a connection to reach China.
So, the first solution i have tried is to setup a reverse proxy (Varnish) with nginx in front (to manage ssl) in a Hong-Kong server. I am trying this because i can get a good access time to Hong-Kong from both China and the Rest of the world.
Now, the application hosted in China on the EC2 server is an Intranet. So very hard to cache anything else than JS, CSS and Pictures. (and those are done with varnish also, and works good)
I did think that perhaps a reverse proxy would be quicker than a direct access, but not very succesfull as yet.
What solutions do i have ? I need to make this website / intranet faster from anywhere is the world and the server has to stay in china.
i am open to any ideas, like: is squid better for this ? a vpn server ?
Notes: It's not a software problem of the intranet. Even with only 1 person it's slow and never more than 20 people on at same time.
Many thanks for any suggestions and advice.
have you tried putting the static content on S3 and using cloudfront?
it's the none static content that is problematic. pages are not broken down into small parts for caching, so each page in dynamic... not static.
The "Great Firewall" is filtering all connections into and out of China. Generally, all connections suffer, there's a lot of packet loss as well.
As long as the Chinese don't change this (highly unlikely) there's next to nothing you can do. You can speed up content delivery by content caching (e.g. caching proxy) but you can't speed up functionality. Set up a server outside China.
see also: https://en.wikipedia.org/wiki/Great_Firewall
so perhaps the only solution is to setup 2 servers: 1 inside china, 1 outside china. But if i do this, if this is the correct place to discuss..., how to i keep database up to date in all locations ? because, with only 1 database in china, it will still be slow outside of china.
You'll need to replicate data and content. For the database, this can be quite difficult if you can't just use a read-only copy.
It is best to just consider China a separate region that is not directly tied to the rest of the world. With the issues of encryption, monitoring, etc. Build separate business models for China versus the rest of the world.
| common-pile/stackexchange_filtered |
Concern of plagiarism if I publish the details of my invention
I have a concern about plagiarizing if I publish the details of my invention (an algorithm) in patent description. If the patent application is approved, the details of my invention will be disclosed to everybody in the world. If somebody plagiarize, it will be time-consuming and costy if I file a lawsuit. Especially in China, the copyright is not respected and not well practiced. As a company in the USA, it is very hard or impossible for us to win the lawsuit.
I am originally from China and understand the situations of China very well.
Somebody suggested me 1) file a patent application in one of the key steps but not the entire procedure in my algorithm; 2) cover a few of the key steps of my algorithm in the patent application; 3) provide misleading information about the key steps; 4) file the patent application after our product has some sales.
I am wondering if I can follow the above suggestions. Thanks for your suggestions.
Benson
You seem confused between the difference between patents and copyright. They are not the same. Someone making your patented product is patent infringement, not plagiarism.
I think you are using the word plagiarism to mean practicing your invent without your permission. That is not the correct meaning of that word.
To keep people from practicing your invention you can either keep it a trade secret or by using the patent system. If you are worried about people using your actual code then copyright can help. But if someone re-implements your algorithm copyright doesn’t help.
Intellectual property is territorial. A U.S. patent only prevents people from doing things in the U.S. To try to protect its use in China you need a Chinese patent. Enforcement of those rights in China and maximum penalties is not great but seems to be improving.
One view is that the market in U.S. and a few major countries is large enough to make exploiting your invention under the protection of patent laws profitable. In this view, don’t worry if people outside that scope can do it without compensation since your primary market is so large.
In disclosing your invention you need to show how to make and use it. That is worldwide. You can’t patent something that, as described, doesn’t work because you left out steps. Further, in the U.S., you must disclose the “best mode” of practicing the invention known to the applicants at the time of filing to prevent people from playing these games. If you optimize after filing there is no need to disclose that information to the patent office.
If you can cleanly separate your invention into two components that have distinct useful purposes you might be able to patent one and keep the other a secret.
You should not have any copyright issues because no patent application relating to a "software" invention is supposed to disclose the source code for the algorithm you are trying to patent. From time to time you can stumble upon a patent application that contains some source code or pseudocode, but it is rare to begin with and in any case only snippets of code are included in the disclosure.
The patent application should describe the algorithm as a series of actions/tasks, which is what might be patentable, and do so in a manner that the skilled person can e.g. hire a programmer and ask her/him to come up with the necessary code for reproducing the actions/tasks.
Since the source code will not be present in the patent application, nobody can copy it.
| common-pile/stackexchange_filtered |
About a sequence of (improper) integrals.
One considers the following sequence
$$
I_n=\int_0^1 \log^2(t).(1-t)^n dt\ ,
$$
using elementary methods (integration by parts, twice), one can show that
$$
I_n=2\sum_{k=0}^n \binom{n}{k}\frac{(-1)^k}{(k+1)^3}
$$
Question : Is there a simple way to prove or disprove that this (decreasing, non-negative) sequence tends to zero ?
Motivation : In the theory of star algebras, one considers the sub-star algebra of $\mathcal{C}(]0,1],\mathbb{C})$ generated by $\{\log(t),t\}$ and the positive linear form $\varphi : P\to \int_0^1 P(t) dt$ (where $P(t)=Q(\log(t),t),\ Q\in \mathbb{C}[X,Y]$) which generates a hilbertian form
$$
\langle u(t)\mid v(t)\rangle:=\varphi(v^*u) \qquad (*)
$$
the target being to prove that the operator
$f\to \log(t)f(t)$ is discontinuous for the norm induced by (*).
Late edit (Thanks to all contributors) We see here that, with $P_n(t)=\frac{n}{\log^2(n)}(1-t)^n$, we have $\lim_{n\to \infty}P_n=0$ whereas $\lim_{n\to \infty}\log(t)P_n(t)=1$ for this norm.
By the Cauchy–Schwarz inequality and Euler's integral $n!=\int_0^1 (-\log (t))^n\mathrm{d}t$,
$$
\int_0^1 {\log ^2 (t)(1 - t)^n {\rm d}t} \le \sqrt {\int_0^1 {\log ^4 (t){\rm d}t} \int_0^1 {(1 - t)^{2n} {\rm d}t} } = \sqrt {4!\frac{1}{{2n + 1}}} = \frac{{2\sqrt 6 }}{{\sqrt {2n + 1} }} \to 0.
$$
For a more precise asymptotics, we can use the dominated convergence theorem:
\begin{align*}
\frac{n}{{\log ^2 (n)}}\int_0^1 {\log ^2 (t)(1 - t)^n {\rm d}t} = \int_0^n {\left[ {1 - \frac{{\log (s)}}{{\log (n)}} } \right]^2\left( {1 - \frac{s}{n}} \right)^n {\rm d}s} \to \int_0^{ + \infty } {{\rm e}^{ - s} {\rm d}s} = 1,
\end{align*}
i.e.,
$$
\int_0^1 {\log ^2 (t)(1 - t)^n {\rm d}t} \sim \frac{{\log ^2 (n)}}{n}
$$
as $n\to+\infty$.
Thank you for your answer. I must ecplain its asymptotics to a physicist which is not keen on hypergeometric functions. That's why I will reuse your way.
You can obtain the antiderivative using hypergeometric functions and the definite integral is "just"
$$I_n=\int_0^1 \log^2(t)\,(1-t)^n\, dt=\frac{6 \left(H_{n+1}\right){}^2-6 \psi ^{(1)}(n+2)+\pi ^2}{6 (n+1)}$$ which is asymptotic to
$$\frac{6 \log ^2(n)+12 \gamma \log (n)+(\pi ^2+6 \gamma ^2)}{6
n}+O\left(\frac{1}{n^2}\right)$$
Thank you for your answer, this enlightens the asymptotics of it.
| common-pile/stackexchange_filtered |
How to retrieve data from Django fields?
I have a model
models.py
class EmployeeModel(models.Model):
Employee_id = models.CharField(max_length=200)
name = models.CharField(max_length=200)
basic_salary = models.IntegerField(blank=True,default=0)
HRA = models.IntegerField(blank=True,default=0)
DA = models.IntegerField(blank=True,default=0)
TA = models.IntegerField(blank=True,default=0)
CCA = models.IntegerField(blank=True,default=0)
Medical = models.IntegerField(blank=True,default=0)
bonus = models.IntegerField(blank=True,default=0)
advance_pay = models.IntegerField(blank=True,default=0)
PF = models.IntegerField(blank=True,default=12)
def __str__(self):
return self.name
All objects of my models.py
>>> employeeModel.objects.all()
<QuerySet [<employeeModel: Emp001>, <employeeModel: Emp003>, <employeeModel: Emp004>, <employeeModel: Emp006>, <employeeModel: Emp006>, <employeeModel: Emp0010>, <employeeModel: Emp0011>, <employeeModel: Emp0012>, <employeeModel: Emp0013>, <employeeModel: Emp0013>, <employeeModel: Emp0013>, <employeeModel: Emp0013>, <employeeModel: Emp0013>, <employeeModel: Emp0013>, <employeeModel: Emp0013>, <employeeModel: Emp0013>, <employeeModel: Emp0013>, <employeeModel: Emp004>, <employeeModel: Emp0014>, <employeeModel: Emp0015>, '...(remaining elements truncated)...']>
For every instance of model 'EmployeeModel',I want to retrieve data from fields to calculate further in 'views.py' for Gross Salary! For example I want to get data of fields TA,DA,HRA individually so I can add them. But I don't know how to get data from Django fields. I'm new to Django.
employeeModel.objects.values_list('TA','DA','HRD') will display the data wanted
https://docs.djangoproject.com/en/2.0/topics/db/
I'm voting to close this question as off-topic because the OP forgot to read the FineManual first.
@brunodesthuilliers nope,have read finemanual, but still cant get proper way of getting results..
@Lemayzeur thanks sir for pin pointed answer, being newbie it hard to understand django manual in depth, as per your answer now i can finish my project. i implemented like this
query = employeeModel.objects.values_list('basic_salary', 'DA', 'TA', 'HRA', 'CCA', 'Medical', 'bonus', 'advance_pay',
'PF','PT','leave','working_days').filter(employee_id=employee_id)[0]
print(query)
basic_salary = query[0]
dearness_allowance = query[1]
travel_allowance = query[2]
house_rent_allowance = query[3]
city_compensatory_allowance = query[4]
medical_allowance = query[5]
bonus = query[6]
advance_pay = query[7]
provident_fund = query[8]
professional_tax = query[9]
leave = query[10]
working_days = query[11]
I know, its not dynamic, to retrieve data usually developers use API and ajax which i am going to learn next .
| common-pile/stackexchange_filtered |
Would a SARS-CoV-2 infection disrupt the blood-brain barrier, leaving the brain more vulnerable to drugs taken simultaneously with the infection?
According to some studies[1], there is some evidence that the virus could cross the BBB. Is that is the case, does that mean that it would weaken the barrier allowing potentially neurotoxic drugs to enter the brain. Could this happen for example if the virus downregulates p-glycoprotein which prevents the uptake of drugs?
An example of this concern is with the drug ivermectin which has gained some recent notoriety as a possible prophylactic and treatment of the infection. There is some evidence for the neurotoxicity of this drug in dogs.[2]
[1] Rhea, E. M., Logsdon, A. F., Hansen, K. M., Williams, L. M., Reed, M. J., Baumann, K. K., ... & Erickson, M. A. (2021). The S1 protein of SARS-CoV-2 crosses the blood–brain barrier in mice. Nature neuroscience, 24(3), 368-378. https://doi.org/10.1038/s41593-020-00771-8 [Open Access]
[2] Merola, V. A., Khan, S., & Gwaltney-Brant, S. (2009). Ivermectin toxicosis in dogs: a retrospective study. Journal of the American Animal Hospital Association, 45(3), 106-111. https://doi.org/10.5326/0450106Free copy at http://jcore-reference.highwire.org/content/45/3/106
Welcome to MedicalSciences.SE. Just a tip, links to often break and therefore, when providing links to scientific papers, please provide references and (where possible) either a pubmed link or doi link in case they do break. It makes it easier to find if needed.
The Rhea et al. article on SARS-CoV-2 suggests that the S1 protein crosses the BBB by a specific mechanism (general albumin protein does not cross at the same time), so no general disruption of the BBB is indicated (See Fig. 1 in paper). The authors also note "Based on experiments with the glycoprotein WGA, we found that brain entry of I-S1 likely involves the vesicular-dependent mechanism of adsorptive transcytosis."
Even without general BBB disruption, ivermectin can cause serious neurological issues in humans.
| common-pile/stackexchange_filtered |
Java: suspend frame while other frame getting information from user
I need to get some information from user by showing a JFrame
I need the first frame pause process until user enter data from the second frame
I thought about using wait() and notify() but I don't know how
How can I do this?
Thanks
It seems to that it would be a lot easier for you is you just use a modal JDialog, which you present to the user. The inputs whatever is needed there and the JFrame that popped the dialog will carry on after the dialog's closed. wait() and notify() are used for thread synchronization btw...
| common-pile/stackexchange_filtered |
How to change the value in char *array[]?
I have an array(Array) and the value define as char array (LIST) in another .h file.
char *Array[]= { "something1", "something2", "something3" };
LIST is defined in .h file.
#define LIST {“a”, “b”, “c”}
If I would like to change all values in Array to be LIST. What should I do?
Please format your code. See How do I format code blocks?
Do you really have LIST defined like that (instead of a char*[])? That's a very weird way to define it.
It's three backtick characters, or four spaces for indentation. You were using some other kind of quotes that don't match.
The correct answer is to get rid of the LIST macro and define a second array instead. Also, these arrays should be const char* array[].
You urgently need to fix your quotes. These are “smart quotes” that do not belong in code. These can cause considerable problems when debugging because they are not syntactically valid but look virtually identical in some fonts. Use a code editor, not a word processor, to edit code.
As an alternative to @tadman's answer, you could use compound literals if you turn char *Array[] into char **Array.
Here's an example:
#define LIST {"a", "b", "c"};
int main(void)
{
char **Array = (char *[3]) {"abc", "def", "ghi"};
Array = (char *[3]) LIST;
}
Compound literals were introduced in the C99 standard, so if you're working with an older version, don't try using this. However, if you choose to turn the LIST macro into, say, a global array, a compound literal wouldn't work since it requires you to use a brace-enclosed initializer.
The problem here is LIST doesn't exist as anything you can copy, you need to instantiate it somehow first, like:
char* list[] = LIST;
Then you need to copy it over, but you have no idea how big it is, so you're sort of stuck again.
What would be better is:
#define LIST {"a" "b", "c", NULL}
Where now you can at least tell where that stops.
You could also define a global const, or a static variable, depending on exactly how this is used, and how often. A #define is really the worst tool for this job even if it can be done.
As for assignment, assuming the lists are the same size:
char** a = &array[0];
for (char** p = &list[0]; *p; ++p, ++array) {
*array = *p;
}
Where that will spin through until it hits the NULL terminator.
| common-pile/stackexchange_filtered |
Relation between rational Tate module and universal cover of a p-divisible group
We can associate two $\mathbb Q_p$ vector spaces to a $p$-divisible group, and I'm a little confused about the relation between these two groups. First of all, I think part of my problem is that when papers discuss these things, they claim that if $R$ is $p$-complete, sending $x\mapsto p^nx$ is topologically nilpotent on $G(R)$, in particular, it is nilpotent if $p^nR=0$. I don't understand why this is true and I would appreciate an explanation or a reference.
But if we accept the claim it is easy to see that for any connected $R$ such that $p^nR=0$, we have:
$$\tilde{G}(R):=\lim_{p:G\to G}(G(R))=\operatorname{Hom}(\mathbb{Q}_p/\mathbb{Z}_p,G(R))[1/p].$$
On the other hand one has
$$T_G(R):=\lim(G[n](R))=\operatorname{Hom}(\mathbb{Q}_p/\mathbb{Z}_p,G(R)).$$
So it seems to me that if $p^nR=0$, then $\tilde{G}(R)$ is just the rational Tate module, and they are different only in mixed characteristic. Is my understanding correct?
Isn't a $p$-divisible group a forward limit of finite $p$-group schemes? So then multiplication by $p^n$ is nilpotent on each $p$-group scheme and thus topologically nilpotent on the whole group?
@WillSawin I understand it is topologically nilpotent in this sense(note that the R-points of this p-divisible group is not the limit of the R-points of those finite group, you need a sheafification.) my question was that if $R$ is a p-adic ring. why multiplication by p is topologically nilpotent on $G(R)$ with $p$- adic topology.(where a base is given by $Ker(G(R)\to G(R/p^n))$).
Are we assuming that $R$ mod $p$ is finite?
@WillSawin No. At least in the context I have seen it( perfectoid space )R mod p) is not even notherian
Let $G$ be a $p$-divisible group over any base $S$. In terms of the functor of points we have for any affine scheme $\mathrm{Spec}(R)$ that $G(R):=\mathrm{colim}_n G[p^n](R)$.
Regarding the universal cover etc, let $C(G)=\lim_p G$ and $T(G)=\lim_{p} G[p^n]$. Then you have a short exact sequence (of fpqc sheaves say): $$0\to T(G)\to C(G)\to G\to 0.$$ Then $\mathrm{colim}_p G=\mathrm{colim}_n \mathrm{colim}_p G[p^n]=0$ hence taking the colimit of this short exact sequence under multiplication by $p$ yields an isomorphism $\mathrm{colim}_p T(G)=T(G)\otimes_{\mathbf{Z}_p} \mathbf{Q}_p \stackrel{\sim}{\to} C(G)$.
Regarding topological nilpotence of $p$ on $G$, if $R=\lim_n R/p^n$ is complete then $G(R)=\lim_n G(R/p^n)=\lim_n \mathrm{colim}_m G[p^m](R/p^n)$ and the topology on $G(R)$ is the inverse limit topology where $G(R/p^n)$ has the discrete topology. But $G(R/p^n)=\mathrm{colim} G[p^m](R/p^n)$ is $p$-power torsion and so $p$ is nilpotent on $G(R/p^n)$ and topologically nilpotent on $G(R)=\lim_n G(R/p^n)$.
| common-pile/stackexchange_filtered |
Javascript library to generate workflow configuration diagrams
I have a set of predefined flow diagrams, and I need a way to display the diagram and allow the user to interactively set inputs and/or properties at various nodes in the diagram. The nodes/connections of the diagram are fixed and cannot be edited by the user.
I know there are several options for diagram editors, but those would need heavy modification for what I need. Any suggestions for javascript libraries/apps that would be able to do this?
You need to tell us what technology you are using for the diagrams if any.
It sounds like you need two things. Firstly a method of displaying a directed graph (which is what a flowchart is) in a browser. Secondly, a tool to add interaction to the graph.
Here is a rough list of some of the graphics toolkits that are relevant:
JsPlumb
JavaScript InfoViz Toolkit
http://processingjs.org/
http://raphaeljs.com/
https://github.com/mbostock/d3
NodeViz might also be usable. It adds a PHP back-end onto some javascript front-end tools.
All of these will require a lot of programming though. I'm not aware of anything "out-of-the-box" that will do what you want - I've certainly been looking for similar tools for a while though what I really want is a data-driven interactive graph tool (not to be confused with charting tools of which there are many).
Update: I've just come across http://www.jointjs.com/ as well. This is built over Raphael and seems promising.
| common-pile/stackexchange_filtered |
Issue with GPS on RPi4 at boot
So I have RPi4 which I configured with multiple UARTs and a Ublox ZED-F9P on a custom designed board. My setup would use the UART1 on the F9P for ubx messages and the UART1 for NMEA messages that used by GPSD and Chrony for time purposes (together with the PPS).
I wrote a python script that configures the F9P so that both UARTs are correctly configured, and the script works.
Now, I want to do the second step and do it automatically at startup. I decided to use systemd and set a unit type as simple and target multi-user. The unit starts with no error but nothing is coming out from the GPS (check on both GPSMON and journalctl adding print statements). I stopped the unit, I got at that point something out and now GPSMON works (hence I configured it correctly). If I restart the unit everything works, with no problem (no computer restarting). I tried to do the same changing the target to default with the same result. At this point I decided to try and go back to rc.local and I am having same behaviour (at boot no error but nothing coming out, then stopping and restarting and everything is good). The only solution that I found at the moment is to keep enabled the unit so that it starts at startup and then stop and re-starting again on rc.local.
Any idea of what is happening?
| common-pile/stackexchange_filtered |
It's hard to click on Bar button Item
I've created custom back bar button. And I added an UIview because I have to change position of it within bar.
UIImage *backButtonImage = [UIImage imageNamed:@"backBtnWhite"];
_backButton = [UIButton buttonWithType:UIButtonTypeCustom];
_backButton.exclusiveTouch = YES;
[_backButton setImage:backButtonImage forState:UIControlStateNormal];
[_backButton setImage:backButtonImage forState:UIControlStateHighlighted];
[_backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
_backButton.frame = CGRectMake(-4.0, 7.0, 40, 40);
UIView * view = [[UIView alloc] initWithFrame:CGRectMake(-4.0, 7.0, backButtonImage.size.width, backButtonImage.size.height)];
[view addSubview:_backButton];
UIBarButtonItem* barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
self.navigationItem.rightBarButtonItem = barButtonItem;
But after that I've added UIView it became difficult to click on it.
I've tried to change button area, but it didn't give results.
More description please.
You set the view's frame to have backButtonImage width and height - are these set properly when the view is instantiated? Also, you could try making sure the view is not absorbing the touch
It seems like you specify incorrect frame for _button or/and view and this changes the tap region. Try to set different background color for _backButton and view. This will show you if frames are in positions that you expect.
If you try to adjust image position by specifying these frames - its more correct to use properties of UIButton like imageEdgeInsets and titleEdgeInsets.
| common-pile/stackexchange_filtered |
Setting the first value as default in dropdown list
Jquery to create new row :
var selectVal = $(parent).children().first().find('select').find('option[selectedGivenTo="true"]').val();
var newSelect = $(parent).children().last().find('select');
newSelect.each(function() {
var cloned = null;
cloned = $(this).clone();
cloned.val(selectVal);
I am trying to select the first value of dropdownlist as default value using jQuery as above but no value is selected & just displaying list in dropdown.I saw many references in stackoverflow but its not working for me.
I'm confused as to the problem you're trying to solve as you get this behaviour by default when creating a new select. Could you show a working example of your problem, including all relevant JS code and the HTML
Can you post the HTML? Are you using any plugin for dropdownlist?
@RoryMcCrossan http://stackoverflow.com/questions/39024914/add-remove-more-rows-dynamically-using-jquery-and-jstl-dropdown please look at this ..this is want i want to do but with JSTL tags and not normal html..
If you want to select it by value, then use the code below:
$('select option[value="defaultValue"]').attr("selected",true);
If you want to select via text contains in option, use the following code:
$('select option:contains("I am defualt Value")').prop('selected',true);
HTML:
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi">Audi</option>
</select>
jQuery:
$(function(){
$("select option:first").attr('selected','selected');
var _select = $('select')[0],
_v = _select.options[_select.selectedIndex].value;
alert(_v);
});
Demo
| common-pile/stackexchange_filtered |
Keeping changes same in merging branches in
I have been using Git for a while and I know basics of merging, tho I have one confusion on how others maintain the code changes after merging?
I have master branch, and feature_a branch which is created from master. There are some changes in master branch and as well as feature_a branch, to get latest changes in master I merged feature_a into master branch.
So now master has all the latest changes, and now i want to continue in feature_a branch to add more changes, but the thing is feature_a does not have changes of master branch which are made after branch out and before merge, which is bothering me from continuing on feature_a branch.
Am I missing any concept or is there any way to keep both branches on same level after merging? Should I merge master in to feature_a after merging feature_a into master ?
but the thing is feature_a does not have changes of master branch which are made after branch out and before merge, which is bothering me from continuing on feature_a branch.
Then all you need to do is rebase the new part of feature_a on top of master:
git switch feature_a
git rebase --onto master A feature_a
You would go from
m--m--M--m (master)
/
a--A--a--a (feature_a)
To
m--m--M--m (master)
/ \
a--a --a'--a' (feature_a)
Ok so after each merge (feature_a into master) I need to rebase feature_a on master, after that i can continue on feature_a for next change and do the same thing when i again need to merge it, is that correct ?
@Darshan That is the general idea, yes. I do the rebase only of the part from feature_a which is not yet merged into master.
What do you mean by "rebase only of the part from 'feature_a' which is not yet merged" ? Do i need to skip the merge part?
@Darshan That is what the rebase --onto does in my answer: rebase everything after A: A is the last commit from feature_A being merged to master.
| common-pile/stackexchange_filtered |
Why is this BeanPostProcessor needed in addition to a UserDetailsService in this Spring 3.0 authentication example?
I'm trying to understand a Spring 3.0 application which contains the following BeanPostProcessor implementation. What is this code needed for? I thought the UserDetailsService was sufficient for getting and setting the User account information.
@Service
public class UserPassAuthFilterBeanPostProcessor implements BeanPostProcessor
{
/**
* The username parameter.
*/
private String usernameParameter;
/**
* The password parameter.
*/
private String passwordParameter;
@Override
public final Object postProcessAfterInitialization(final Object bean, final String beanName)
{
return bean;
}
@Override
public final Object postProcessBeforeInitialization(final Object bean, final String beanName)
{
if (bean instanceof UsernamePasswordAuthenticationFilter)
{
final UsernamePasswordAuthenticationFilter filter = (UsernamePasswordAuthenticationFilter) bean;
filter.setUsernameParameter(getUsernameParameter());
filter.setPasswordParameter(getPasswordParameter());
}
return bean;
}
/**
* Sets the username parameter.
*
* @param usernameParameter
* the username parameter
*/
public final void setUsernameParameter(final String usernameParameter)
{
this.usernameParameter = usernameParameter;
}
/**
* Gets the username parameter.
*
* @return the username parameter
*/
public final String getUsernameParameter()
{
return usernameParameter;
}
/**
* Sets the password parameter.
*
* @param passwordParameter
* the password parameter
*/
public final void setPasswordParameter(final String passwordParameter)
{
this.passwordParameter = passwordParameter;
}
/**
* Gets the password parameter.
*
* @return the password parameter
*/
public final String getPasswordParameter()
{
return passwordParameter;
}
}
Yes, UserDetailsService is sufficient.
This BeanPostProcessor changes the names of username and password parameters in login request (i.e. names of fields in login form) - these properties can't be configured via namespace configuration, and using BeanPostProcessorss in order to customize such properties is an ugly but quite common practice.
Sorry if this is a stupid question but how do you know the parameter names are being changed?
@pnut: From the documentation of UsernamePasswordAuthenticationFilter (http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.html), properties of which is changed after instantiation by this postprocessor.
This postProcessBeforeInitialization() method is implemented from BeanPostProcessor interface which automatically executes after your getter and setter methods finish executing
and once the postProcessBeforeInitialization() method finish execution, objects are initialized and then postProcessAfterInitialization() will execute.
These are something like life cycle methods.
| common-pile/stackexchange_filtered |
How to update Kivy GridLayout "rows" property in dynamic class
Suppose I have this in my .kv file:
<VerticalLayout@GridLayout>:
cols: 1
<Root>:
VerticalLayout:
rows: len(self.children)
Button:
text: 'Sample 1'
Button:
text: 'Sample 2'
Button:
text: 'Sample 3'
It works perfectly like that. But what I want to to is add the "rows" part that updates automatically based on the children in the layout to the dynamic class, like this:
<VerticalLayout@GridLayout>:
cols: 1
rows: len(self.children)
But when I do that it doesn't work! How can I get this functionality inside of the Kivy Language without anything in my .py file?
Adding a row dynamically to a GridLayout is a one-line python statement:
self.mylayout.rows += 1
Is that something you still don't want to do? If subtracting rows like this, you'll need to remove widgets that may be occupying them.
| common-pile/stackexchange_filtered |
SQL, count both open and closed sessions
Given this table:
Session | User | Start | Stop
1 | 1 | 2014-10-10 | null
2 | 1 | 2014-10-10 | 2014-10-10
3 | 1 | 2014-09-10 | 2014-09-10
4 | 2 | 2014-10-10 | null
5 | 2 | 2014-10-10 | 2014-10-10
I want to count how many open sessions each user has, AND the total number of sessions for that user for a given date:
User | Date | Open | Total |
1 | 2014-10-10 | 1 | 2 |
1 | 2014-09-10 | 0 | 1 |
2 | 2014-10-10 | 1 | 2 |
By grouping on both user, start and stop, I'm able to get two rows, one with open sessions and one with closed, but I would rather have two columns...
(I'm using SQL Server 2008 R2)
Is it a valid case for a session to span more than one day? That would complicate things a bit, right?
Nah. The whole point of this is to show some basic statistics on how many current vs total users there are. So if a session is started one day, and closed the next, the stats will count it the day it started. If it started yesterday, and it's still open, I will count it as part of yesterdays total.
Use a case expression to count conditionally:
select
user,
start as [date],
count(case when stop is null then 1 end) as open,
count(*) as total
from sessions
group by user, start;
ISNULL(sum(case when stop is null then 1 end), 0) AS open, because SUM for NULL == NULL, and if we not have a columns with stop IS NULL, it return NULL
@realnumber3012: Yes, I had just noticed that. So I use COUNT now. You are right, with SUM one would have to use COALESCE or the like to make the null a zero.
Great! One more thing: I have timestamps that I convert into dates with cast(start as Date). Is there a way of defining that once, so that I can refer to that value later without doing a new cast? Like in where date = '2014-09-10'?
The only thing that comes to mind is a derived table, i.e. select the date in a sub query: select mydate from (select cast(start as date) as mydate from mytable) where mydate = '2014-09-10'.
For future reference, this is what I ended up with:
select user, cast(s.start as Date) as date, count(case when (s.stopp is null) and (s.Start >= cast(GETDATE() as Date)) then 1 end) as [open], count(*) as total from sessions as s group by s.user, cast(s.start as Date) order by date
Try this:
SELECT t.user, t.start,
sum(
case
when stop is null then 1 else 0
end) as 'Open',
count(t.start) as 'Total'
FROM yourtable t
GROUP BY t.user, t.start
| common-pile/stackexchange_filtered |
Let $F:\Bbb{R} \to \Bbb{R}$ be a positive, smooth and periodic function with period $P>0$. Proof that...
Let $F:\Bbb{R} \to \Bbb{R}$ be a positive, smooth and periodic function with period $p>0$. Prove that if $\Phi(t)$ is a solution to the differential equation $x'=F(x)$ and
$$ T=\int_0^p {1\over F(y)}dy$$
then: $$\Phi(t+T)-\Phi(t)=p,\, \forall t \in \Bbb{R}$$
I already proved that if G is the antiderivate function of ${1\over F(y)}$ then $G(y+p)-G(y)=C$ where $C$ is a constant, but I don't know how to use this to solve the problem, it will help a lot a hint on how can I use this or where I can start to solve this problem. (Sorry if my english is bad)
Since $F$ (hence $1/F$) is $p$-periodic you have
$$
\forall \xi \in \mathbb{R}: ~ \int_\xi^{\xi+p} \frac{1}{F(y)} dy=T.
$$
By the method of separation of variables
$$
\int_{\Phi(t)}^{\Phi(t+T)} \frac{1}{F(y)}dy = \int_{t}^{t+T} \frac{\Phi'(s)}{F(\Phi(s))}ds = T = \int_{\Phi(t)}^{\Phi(t)+p} \frac{1}{F(y)} dy.
$$
Hence $\Phi(t+T)= \Phi(t)+p$.
It was a very understandable answer, thanks for your help
@MauricioRosendoMontiel Glad I could help. If you like the answer you can mark it as accepted..
| common-pile/stackexchange_filtered |
How to get all the rows given a part of the row key in Hbase
I have the following table structure in Hbase:
Row column+cell
Mary_Ann_05/10/2013 column=cf:verified, timestamp=234454454,value=2,2013-02-12
Mary_Ann_06/10/2013 column=cf:verified, timestamp=2345454454,value=3,2013-02-12
Mary_Ann_07/10/2013 column=cf:verified, timestamp=2345454522454,value=4,2013-02-12
Mary_Ann_08/10/2013 column=cf:verified, timestamp=23433333454,value=1,2013-12-12
I want to retrieve all the records that start with Mary_Ann using java. How do I do that?
You could achieve that using PrefixFilter. Given a prefix, specified when you instantiate the filter instance, all rows that match this prefix are returned to the client. The constructor is : public PrefixFilter(byte[] prefix)
Usage :
Filter filter = new PrefixFilter(Bytes.toBytes("Mary_Ann"));
Scan scan = new Scan();
scan.setFilter(filter);
ResultScanner scanner = table.getScanner(scan);
for (Result result : scanner) {
for (KeyValue kv : result.raw()) {
System.out.println("KV: " + kv + ", Value: " +
Bytes.toString(kv.getValue()));
}
}
scanner.close();
HTH
| common-pile/stackexchange_filtered |
References for listings of point group operations
I am looking for a listing of the operations of point groups (preferrably as matrices). Nearly every textbook lists the irreducible representations and characters of the groups, but I have not found any that lists the specific operations. As an example, I am looking for the operations of the operations of the point group $m\bar{3}m$.
Alternatively: Is there a way I can compute these operations using a computer?
I don’t think you will not find these in terms of matrices since these are basis dependent and take huge amounts of space.
| common-pile/stackexchange_filtered |
Causality violation of naive RQM
So I am starting to read QFT from P&S, and in the very beginning they set out to clarify why a naive approach of writing a single particle relativistic hamiltonian would lead to propagation outside the light cone. I have several questions about their line of argument, some technical and some physical.
Technical question: How do I get from the second to the final step?
The phase is stationary when $p = \frac{imx}{\sqrt{x^2 - t^2}}$, but that does not lead me to the same conclusion as P&S in a straightforward way. Am I missing some further approximations?
Here P&S talks about causality in terms of measurements outside the light cone affecting the inside. They say that QFT will take care of it by introducing antiparticles, which will cancel out the contribution from the particle. But didn't we just argue that, for real particles at least, the amplitude does not cancel? (since their antiparticle are themselves) So what happens to the causality, or are there no real particles? I am confused.
I know its really three questions but they are connected, so it made more sense to pack them into one. Can someone help me out with explicit calculations and explanations?
Thanks in advance.
References: Peskin & Schroeder p.14
Possible duplicates: https://physics.stackexchange.com/q/346780/2451 , https://physics.stackexchange.com/q/194877/2451 and links therein.
The first 2 subquestions seems to be technical exercises. The third subquestion is conceptional. To reopen this post (v2), consider to only ask one subquestion per post.
None of the links you gave answers any of my questions above. Plus, I agree it's too many subquestions but it's related to essentially a single derivation in P&S. Would you please reconsider opening this thread on these grounds?
| common-pile/stackexchange_filtered |
Converting a key press to text box in vb.NET
I am currently using Visual Basic 2010 and am making a basic calculator. It should recognize keystrokes from the numpad and treat them like the buttons on my calculator used for numbers and operations. However, I cannot get it to work.
For example, I'd like my program to display the number 4 in the command line when numpad 4 is pressed and am trying to do it like this:
Private Sub BeforeLoad(sender As System.Object, e As System.EventArgs) Handles MyBase.Load, Me.KeyDown
Me.KeyPreview = True
If Keys.NumPad4 = True Then
If (Input AndAlso txtDisplay.Text <> "0") Or Point Then
txtDisplay.Text += btn4.Text
Else
txtDisplay.Text = btn4.Text
Input = True
End If
End If
End Sub
However, when I start my program and try to click numpad4, nothing shows up. Any help into this matter would be greatly appreciated. [Solved]
My other problem is that the enter button returns a value of '1' on the numpad instead of calculating the answer that I'd like it to.
Case Keys.Enter
EnterPress(btnEqual)
Private Sub EnterPress(btn As Button)
'# Enter Button
If txtDisplay.Text.Length <> 0 Then
CalculateTotals()
Operation = String.Empty
Point = False
End If
End Sub
My code in its entirety can be found here: http://pastebin.com/dsMCNy3i
Here is the code to my equals button:
Private Sub Master(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEqual.Click
If ModOp = True Then
Num2 = Val(txtDisplay.Text)
txtDisplay.Text = Num1 Mod Num2
ElseIf txtDisplay.Text.Length <> 0 Then
CalculateTotals()
Operation = String.Empty
Point = False
End If
End Sub
have you put a breakpoint in and stepped through your code to see what it is doing?
Are you using WinForms?
You cannot subscribe to the KeyDown in a method set up for Form Load. Recreate the event via the event list and then check If e.KeyCode = Keys.Numpad4 Then.
Here's an answer I gave to a similar question a few weeks ago: http://stackoverflow.com/a/36662317/3740093
@MaCron : I don't know what a breakpoint is since I really don't know what I'm doing, so no. @GibralterTop : Yes. @Visual Vincent : Thanks for your answer, however, for some reason that didn't work for me.
It appears I've found two solutions to this.
1) Put a '&' symbol before the number in the button's text in the properties window.
2) This code worked for me:
Private Sub Keystrokes(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
Select Case e.KeyCode
Case Keys.NumPad1
btn1.PerformClick()
Case Keys.NumPad2
btn2.PerformClick()
End Sub
| common-pile/stackexchange_filtered |
Is there a way in android to execute an action when the user double clicks the power button?
In general there are three ways to interact with buttons in android. Normal click, long click and double click. Android by default assigns actions to normal click and double click of the power button.
In there a way to assign an action when the user double clicks the power button?
| common-pile/stackexchange_filtered |
Sharepoint backup methods?
I currently do indiidual site collection (6) backups on my sharepoint site.
What are some of the best autmoized methods to backup a sharepoint site (site collections and sites with content)?
For some reason everytime I try to do a web app backup it fails.
Thanks
here are a few methods that you could use to backup!
this one is using powershell
http://sharepointpolice.com/blog/2010/12/07/automated-powershell-script-to-backup-sharepoint-farm-or-site-collection-with-email-notification/
do it using sharepoints own tools!
http://blogs.msdn.com/b/markarend/archive/2010/05/27/backup-restore-for-sharepoint-2010.aspx
tech from microsoft using Owsadm.exe (command line)
http://technet.microsoft.com/en-us/library/cc768008.aspx
also have a look at this automated backup someone created
http://social.technet.microsoft.com/Forums/da/sharepoint2010setup/thread/15d5a8ae-c112-4841-a105-8836b2de1a7e
no probs glad to help :)
| common-pile/stackexchange_filtered |
Building Swift Package Manager project with xcodebuild, how to ignore xcodeproj and xcworkspace?
I have an SPM project that I need to test with xcodebuild (because it has iOS resources such as XIBs). This project also supports Cocoapods so it also has .xcodeproj and .xcworkspace files.
Normally xcodebuild will automatically detect the Package.swift file and use that to build, but now it detects the Cocoapods workspace and tries to go from that instead.
I read through the documentation for xcodebuild, but couldn't find a flag to explicitly point it to the Package.swift.
Is there any equivalent to the --project or --workspace flag that I can use to tell xcodebuild to use the Package.swift file and ignore the project and workspace?
did you find a solution to this?
I ended up calling swift package generate-xcodeproj --output ./tmp to generate an Xcode project in a subdirectory first. Then I call xcodebuild build -project ./tmp/[project].xcodeproj to build the SPM specific project.
Update: Turns out that generating an xcodeproj also didn't work, because that doesn't support resources. Final solution I settled on was just to move the CocoPods project and workspace to a subfolder.
Its been a while, but wondering if anyone knows whether this is still the case? I'm trying to extend some existing build scripting that runs in a different directory than where the code lives. Today, that works just fine for projects and workspaces because you can pass the full path in, but SPM packages don't appear to support that in any way
To use xcodebuild with Swift Package Manager, you specify the scheme name: xcodebuild -scheme [SchemeName].
If there is a conflict with Cocoapods, I suggest you change the scheme names to be unique.
As swift package generate-xcodeproj has been deprecated, the instruction to build the Swift package via command line is as follows:
Determine the valid scheme from your package directory using xcodebuild -list
$xcodebuild -list | grep -A100 Schemes
Schemes:
MySwiftPackage
Build the package using xcodebuild build -scheme <SCHEME> -sdk <SDK> -destination <DESTINATION>
#iOS
$xcodebuild build -scheme MySwiftPackage -sdk iphonesimulator16.0 macosx -destination -destination "OS=16.0,name=iPhone 13 Pro"
#Mac Catalyst
$xcodebuild build -scheme MySwiftPackage -sdk macosx -destination "generic/platform=macOS,variant=Mac Catalyst,name=Any Mac"
You can find other destination strings here.
https://stackoverflow.com/questions/60245159/how-can-i-build-a-swift-package-for-ios-over-command-line
| common-pile/stackexchange_filtered |
Regex to suppress line breaks to aggregate groups of 3 lines into 1
I'm trying to fix a txt file format using python and regex. For that I used this post as a point of start, but I can't make it work with my file format.
Regex:
([^1|-])[\n](.)|(.)[\n]([^|-])
My file format is something like this:
|A |B |C |
D |E |
F |G |
I want to parse it like this:
|A |B |C |D |E |F |G |
Without removing any separator pipes or content just the newline breaks between then.
The problem is that it replaces the pipes and other chars that are near the line breaks.
What do I need to change in the regex?
Maybe txt = txt.replace('\n', '') is enough?
Your pattern ([^1|-])\n(.)|(.)\n([^|-]) uses an alternation with 2 capture groups on the left and the right, matching 3 characters in total on each side.
So if you want the capture group data in the result, you would have to use those groups in the replacement.
But this negated character class [^1|-] can also match a space or newline, and does not take multiple whitespace chars into account.
What you might do is match a pipe followed by optional spaces around a newline, and in the replacement use a single pipe.
\|[^\S\n]*\n[^\S\n]*
See a regex 101 demo.
import re
regex = r"\|[^\S\n]*\n[^\S\n]*"
s = ("|A |B |C |\n"
" D |E |\n"
"F |G |")
print(re.sub(regex, '|', s))
Output
|A |B |C |D |E |F |G |
As \s can also match a newline, a shorter option could be using regex = r"\|\s+" but then it will also match spaces after the pipe when there is no newline present.
| common-pile/stackexchange_filtered |
Gmail Label API returns unspecified 500 error for certain threads
I'm updating the labels through the Gmail API using the Python client library, using the following line of code:
thread = service.users().threads().modify(userId='me', id=thread_id, body=msg_labels).execute(http=http)
This works for most threads, but for certain threads it keeps returning a 500 backend error without any specification. The values for "thread_id" and "msg_labels" are correct, I've triple checked. And as said, it works for other threads through the same line of code. What could be causing this error?
500 is a flooding error you are going to fast slow your code down and run the same request again.
This happens after 5 retries, with a random nr of seconds waiting time in between, always on the same threads.
You can make a max of 10 requests a second I believe. If your code gets this error pause it for a second and then run the same request again. Look into implementing exponential backoff.
I have exponential backoff implemented. Also, it is running in a task queue which only allows 10 requests per second and it always happens on the same threads. The issue has to be something else.
Next steps would be to examine the problematic threads and determine if something is unique about them. Might they be chat messages? Any thing else you can identify as unique to these threads (all have certain label maybe?)
Turns out for some reason my code was trying to write a Label Id that didn't exist. Don't know how this could happen, since IDs are retrieved from Gmail directly and I didn't delete it myself. Nevertheless it solved the issue.
| common-pile/stackexchange_filtered |
NoSQL Database Design - Documents with Tagging
Which NoSQL database do you recommend and how would the schema look for the following web application requirements.
There can be lot of users (500k+)
Every user can enter his/her documents
Every user will probably create 10-200 documents per month
Every document will be small (around 100 words)
User can tag documents with his/her own tags
Data from different user does NOT interact with other users and their data
User can search his entries by tags
Fast access to all entries from one user
user can create complex dynamic queries to query his / her data
My idea is to use MongoDB. But the problem that I see is that there would be just two collections: users and entries.
Searching by tags through one gigantic collection looks like a bad idea to me. I am afraid that the size of indexes will be really large, since every user can have his own tags. MongoDB will create tag indexes for the whole collection, but I will always search by tags only through entries from one user and not from all.
Thus a collection per user idea seems more suitable, but there seems to be a limit on how many collections one can create, also this approach appears to be undesired.
CouchDB does not support dynamic queries,...
How should I implement this in MongoDB? Or name a more appropriate NoSQL database.
Examples of similar applications: rememberthemilk, Trello, ...
Which NoSQL database do you recommend and how would the schema look for the following web application requirements.
I am not going to define your application for you as you have asked since we are not here for that however I will answer some of the problems and questions you actually state here.
I am afraid that the size of indexes will be really large, since every user can have his own tags
That is true the index size could be considerable, unless you limited the amount of tags a user can apply. Most sites limit tags by 10 at most, sometimes (like for questions here) 5.
You might wanna look into sharding that collection into smaller pieces across a cluster. Querying by these tags over a properly defined shard index is by no means slow or bad.
Even if the tags index is not your shard index it will still perform a very fast global scatter and gather operation (a good example of query usage across large collections is here: http://docs.mongodb.org/manual/core/sharding/ ).
Sharding can also help distribute the huge size of the index across many commodity computers allowing you to reduce costs but keep up the flow of data.
So the first thing you want to look into is sharding and how it can work to help you, a good place to start in this respect is here: http://docs.mongodb.org/manual/core/sharding/
Thus a collection per user idea seems more suitable, but there seems to be a limit on how many collections one can create, also this approach appears to be undesired.
You also have the problem of a lock, since the lock is not collection level unlike SQL it is infact DB level (and don't forget the namespace restriction which is dependant upon the size of your now "massive" indexes). Many people fall into the trap and I am gong to state now that a normal setup is fine for like 99% of cases, unless you might be Facebook but even then I think it might be fine.
Examples of similar applications: rememberthemilk, Trello, ...
I actually just had someone ask a similar style question: How does Trello store data in MongoDB? (Collection per board?) if you look to the comments there might be some help there too.
The problem with tags is that each user can have his own set of tags. Here at SO all users use the same tags. Even if there is a limit on the number of tags per document, there is not a limit on the number of tags one user can have. Thus there can be a lot of different tags in one collection. Of course I would always search first by user ID and only then by tags...
@Ben Not always, at 1k rep you can make your own tags, even with the high selectivity of the field I don't see a massive problem, fair enough I haven't built your app but immediatly, without testing, I don't see a serious problem if you plan your cluster right. It will be a big index but it is something that cannot be avoided, you could split tags off but then you will loose context searching for some documents since MongoDB has no joins and NoSQL in general don't.
So you think that I should shard per UserID and add indexes to UserID and tags and other fields that I may need to. And that should scale without problems?
@Ben It depends, if 95% of your queries are both user_id and tag then I would shard on a compound index of the two, really this comes down to your querying pattern. What do you do most? You should really really REALLY think about your shard index
All queries are by user_id. Most of the queries are by both user id and tags. No queries are by tags only. But why should I choose more than one sharding key. because if I shard based on user_id, then all data from (at least one) user will be one one server. Thus there is no need for additional tag based sharding, or is it?
@Ben Im gonna go with the bet of a compound index on user_id and tags in that case, MongoDb can use partial indexes so a query only using user_id should be able to use the main shard index. Not all of one users data might be on one server, mongodb will split the chunks as it sees fit which means not all of that user data might be on the single server, though that just gave me another idea, you can use tag aware sharding (v2.2) to actually accomplish that if you like :) which maybe (would need testing) would lower your index size
@Ben I realised that I fleshed out my idea without much explanation just then. You are right in 90% of cases ranging on a single collection will result with that users data being on one shard (unless it doesn't fit, in which case it will be moved) but if you got multiple collections and wanna group the users data then you can do a few tricks with tag aware sharding to get this working right, which in turn could lower index size.
| common-pile/stackexchange_filtered |
In Endgame, why is the female leading the dance, and not the male?
So, in the last scene of Avengers: Endgame, where
Captain America flashes back to his trip to the past to return the Infinity Stones to their rightful places in space-time,
he dances with
Peggy, his past [romance-partner thingy].
The two characters being respectively referred to as X and Y.
In that scene, it is clear that X and Y are dancing backwards. That is, Y's right arm is clearly visible on X's back, meaning that Y's left arm is extended outwards. Therefore, Y is the leading partner in the dance. However, traditionally, this general style of dance has the male partner lead, which is inconsistent with Y (female) leading the dance.
I can't get that (horrible quality) leaked video into the question without spoilers, but I was just using it to show what scene anyway. I've seen the movie, and I'm pretty sure that I remember which person was where, but an image would be appreciated if one exists.
What's going on here? Why are the two dancing backwards? Am I just blind? Is this a mistake? Is there a reason why this occurs?
maybe not answer-worthy, but in the first movie in which they discuss the dance for the first time, they clearly state that Y has danced before, while X never danced (https://www.youtube.com/watch?v=EbpCqCZRj0U). If this is their first dance, it would make sense that she is teaching him how to do that.
@close-voters Okay people, you can't just click the next best close-reason your mouse is over. If you think the question is nitpicky, useless, irrelevant, or opinionated because the asker just doesn't know how dancing works, you'll have to say so. There's enough close-reasons for all of these things and enough room to explain in a custom close-reason, too. But if anything, it's quite clear what he wants to know here. I have reopened the question accordingly.
I might remember it incorrectly, but don't think anyone was leading, instead they were holding each other tight while dancing
Wonderful observation! :)
As established in Captain America: The First Avenger:
Steve Rogers has never had a dance
Steve Rogers does not know how to dance
Since Steve hasn't had the opportunity to learn how to dance since, I would expect this is still the case so Peggy is leading because she knows how to dance.
good answer, I like this one.
| common-pile/stackexchange_filtered |
iPhone SDK strange console message launchd_core_logic.c
I am running release version of the app on the iPhone, it works fine. There is no error messages in the XCode debugger:
Running…
Switching to thread 11779
Switching to thread 11779
sharedlibrary apply-load-rules all
(gdb) continue
Switching to thread 12291
Switching to thread 11779
Switching to thread 13059
Debugger stopped.
Program exited with status value:0.
However I see these messages in the console of iPhone when connect to it via Organizer:
WWed Oct 7 15:37:01 unknown com.apple.launchd[1] : (UIKitApplication:com.blah.blah[0x830c]) Bug: launchd_core_logic.c:2649 (23909):10
Wed Oct 7 15:37:01 unknown com.apple.launchd[1] : (UIKitApplication:com.blah.blah[0x830c]) Working around 5020256. Assuming the job crashed.
Wed Oct 7 15:37:01 unknown com.apple.launchd[1] : (UIKitApplication:com.blah.blah[0x830c]) Job appears to have crashed: Segmentation fault
Wed Oct 7 15:37:01 unknown com.apple.debugserver-43[6124] : 1 [17ec/1603]: error: ::read ( 7, 0x28091c, 1024 ) => -1 err = Bad file descriptor (0x00000009)
Wed Oct 7 15:37:01 unknown SpringBoard[25] : Application 'blah' exited abnormally with signal 11: Segmentation fault
I have tried Apple's UICatalog sample and empty view based app generated by the XCode. They both report exactly the same message as my code in the console. So this is NOT my app related.
There is no crash logs created, so I don't think it is a crash.
What is it? Is it a problem, even though application works perfectly fine?
Thanks
I'm facing the exact same problem, however my app is crashing on me! There is a "low memory warning" sometimes before these logs, but it is not always the case. Also monitoring the memory over the duration of 15-20 mins using Instruments showed nothing alarming, and the app didn't crash at this point. I'm at a loss to debug this. Due to the "file descriptor" error I thought it was because of some sockets I was using in the app, but this looks to be more generic. Please help. (since I'm facing EXACTLY the same logs, not creating a new question).
Also, this crash occurs almost exactly 10-12 minutes after launch - which seems symptomatic of a memory issue, but like I said, Instruments is showing no abnormal usage.
I had the same problem and it gave me problems when testing in app purchases. In the end I found out that I was running the program with an iPhone Distribution code signing instead of an iPhone Development code signing. When I changed that for the Debug configuration (and removed the Entitlements.plist) it worked again. Hope it helps.
It's not a problem. I have similar messages on my console all the time. And as you said it's not your apps fault, so as long as you app runs ok there is no problem.
The message is not from your app, it's from the com.apple.launchd. I think that only the xcode console output is really relevant for you.
Thank you (well, here went 4 hours of my time I spend debugging it :)
| common-pile/stackexchange_filtered |
Date Filtering Malfunction in Powerview
I am building a reporting solution using Powerview on Sharepoint Server 2013 with ssas multidimensional data source.
On the powerview reports I have encountered a strange problem. When I filter using a date attribute with multiple values only the non calculated facts (simple measures, not mdx) are being filtered, while for single date selection everything is filtered correctly.
The strange thing is that in the cube browser everything works fine for all facts and all dates selections.
Any idea would be highly appreciated.
Thanks!
Sample Calculations :
CREATE MEMBER CURRENTCUBE.Measures.NewRequestsCount
as
aggregate({[DM RMS Workflow Actions].[Standard Action FK].&[13],[DM RMS Workflow Actions].[Standard Action FK].&[1]},[Measures].[FC RMS Request Actions Count]),
ASSOCIATED_MEASURE_GROUP='FC RMS Request Actions',format_string="#,##0";
and
CREATE MEMBER CURRENTCUBE.Measures.ForwardsCount
as
aggregate(([DM RMS Workflow Actions].[SN].&[62],[DM RMS Is Fake].[Value].&[Real]),[Measures].[FC RMS Request Actions Count]),
ASSOCIATED_MEASURE_GROUP='FC RMS Request Actions',format_string="#,##0";
Can you include a sample calc which isn't working?
Yes of course, thanks
I just noticed that the behavior is the same for every filter not only the date filters. If I choose multiple values then the calculation is shown for all values.
What is the calculation behind [Measures].[FC RMS Request Actions Count]? Or if it's a physical measure what's the AggregateFunction? If you change Aggregate() to Sum() do you have the same problem?
It is the default count of the measure group. Nothing changes if I use sum. The filters work fine in excel pivot tables also...It must be a Power View related problem
If you comment out the entire MDX script except for the CALCULATE statement and use a physical measure in your report does the multiselect work? I'm wondering if your MDX Script has a scope statement that's causing problems.
Yes the multiselect works. I have encountered problems in the scope on the past but they were happening both in Power View and Cube Browser. Now the problem happens only in Power View :/
So what's the problem SCOPE statement?
It was in a different project than the current in which I am having the problem. Sorry for the misunderstanding
So you are saying that a physical measure works for multiselect but any calculated measure does not work? Even if the calculated measure is Measure*2 or something simple?
Yes exactly! Even for the simplest calculated measure...(tested with measure-1)
Finally I found a solution.
The problem was solved by installing Sql Server 2012 sp3
https://www.microsoft.com/en-us/download/details.aspx?id=49996.
Great news! What version were you on before?
Yes it was a relief, thank you. I was on Sql Server 2012 sp2
| common-pile/stackexchange_filtered |
How to make saved files end up nowhere?
I want to disallow a program from keeping local files, and I thought I would accomplish that by pointing a shortcut with its local folder's name to /dev/null, but I cannot seem to get it working.
If I try ln .app /dev/null, I get a message saying
ln: ‘.app’: hard link not allowed for directory
And if I add symbolic, by doing ln .app /dev/null -s, then I get
ln: failed to create symbolic link ‘/dev/null’: File exists
So I don't really know how to accomplish this idea. What is the correct solution?
Your app is going to assume .app is a directory, but /dev/null is a file, so this isn't likely to work. See How can I create a /dev/null-like “blackhole” directory?
You should be using:
ln -s /dev/null .app
to create a symlink called .app pointing to /dev/null
| common-pile/stackexchange_filtered |
When is Queue.join() necessary?
The Python 3 docs give an example of a worker thread that uses a queue (https://docs.python.org/3/library/queue.html):
def worker():
while True:
item = q.get()
if item is None:
break
do_work(item)
q.task_done()
q = queue.Queue()
threads = []
for i in range(num_worker_threads):
t = threading.Thread(target=worker)
t.start()
threads.append(t)
for item in source():
q.put(item)
# block until all tasks are done
q.join()
# stop workers
for i in range(num_worker_threads):
q.put(None)
for t in threads:
t.join()
In this example, why is q.join() necessary? Don't the subsequent q.put(None) and t.join() operations accomplish the same thing of blocking the main thread until the worker threads have completed?
Here's how I'm understanding the example.
Each worker loops infinitely, always looking for something new from the Queue. If the item it gets is None, it breaks and returns control to main.
So, first we make the program wait for the Queue to be empty. Each call to q.task_done() marks a new item as complete. The code hangs on the following so we make sure every item is marked as done.
# block until all tasks are done
q.join()
Then, below, we add the same number of None items into the queue as there are workers (so we make sure each worker gets one.)
for i in range(num_worker_threads):
q.put(None)
Next, we join all the threads. Since we gave every worker a None item through the Queue, they will all break. Until they all break and return control, we want to hang here.
for t in threads:
t.join()
Doing it this way, we make sure that every item in the Queue is handled, every worker breaks when the Queue is empty, and each worker is shut down before we move on with our code, helping avoid orphan processes.
That's pretty much how I interpreted the example too. So, my question is, isn't every item in the queue handled (and all threads cleaned up) even if we remove the q.join() statement? By joining all the worker threads (the last step) we're still waiting for all the items in the queue to get handled.
Yes, we are still waiting, but I think it's a coded security measure. What if the addition of None were added miraculously before all the items in the Queue were handled and a worker got one? I think it's just a tediously programmed example to make sure you understand what's happening without having to understand completely that Queue goes FIFO (First In, First Out). And besides, this example could be adapted for a LIFO (Last In, First Out) implementation. But, with this current example, I believe you could take out q.join() and it would be fine.
| common-pile/stackexchange_filtered |
How to create a build.xml file for this folder strucure
I have,
build/classes - compiled java codes
libs - some jar files
src - java codes
WebContent - all the .jsp files, WEB-INF/lib and META-INF
i create some build files but they did not work. How to create a build.xml file for this folder structure.
By not making the mistakes that you are currently making :-)
Get Latest Apache ant and start writing :)
Sounds like "Hello, Ant" to me.
Seriously, given the information you've provided, the only sensible answer is to point you at the Ant documentation and/or an example. Now if you showed us your current build.xml file and the error messages you are currently getting, we might be able to answer this more concretely.
Now i get it, error in my folder path. Thanks
Detailed Example of Ant for War File
All the classes inside the src directory should be compiled and placed in a separate build/classes directory. The created war file will be placed inside the dist directory.
So first we create the build/classes and the dist directory. The init target does this job.
The next step is to compile all the classes in the src directory and
place them in the build/classes directory. To do this first you need
to add all the lib files inside the "WebContent/WEB-INF/lib"
directory to the classpath.
The target compile uses the javac task to compile the java classes
and it depends on the target init, because only when you have the
directory ready you can place the classes inside them.The path we created earlier will be refered here using the element.
Now we can create the war file using the war task. To create the war
file you need to specify the web directory, lib directory and the
classes directory. The destfile attribute specifies the war file
location and the webxml attribute specifies the web.xml file
location
You can use the clean target to clean the project. The clean target
deletes the build and the dist directory.
@AmitD Please include a summary from that link (as well as the answer the user needs) and put it in your answer, otherwise it's likely your answer will be deleted as 'not an answer'. We expect answers to be self-containing on this site.
| common-pile/stackexchange_filtered |
placing an element to the right in a linear layout in android
I want to place an image to the right of the view. For that I am tyring to use something like
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
...some other elements
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ImageView
android:id="@+id/imageIcon"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:src="@drawable/image_icon" >
</ImageView>
</LinearLayout>
...
</RelativeLayout>
The above seems to put the image somewhere in the center. How do I ensure that the image is right aligned regardless of whether we are in portrait or landscape mode?
Thanx!
Following seems to work. Two changes
1. use orientation = vertical as suggested by Zortkun
2. Use wrap_content in layout_width.
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="@+id/settingsIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:src="@drawable/settings_icon" >
</ImageView>
</LinearLayout>
android:orientation="vertical" was missing all along.. :) remove it and u ll see..
The default orientation of LinearLayout is horizontal. Make sure the Linear layout's orientation is set to Vertical ortherwise you cannot aling stuff horizontally.
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
Thanx for a super quick response - but sorry - that did not work.
whatelse is in your linearlayout ?
Nothing else. The remaining stuff is within the outer relative layout - basically I want a row with only one image at the right hand side. I can of course use left margin (that works) but I want to use alignment so I do not have to worry about portrait/landscape mode...
yeah you shouldnT use margins in that situation. It should be easy tho. Could you please post your entire xml so we can test better?
Yeah it s definitely the layout orientation: android:orientation="vertical"
Hi Zortkun - thanx for your answer. I did not need to have the "center}right". I thought I had tried this before. Perhaps the "orientation = vertical" is the new thing. Thank you !
Hi ZortKun, Can you please edit your answer to use the layout I gave in my answer (since I know that works in my particular scenario). I would like to mark your answer as the right one. Thanx!
damn you are right! i lost the fight :D i missed that one.. sorry. well, you can always mark urs as the answer. doNT worry :)
You don't need a Linearlayout if you use only one view inside the Linearlayout.
Anyway its here,
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
//...some other elements
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right">
<ImageView
android:id="@+id/imageIcon"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:src="@drawable/image_icon" >
</ImageView>
</LinearLayout>
</RelativeLayout>
| common-pile/stackexchange_filtered |
How can I declare a new operator "!??" (test object is not null)
Is there a way to declare a unary operator such as '!??'
I imagine something like this (non working code)
public bool operator !??<T> (this <T> item) {
return item != null;
}
so I would use it like such
// day is a value and might possibly be null
string greeting = name !?? "hello there " + name;
I find myself often having to do this awkwardness
// day is a value and might be null
string greeting = day != null ? "hello there " + name : "";
It's fairly clear in the example I've provided, but when you are using getter/setters for view-models, it gets a bit confusing to stare at, and raises the chance of a logical error being missed. As such:
public DateTime? SearchDate {
get { return _searchDate; }
set { _searchDate = value != null ? value.Value : value; }
}
This is completely impossible. However, you want C# 6's ?..
#EricLippert has already invented such an operator in his C#6.0 or whatever.
Also, that would be a binary operator.
@AgentFire: Eric Lippert left the C# team before that operator was introduced.
Btw, the setter could simply be _searchDate = value and the other sample is confusing.
How is the example setter any different than set { _searchDate = value; }?
Also note that you can use operator true and operator false to allow instances of types to be used as a condition.
@SLaks Perhaps you could explain the difference between binary operator and unary operator then? I thought it depended on how many operands you must provide, e.g., x < y (here less-than is a binary operator) whereas !x (here exclamation is a unary operator).
@PatrickQ: Exactly. Since you want to write x !?? y, that would be a binary operator.
@TimSchmelter I may have simplified the code too much for the sake of the question. The setter I am actually working with actually does a few operations on the data, IF there is actually data, otherwise it just leaves it as null. So it would be searchDate = value.Value.Date.AddDays(1), for example.
@SLaks Nope, it's unary. In x !?? y, y is not an operand because the statement would expand to if (x != null) then return y. So y is simply the output. y fulfills the then clause of the conditional statement. I'm sure we are probably both saying the same thing, and ultimately I just failed to explain my question very well.
@PatrickQ: That is exactly what an operand means.
@SLaks I disagree. the value returned in the then portion of a conditional statement, has nothing to do with the operator in the condition. if (condition) then {} else {}. what you are saying would imply that !x would be unary operator if used as such bool answer = !answer and a binary operator if used as such string msg = !answer ? "i dont know" : "i found it" Your suggestion is inconsistent. By definition, an "operand" is "the quantity on which an operation is being done", which does not include results.
if is a statement, not an operator. ?: is a ternary operator.
As has been said, you cannot declare new operators in C#, ever, at all. This is a limitation of the language, the compiler, and the environment.
What you CAN do is utilize the null coalescing operator or write a few generic Extension Methods to handle what you want, such as
public static string EmptyIfNull(this string source, string ifValue, string ifNull = "")
{
return source != null ? ifValue : ifNull;
}
and implemented via
string greeting = name.EmptyIfNull("hello there " + name);
Not only do I like this answer, but I understand the question better after having read it! :)
@aravol thanks. This is what I am doing already. I was just hoping to do something that read a little more clearly. Thanks for taking the time to answer me :)
This is completely impossible.
Instead, you can use C# 6's ?. operator:
value?.Value
You have it backwards sir, ?.
@Haney: Oops; fixed. Thanks!
There is no way to declare new operators in C# at all, all you can do is override the existing ones.
C# does not let you define completely new operators, you can only overload a specific set of existing operators.
| common-pile/stackexchange_filtered |
Syntax to put a variable in a string in swift3
A question I think pretty simple but I never had to do it in swift. it's pretty simple PHP but here I do not find my solution on the internet.
ask: I would like to add a variable in this chain of character. Instead of 123, I would need a variable.
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_123.json"
result = final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_VARAIBLE.json"
Can you give me the syntax in swift3 or direct me to a good tutorial.
final let is a contradiction in terms.
You can create a string using string formatting.
String(format:"https://ozsqiqjf.preview.infomaniak.website/empdata_%d.json", variable)
There is good documentation about Strings in Swift Language Guide. Your options are:
Concatenating Strings
let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_" + value + ".json"
String interpolation
let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(value).json"
Swift4 You can add a string in these ways:
var myString = "123" // Or VARAIBLE Here any string you pass!!
var urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(myString).json"
let variable = 123
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(variable).json"
\(variable) is what you need
OR
use string formatting
let variable = 123
final let urlString = String(format:"https://ozsqiqjf.preview.infomaniak.website/empdata_%d.json", variable)
A simple way of doing it could be:
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_" + variablename + ".json"
You can also do it like this (a little more typesafe):
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(variablename).json"
Swift will read \(variablename) into the string automatically and accepts - among all things - integers.
let variable = 123
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_" + variable + ".json"
or
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(variable).json"
| common-pile/stackexchange_filtered |
Not able to access redis port inside a docker container, bind <IP_ADDRESS>
I have installed Redis on an Ubuntu 18 server and it is bind to <IP_ADDRESS>.
Inside that host I have installed Docker as well. If I'll try to connect to the port from the host itself it will work (curl hostIP:6379)
The problem appears when I'm creating a docker service and exec to that container. If I'll try to curl from there I'm receiving: curl: (1) Received HTTP/0.9 when not allowed
The think is that on the same server I have installed RabbitMQ, Elasticsearch and curl on those ports it is working (inside docker container as well), only Redis has that issue.
Any idea?
Thanks,
LE: I founded the issue, is this image: mcr.microsoft.com/dotnet/core/runtime:3.1.1-alpine3.10
but still ... why it is not working inside it?
I'm also asking as I think there is an environment where it is working inside it, and an environment where it is not
Try changing the protected-mode yes to protected-mode no
Did that but still not working
curl only makes HTTP request; Redis isn't an HTTP service (nor is RabbitMQ, but its management interface is).
Of course, the idea is that I can't reach the port :-) ... so ... there is another idea ... and still I can't figure it out
| common-pile/stackexchange_filtered |
Force the JVM to collect garbage early and reduce system memory used early
We operate a Java application that we did not develop.
This application uses quite a lot of memory for certain tasks, depending on the data, that is manipulated, up to 4GB. At other times, very little memory is needed, around 300MB.
Once the JVM grabs hold of a lot of memory, it takes a very long time until the garbage is collected and even longer until memory is returned back to the operating system. That's a problem for us.
What happens is as follows: The JVM needs a lot of memory for a task and grabs 4GB of Ram to create a 4GB Heap. Then, after processing finished, the memory is filled only 30%-50%. It takes a long time for memory consumption to change. When I trigger a GC (via jConsole) the heap shrinks below 500MB. Another triggered GC and the heap shrinks to 200MB. Sometimes memory is returned to the system, often not.
Here is typical screenshot of VisualVM. The Heap is collected (Used heap goes down) but Heap size stays up. Only when I trigger the GC through the "Perform GC"-Button, Heap size is reduced.
How can we tune the GC to collect memory much earlier? Performance and GC-Pause-Times are not much of an issue for us. We would rather have more and earlier GCs to reduce memory in time.
And how can we tweak the JVM to release memory back to the operating system, making the memory used by the JVM smaller?
I do know -XX:MinHeapFreeRatio and -XX:MaxHeapFreeRatio, which helps a bit, but watching the heap with VisualVM shows us, that it's not always obeyed. We set MaxHeapFreeRatio to 40% and see in VisualVM, that the heap is only filled to about 10%.
We can't reduce the maximum memory (-Xmx) since sometimes, for a short period, a lot of memory is acutally needed.
We are not limited to a particular GC. So any GC that solves the problem best can be applied.
We use the Oracle Hotspot JVM 1.8
Maybe try [this question].( http://stackoverflow.com/questions/12842863/why-is-garbage-collector-not-doing-a-more-aggressive-garbage-collection-sooner-t) Not sure what you mean by "Give memory back", though.
"Give memory back" means to release memory back to the operating system, so more memory can be used by other applications and that the memory used by the jvm is lower again.
Gotcha. I made the (incorrect) assumption GC released the memory back to the OS.
Possible duplicate of Does GC release back memory to OS?
None of the possible duplicates really helps in solving the problem fully. It does help to get earlier GC to reduce the used heap. But the JVM does not seam to release memory back to the OS by itself. It does so when a GC is triggered explicitly externally (via Java VisualVM) or internally (via System.gc()).
I'm assuming you use the HotSpot JVM.
Then you can use the JVM-Option -XX:InitiatingHeapOccupancyPercent=n (0<=n<=100) to force the JVM to do garbage collection more often. when you set n to 0, constant GC should take place. But I'm not sure whether this is a good idea regarding your applications response time.
Do you know, what happens, when the heap is filled more than the provided Threshold, but the memory is all used and can't be freed? Will that result in recurring collections until the heap can actually be collected?
OP did not state which collector he's using. InitiatingHeapOccupancyPercent is only applicable to concurrent collectors, so this advice may not be useful.
The JVM Option -XX:InitiatingHeapOccupancyPercent=n does not really cause lower memory consumption. It does cause earlier GC and lower used heap, but the memory is not given back to the OS. Only when a GC is triggered explicitly externally (via Java VisualVM) or internally (via System.gc()), memory is given back to the OS.
| common-pile/stackexchange_filtered |
CSS Two Boxes with same height
All I want is to make right column's height (and images in it) depend on the left. Left one's height keeps changing based on width and right column's height changes too but they are never equal.
CSS
div.home-bottomleft, div.home-bottomright {
float:left;
display:table-row;
padding:10px 0;
}
div.home-bottomleft {
width:45.3%;
background: url(/wp-content/themes/jdesign/images/div-separator.png) right no-repeat;
}
div.home-bottomright {
width:54.7%;
}
HTML
<div class="home-bottomleft">
<img class="home-bottom-motive" src="/wp-content/themes/jdesign/images/homepage-motive.png" alt="Bottom Top Motive" /></p>
<p class="book_antiqua home-bottomtext">XX Events is a full-service event planning company in Chicago dedicated to creating an enjoyable and stress-free planning experience for our clients. We are motivated by event trends, inspired by traditions, and fascinated by all of the details that go into a personalized and flawless event!</p>
</div>
<div class="home-bottomright">
<div class="home-brbox"><img class="home-brbox-img" src="/wp-content/uploads/2013/05/XXevents-bottomleftimg.jpg" alt="XXevents" /></p>
<p>Weddings</p>
</div>
<div class="home-brbox"><img class="home-brbox-img" src="/wp-content/uploads/2013/05/XXevents-bottommiddleimg.jpg" alt="XXevents" /></p>
<p>Social Events</p>
</div>
<div class="home-brbox"><img class="home-brbox-img" src="/wp-content/uploads/2013/05/XXevents-bottomrightimg.jpg" alt="XXevents" /></p>
<p>Showers</p>
</div>
</div>
Left one's height keeps changing based on width and right column's height changes too but they are never equal So what is 45.3% and 54.7% for right and left
What do u want to be equal ?
45.3 and 54.7 is so the separator in the between corresponds the specific part of the page and looks organized
I want left side last line's to be lined up with right side's last line's text.
It's fluid design. I want both sides to get bigger/smaller together not on their own. Images go overboard
is this web alive ? mean public ?
This is part of a WordPress theme? Which means the HTML is probably not open to any change otherwise the layout will break.
You are asking for some tricky stuff here. In your top example, the text is large, so the images may be scaled to fit the height of the parent container, but that would also mean that the width would increase, which could force the images to start another line if they are floated. In your second example with smaller text, you could shrink the images or make the line-height in the left area larger (in some flexible manner, but that could lead to readability problems. How about vertically centering the text block on the left?
So, you have a left column with varied height, and you want the right column's height to be determined by the left (I think - your question is not entirely clear).
The easiest way to do this is to have the left element in flow, and the right element absolutely positioned and stretched to its container.
You can see this effect at: http://jsfiddle.net/yNKxG/1/
A pseduo-HTML example:
<container>
<div, width: 50%;></div>
<div, position: absolute; top: 0; right: 0; bottom: 0; width: 50%;></div>
</container>
Note that this won't include the text resizing you show in your mockup; that will have to be achieved through some other means (possibly only JavaScript, unless the change in the height of the left column is triggered through media query breakpoints).
I don't know how to apply this to my case though.
In the parent element add display:table to your CSS; then on your CSS Columns add display:table-cell.
| common-pile/stackexchange_filtered |
Entity Framework and adding POCOs without adding child objects
So perhaps I'm addressing this problem the wrong way, but I wanted to get the opinion from you fine people on StackOverflow about how to more correctly do this.
I've got a program that has to retrieve information from a repository around an Entity Framework 6.0 code-first context, do some work on the information contained and then it adds a new record to the database.
Anyway, here's the simplified look at the class I'm retrieving from EF through the repository:
public class Product
{
public int Id { get;set; }
public virtual ProductCategory Category { get;set; }
public string Name { get;set; }
}
I then build a ProcessedProduct with the following definition and pass in the previously retrieved Product as the BaseProduct:
public class ProcessedProduct
{
public int Id { get;set; }
public virtual Product BaseProduct { get;set; }
}
I use a repository layer that I saw on an EF lesson on Pluralsight and have purposed here. I've added all the relevant bits below:
public class MyContext : BaseContext<MyContext>, IMyContext
{
//Lots of IDbSets for each context
public void SetModified(object entity)
{
Entry(entity).State = EntityState.Modified;
}
public void SetAdd(object entity)
{
Entry(entity).State = EntityState.Added;
}
}
public class MyRepository : IMyRepository
{
private readonly IMyContext _context;
public MyRepository(IUnitOfWork uow)
{
_context = uow.Context as IMyContext;
}
public ProcessedProduct FindProcessedProduct(int id)
{
return _context.ProcessedProducts.Find(id);
}
public ProductCategory FindCategory(int id)
{
return _context.Categories.Find(id);
}
public int AddProcessedProductWithoutProduct(ProcessedProduct newRecord)
{
newRecord.Product = null;
Save();
return newRecord.Id;
}
public int UpdateProcessedProductWithProductButWithoutChildProperties(int processedProductId, int productId)
{
var processedProduct = FindProcessedProduct(processedProductId);
processedProduct.BaseProduct = FindProduct(productId);
processedProduct.BaseProduct.Category = null;
_context.SetModified(product);
Save();
return processedProduct.Id;
}
public int UpdateProductChildren(int processedProductId, int categoryId)
{
var processedProduct = FindProcessedProduct(processedProductId);
var category = FindCategory(categoryId);
processedProduct.BaseProduct.Category = category;
_context.SetModified(product);
Save();
return processedProduct.Id;
}
}
And finally, here's the portion that pulls it all together:
try
{
//Create the processed product without the product instance
var processedProductId = repo.AddProcessedProductWithoutProduct(finishedProduct);
//Now, update this processed product record with the product. This way, we don't create a
//duplicate product.
processedProductId = repo.UpdateProcessedProductWithProductButWithoutChildProperties(processedProductId, product.Id);
//Finally, update the category
processedProductId = repo.UpdateProductChildren(processedProductId, product.Category.Id);
//Done!
}
When I attempt to insert this ProcessedProduct into EF, it correctly creates the ProcessedProduct record, but it also creates a new Product and new Category row. I've tried manually changing the change tracking for each object so ProcessedProduct would be 'added' and the others would be either 'modified' or 'unchanged', but I would get foreign key reference exceptions thrown by Entity Framework.
My "fix" was to simply break this up into a number of different calls:
I create the new ProcessedProduct record, but I assign the Product value to null.
I query for that ProcessedProduct record with the Id, query for the appropriate Product with its Id and assign that Product to the newly retrieved ProcessedProduct record. However, I have to null out the Category property or else this will add a new duplicate Category record. I save and the ProcessedProduct record is modified.
Finally, I query the ProcessedProduct once more as well as the ProductCategory and then assign that ProductCategory to the Category property of the ProcessedProduct.BaseProduct. I can save once more and now I've created all the records I need without making any of the duplicates.
However, this approach seems quite convoluted since all I originally wanted to do is save the new parent record and simply not create duplicate child records. Is there a better way to go about doing this that I'm missing? Thanks!
Edit: And I guess the larger question is say I have a complex object with a whole bunch of these child complex objects. What's the easiest way to create a new parent without having to go through the entire graph of child objects to update the parent with them one layer at a time?
did you miss the BaseProductId (or something else) in you ProcessedProduct? or you have it but didn't show it?
No, if I look at the debug, all the Ids are there as expected (it's where I actually get the ProductId for the future lookups). If I look at the originally created ProcessedProduct, I can get the Id for the ProcessedProduct.Product.Id as well as ProcessedProduct.Product.Category.Id.
Just usually I create explicitly add id of dependent entities. In that case you can try just to create new ProcessedProduct setting that Id.
Can you show us the code how you insert the ProcessedProduct?
@J.W. Code added above. Let me know if you need any more than that, though I think that about covers it.
@Nicolai, the problem with that is if I have a huge chain of child entities, that's an awful lot of code I'll have to dig through to manually just specify the Id for every single one of them. Surely this has been addressed in the framework somewhere.
I highly recommend not setting Product & Category as navigation properties when editing. As you saw when you add the graph of processed product (with a product & category attached) to the EF context, it's marking everything in the graph as added and does inserts on everything.
The pattern I always recommend (and Nikolai also suggested in his comment, so up-vote his comment like I did :)) is to include the FK IDs in your entity and set those values, not the navigations. e.g.
newRecord.ProductId=theProductIdValue.
I've had many people cry "but foreign keys? ewwww! They will make my classes so dirty and impure!" but after they see how much easier it is to code things without tangling with the navigations in these scenarios, they have come back to say "okay, it was worth it!"
BTW if you are talking about my EF in the Enterprise course, I have a whole module about dealing with this problem...it's called something bout graphs in disconnected scenarios. :)
| common-pile/stackexchange_filtered |
Unit testing method with input parameters from multiple data tables
I would like to create unit test method using Microsoft Unit testing and this method take its input parameters from different tables inside the same DB .
[TestMethod()]
[DataSource("System.Data.SqlClient", "Data Source=ServerName;Initial Catalog=DBName;Persist Security Info=True;User ID=--;Password=--",
"Table1", DataAccessMethod.Random), TestMethod]
public void MyTestMethod(int parameter1,int parameter2)
{
}
For example, parameter1 from table1 and parameter2 from table 2. Can I do that ?
Also, can I make a condition e.g join 2 tables to retrieve sample test data or you can retrieve parameter2 from table2 filtering by parameter1?
All ideas are welcomed.
I don't think it's possible, given TableName property on DataSource attribute requires you to specify one name explicitly. What you could do instead, is create a view with data you need, that includes joining your two original tables.
Examples on how to use DataSource attribute properly can be found at online MSDN documentation.
| common-pile/stackexchange_filtered |
1: This network topology problem is driving me crazy. We need a graph that's sparse but still maintains good connectivity between any two nodes.
2: What do you mean by "good connectivity"? If we want every pair connected with short paths, wouldn't we just make it dense?
1: That's the issue - we can't afford dense connections. Think about it: if we have $n$ nodes and make it dense, we're talking about $O(n^2)$ edges. But what if we only use $O(n)$ edges and still get the connectivity properties we want?
2: How's that even possible? With linear edges, most graphs would have bottlenecks where removing just a few edges disconnects large chunks.
1: Unless the edges are distributed really cleverly. Look, suppose we have any subset $S$ of vertices with at most $n/2$ nodes. In a good sparse graph, the number of edges leaving $S$ should be proportional to the size of $S$.
2: Wait, that sounds backwards. Smaller sets would have fewer boundary edges, making them easier to isolate.
1: Exactly the opposite! That's what makes these graphs special. Even small sets have lots of connections to the rest of the graph. If every set of size $k$ has at least $\alpha k$ edges leaving it, then you can't create bottlenecks.
2: So you're saying the expansion ratio - boundary edges divided by set size - stays bounded below by some constant $\alpha$?
1: Right! And here's the weird part: random $d$-regular graphs actually achieve this with high probability. Just pick random perfect matchings and union them.
2: But wouldn't random graphs be useless for practical applications? You can't tell someone "just use a random graph" in a real system.
1: That's where the explicit constructions come in. People have found algebraic ways to build these graphs determin | sci-datasets/scilogues |
C++ wstring how to assign from NULL-terminated wchar_t array
Most texts on the C++ standard library mention wstring as being the equivalent of string, except parameterized on wchar_t instead of char, and then proceed to demonstrate string only.
Well, sometimes, there are some specific quirks, and here is one: I can't seem to assign a wstring from an NULL-terminated array of 16-bit characters. The problem is the assignment happily uses the null character and whatever garbage follows as actual characters. Here is a very small reduction:
typedef unsigned short PA_Unichar;
PA_Unichar arr[256];
fill(arr); // sets to 52 00 4b 00 44 00 61 00 74 00 61 00 00 00 7a 00 7a 00 7a 00
// now arr contains "RKData\0zzz" in its 10 first values
wstring ws;
ws.assign((const wchar_t *)arr);
int l = ws.length();
At this point l is not the expected 6 (numbers of chars in "RKData"), but much larger. In my test run, it is 29. Why 29? No idea. A memory dump doesn't show any specific value for the 29th character.
So the question: is this a bug in my standard C++ library (Mac OS X Snow Leopard), or a bug in my code?
How am I supposed to assign a null-terminated array of 16-bit chars to a wstring?
Thanks
Just a shot in the dark, try a double null terminator
@obelix, a null character is the same both big- and little-endian.
@Nick - yep. i saw binary and thought it might be endianness
Under most Unixes (Mac OS X as well), whar_t represents UTF-32 single code point, and not 16bit utf-16 point like at windows.
So you need to:
Either:
ws.assing(arr,arr + length_of_string);
That would use arr as iterator and copy each short int to wchar_t.
But this would work only if your characters lay in BMP or representing UCS-2
(16bit legacy encoding).
Or, correctly work with utf-16: converting utf-16 to utf-32 -- you need to find surrogate pairs and merge them to single code point.
Just do it. You didn't in your code, you assigned an array of unsigned shorts to a wstring and you used a cast to shut the compiler up. wchar_t != unsigned short. You certainly can't assume they have the same size.
I'd think your code would work, just by inspection. But you could always work around the trouble:
ws.assign(static_cast<const wchar_t*>(arr), wcslen(arr));
If ws.assign can't find the proper terminating point of the string by picking out the null character, why would wcslen? I think Artyom hit the nail on the head -- wchar_t != unsigned short.
| common-pile/stackexchange_filtered |
When to use references in for loops?
An example from the documentation about vectors:
let v = vec![1, 2, 3, 4, 5];
let third: &i32 = &v[2];
println!("The third element is {}", third);
match v.get(2) {
Some(third) => println!("The third element is {}", third),
None => println!("There is no third element."),
}
I can't see why third needs to be a reference. let third: i32 = v[2] seems to work just as well. What does making it a reference achieve?
Similarly:
let v = vec![100, 32, 57];
for i in &v {
println!("{}", i);
}
why is it in &v instead of just in v?
let third: i32 = v[2] works because i32 implements Copy trait. They don't get moved out when indexing the vector, they get copied instead.
When you have a vector of non Copy type, it is a different story.
let v = vec![
"1".to_string(),
"2".to_string(),
"3".to_string(),
"4".to_string(),
"5".to_string(),
];
let third = &v[2]; // This works
// let third = v[2]; // This doesn't work because String doesn't implement Copy
As for the second question about the loop, for loop is syntactic sugar for IntoIterator which moves and consumes.
So, when you need to use v after the loop, you don’t want to move it. You want to borrow it with &v or v.iter() instead.
let v = vec![100, 32, 57];
for i in &v { // borrow, not move
println!("{}", i);
}
println!("{}", v[0]); // if v is moved above, this doesn't work
| common-pile/stackexchange_filtered |
Model of ordered plane with the negation of Pasch's axiom
I am interested in finding the model of particular set of geometry axioms in which Pasch's axiom fails. First I'll give the definitions.
By ordered line I mean the set $L$ (line) with one three-argument relation $B$ whenever the following axioms are satisfied:
There exist $a,b$ such that $a\neq b$
If $a\neq b, b\neq c, a\neq c$, then $B(abc)\vee B(bac)\vee B(acb)$
If $B(abc)$, then $a\neq c$
If $B(abc)$, then $B(cba)$
If $B(abc)\wedge B(acd)$, then $B(bcd)$
If $a\neq b$, then there exists $c$ such that $B(abc)$
If $a\neq c$, then there exists $b$ such that $B(abc)$
I'll also give Hilbert's plane axioms of incidence: We consider a set $P$ (plane) and a family $\mathcal{L}$ of subsets of $P$ (family of lines) with axioms:
For any two distinct points $a,b$, there exists exactly one line $L$ such that $a,b\in L$
For any line $L$, there exist two distinct points $a,b$ such that $a,b\in L$
There exist three distinct points not lying on one line
Question.
What I am looking for is the model $(P,\mathcal{L},B)$ such that
$(P,\mathcal{L})$ is the model of Hilbert's plane incidence axioms
For any line $L\in\mathcal{L}$, $(L,B|_L)$ is an ordered line
Whenever $B(abc)$, then $a,b,c$ are collinear
Pasch's axiom fails
I am aware of these two questions
A model of geometry with the negation of Pasch’s axiom?
Are there simple models of Euclid's postulates that violate Pasch's theorem or Pasch's axiom?
and the model constructed using the solutions of Cauchy's equation is also the model for my problem, but I wonder whether we can construct the model for my problem without axiom of choice (note that I don't require congruence, continuity and parallel axioms to hold)
By the way, often people drop axioms 5 and 7 of your ordered line, since they can be deduced from Pasch's axiom. (For example, see Hilbert's axioms on Wikipedia.) In that case, if we also drop Pasch's axiom, we get weirder models, including even some finite geometries. But your axiomatization of an ordered line, I think, guarantees that the line contains infinitely many points.
One possible example is coordinate geometry over the dyadic rationals: numbers of the form $\frac{a}{2^b}$,where $a,b \in \mathbb Z$.
We give this the inherited structure of the usual geometry on $\mathbb R^2$, but throw away all points whose $x$- and $y$-coordinates don't have this form, and throw away all lines not containing at least two of the remaining points.
Since all of your axioms were satisfied before we threw away points, the only ones we need to check are the axioms that claim something exists. (We need to check we didn't throw it away.) So:
There is still a line through any two points. We only threw away lines that only contained at most one dyadic rational point, such as the line $y = \pi x$.
Any line contains at least two points. If it didn't, then we threw it away!
If $P,Q$ are distinct points, there is a point $R$ such that $B(P,Q,R)$. If $P = (x_1,y_1)$ and $Q = (x_2,y_2)$, then we can take $R = (2x_2 - x_1, 2y_2 - y_1)$.
If $P,Q$ are distinct points, there is a point $R$ such that $B(P,R,Q)$. If $P=(x_1,y_1)$ and $Q = (x_2,y_2)$, then we can take $R = (\frac{x_1 + x_2}{2}, \frac{y_1 + y_2}{2})$.
Finally, Pasch's axiom is violated because some lines no longer have the intersection points they should. For example, if we take the triangle with vertices $A = (1,0)$, $B = (-1,0)$, and $C = (0,1)$, then the line $y=2x$ intersects side $AB$ at $(0,0)$ but doesn't intersect $AC$ or $BC$. (It used to intersect $AC$ at $(\frac13,\frac23)$, but then we threw away that point.)
The other common axioms this violates are:
Completeness: we can extend this plane to a bigger one that contains it by returning to $\mathbb R^2$. (We don't even have any of the circle intersection properties, which are weaker than completeness.)
The parallel postulate: lots of lines become parallel because we threw away their intersection points.
Segment copying: we can't, for example, copy a segment of length $1$ onto the line $y=x$.
Also, depending on how some of your angle axioms are stated, they might be iffy here since this geometry doesn't have plane separation. (This will always be an issue, though, since plane separation is equivalent to Pasch's axiom!)
Another kind of example is the missing strip plane. Here, we also throw away some points: we start with $\mathbb R^2$ and throw away the points $(x,y) : 0<x \le 1$, along with vertical lines with equation $x=c$ where $0<c\le1$. We modify the definition of the length of a line segment: if a line segment $AB$ lies on a line with slope $m$, and $A$ and $B$ are on opposite sides of the missing strip, then we decrease the length of $AB$ by $\sqrt{1+m^2}$ from the usual length.
This plane actually satisfies some notions of completeness: for example, it satisfies the line completeness axiom, since every line in the missing strip plane looks exactly like a line in the usual Cartesian plane, on its own.
Apart from Pasch's axiom (which is violated because we can draw a diagram where an intersection point ought to be in the missing strip), it only violates the parallel postulate (for similar reasons) and SAS triangle congruence (which Hilbert takes as an axiom).
| common-pile/stackexchange_filtered |
Read already allocated memory / vector in Thrust
I am loading a simple variable to the GPU memory using Mathematica:
mem = CUDAMemoryLoad[{1, 2, 3}]
And get the following result:
CUDAMemory["<135826556>", "Integer32"]
Now, with this data in the GPU memory I want to access it from a separate .cu program (outside of Mathematica), using Thrust.
Is there any way to do this? If so, can someone please explain how?
No, there isn't a way to do this. CUDA contexts are private, and there is no way in the standard APIs for a process to access memory which is allocated in another processes context.
During the CUDA 4 release cycle, a new API called cudaIpc was released. This allows two processes with CUDA contexts running on the same host to export and exchange handles to GPU memory allocations. The API is only supported on Linux hosts running with unified addressing support. To the best of my knowledge Mathematica doesn't currently support this.
Thank you for your answer talonmies. I know that in C++ however it is possible to read memory locations by manually setting a pointer such as chare=(char)0x28fe45. As Thrust uses pointers and Mathematica gives me the memory offet (on the GPU), <135826556> I was thinking that maybe I could manually point to it. Also as I know the var type I should be able to know where the allocation ends as well. Does this seem possible?
As I already said in my answer, No. There is memory protection in the driver which keeps each context private. The GPU addresses in each context are also virtual, it requires context specific translation lookaside buffer programming to map them to real addresses. The only way this can be done is via cudaipc and Mathematica doesn't support it.
| common-pile/stackexchange_filtered |
Angular route does not navigate to route until data is resolved
I have a simple web app that has a detail page. When end users click on the link the route does navigate to the page until the data on the page is ready. Ideally I would like to display the page right away and update the UI accordingly. Is there anything I am doing incorrectly? Below please review what I have.
In my routes file:
import { Routes } from '@angular/router';
import { DetailsComponent } from './details/details.component';
export const AppRoutes:Routes = [
{ path: 'details/:id', component: DetailsComponent },
{ path: '', redirectTo:'/home', pathMatch: 'full' }
]
View from where link is clicked to navigate to details
<div *ngFor="let data of privateInfo; let i = index">
<span>{{i}}</span>
<span><a [routerLink]="['/details', i]">Review Details</a></span>
</div>
Detail Component
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { PrivateModel } from '../models/app-model';
@Component({
selector: 'app-details',
template: `
<div>
<pre>{{ privateInfo }}</pre>
</div>
`
})
export class DetailsComponent implements OnInit {
public privateInfo:Array<any>;
public detailID;
constructor(public PrivateModel:PrivateModel, private route:ActivatedRoute) {
this.detailID = route.snapshot.params['id'];
}
ngOnInit() {
this. privateInfo = this.PrivateModel[this.detailID];
}
}
Looking at the Angular docs there seems to be a noPreloading class but not sure how to utilize that. Any help and or an extra set of eyes would be greatly appreciated.
You should be using the resolve property during your route definition as below,
export const AppRoutes:Routes = [
{ path: 'details/:id', component: DetailsComponent ,resolve: {details: DetailsResolver} },
{ path: '', redirectTo:'/import', pathMatch: 'full' }
]
Your DetailsResolver service must be as below
import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot,
ActivatedRouteSnapshot } from '@angular/router';
import { DetailsService } from '....';
@Injectable()
export class DetailResolver implements Resolve<Details> {
constructor(private cs: DetailsService, private router: Router) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<Details> {
let id = route.params['id'];
return this.cs.getDetails(id).then(details => {
if (details) {
return details;
} else { // id not found
this.router.navigate(['/error']);
return null;
}
});
}
}
| common-pile/stackexchange_filtered |
Cohomology of a smoothly embedded space curve
Let $\mathbb{P}^3 = P(\mathbb{C}^4)$ and $\gamma:C\rightarrow \mathbb{P}^3$ be a smoothly embedded algebraic space curve. Then its total Chern class is $c(C) = c(TC) = 1+a\in H^*(C)$, where $a^2=0$. Since $C$ is compact and orientable we have Poincare duality and hence a well defined 'shriek - map' $$\gamma^!: H^*(C)\overset{PD_C}{\longrightarrow} H_{2-*}(M) \overset{\gamma_*}{\longrightarrow} H_{2-*}(\mathbb{P}^3)\overset{PD_{\mathbb{P}^3}^{-1}}{\longrightarrow}H^{*+4}(\mathbb{P}^3).$$
Let $g$ be the genus of $C$ and let $\chi(C):=2-2g$ and $d$ be the degree of $C$. Then $$\gamma^!(1) = d\cdot c_1(\mathcal{O}_{\mathbb{P}^3}(1))^2\quad\text{and }\quad \gamma^!(a) = \chi \cdot c_1(\mathcal{O}_{\mathbb{P}^3}(1))^3.$$
Does anyone know why these two relations hold and point me to some literature? My knowledge in algebraic geometry is very limited since I am more familiar with manifolds, homology/cohomolgy of topological spaces so Chern classes for me are always defined in that context. I know that there are Chern classes in algebraic geometry (i.e. for Chow rings) and that these notions are related, but my understanding is very superficial.
Still it would help me a lot if I could understand the relations above. Thanks!
The answer is pretty exhaustive, but let me just mention that there is a functorial map $A^(X) \to H^{2}(X)$ when said groups are defined, and it basically does what you expect. So your knowledge of topological Chern classes can be ported with relative ease to AG.
It is, and I don't expect anyone to give me all the details but maybe sketch the ideas behind it and tell me what keywords to look for. At my institute, I am literally the only one working with cohomology/homology, characteristic classes and so on so there is nobody to ask.
Take a look at Eisenbud-Harris' 3264 & All That. It's an introduction to methods of working with the Chow ring based on solving specific enumerative problems that should give you a pretty good idea of how these things fit together. It was deliberately written to be as orthogonal as possible in presentation to Fulton's Intersection Theory, which is the unique rigorous exposition of the foundations of this subject and is a useful supplement.
I actually have it here but I found myself getting distracted by details about schemes. Still, I know most of what I know about Chow rings from this book. I work in the field of global singularity theory, mostly Thom polynomials. The language used there is mostly algebraic topology, but there are applications in enumerative geometry, that unavoidably lead to algebraic geometry...
I see; I suppose there's nothing in particular to clear up then? It's just a global problem with the language?
I'd call myself a beginner still so there are many things in particular I haven't quite understood yet. Eric below answered my specific question very detailed, but still I have to work my way through his the answer step by step. The key point, as I see it, is the relation of Poincaré duality of fundamental classes of oriented submanifolds and their intersection.
OK; one thing I might recommend if Eisenbud and Harris' use of scheme-theoretic language is confusing you is taking a look at their older book The Geometry of Schemes. I believe in the introduction of 3264 they say something like "an evening spent with TGoS is probably enough background in schemes for getting started with this book." It's a fairly short and informal book that is unconcerned with systematic exposition; instead, the focus is on elucidating how the language of schemes gives us access to more refined geometric information via pictures and examples.
You can understand these facts using just a bare minimum of algebraic geometry.
All you need to know about $c_1(\mathcal{O}_{\mathbb{P}^3}(1))$ in this context is that it is the standard generator of $H^2(\mathbb{P}^3)$ (corresponding to the fundamental class of $\mathbb{P}^1=S^2$ when you restrict to $\mathbb{P}^1\subset\mathbb{P}^3$). This can also be described as the Poincaré dual of the fundamental class of $\mathbb{P}^2\subset\mathbb{P}^3$, or of any hyperplane in $\mathbb{P}^3$ (since the inclusion maps of different hyperplanes $\mathbb{P}^2\to\mathbb{P}^3$ are all homotopic). How you prove this depends on how you define Chern classes, but for some definitions it is essentially by definition: for instance the first Chern class of the tautological line bundle on $\mathbb{P}^\infty$ can be defined to be negative the standard generator of $H^2(\mathbb{P}^\infty)$, and then for other line bundles it can be defined by pulling back under the classifying map to $\mathbb{P}^\infty$. The bundle $\mathcal{O}_{\mathbb{P}^3}(1)$ is just the dual of the tautological bundle on $\mathbb{P}^3$, so its first Chern class is the negative of the first Chern class of the tautological bundle, which is just the pullback of the tautological bundle under the inclusion $\mathbb{P}^3\to\mathbb{P}^\infty$.
Let me now say a bit about Poincaré duality on $\mathbb{P}^3$. If you have two smooth oriented submanifolds $A$ and $B$ of an oriented manifold which intersect transversely, then the Poincaré dual of the fundamental class of the intersection $A\cap B$ is just the cup product of the Poincaré duals of the fundamental classes of $A$ and $B$. This plays very nicely with smooth subvarieties of $\mathbb{P}^3$ via Bézout's theorem. In particular, if $H\subset\mathbb{P}^3$ is a hyperplane, Bézout's theorem says that for any smooth curve $C\subset\mathbb{P}^3$ of degree $d$ which intersects $H$ transversely, $C$ and $H$ intersect at $d$ points. So, writing $t$ for the Poincaré dual of the fundamental class of $H$ (which, as mentioned above, is $c_1(\mathcal{O}_{\mathbb{P}^3}(1))$) and $c$ for the Poincaré dual of the fundamental class of $C$, $tc=dt^3$.
Now to compute $\gamma^!(1)$, we first take the Poincaré dual of $1\in H^0(C)$, which is just the fundamental class $[C]\in H_2(C)$. Then we push this forward to get the class $[C]\in H_2(\mathbb{P}^3)$, and take its Poincaré dual $c\in H^4(\mathbb{P}^3)$. Since $tc=dt^3$, this class $c=\gamma^!(1)$ must be $dt^2$.
To compute $\gamma^!(a)$, we first take the Poincaré dual of $a=c_1(TC)\in H^2(C)$. The top Chern class of a vector bundle is the same as its Euler class, and the Euler class of the tangent bundle of an oriented manifold is dual to the Euler characteristic of the manifold (that's why it's called the Euler class). So the Poincaré dual of $a$ is $\chi\in H_0(C)$ (when you identify $H_0(C)$ with $\mathbb{Z}$ in the canonical way). Pushing this forward to $\mathbb{P}^3$ we get $\chi\in H_0(\mathbb{P}^3)$, whose Poincaré dual is $\chi t^3$.
This was indeed very helpful, thanks! I have a decent understanding of Chern classes in the context of topology, i.e. Milnor/Stasheff is my "bible" in that regard. I know that the $\mathcal{O}_X(n)$ notations means Serre's twisted sheaves and that it's the same as (tensor products) of the tautological line bundle and/or its duals for $X=\mathbb{P}^n$. But still I would call myself a beginner in that field (as you see from my question), especially when it comes to applications and the relation to AG.
Your explanations are very helpful for me!
| common-pile/stackexchange_filtered |
Function to activate WordPress theme inside a plugin
I am creating a plugin that generates a theme, and so I want to have a checkbox at the end of the theme generation process that gives the possibility to activate the freshly created theme without having to do it manually.
Is there any function that can do that?
Of course there’s a function for that (Codex):
switch_theme( $stylesheet )
It:
Switches current theme to new template and stylesheet names. Accepts
one argument: $stylesheet of the theme. ($stylesheet is the name of
your folder slug. It's the same value that you'd use for a child
theme, something like twentythirteen.) It also accepts an additional
function signature of two arguments: $template then $stylesheet. This
is for backwards compatibility.
And why is that any better? WordPress uses filters and actions for many things. For example, when you switch the theme, the unused widgets will get saved, so you can restore them in new sidebars... All of that won’t be done, if you switch the theme directly in DB.
The only thing that comes to my mind is to do it from the database, so basically after you check the checkbox status, you will have to select the wp_options table, you will need to locate two rows template and stylesheet.
Then you will have to update alexandria for youThemeName. That query will look like this:
$query = "UPDATE wp_options SET option_value='youThemeName' WHERE option_name='template' OR option_name='stylesheet';";
$wpdb->query($query);
I don’t think that’s the best way to do it. It’s always pretty risky to mess with DB in such cases...
Thanks for pointing that out, I didn't know about that.
| common-pile/stackexchange_filtered |
Should I implement lazy loading based on a client cursor or a publication?
I need to confirm something. Considering that a publication returns a cursor, and the cursor is a handle on the related collection on client side:
As long as I don't fetch() the cursor documents, I don't have actually downloaded their data?
Does that mean that it could be a good approach to filter publishable documents in the publication and do the lazy loading of them client side?
As long as I don't fetch() the cursor documents, I don't have actually downloaded their data?
That's false. When the client subscribes to a publication, the server will send the entire matching set immediately, even if the client doesn't use the data for some time. That's why fetch on the client is able to return the documents synchronously (assuming the subscription is ready()).
If you don't want the client to download something, you have to filter it out in the publish function.
You can also track the state of the download with the reactive ready().
Ok. Thank you for the answer. I split my items by channel, each of them is filtered depending on if the user is member of the channel. It's gonna be a pain to lazy load each channel items in the publication (3 first items or a 9 item range).
| common-pile/stackexchange_filtered |
Trying to focus on an element in a $mdSideNav
I am making an angular app that has a chat function. I have a sidenav that loads messages and a chat box. The chat box is fixed to the bottom of the screen and the messages are separately scrollable above it. I would like to focus on the last message when the sidenav is opened. I am no sure how to do this however as the messages are being displayed in an ng-repeat.
HTML:
<div style="display: flex; flex-flow: column; height: 100%;">
<div>
<md-toolbar class="md-blue-grey" >
<h1 class="md-toolbar-tools">
<span>Chat</span>
</h1>
</md-toolbar>
</div>
<div style="min-height: 0; flex: 1; overflow: auto;">
<div style="height: 200px;">
<div id="messages" ng-repeat="mess in messages track by $index" >
<md-card ng-attr-id="mess{{$index}}" >
<p ><b>{{mess.user}}</b></p>
<p >{{mess.time | date:'medium'}}</p>
</md-card>
</div>
</div>
</div>
<div>
<chat-input></chat-input>
</div>
</div>
I dont think you guys need to see my Javascript but if you do. Let me know and I will post it. Any and all help would be greatly appreciated.
This will change the background-color of yr message, similarly u can add yr custom effects to last message.
<md-card ng-attr-id="mess{{$index}}" >
<span ng-style="$last && {'background-color':'red'}">
<p ><b>{{mess.user}}</b></p>
<p >{{mess.time | date:'medium'}}</p>
</span>
</md-card>
This will highlight the last md-card in yr md-cards. Make a plunk with yr code for quick help.
| common-pile/stackexchange_filtered |
php recursive include function in 2 file with different path
Hi all I've a problem with include function in php:
I have 4 file:
dir1/file1.php
dir4/dir2/file2.php
dir3/file3.php
dir3/file4.php
In file1.php I have:
include_once('../dir3/file3.php');
In file3.php I have:
required('../dir3/file4.php');
In file2.php I want write:
include_once('../../dir3/file3.php');
but the required function in file3 doesn't work because the path of file4 must be
../../dir3/file4.php
and not
../dir3/file4.php
How can I fix it?
If you figured it out yourself, you can post a answer if you want, don't write it in the question. (Added a answer, maybe it solves your problem too)
You can use only dot (.) before your filename which will find that file from root of dir..for eg ./dir3/file4.php but it increase the overhead..Another way is to use
$base = __DIR__ . '/../';
require_once $base.'_include/file1.php';
with include_once('./dir3/file3.php'); in file1.php not work.
And I want use the php application in window e linux system.
If you are calling file3 from file2 you will have to go back 2 directories. The best way is using the full path like :
home/mysite/public_html/dir3/file3.php
It maybe (is) troublesome but good uptill some level.
Edit: DIR and rest is also handy, depending on your need
sorry but the path can change with different OS. I want a portable php application.
I FIX it with:
In file1.php I have:
$path = '..';
include_once($path.'/dir3/file3.php');
In file3.php I have:
required($path.'/dir3/file4.php');
In file2.php I want write:
$path = '../..'
include_once($path.'/dir3/file3.php');
This work for me.
| common-pile/stackexchange_filtered |
Add quick view button on magento products
I am trying to add a quick view button on all magento products. I am able to add the button next to the add to cart on product info page but not getting the reference for the product image.
This is my layout xml file.As the reference here is head it adds the button to the head of every page. I want it on every product image on that page.
<default>
<reference name="head">
<block type="core/template"
name="mudit_swiftview_footer"
template="mudit_swiftview/swiftview.phtml" />
</reference>
</default>
check http://www.magentocommerce.com/magento-connect/em-quick-shop-quick-view-product.html.
they use JavaScript to insert the button on the fly. the example below will insert the quick view button on the top/left corner (in this case) on mouseover.
$(selectorObj.imgClass, this).bind('mouseover', function() {
var o = $(this).offset();
$('#em_quickshop_handler').attr('href',reloadurl).show()
.css({
'top': o.top+(1.5 * $(this).height() - qsHandlerImg.height())/2+'px',
'left': o.left+(1.5 * $(this).width() - qsHandlerImg.width())/2+'px',
'visibility': 'visible'
});
});
_qsJnit({
itemClass : '.products-grid li.item', //selector for each items in catalog product list,use to insert quickshop image
aClass : 'a.product-image', //selector for each a tag in product items,give us href for one product
imgClass: '.product-image img' //class for quickshop href
});
check their JS code to learn more.
hope it helps.
| common-pile/stackexchange_filtered |
Elastic APM does not track http-transactions
APM client for PHP does not track HTTP transactions.
In the view, I see only cli transaction type.
Also, other services which call this service does recognize this service as external.
APM version: 1.7.1
PHP version: 8.1
The issue was due to APM version 1.7.1.
Probably 1.7.2 have fixed integration with fpm or something
I have updated to 1.8.1 and integration start to work correctly.
| common-pile/stackexchange_filtered |
Multiple Image upload in django rest framework
How to upload multiple images in DRF. I'm getting all the list of images while looping through it, but it only saves the last one. I want to save all the image and show it in response. Do I have to create separate serializer for Multiple Image serialization?
#models
class ReviewRatings(models.Model):
user = models.ForeignKey(Account, on_delete=models.CASCADE)
product = models.ForeignKey(Products, on_delete=models.CASCADE)
rating = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(5)])
created_at = models.DateField(auto_now_add=True)
review = models.CharField(max_length=500, null=True)
updated_at = models.DateField(auto_now=True)
def __str__(self):
return self.product.product_name
class ReviewImages(models.Model):
review = models.ForeignKey(ReviewRatings, on_delete=models.CASCADE, related_name='review_images', null=True, blank=True)
images = models.ImageField(upload_to='reviews/review-images', null=True, blank=True)
def __str__(self):
return str(self.images)
#Serilaizer
class ReviewImagesSerializer(ModelSerializer):
class Meta:
model = ReviewImages
fields = ["images"]
class ReviewSerializer(ModelSerializer):
user = SerializerMethodField()
review_images = ReviewImagesSerializer(many=True)
class Meta:
model = ReviewRatings
fields = [
"user",
"rating",
"review",
"created_at",
"updated_at",
"review_images",
]
def get_user(self, obj):
return f"{obj.user.first_name} {obj.user.last_name}"
#Views
class SubmitReview(APIView):
permission_classes = [IsAuthenticated]
def post(self, request, product_slug):
data = request.data
if data["rating"] == "" and data["review"] == "":
review = ReviewRatings.objects.create(
user=request.user,
product=product,
rating=data["rating"],
review=data["review"],
)
review_images =request.FILES.getlist('review_images')
rev = ReviewImages()
for image in review_images:
rev.review=review
rev.images = image
rev.save()
serializer = ReviewSerializer(review, context={'request':request})
return Response(serializer.data, status=status.HTTP_201_CREATED)
#Postman
Response I get on the current implementation
{
"user": "Jackson Patrick Gomez",
"rating": 4.8,
"review": "Pendant -1 review by jackson with image uploadss",
"created_at": "2022-12-05",
"updated_at": "2022-12-05",
"review_images": [
{
"images": "http://<IP_ADDRESS>:8000/media/reviews/review-images/pendant3_rAe0hqS.webp"
}
]
}
The response I want to get is like this
{
"user": "Jackson Patrick Gomez",
"rating": 4.8,
"review": "Pendant -1 review by jackson with image uploadss",
"created_at": "2022-12-05",
"updated_at": "2022-12-05",
"review_images": [
{
"images": "http://<IP_ADDRESS>:8000/media/reviews/review-images/pendant3_rAe0hqS.webp"
},
{
"images": "http://<IP_ADDRESS>:8000/media/reviews/review-images/pendant3_rAe0hqS.webp"
},
{
"images": "http://<IP_ADDRESS>:8000/media/reviews/review-images/pendant3_rAe0hqS.webp"
}
]
}
I want to upload multiple images.
Are you not saving the same object instance over and over?
rev = ReviewImages()
for image in review_images:
rev.review=review
rev.images = image
rev.save()
Create a new instance for every image:
for image in review_images:
rev = ReviewImages(review=review, image=image)
rev.save()
Thanks man but I have already found out my mistake. It was so simple. My bad and I have updated my solution also please vote it
Just because I didn't think of .objects.create() to make it cleaner :)
Yeah it can make it lot more cleaner
I have found out the mistake. I was only creating one instance. Hence only one object was getting created.
#Mistake
rev = ReviewImages()
for image in review_images:
rev.review=review
rev.images = image
rev.save()
#Correct
for image in review_images:
rev = ReviewImages()
rev.review=review
rev.images = image
rev.save()
or
for image in review_images:
ReviewImages.objects.create(images=image, review=review)
| common-pile/stackexchange_filtered |
Inserting paired input fields into mysql
I need to insert pairs of input values from a form into mysql database. For example here are my input boxes:
<input type="text" name="roomType1" size="30" />
<input type="text" name="roomRate1" size="30" />
<input type="text" name="roomType2" size="30" />
<input type="text" name="roomRate2" size="30" />
<input type="text" name="roomType3" size="30" />
<input type="text" name="roomRate3" size="30" />
etc..
And my sql database is set up as follows:
RoomType
RoomRate
HID
So basically I need to figure out how to pass the two input fields into each field together in the same row. I am not sure if I should do a for loop or how I can get each two and insert it with the same ID. I hope this makes sense. and any help would be GREATLY appreciated!
Have u tried using any loop??
Those inputs must be part of a form with method="post". Then, on the php side use this:
<?php
$i = 1;
while(isset($_POST['roomType'.$i]))
{
$roomType = $_POST['roomType'$i];
$roomRate = $_POST['roomRate'$i];
// perform your sql statements here
$i++;
}
?>
Since your inputs are paired, it's enough to check if only one of them exists;
Thank you so much.. I thought it would be something like this just couldn't wrap my head around it.
| common-pile/stackexchange_filtered |
get byte array from database
I would like to get a byte array (java) from the database (mongo) and manipulate it, send it to the DOM as the original image, etc.
BasicDBObject condition = new BasicDBObject("_id", new ObjectId(_id));
DBObject dataset = DataAccess.GetInstanceClass().Getdatasets().findOne(condition);
byte[] image = (byte[]) dataset.get("image").toString().getBytes();
String s = new String(image);
System.out.println("provider: " + s);
This only returns
INFO: provider: [B@3b249009
"[B@3b249009" is the result of calling toString on a byte[] object.
Initially, I would like to dump it in the glassfish console just to give me confidence that it's being returned, then I would like to return it to the view as an image. It seems like Java would provide a way to convert if I want to.
That's what a debugger (or unit test) is for, not modifying source code to emit debugging junk :) In any case, you'll want to start looking at the result of dataset.get("image") and not the result of all the other unnecessary transformations. The operation actualValue.toString().getBytes() effectively obliterates whatever useful [typed] value it had - as per above, byteArrayObject.toString() will return "[B@deadbeef" which is not what you want.
Okay. Yes, of course! Type casting back and forth is ludricrous and and expresses a specific moment and level of frustration in the process. So, per your suggestion, I went back to what I had started with: ie; dataset.get() which returns a similar object [B@438d3c21 Just not sure what to do with it. I have tried numerous solutions from StackOverflow, all to no avail.
Maybe a string ("[B@438d3c21") was stored? If so then I suspect it was stored after byte[] was (accdidentally) stringified as per above.
Doing:
System.out.println("provider: " + image);
or:
System.out.println("provider: " + new String(image));
both result in printing the default toString() of an array, which is the pointer to the array (in your case, the rather ugly [B@3b249009)
If you want to look at a more useful String representation of the byte array, you can find the answer from this question:
System.out.println("byte array as pretty string: " + Arrays.toString(image));
Also, as you note, you don't need to (in fact, shouldn't) do
dataset.get("image").toString().getBytes();
you're putting your data through all sorts of mangling.
I've written a short test to demonstrate how to get the byte array out of MongoDB, and the differences in writing it as the default String vs using the Arrays.toString() method:
@Test
public void shouldBeAbleToGetANiceStringRepresentationOfAByteArray() {
// given
ObjectId id = new ObjectId();
byte[] bytes = {1,2,3,4};
collection.insert(new BasicDBObject("_id", id).append("image", bytes));
// when
BasicDBObject condition = new BasicDBObject("_id", id);
DBObject dataset = collection.findOne(condition);
byte[] image = (byte[]) dataset.get("image");
// then
// this instanceof is actually pointless, since casting it to a byte array above means it must be a byte array, but the point is to demonstrate it's not a String
assertTrue(image instanceof byte[]);
assertThat(image.toString(), startsWith("[B@"));
assertThat(image.toString().length(), is(11));
System.out.println("byte array toString(): " + image);
assertThat(Arrays.toString(image), is("[1, 2, 3, 4]"));
System.out.println("byte array as pretty string: " + Arrays.toString(image));
}
| common-pile/stackexchange_filtered |
Introspecting Child Components in Ember
If I have two components involved in a list:
my-list
my-item
But let's say actually there are two types of "items" that a list might contain so there is another component:
my-other-item
At run time I instantiate my list with something like:
{{my-list items=items type='my-other-item'}}
What I'd like is that my my-list component be able to do some introspection on the item component that has been chosen and react appropriately. In my example, lets say that each item component has a meta-attribute called _aspects and I'd like to do something like:
if(App[type]._aspects === 'foo') { ... }
where 'type' is the name of the item component. Has anyone tackled this problem before?
I've included the 'ember-cli' tag as well as 'ember' only because maybe my problems are associated with not fully understanding the CLI's resolver
Are you using ur components in the block form? Well you could register your child components to ur parent on 'init' or 'willInsertElement' using something like this.get('parentView').register(this). Here 'register' will be a method u define in the parent component which just keeps an array of child components passed in.
@blessenm yes something like this is what I was thinking. WRT to block or inline forms the answer is both. For 90% cases the inline form will be more compact and meet the needs but switching to block mode allows a richer set of options where you need them.
Is the "parentView" property always available to a component which was instantiated within the block of another component?
I think parentView is always available. Its worked for me so far. You can also use nearestWithProperty or 'nearestOfType' methods of component to look up the ancestors. Ben Lesh uses this technique with his components. https://github.com/blesh/ember-composable-components-example
You can use the component helper, introduced in Ember 1.11, which allows you to decide which component should render based on a bound value: http://emberjs.com/blog/2015/03/27/ember-1-11-0-released.html#toc_component-helper
Here is an article on the subject. Option C near the bottom is what you are looking for:
http://spin.atomicobject.com/2015/03/26/emberjs-dynamically-render-components/
Working JSBin Demo
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="//builds.emberjs.com/tags/v1.11.3/ember-template-compiler.js"></script>
<script src="//builds.emberjs.com/tags/v1.11.3/ember.debug.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<script type='text/x-handlebars'>
{{my-list model=model}}
</script>
<script type='text/x-handlebars'
data-template-name='components/my-list'>
<ul>
{{#each model as |item|}}
{{component item.componentType tag='li' item=item}}
{{/each}}
</ul>
</script>
<script type='text/x-handlebars'
data-template-name='components/my-item-type1'>
<b style='color:green'>{{item.componentType}}</b><br>
({{item.description}})
</script>
<script type='text/x-handlebars'
data-template-name='components/my-item-type2'>
<i style='color:orange'>{{item.componentType}}</i><br>
({{item.description}})
</script>
</body>
</html>
Javascript:
var fixtureData = [
{
name: 'Item 1',
componentType: 'my-item-type1',
description: 'Should be rendered with component type1'
},{
name: 'Item 2',
componentType: 'my-item-type2',
description: 'Should be rendered with component type2'
}
];
App = Ember.Application.create();
App.ApplicationRoute = Ember.Route.extend({
model: function() {
return fixtureData;
}
});
I share you enthusiasm for the component helper and I am using it. In fact, it's because of this to some degree that I'm trying to solve this problem. You see, once you've abstracted the Item component then you need to discern which properties the underlying item cares about. So item-a component may care about a color and style property whereas item-b cares about image and foobar. What I want is for the list component to become aware of its child's needs through some mechanism. Without which you could have a lot of extra observers and parameters passed around. Hope that makes sense.
I see. I don't know about your specific use case but this feels like it may be going against the grain of the framework. Could you update your question with more information about what you are hoping to acheive?
My goal is that the parent should know as little as possible about the various needs of the child components while still providing the children with the flexibility they need. The registration pattern introduced by @blessenm in the question comments is a standard way to solve this problem but I'm wondering if there are other ways that people recommend.
This can be done with the component helper. The child components can care about whatever they want and the parent doesn't need to know about it. As far as I'm concerned this approach does exactly what you're asking for. Hopefully someone else will come along with a totally different solution that does the same thing.
I'm not being clear ... the list DOES need to know about specifics of the item type but in a generic/reusable way. ;)
If one type of ITEM has properties A,B,C that it cares about and another has properties D,E,F then the list needs to know which properties to proxy into the item. What I'm looking for is a list to startup, ask the item what it cares about, and then deliver those properties only.
You could write your own handlebars helper based on the component helper but with the ability to pull that list of properties from a hash on the child component's backing data... just thinking out loud.
| common-pile/stackexchange_filtered |
selecting (highlighting) the text of jdatechooser when focus gained
im looking for the line of code, which will select (highlight) the Date-text-string in the jDateChooser when it gets focused.
I read that I might have to do something like .selectAll();. but i cant get access to the textfield of the jDateChooser.
also jDateChooser.selectOnFocus(true); wont compile. NetBeans says: "cannot find symbol".
eventhough i have imported:
import com.toedter.calendar.JDateChooser;
import com.toedter.calendar.demo.DateChooserPanel;
any ideas anyone ?
there is JSpinner, JSpinner has Editor, there should be possible to select all, days, month or year, somewhere (maybe here too) must be solved this basic issue
Change the library jar for calendar few libraries do not have all the symbols.
You can download from here and replace it with new one and then check:
JDateChooser dateChooser = new JDateChooser(new Date());
dateChooser.getDateEditor().getUiComponent().addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent evt) {
((JTextFieldDateEditor)evt.getSource()).selectAll();
}
});
dateChooser.getDateEditor().getUiComponent().addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent evt) {
if (evt.getSource() instanceof JTextComponent) {
final JTextComponent textComponent=((JTextComponent)evt.getSource());
SwingUtilities.invokeLater(new Runnable(){
public void run() {
textComponent.selectAll();
}});
}
}
});
| common-pile/stackexchange_filtered |
If $m > 3$, then $m^2 - 4$ is not prime
I am trying to create a proof that for all integers $m$, if $m > 3$, then $m^2-4$ is not prime. I am having issue however actually figuring out how to finish it off. Here's what I have so far...
Proof: Let integer m be given. $m^2 - 4 = (m-2)(m+2)$. Suppose that $m > 3$. Since $m > 3$, $m+2 > m-2 > 1$...
Most of the examples that I have create an integer $k$ and use it to finish the proof but I'm not sure how to define it in this example. Any help would be wonderful! Thanks.
$m^2-4$ can be factored!
And that gives me (m+2)(m-2). Would i set my k equal to that?
Since $m>3$, $m+2>m-2>1$, a prime can' t be a product of two integers both greater than 1.
Alright almost got it down but where did the 1 come from? I get that m+2 > m-2. Why the 1 though?
$m>3=2+1\implies m-2>1$
Okay I think I got it Thanks!
Hint:
$$
m^2 - 4 = (m - 2)(m + 2)
$$
| common-pile/stackexchange_filtered |
Trouble installing caldecott osx mountain lion
I'm having trouble installing caldecott on osx mountain lion. I keep getting this error:
$ sudo gem install caldecott --no-rdoc --no-ri
ERROR: Error installing caldecott:
ERROR: Failed to build gem native extension.
/Users/Jay/.rvm/rubies/ruby-1.9.3-p327/bin/ruby extconf.rb
checking for main() in -lssl... * extconf.rb failed *
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
details. You may need configuration options.
/Users/Jay/.rvm/rubies/ruby-1.9.3-p327/lib/ruby/1.9.1/mkmf.rb:369:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
You have to install development tools first.
Here is my gem list:
* LOCAL GEMS *
addressable (2.2.8)
af (<IP_ADDRESS>)
bundler (1.2.3)
cfoundry (0.4.15)
clouseau (0.0.2)
interact (0.5.1, 0.4.8)
json_pure (1.6.7)
manifests-vmc-plugin (0.4.19)
mime-types (1.19)
mothership (0.3.5)
multi_json (1.4.0)
multipart-post (1.1.5)
rake (10.0.2)
rb-readline (0.4.2)
rest-client (1.6.7)
rubygems-bundler (1.1.0)
rubyzip (0.9.9)
rvm (<IP_ADDRESS>)
terminal-table (1.4.5)
tunnel-dummy-vmc-plugin (0.0.2)
uuidtools (2.1.3)
vmc (0.4.7)
Any ideas on how I can get this to work. Or is there another way to tunnel to my mongodb on appfog?
First thing I notice is that your running gem install as root. If you're using RVM, you don't need to do this.
The likely issue here is that you don't have a C compiler installed, Caldecott uses native libraries and it requires them to be built. In the case of OS X, you need to install xcode. Do you have that installed?
You'll need Xcode with command line tools installed, the process for which has changed in Mavericks. Take a look over here: http://stackoverflow.com/questions/19066647/xcode-5-0-error-installing-command-line-tools
| common-pile/stackexchange_filtered |
Discriminator in a Joined Table with Doctrine2
I have an abstract parent class called Divers which is extended by few other classes.
So, I use inheritance mapping with D2 using Single Table Inheritance strategy.
namespace MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* ParentClass
*
* @ORM\Table(name="PARENTCLASS")
* @ORM\Entity
* @ORM\InheritanceType("SINGLE_TABLE")
* @ORM\DiscriminatorColumn(name="idtable", type="string")
* @ORM\DiscriminatorMap({
* "CHILD-CLASS1" = "ChildClassOne",
* "CHILD-CLASS2" = "ChildClassTwo",
* "CHILD-CLASS3" = "ChildClassThree",
* "CHILD-CLASS4" = "ChildClassFour"
* })
*/
abstract class ParentClass
{
...
}
What I want to achieve is to display the discriminator in the browser with a little description that explains what is it to the user.
I googled for a solution like putting the discriminator in a joined table but found nothing.
Do you have any advice to achieve my goal ?
Thanks by advance for your help.
You're looking for a way to display the string stored in the discriminator-column inside a twig template?
Yes and also how to attach another field to this discriminator. That's why I was speaking about a joined table which would contain the discriminator and the other field as column.
adding another field depending on the discriminater field should be easily achieved using a postPersist/postUpdate listener.
The discriminator column has special meaning for Doctrine 2 and thus cannot be part of a relation.
But there is an easy work around. Just add another column and give it the same value that your discriminator column has. The value will never change so it's easy enough to do. You can then of course use your new column in the same way as any other column.
I know having two columns with the same value is not ideal from a database perspective. But from an object perspective, it's no big deal since the discriminator column is never exposed as a property. And it's just the way doctrine works. It wants that column all to itself.
Yeah. I thinked about this solution but rejected it in a first time because of it's not ideal from a database perspective. I think I'll go with this now. Thanks for your help.
You can achieve it using PHP, whitout adding another field in the db as long as you don't need the field in a SQL query.
Since the discriminator is an abstract class, just adding a public abstract method returning your hard-coded discriminator value would do the trick. Then you can use your entity in twig or a json serializer.
abstract class ParentClass {
public abstract function getDiscriminator(): string; // The discriminator type
}
class ChildClassOne extends ParentClass
{
public function getDiscriminator(): string
{
return 'CHILD-CLASS1';
}
}
If you need to fetch in SQL, use $qb->andWhere($qb->isInstanceOf(ChildClassOne::class)) since the method or discriminator attribute is not available in sql.
| common-pile/stackexchange_filtered |
UITextField where to set clearsOnBeginEditing
I'm really used to VS where all properties are nicely listed in a big dialog.
In Interface Builder I can find no such dialog.
If I want to set the clearsOnBeginEditing field of a UITextField to FALSE, where is the best place to do it? Is there an interface to a control's properties in interface builder that I'm just missing?
It is available through the inspector in IB:
IB Inspector view http://img338.imageshack.us/img338/3015/screenshot20091101at155.png
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.