text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
GCS - DataCorruption: Checksum mismatch while downloading
I'm using python's google-cloud client to download a file from Google Cloud Storage (GCS), getting the following error:
File "/deploy/app/scanworker/storagehandler/gcshandler.py" line 62 in download_object
blob.download_to_file(out_file)
File "/usr/local/lib/python3.5/dist-packages/google/cloud/storage/blob.py" line 464 in download_to_file self._do_download(transport, file_obj, download_url, headers)
File "/usr/local/lib/python3.5/dist-packages/google/cloud/storage/blob.py" line 418 in _do_download
download.consume(transport)
File "/usr/local/lib/python3.5/dist-packages/google/resumable_media/requests/download.py" line 169 in consume
self._write_to_stream(result)
File "/usr/local/lib/python3.5/dist-packages/google/resumable_media/requests/download.py" line 132 in _write_to_stream [args] [locals]
raise common.DataCorruption(response, msg)
DataCorruption: Checksum mismatch while downloading:
https://www.googleapis.com/download/storage/v1/b/<my-bucket>/o/<my-object>?alt=media
The X-Goog-Hash header indicated an MD5 checksum of:
fdn2kKmS4J6LCN6gfmEUVQ==
but the actual MD5 checksum of the downloaded contents was:
C9+ywW2Dap0gEv5gHoR1UQ==
I use the following code to download the blob from GCS:
bucket_name = '<some-bucket>'
service_account_key = '<path to json credential file>'
with open(service_account_key, 'r') as f:
keyfile = json.load(f)
project_id = keyfile['project_id']
credentials = service_account.Credentials.from_service_account_file(service_account_key)
client = storage.Client(project=project_id,
credentials=credentials)
bucket = client.get_bucket(bucket_name)
blob_name = '<name of blob>'
download_path = "./foo.obj"
blob = bucket.blob(blob_name)
with open(download_path, "w") as out_file:
blob.download_to_file(out_file) # it fails here
Some info:
Using python3
running in a Ubuntu 16.04 Docker container in Kubernetes
using google-cloud client library version 0.27.0 downloaded with pika
Also, I cannot seem to reproduce the error on my local desktop, downloading the same files that failed from my Docker container.
Is this an error with the client library? Or could it be a network issue?
Tried downloading different files, all giving the same error from Kubernetes. The same code has been running for months without problem, only seeing this error now.
Edit:
Rebuilding the Docker container from the exact same code as before seems to have fixed the problem. I'm still curious to what caused the error in the first place though.
Edit 2:
We use circleci to deploy the webapp to production. Now it looks like the image built on circleci fails, while building it locally does seem to work. Since it's contained in a Docker container this is really weird, should not matter where we build it from?
Edit 3:
Logging in to the very same container in kubernetes giving the error above, I tried running gsutil cp gs:/<bucket>/<blob-name> foo.obj
This ran without any problem
A:
As pointed out in the comment by Mike: This was an issue with version 0.3.0 of google-resumable-media library. (See the issue here: https://github.com/GoogleCloudPlatform/google-resumable-media-python/issues/34)
Specifying google-resumable-media==0.2.3 in our pip's requirements.txt did the job!
The reason the error did not appear in the Docker image built from my desktop was that I had cached images with the old version of google-resumable-media.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
HTML5 data attributes casting null and undefined to string
Consider the example code bellow from an HTML file:
<div id="book"
data-id="47909"
data-title="Under The Dome"
data-author="Stephen King"
data-year="2009">
</div>
Selecting the book element with:
book = document.querySelector("#book");
Whenever I set some attribute to null or undefined it sets it to a string "null", "undefined" respectively:
book.dataset.author = null
typeof book.dataset.author
"string"
book.dataset.year = undefined
typeof book.dataset.year
"string"
While
let a = null;
typeof a
"object"
let b = undefined;
typeof b
"undefined"
Can someone please explain me why it behaves like this? Does it has to do with the fact that in the end everything will be converted to a string due to the nature of it being an element attribute?
Thanks!
A:
As per spec of dataset
On getting, the dataset IDL attribute must return a DOMStringMap whose
associated element is this element.
and as per spec of DOMString's value
Attributes have a namespace (null or a non-empty string), namespace
prefix (null or a non-empty string), local name (a non-empty string),
value (a string), and element (null or an element).
hence the value is casted to String before returning
String(null); //"null"
String(undefined); //"undefined"
String(1); //"1"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Microsoft Access can't find the field '|1'
I keep getting a run time error '2465' when running a query via VBA in Access.
Error: Microsoft Access can't find the field '|1' referred to in your expression
I can't seem to find where this issue is occuring. Below is the VBA code that I'm currently using to requery a form.
Dim Test As String
Test = "*" & Combo161.Value
Dim strSQL As String
Dim strWhere As String
strWhere = (Chr(34) + Test + (Chr(34)))
'MsgBox (strWhere)
strSQL = "SELECT * FROM Test_Query WHERE TestID " & strWhere
'MsgBox (strSQL)
[Form_Test (subform)].RecordSource = strSQL
[Form_Test (subform)].Requery
The TestID had a field formatting of text, rather than a number. Does this matter at all?
A:
Try:
Dim Test As String
Test = "*" & Combo161.Value
Dim strSQL As String
Dim strWhere As String
strWhere = (Chr(34) & Test & (Chr(34)))
'MsgBox (strWhere)
strSQL = "SELECT * FROM Test_Query WHERE TestID Like " & strWhere
'To test
'Debug.print strSQL
If this is a subform, then:
Me.[Form_Test (subform)].Form.RecordSource = strSQL
''Not needed when changing record source
''Me.[Form_Test (subform)].Form.Requery
You did not have an equals sign / Like and the concatenator in VBA is &, not +, using + can lead to problems with nulls, but in this case, I reckon the problen is the missing Like, that is
TestID Like "*something"
You can control the contents of a subform with a combo and a link field:
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In a UIView dealloc method do you dealloc your properties BEFORE or AFTER [super dealloc]?
I have a custom UIView which gets loaded through a NIB inside a UIViewController.
I've been struggling with a -[UIScrollView retainCount]: message sent to deallocated instance error all day.
My custom UIView subclass dealloc method looked like this:
-(void)dealloc {
[myScrollView dealloc];
[someProperty dealloc];
[super dealloc];
}
The problem was that it was always crashing on [super dealloc] because of the [myScrollView dealloc] preceding it.
When I changed the method around to:
-(void)dealloc {
[super dealloc];
[myScrollView dealloc];
[someProperty dealloc];
}
Everything is working fine. My question is, does it make a difference if [super dealloc] is called first or last? In most examples I see it called last.
A:
[super dealloc] should always be the last call in dealloc. Your problem is that you should be calling release on the other objects, not dealloc. dealloc is called by the runtime when the release count of the object reaches zero, your code should never call it directly.
Your code should therefore actually look like:
-(void)dealloc {
[myScrollView release];
[someProperty release];
[super dealloc];
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to prove an inifnite sum
How can I prove that $$\sum_{n=0}^{\infty}\frac{(-2)^n}{n!}=e^{-2}$$
I do know that $$\sum_{n=0}^{\infty}\frac{x^n}{n!}=e^{x}=\lim_{n\rightarrow\infty}(1+\frac{x}{n})^n$$
But I never had a real proof of it and is there an other way to prove the infinite sum above?
A:
Let's prove that series.
$$\lim_{n\to \infty}\left(1 + \frac{x}{n}\right)^n$$
From the binomial theorem we have
$$
\begin{align}
\left(1 + \frac{x}{n}\right)^n & = 1 + x + \frac{n(n-1)}{2!n^2}x^2 + \frac{n(n-1)(n-2)}{3! n^3}x^3 + \cdots
\\\\
& = \frac{x^0}{0!} + \frac{x^1}{1!} + \left(\frac{n-1}{n}\right)\frac{x^2}{2!} + \left(\frac{(n-1)(n-2)}{n^2}\right)\frac{x^3}{3!} + \cdots
\end{align}
$$
Now as $n\to \infty$ each term in the brackets is $1$
$$\lim_{n\to \infty} \left(\frac{n-1}{n}\right) = 1$$
$$\lim_{n\to \infty} \left(\frac{(n-1)(n-2)}{n^2}\right) = 1$$
Et cetera.
What remains is
$$
\begin{align}
\lim_{n\to \infty}\left(1 + \frac{x}{n}\right)^n & = \frac{x^0}{0!} + \frac{x^1}{1!} + \frac{x^2}{2!} + \frac{x^3}{3!} + \cdots
\\\\
& = \sum_{k = 0}^{+\infty} \frac{x^k}{k!}
\\\\
& = e^x
\end{align}
$$
Thence use $x = -2$ and make a backwards calculation, et voilà.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Programmatically flush data to cassandra every time before cassandra shut down
I am using embedded Cassandra. When I shut down and restart my Cassandra service data is lost. I think decent data are not properly flushed into the disk. So I tried using nodetool to flush data manually and check if data are available. But nodetool doesn't seem to work properly for embedded Cassandra service. I get the following error:
c:\vijay\cassandra\bin>nodetool -host 192.168.2.86 -p 7199 drain
Starting NodeTool
Failed to connect to '192.168.2.86:7199': Connection refused: connect
I tried setting jmx properties still I am getting error. I added following lines to my code:
System.setProperty("com.sun.management.jmxremote", "true");
System.setProperty("com.sun.management.jmxremote.port", "7197");
System.setProperty("com.sun.management.jmxremote.authenticate", "false");
System.setProperty("com.sun.management.jmxremote.ssl", "false");
System.setProperty("java.rmi.server.hostname", "my ip");
So, is there any way to manually flush data to Cassandra without using nodetool?
Edit 1:
After hours of trying I am now able to run nodetool (instead of adding jmx configurations to the code I added to Eclipse debug configurations and it worked). I ran drain command now the data is properly flushed to the disk. So now my question is: why isn't data properly flushed? Every time when I restart Cassandra service recent changes are gone.
A:
Commitlogs are not properly flushed in cassandra versions 1.1.0 to 1.1.4 This is a open issue. Please refer the following jira ticket.
Commitlog not replayed after restart
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to sort array of strings in numerical order?
I have a String[] of prices that might look like this:
String[0] = 1.22
String[1] = 230.08
String[2] = 34.11
I need to cast the array and order it in ascending order. What is the best way to do this? The Array may be very large so performance important. Thank you in advance.
A:
You can define a specialized string comparator:
class MyComparator implements Comparator<String> {
public int compare(Object a, Object b) {
return Float.valueOf(a.toString()).compareTo(Float.valueOf(b.toString());
}
}
and then sort your String array using:
Arrays.sort(aStringArray, new MyComparator());
(N.B. There may be more efficient ways of comparing two strings representing float values.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
HtmlUnit: saving pdf link
How do I download a pdfLink from a website using HtmlUnit?
The default return from HtmlClient.getPage() is an HtmlPage. This does not handle pdf Files.
A:
The answer is that HtmlClient.getPage will return an UnexpectedPage if the response was not an html file. THen you can get the pdf as an inputstream and save.
private void grabPdf(String urlNow)
{
OutputStream outStream =null;
InputStream is = null;
try
{
if(urlNow.endsWith(".pdf"))
{
final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_45);
try
{
setWebClientOptions(webClient);
final UnexpectedPage pdfPage = webClient.getPage(urlNow);
is = pdfPage.getWebResponse().getContentAsStream();
String fileName = "myfilename";
fileName = fileName.replaceAll("[^A-Za-z0-9]", "");
File targetFile = new File(outputPath + File.separator + fileName + ".pdf");
outStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[8 * 1024];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1)
{
outStream.write(buffer, 0, bytesRead);
}
}
catch (Exception e)
{
NioLog.getLogger().error(e.getMessage(), e);
}
finally
{
webClient.close();
if(null!=is)
{
is.close();
}
if(null!=outStream)
{
outStream.close();
}
}
}
}
catch (Exception e)
{
NioLog.getLogger().error(e.getMessage(), e);
}
}
Sidenote. I didn't use try with resources because the outputstream can only be initialized within the try block. I could break into two methods but that would be cognitively slower for the programmer to read.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
DateInput yields empty strings for allowEmpty inputs
One hiccup we ran into with React Admin was around date fields for a table. We're just using the stock ra-data-json-server package. Our backend should be receiving a null value for an empty date, but it comes through as a blank string instead. What's the best approach for handling this?
Creating a custom DateInput component that yields null for an empty date.
Creating a custom data provider that would convert an empty string to null (not sure if it would have enough context to do this, though).
Something else I haven't thought of.
I'm not keen on doing the translation at the API end, since I'd like to keep the API clean and only allow for a valid date or a null value.
A:
You can transform the input value using the parse / format functions:
https://marmelab.com/react-admin/Inputs.html#transforming-input-value-tofrom-record
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Triggers on change date
I'm trying to create some triggers in my db.
Now I need to create a trigger that "fire" a procedure when the date have changed. It's a Db for the management of a Bank.
I need some procedure that start at a programmed date. For example, if I want to set an operation of accredit for the 24/05/2014, this procedure starts only when the current date is equal to the specified value.
I have read that there are some "scheduler" that can help me, but I don't know how to use them! (I'm using phpPgAdmin) There's something that I can do without setting some scheduled procedure? Only using a trigger?
this is my (wrong) trigger
CREATE TRIGGER programmata
AFTER INSERT ON transazione
FOR EACH ROW
EXECUTE PROCEDURE trans_programmata();
and this is the (wrong) procedure "trans_programmata()"
DECLARE
p bit := 0;
BEGIN
IF(new.programmata = p)THEN
PERFORM * FROM aggiorna_conto();
ELSE
IF new.data >= current_date THEN
PERFORM * FROM aggiorna_conto();
END IF;
END IF;
RETURN NULL;
END;
Here is the table "transazione"
CREATE TABLE transazione (
id integer NOT NULL,
data date NOT NULL,
tipo bit(1) NOT NULL,
ammontare numeric(11,2) NOT NULL,
programmata bit(1) NOT NULL,
descrizione character varying(50) NOT NULL,
fk_conto integer NOT NULL,
fk_utente character(16) NOT NULL,
fk_categoria character varying(20) NOT NULL
);
obviously, this way the trigger only "fires" when the inserted value of "data" is equal to the current date.
A:
Triggers (or event triggers in pg 9.3+) only fire on defined data events. What you are talking about is a scheduled (time-based) event. There is nothing built into Postgres for that.
I generally use cron jobs to schedule jobs like this.
There is also pgAgent, which used to be packaged with pgAdmin. (From pgAdmin v1.9 onwards, pgAgent is shipped as a separate application.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Added value of Windows Server 2008 over 2003 in terms of security
What is the added value of a Windows 2008 Server over Windows 2003 in terms of security?
Does Windows Server 2008 has enhanced/new security features compared to 2003?
A:
There's a lot of added value in Server 2008 as compared to 2003. You can, roughly speaking, think of Server 2003 as "XP" and 2008 as Vista. In which case the following are notable changes that impact security:
UAC, UIPI are brought in in Vista. That is, Administrator users are handed two authentication tokens - one with full admin privileges and one with filtered privileges (standard user privs). This is what explorer starts with, thus, most apps are run as a standard user by default, even on an admin account. UIPI allows these windows to share a desktop whilst theoretically keeping them isolated.
Address Space Layout Randomisation. Vista got a full implementation of this.
Proper logon credential handling - whereas previously one could totally re-write the logon dialog with a GINA, now you install credential providers. Risk of intercepted passwords is thus decreased.
In 64-bit versions of XP and Vista, Kernel Patch Protection. Prevents rootkits from hooking interrupt tables by force-bluescreening Windows if they do. Very handy.
A series of protocol improvements were introduced, possibly most notably SMB 2.0.
and so on...
The Vista kernel and operating system was in many ways a very audacious release, containing a whole slew of additional features. There really is no reason to stay on 2003 if security is your end game.
That said, if you're considering an upgrade, practicalities come into play. Server 2008 R2 is already in production use and Server 8 is not that far distant either. I wouldn't upgrade to 2008 given the choice of R2 or Server 8 - I'd be inclined to wait for S8.
A:
In addition to the elements that @ninefingers mentioned, there's another aspect of Server 2008 which could be of use which is the release of the Server Core edition, which gets rid of a lot of the default install (eg, no web browser installed) and thereby reduces the attack surface of the server, if it's used.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
BusinessListBase.Remove doesn't work
I'm new on CSLA.Net and I've some difficult to remove a child object from a list.
I've 3 classes :
Scenario : BusinessBase<Scenario>
ScenarioPermissions : BusinessListBase<ScenarioPermissions, ScenarioPermission>
ScenarioPermission : BusinessBase<ScenarioPermission>
Class Scenario contains one field of type ScenarioPermissions.
When I Try to do Scenario.Permissions.Add(obj) and Scenario.Save(), it works correctly.
But if I want to do Scenario.Permissions.Remove(obj) and Scenario.Save(), it continues without deleting my ScenarioPermission object from the database.
public class Scenario : BusinessBase<Scenario>, IMakeCopy
{
private static readonly PropertyInfo<ScenarioPermissions> m_PermissionsProperty = RegisterProperty<ScenarioPermissions>(c => c.m_Permissions);
public ScenarioPermissions m_Permissions
{
get
{
if (!FieldManager.FieldExists(m_PermissionsProperty))
{
SetProperty(m_PermissionsProperty, ScenarioPermissions.NewPermissions());
}
return GetProperty(m_PermissionsProperty);
}
}
public ReadOnlyCollection<Model.Users.User> Permissions
{
get
{
var collection = new List<Model.Users.User>();
foreach (var item in m_Permissions)
{
collection.Add(Model.Users.User.GetUser(item.UserID));
}
//Adds administrators users...
var admins = Users.Users.GetUsers(true).Where(u => u.Role.InvariantName == "SystemAdministrator" || u.Role.InvariantName == "SuperAdministrator");
foreach (var item in admins)
{
collection.Add(item);
}
return new ReadOnlyCollection<Model.Users.User>(collection.OrderBy(u => u.FullName).ToArray());
}
}
public void AddPermission(Model.Users.User user)
{
if (user == null)
{
throw new ArgumentNullException("user");
}
ScenarioPermission permission = ScenarioPermission.NewPermission(this, user);
if (!this.m_Permissions.Contains(permission))
{
this.m_Permissions.Add(permission);
}
}
public void RemovePermission(Model.Users.User user)
{
if (user == null)
{
throw new ArgumentNullException("user");
}
ScenarioPermission permission = this.m_Permissions.FirstOrDefault(p => p.UserID == user.Id);
if (permission != null)
{
this.m_Permissions.Remove(permission);
}
}
protected override void DataPortal_Update()
{
using (var ctx = DbContextManager<DatabaseContext>.GetManager())
{
var context = ctx.DbContext;
var scenarioId = ReadProperty(m_IdProperty);
var scenario = context.Scenarios.FirstOrDefault(s => s.Id == scenarioId);
if (scenario != null)
{
scenario.Name = ReadProperty(m_NameProperty);
//Some codes....
context.SaveChanges();
}
FieldManager.UpdateChildren(this);
}
}
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(ReadProperty(m_IdProperty));
}
private void DataPortal_Delete(Guid id)
{
using (var contextManager = DbContextManager<DatabaseContext>.GetManager())
{
var context = contextManager.DbContext;
var scenario = context.Scenarios.FirstOrDefault(s => s.Id == id);
if (scenario != null)
{
context.Scenarios.Remove(scenario);
context.SaveChanges();
}
}
Dispatcher.CurrentDispatcher.Invoke(new Action(() => ScenarioList.Delete(id)));
}
}
public class ScenarioPermissions : BusinessListBase<ScenarioPermissions, ScenarioPermission>
{
public static ScenarioPermissions NewPermissions()
{
return DataPortal.Create<ScenarioPermissions>();
}
public static ScenarioPermissions GetUsersByScenario(Scenario scenario)
{
return DataPortal.FetchChild<ScenarioPermissions>(scenario);
}
private void Child_Fetch(Scenario obj)
{
using (var ctx = DbContextManager<DatabaseContext>.GetManager())
{
var context = ctx.DbContext;
var scenario = context.Scenarios.Where(s => s.Id == obj.Id).FirstOrDefault();
if (scenario != null)
{
foreach (var item in scenario.Users)
{
this.Add(ScenarioPermission.NewPermission(scenario.Id, item.Id));
}
}
}
}
}
public class ScenarioPermission : BusinessBase<ScenarioPermission>
{
private static readonly PropertyInfo<Guid> m_ScenarioID = RegisterProperty<Guid>(p => p.ScenarioID);
public Guid ScenarioID
{
get { return GetProperty(m_ScenarioID); }
private set { SetProperty(m_ScenarioID, value); }
}
private static readonly PropertyInfo<int> m_UserID = RegisterProperty<int>(p => p.UserID);
public int UserID
{
get { return GetProperty(m_UserID); }
private set { SetProperty(m_UserID, value); }
}
public static ScenarioPermission NewPermission(Scenario scenario, Model.Users.User user)
{
return NewPermission(scenario.Id, user.Id);
}
public static ScenarioPermission NewPermission(Guid scenarioID, int userID)
{
var newObj = DataPortal.CreateChild<ScenarioPermission>();
newObj.ScenarioID = scenarioID;
newObj.UserID = userID;
return newObj;
}
private ScenarioPermission() { /* Used for Factory Methods */}
private void Child_Insert(Scenario scenario)
{
DataPortal_Insert();
}
private void Child_DeleteSelf(Scenario scenario)
{
DataPortal_DeleteSelf();
}
private void Child_DeleteSelf()
{
DataPortal_DeleteSelf();
}
protected override void DataPortal_Insert()
{
using (var ctx = DbContextManager<DatabaseContext>.GetManager())
{
var context = ctx.DbContext;
var scenario = context.Scenarios.FirstOrDefault(s => s.Id == ScenarioID);
var user = context.Users.FirstOrDefault(u => u.Id == UserID);
if (scenario != null && user != null)
{
scenario.Users.Add(user);
context.SaveChanges();
}
}
}
protected override void DataPortal_DeleteSelf()
{
using (var ctx = DbContextManager<DatabaseContext>.GetManager())
{
var context = ctx.DbContext;
var scenario = context.Scenarios.FirstOrDefault(s => s.Id == ScenarioID);
var user = context.Users.FirstOrDefault(u => u.Id == UserID);
if (scenario != null && user != null)
{
if (scenario.Users.Contains(user))
{
scenario.Users.Remove(user);
context.SaveChanges();
}
}
}
}
public override bool Equals(object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to ScenarioPermission return false.
ScenarioPermission p = obj as ScenarioPermission;
if ((System.Object)p == null)
{
return false;
}
// Return true if the fields match:
return (this.ScenarioID == p.ScenarioID) && (this.UserID == p.UserID);
}
}
A:
I've just find the solution :
When I fetched the children of ScenariosPermissions, I created children instead of fetching existing... So, when I wanted to remove permissions, the existing objects was considered by CSLA as a NewObject, so it does not the Delete() ;-)
Correction :
public class ScenarioPermissions : BusinessListBase<ScenarioPermissions, ScenarioPermission>
{
public static ScenarioPermissions NewPermissions()
{
return DataPortal.Create<ScenarioPermissions>();
}
public static ScenarioPermissions GetUsersByScenario(Scenario scenario)
{
return DataPortal.FetchChild<ScenarioPermissions>(scenario);
}
private void Child_Fetch(Scenario obj)
{
RaiseListChangedEvents = false;
using (var ctx = DbContextManager<DatabaseContext>.GetManager())
{
var context = ctx.DbContext;
var scenario = context.Scenarios.Where(s => s.Id == obj.Id).FirstOrDefault();
if (scenario != null)
{
foreach (var item in scenario.Users)
{
this.Add(ScenarioPermission.GetPermission(scenario.Id, item.Id));
}
}
}
RaiseListChangedEvents = true;
}
}
public class ScenarioPermission : BusinessBase<ScenarioPermission>
{
public static ScenarioPermission GetPermission(Guid scenarioID, int userID)
{
return DataPortal.FetchChild<ScenarioPermission>(scenarioID, userID);
}
private void Child_Fetch(Guid scenarioID, int userID)
{
LoadProperty(m_ScenarioID, scenarioID);
LoadProperty(m_UserID, userID);
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
My commitment token from the UI site hasn't been returned
Is returning the commitment token from a site a manual process or is it automatic?
If it's automatic what are the criteria? I've made 14 posts (2 questions and 12 answers), commented and earned 11 badges including the beta.
I'm not concerned as I still have one token left and there's nothing I really want to commit to at the moment. It's just that it was discussed on chat yesterday and someone mentioned that they'd had their token from the Unix site returned and that went into beta after the UI site.
A:
This is fixed now.
Commitment tokens are supposed to be returned automatically, but we had a bug in which Area 51 was failing to take account for the Beta badge having a different Id in the newer sites (16) than in the older sites (30).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C# 6 null conditional operator check for .Any()?
In the example shown here (and on numerous other websites) with regards to the null-conditional operator, it states that
int? first = customers?[0].Orders.Count();
can be used to get the count for the first customer. But this statement does not check for the existence of customers in the collection and can throw an index out of range exception. What should be the correct (preferably single-lined) statement that takes care of checking for the existence of elements?
A:
The null conditional operator is intended for conditionally accessing null but this isn't the issue you're having.
You are trying to access an empty array. You can turn that into a case of accessing null with FirstOrDefault and use the operator on that:
int? first = customers.FirstOrDefault()?.Orders.Count();
If the array isn't empty it will operate on the first item, and if it is empty FirstOrDefault will return null which will be handled by the null conditional operator.
Edit: As w.b mentioned in the comments, if you're looking for another item than the first one you can use ElementAtOrDefault instead of FirstOrDefault
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Fetch data from RSS and bind to a asp control
I have to display weather details of a perticular city in a asp control as a widget. I hope i can get the weather details as rss feed data. Here how to bind this data to a asp control?. I need to show next 10 days weather details also.
A:
Try the below code. You can use your desired attributes. I used Date, Title, Description,
Link
internal class RssItem
{
public DateTime Date;
public string Title;
public string Description;
public string Link;
}
XmlDocument xmlDoc = new XmlDocument();
private Collection<RssItem> feedItems = new Collection<RssItem>();
xmlDoc.Load("URL of the RSS Feeds");
ParseRssItems(xmlDoc);
private void ParseRssItems(XmlDocument xmlDoc)
{
this.feedItems.Clear();
foreach (XmlNode node in xmlDoc.SelectNodes("rss/channel/item"))
{
RssItem item = new RssItem();
this.ParseDocElements(node, "title", ref item.Title);
this.ParseDocElements(node, "description", ref item.Description);
this.ParseDocElements(node, "link", ref item.Link);
string date = null;
this.ParseDocElements(node, "pubDate", ref date);
DateTime.TryParse(date, out item.Date);
this.feedItems.Add(item);
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Followers model in Rails
In my app Users can follow each other. I have two tables: users and followers.
users
id
name
followers
id
user_id
follower_id
And two models:
class User < ActiveRecord::Base
has_many :followers
belongs_to :follower
end
class Follower < ActiveRecord::Base
belongs_to :user
end
What I want to do is list the followers for a user. e.g.
<ul>
<% @users.each do |user| %>
<li><%= user.name %></li>
<ul>
<% user.followers.each do |follower| %>
<li><%= follower.name %></li>
<% end %>
</ul>
<% end %>
</ul>
However it doesn't look to be seeing the association...
After updating my model as per Deep's suggestions I got it working... however I'm unable to query followers and following users.
e.g.
I have two methods in my UsersController:
def user_followers
@user = User.where(id: params[:id]).first
@followers = @user.get_followers
end
def user_following
@user = User.where(id: params[:id]).first
@following = @user.get_following
end
and then in my User model I have:
def get_followers
Follower.where(follower_id: self.id)
end
def get_following
Follower.where(user_id: self.id)
end
Which should be returning the followers for the user or who the user is following. The views look like so:
<% @followers.each do |follower| %>
<%= follower.user.name %>
<% end %>
<% @following.each do |following| %>
<%= following.user.name %>
<% end %>
However it only returns the name of the user I'm supposed to be viewing.
The Follower model now looks like:
class Follower < ActiveRecord::Base
belongs_to :user, foreign_key: 'follower_id', class_name: 'User'
end
A:
The follower.name will not work because your follower model has no attribute named name. Also the association you have given is belongs_to :user which will fetch the user who has been followed. You need another association in the Follower model like:
belongs_to :following_user, foreign_key: 'follower_id', class_name: 'User'
And then in your view what you can do is:
<%= follower.following_user.name %>
This will fetch the user who has followed and from that object it will fetch the name attribute.
Update:
Don't remove the existing association you have. Means your model should look like:
belongs_to :user
belongs_to :following_user, foreign_key: 'follower_id', class_name: 'User'
Now as discussed in comments user_id will consist of the user who is being followed and follower_id will consist of the user who is following.
To fetch the followers of a user you have the association which will find the followers. Just like user.followers. And to fetch the name:
<% user.followers.each do |follower| %>
<li><%= follower.following_user.name %></li>
<% end %>
To find the followed users:
def followed_users
Follower.where(follower_id: id)
end
And to fetch the name:
<% user.followed_users.each do |follower| %>
<li><%= follower.user.name %></li>
<% end %>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Little 'o' / Big 'O' Definitions
I understand, or at least think I understand, the nature of a function that is "little o": If $f$ is a function between Banach spaces E and F, then it is "little-o" if
$$|x|\rightarrow 0 \implies \frac{|f(x)|}{|x|} \rightarrow 0$$
Thus the evaluation of $f$ at $x$ approaches $0$ faster than $x$ itself. I have read other posts on here, such as this one that give a different definition. Also, textbook authors don't seem to be in agreement either. For instance, in their advanced calculus text, Loomis and Sternberg declare a function to be "little o" if it satisfies essentially the definition I just gave but also add the condition that $f(0) = 0$. On the other hand, Marsden et. al. in "Manifolds, Tensor Analysis and Applications" define a "little o" function as any continuous function $f:E\rightarrow F$ such that
$$
\lim_{x\rightarrow 0}\frac{f(x^k)}{|x|^k} = 0
$$
Is there any hope of reconciling these definitions? They seem to be saying approximately the same thing, but not quite.
A:
This is more of a long comment to the comment of Henning Makholm. The objective of the $o$ and $O$ notations is to compare growth (asymptotic behavior) of 2 functions $f$ and $g$. The function $g$ doesn't have to be $x$ or $x^k$. Defining $f(x) = \underset{x\to a}{o}(g(x))$ as saying $|f(x)|/|g(x)| \underset{x\to a}{\to} 0$ is also bad because it leads to writing nonsense when $g$ has zeros.
A good definition would be $f(x) = \underset{x\to a}{o}(g(x))$ if there exists a nonnegative function $\varepsilon$ and a neighborhood $U$ of $a$ such that $\varepsilon(x) \underset{x\to a}{\to} 0$ and for every $x$ in $U\setminus\{a\}$, $|f(x)| = \varepsilon(x)|g(x)|$.
Similarly $f(x) = \underset{x\to a}{O}(g(x))$ if there exists a nonnegative bounded function $\varepsilon$ and a neighborhood $U$ of $a$ such that for every $x$ in $U\setminus\{a\}$, $|f(x)| = \varepsilon(x)|g(x)|$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
API for stumbleupon - get the number of stumbleupon shares for a page
Is there an API for getting the number of stumbleupon shares for a page?
I would like to supply a full url of a page and get the number of shares it got on stumbleupon.
How can I achieve that?
A:
We don't have an API which will allow you to see the number of shares that a particular page has. The closest thing we offer is our badge, which will allow you to see the number of likes that one of your pages has. You can set one up at http://www.stumbleupon.com/dt/badges.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Use CSV file to change URL for web test
In Visual Studio Web test my URL is
https:example//api/{{test1}}/mode/{{test2}}
Here I want to pass values of test1 and test2 from a CSV file.
I tried
https://exampl/api/{{DataSource1.Table5002#csv.objectId}}/mode/{{DataSource1.Table5002#csv.model}}
where in table5002, columns objectId and model are added.
Values from CSV work fine when I use them in string body.
I tried these:
Context parameters, here I can't bind context parameters with datasource.
Tried giving https://exampl/api/{{DataSource1.Table5002#csv.objectId}}/mode/{{DataSource1.Table5002#csv.model}} in URl. This doesn't take values from data source.
Please help me on how to use CSV values in URL.
A:
When i give my URL like this:https://exampl/api/{{DataSource1.Table5002#csv.objectId}}/mode/{{DataSource1.Table5002#csv.model}}, now it is working fine.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Replacement for "too" in "too X to Y"
In phrases of the form "too X to Y" (e.g. "too big to fail"), can "too" ever be replaced by a word such as "exceedingly", e.g. "exceedingly big to fail"? It sounds wrong to me, although "exceedingly big" on its own sounds certainly correct.
If it isn't correct, how else can I express in formal writing that something is "too X to Y" by a large margin? "Much too X to Y" sounds informal.
A:
Too in the too Adj to VP construction is a negative word.
If something is too big to fail, then it's so big that it can't/won't/shouldn't/must not fail.
The negative is part of the meaning; the modal (can, will, should, etc.) is supplied by context.
This is related to the so Adj that S and such NP that S construction, as in
It was so spicy (that) I couldn't eat it.
It was such spicy food (that) I couldn't eat it.
The too construction uses an infinitive VP instead of a whole tensed clause like the so/such construction, but the sense is the same, except for the hidden negative and modal in the too construction.
But they're all idiomatic constructions and don't follow other grammatical rules.
Consequently *exceedingly big to fail doesn't work at all.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to kill a command executed within xterm
I'd like to control the execution of shell commands within an xterm window.
This is an example code (Ruby):
pid = Process.fork
if pid.nil?
exec "xterm -e 'while true; do echo -n .; sleep 1; done'"
else
puts "pid is: #{pid}"
Process.detach(pid)
end
However, the xterm window doesn't get killed:
$ ./tst2.rb
pid is: 26939
$ ps aux | grep xterm | grep -v grep
user 26939 0.0 0.0 4508 800 pts/3 S 13:11 0:00 sh -c xterm -e 'while true; do echo -n .; sleep 1; done'
user 26943 0.6 0.0 72568 6280 pts/3 S 13:11 0:00 xterm -e while true; do echo -n .; sleep 1; done
$ kill 26939
$ ps aux | grep xterm | grep -v grep
user 26943 0.1 0.0 72568 6280 pts/3 S 13:11 0:00 xterm -e while true; do echo -n .; sleep 1; done
How can the xterm window be killed?
A:
You need to find the PID of the xterm process in order to kill it. In your case, the easiest way would be to bypass the sh process, as you don't need it. To do this, you have to pass the arguments to exec in an array, not as a command line:
exec('xterm', '-e', 'while true; do echo -n .; sleep 1; done')
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Clarification On MySQL Join Query
I am having some issues creating this JOIN query.
The table setup is as follows
| tags || tag_links || articles |
|________________||________________||________________|
| | | | | |
| id | | article_id | | id |
| tag_name | | tag_id | | |
There are 3 tables, and this is a many-to-many relationship.
The objective is to find all the tags associated with a given article
id.
The tags table contains all of the tags
The tag_links table contains the link between the articles and the
tags, where the tag_id is equal to the id in the tags table, and the
article_id is equal to the id in the article table
The articles table contains the id ( amongst other columns, but the
other columns are not important )
I am having a hard time because the article id is already provided. I don't think that this is even needed in the query, but I am at a loss right now. I am trying to grab all of the tag_id's that are associated with the article_id that I pass in, and then grab all of the tag_names from all of the tag_id's i just queried for.
Any help is greatly appreciated. Thanks!
A:
This is a simple join you can use to get tag names for a given article id
select distinct t.* from tags t
join tag_links tl on(t.id = tl.tag_id)
where tl.article_id=@id <---- article id
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JQuery executing onLoad
So I'm trying to execute a function on a component when the page loads. This is what I have so far.
$(document).ready(function() {
var $foo = $('#data_lost').hide();
$f = function () {
doSomething...
};
$foo.change($f);
});
So this all works fine and dandy. Here's the problem. I also need $f executed on $foo when the page loads. I tried setting $foo.ready($f), but that doesn't work. I tried setting it inside and outside of document.ready(). Neither options work. I'm assuming that doing it outside doesn't work because the tag doesn't exist until document is ready, and doing it inside doesn't work because when the document is ready, the tag has already become ready, so it won't ever be ready again, so $f isn't called.
Ideas??
TIA!
A:
Well, goes to show...you ask...fate has it that you find your own answer soon after...
added:
$foo.change();
after $foo.change($f).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Javascript analysis fail for .js files containing ES7 Decorators
I'm currently using Babel (the Javascript transpiler) which allows me to use the future syntax now. I'm using the decorator functionality (https://github.com/wycats/javascript-decorators). However when I run analysis on that code, SonarQube throws the following error:
[09:19:43] 09:19:43.693 ERROR - Unable to parse file: /...../my-form.js
09:19:43.693 ERROR - Parse error at line 10 column 1:
1: import {View, Component, Inject, NgScope} from 'app/app';
...
9:
10: @Component({
^
11: selector: 'my-form'
12: })
13: @View({
14: template: myTemplate
15: })
Will this be covered soon by the Javascript plugin (or at least skipped by the parser but allowing it to continue processing of the file)?.
Is there a way to file a JIRA issue for this?
A:
From the SonarQube user group:
Regarding the support of the decorator construction, it will not be supported by the JavaScript plugin as long as it will not be part of the ECMAScript Standard.
Moreover when the JavaScript plugin is not able to parse a file the analysis should not fail, it should succeed but no issue will be reported on the unparsed file.
However there is already a JIRA ticket where you can vote up to show them the need for this feature.
JIRA - Support experimental JavaScript features
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What does the negative balance number mean?
My credit card has a negative number but my credit limit has not been exceeded. Do I owe that negative sum to the bank? I have only spent 26$ since I made my last payment to the card. Does this actually mean I owe them that negative balance?
A:
A negative balance on a credit card account means they owe you money. This typically happens when you are issued a refund on a purchase around the same time as your payment goes through.
Your transaction history should show each purchase as a positive amount, and any payments/refunds as negative amounts. A negative balance can be paid out by the bank if it remains for a length of time (~6 months, or sooner if you request a refund), but usually they just show a negative balance and it gets resolved as you make additional purchases with the card.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Disable Resharper Extensions
I have installed some resharper plugins and since resharper is not loading anymore into VS2013. (Unable to load package).
Does anyone know how to disable/uninstall resharper packages from outside VS?
Running latest (2016.2) version of R#
A:
This may be a bit like cracking a nut with a hammer but you could try removing all traces of Resharper from %LOCALAPPDATA%\JetBrains and %APPDATA%\JetBrains and re-install it and then re-add the extensions to see which caused you the problem (would be good to know which one it is so that others don't have the same problem.) It seems that the Resharper installation is following the Microsoft standard of spreading numerous cached versions of the same files all over your hard drive to fill it up, not like back in the old days when it was all in just one location.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java: Make one item of a jcombobox unselectable(like for a sub-caption) and edit font of that item
How to make one item in a combobox unselectable because I need to separate items in a combobox with a sub-topic.
And is it possible to modify the font of that particular item individually?
jComboBox_btech_course.setFont(new java.awt.Font("Tahoma", 0, 14));
jComboBox_btech_course.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select Course" }));
jComboBox_btech_course.setName("");
private class theHandler implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
//BTech courses
if(jComboBox_mtech_dept.getSelectedItem().equals("Civil Engineering"))
{
jComboBox_btech_course.removeAllItems();
jComboBox_btech_course.addItem("Building Construction");
jComboBox_btech_course.addItem("Principle And Practice");
jComboBox_btech_course.addItem("Surveying");
jComboBox_btech_course.addItem("Engineering Geology");
jComboBox_btech_course.addItem("Structural Analysis");
jComboBox_btech_course.addItem("Hydraulic Engineering");
jComboBox_btech_course.addItem("Environmental Engineering");
jComboBox_btech_course.addItem("Structural Design");
jComboBox_btech_course.addItem("Geotechnical Engineering");
/*This item has to be unselectable*/
jComboBox_btech_course.addItem("***Sub-topic***");
jComboBox_btech_course.addItem("Transportation Engineering");
jComboBox_btech_course.addItem("Foundation Engineering");
jComboBox_btech_course.addItem("Estimation & Valuation");
jComboBox_btech_course.addItem("Hydrology & Flood Control");
jComboBox_btech_course.addItem("System Analysis, Project Planning And Construction Management");
jComboBox_btech_course.addItem("Irrigation Engineering");
jComboBox_btech_course.addItem("Computer Application in Civil Engineering");
jComboBox_btech_course.addItem("Planning, Design & Detailing");
}
}
}
A:
Foreword: In the proposed solution I assume that you want to disable items that start with "**". You can change this logic to whatever you want to. In an improved version the MyComboModel class (see below) may even store which items are disabled allowing arbitrary items to be marked disabled.
Solution to your question involves 2 things:
1. Disallow selecting items which you want to be disabled
For this you can use a custom ComboBoxModel, and override its setSelectedItem() method to do nothing if the item to be selected is a disabled one:
class MyComboModel extends DefaultComboBoxModel<String> {
public MyComboModel() {}
public MyComboModel(Vector<String> items) {
super(items);
}
@Override
public void setSelectedItem(Object item) {
if (item.toString().startsWith("**"))
return;
super.setSelectedItem(item);
};
}
And you can set this new model by passing an instance of it to the JComboBox constructor:
JComboBox<String> cb = new JComboBox<>(new MyComboModel());
2. Display disabled items with different font
For this you have to use a custom ListCellRenderer and in getListCellRendererComponent() method you can configure different visual appearance for disabled and enabled items:
Font f1 = cb.getFont();
Font f2 = new Font("Tahoma", 0, 14);
cb.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (value instanceof JComponent)
return (JComponent) value;
boolean itemEnabled = !value.toString().startsWith("**");
super.getListCellRendererComponent(list, value, index,
isSelected && itemEnabled, cellHasFocus);
// Render item as disabled and with different font:
setEnabled(itemEnabled);
setFont(itemEnabled ? f1 : f2);
return this;
}
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it possible to find the current (x,y,z) of an element as it moves using translate3d(x,y,z)?
Using CSS3s -webkit-transform: translate3d(x,y,z); is it possible to trace the (x,y,z) movement as it moves with javascript?
Example:
An object begins at (0,0,0) and we translate it to (4,4,0) over a 4sec duration.
Theoretically, at the first sec the element should be placed at (1,1,0), while at the second sec the element should be at (2,2,0), etc.. Is there a way for Javascript to track the object?
Retrieving the css property of translate3d(x,y,z) will just return the final translation coordinates. Which is to be expected as that what it is set to.
A:
If you are moving the element through CSS transitions then no, there is no way to tack the element. There are eventlisteners for transitionstart and transitionend only.
If you are animating through javascript then yes, you can trace x,y,z through:
node = document.getElementById("yourid");
//your animation loop
console.log(window.getComputedStyle(node).webkitTransform); //this will return a string
var curTransform = new WebKitCSSMatrix(window.getComputedStyle(node).webkitTransform);
console.log(curTransfrom); //this will return an object
//end animation loop
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Core Data: Strange faulting behavior when using lazy instantiation
I have added a category to my NSManagedObject IBCompany, which should retrieve a specific time period, which is one of the IBCompany's relationships, based on a simple date comparison.
When I run the following code, the NSArray sortedFinPeriodsDesc contains the faulted periods in the correct sorted order. However, when accessing them in the for each loop, each of the periods returns nil for its attributes, and in particular, nil for its EndDate. For this reason my method lastReportedPeriodforDate always returns nil, which is an error.
#import "IBCompany+FinstatAccessors.h"
@implementation IBCompany (FinstatAccessors)
NSArray *sortedFinPeriodsDesc;
- (IBFinPeriod*)lastReportedPeriodforDate:(NSDate*)date;
{
if ( !sortedFinPeriodsDesc ) {
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"EndDate" ascending:NO];
sortedFinPeriodsDesc = [self.finperiod sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
}
IBFinPeriod *lastPeriod;
for (IBFinPeriod *finPeriod in sortedFinPeriodsDesc) {
if ( [finPeriod.EndDate compare:date] == NSOrderedAscending ){ // finPeriod.EndDate < date
lastPeriod = finPeriod;
break;
}
}
return lastPeriod;
}
However, when replacing the first lines (lazy instantiation) in the method by removing the if clause and always instantiating and sorting NSArray sortedFinPeriodsDesc, the code works fine.
Hence, I have a couple of questions:
What is the error in my code? How does affect lazy instantiation
faulting?
Would you recommend defining the NSArray sortedFinPeriodsDesc as transient attribute and sorting it in awakeFromFetch instead?
What would be the best option in your view?
Thank you very much for your help!
A:
The "lazy loading" smacks of a premature optimisation. Particularly the way you've implemented it, you aren't actually using an instance variable, but a global variable (see here for details), meaning that each object isn't holding its own version of the array.
I would suggest having the array local and generating it each time it is required. If this impacts performance, you can look at other methods, but even with the ivar problem above resolved, you are going to hit problems if the periods set is updated - your array is now out of date.
You haven't said how many times your objects are being asked for this period, or how many objects, or how many periods, so it is difficult to give more specific advice.
A fetched property might be a more efficient way of getting the period, but I don't have enough experience with them to help in your specific case.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Prolog list search returns false if list is predefined
I'm trying to write a prolog program to demonstrate how a cut can be used to increase efficiency. I'm using the following member declaration to search through a list.
member(Element, [Element | _]).
member(Element, [_ | List]) :- member(Element, List).
The function seems to be working just fine ex:
?- member(1,[3,1,4]).
true
The issue that i'm running into is I need to be able to use member with a predeclared list. like so:
someList([3,1,4]).
?- somelist(X).
X = [3, 1, 4].
3 ?- member(1,somelist).
false.
Even though somelist is defined as [3,1,4] which works in the first test, when called this returns false. I just need to know what I'm doing wrong that ?- member(1,somelist). is returning false. Any help would be greatly appreciated.
A:
someList is the name of a proposition that does not exist, not a list, so it'll always produce false/no.
Prolog accepts queries and produces answers. What you seem to be asking for is the concept of variables in an imperative language, which doesn't exist here.
You can, for example, ask Prolog for all of the lists that have 1 as their member with member(1, X), or for a particular list member(1, [3,1,4]), but you can't store a list and ask about it in this way.
Prolog works with a Knowledge Base, and infers truthness through rules/predicates, facts and propositions that it knows. You need to ask it what you want to know.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
.NET How to get Sql response to string?
After inserting something into the DB I would like to get the server's response.
For example "x rows effected" or other messages, and put them into a string variable.
How do I implement this in code? C# or VB - doesn't matter to me.
I couldn't find anything specific on this, but I am a n00b @ programming.
Thank you kindly.Could you kindly provide an example for me? Here is my code:
Private Function insertScr(ByVal byte2insert As Byte()) As Boolean
Dim _con As SqlConnection
Dim queryStmt As String
Dim _cmd As SqlCommand
Dim param As SqlParameter
Try
_con = New SqlConnection(My.Settings.DBconnStr)
queryStmt = "update ErrorLog set screen = @Content where(ErrorLogID = 2)"
_cmd = New SqlCommand(queryStmt, _con)
param = _cmd.Parameters.Add("@Content", SqlDbType.VarBinary)
param.Value = byte2insert
_con.Open()
_cmd.ExecuteNonQuery()
_con.Close()
Return True
Catch ex As Exception
Return False
End Try
End Function
A:
Assuming SQL Server, the SqlConnection object has an InfoMessage event that is raised for each of these sorts of messages (it also has a mode that can be enabled so that error messages are delivered via the same event, see FireInfoMessageEventOnUserErrors)
You would access the text of these messages by extracting the Message property from the second argument passed to your event handler.
Something like:
...
_con = New SqlConnection(My.Settings.DBconnStr)
AddHandler _con.InfoMessage,Sub(sender,e)
MessageBox.Show(e.Message)
End Sub
queryStmt = "update ErrorLog set screen = @Content where(ErrorLogID = 2)"
...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
python numpy cast problem
I'm trying to interpolate with the following code
self.indeces = np.arange( tmp_idx[len(tmp_idx) -1] )
self.samples = np.interp(self.indeces, tmp_idx, tmp_s)
where tmp_idx and tmp_s are numpy arrays. I get the following error:
array cannot be safely cast to
required type
Do you know how to fix this?
UPDATE:
class myClass
def myfunction(self, in_array, in_indeces = None):
if(in_indeces is None):
self.indeces = np.arange(len(in_array))
else:
self.indeces = in_indeces
# clean data
tmp_s = np.array; tmp_idx = np.array;
for i in range(len(in_indeces)):
if( math.isnan(in_array[i]) == False and in_array[i] != float('Inf') ):
tmp_s = np.append(tmp_s, in_array[i])
tmp_idx = np.append(tmp_idx, in_indeces[i])
self.indeces = np.arange( tmp_idx[len(tmp_idx) -1] )
self.samples = np.interp(self.indeces, tmp_idx, tmp_s)
A:
One of your possible issues is that when you have the following line:
tmp_s = np.array; tmp_idx = np.array;
You are setting tmp_s and tmp_idx to the built-in function np.array. Then when you append, you have have object type arrays, which np.interp has no idea how to deal with. I think you probably thought that you were creating empty arrays of zero length, but that isn't how numpy or python works.
Try something like the following instead:
class myClass
def myfunction(self, in_array, in_indeces = None):
if(in_indeces is None):
self.indeces = np.arange(len(in_array))
# NOTE: Use in_array.size or in_array.shape[0], etc instead of len()
else:
self.indeces = in_indeces
# clean data
# set ii to the indices of in_array that are neither nan or inf
ii = ~np.isnan(in_array) & ~np.isinf(in_array)
# assuming in_indeces and in_array are the same shape
tmp_s = in_array[ii]
tmp_idx = in_indeces[ii]
self.indeces = np.arange(tmp_idx.size)
self.samples = np.interp(self.indeces, tmp_idx, tmp_s)
No guarantees that this will work perfectly, since I don't know your inputs or desired outputs, but this should get you started. As a note, in numpy, you are generally discouraged from looping through array elements and operating on them one at a time, if there is a method that performs the desired operation on the entire array. Using built-in numpy methods are always much faster. Definitely look through the numpy docs to see what methods are available. You shouldn't treat numpy arrays the same way you would treat a regular python list.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pagina se cuelga en Validacion del Login
Pues yendo al grano, tengo un problema con una pagina que subi, el problema es que al iniciar sesion o "loguearse" y l hacer la validacion , la pagina se queda colgada en la validacion y no redirecciona la pagina, probe todo en local y funciona, solo que al subirla se cuelga ahi.
agradeceria si me pudieran orientar como solucionarlo gracias.
Lo unico que hice fue reemplazar,http://localhost:8082 por la pagina del host donde esta alojada
la base de datos si esta conectada, ya que hice un echo en la validacion para ver que me arrojara algo y si, solo que como mencione en la validacion se cuelga
Anexo codigo de la validacion
introducir el código aquí
<?php
session_start();
?>
<?php
include 'conexion.php';
$conexion = new mysqli($host_db, $user_db, $pass_db, $db_name);
if ($conexion->connect_error) {
die("La conexion falló: " . $conexion->connect_error);
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM $tbl_name WHERE username = '$username'";
$result = $conexion->query($sql);
if ($result->num_rows > 0) { }
$row=mysqli_fetch_array($result);
// if (password_verify($password, $row['password'])) {
if ($password==$row['password']) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
$_SESSION['id'] =$row['id'];
$_SESSION['name'] =$row['name'];
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (5 * 60);
header('Location: http://localhost:8082/Andor%20Shop/productos.php');//redirecciona a la pagina del usuario
} else {
echo "Username o Password estan incorrectos.";
echo "<br><a href='login.html'>Volver a Intentarlo</a>";
}
mysqli_close($conexion);
?>
Conexion
<?php
$host_db = "localhost";
$user_db = "id12893306_andorstore";
$pass_db = "123456";
$db_name = "id12893306_tienda";
$tbl_name = "clientes";
?>
A:
estoy convencido que es por el header
prueba poner un exit depues del header
header(".....");
exit;
o prueba con un die
header(".....");
die();
por cierto esta linea de codigo no te estara dndo algun tipo de problema ???
if ($result->num_rows > 0) { }
le estas indicando que si hay mas de un registro que haga algo pero no haces nada.....
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to display illegal characters on downloaded file name in Spring?
My downloaded file name becomes Ça_r_lar_02_07_2019_12_09.xlsx, however, I want it Çağrılar_02_07_2019_12_09.xlsx. How Can I fix it?
try (Workbook workbook = new XSSFWorkbook()) {
new XlsExporter().exportXls(workbook, grh);
SimpleDateFormat sdf = new SimpleDateFormat("_dd_MM_yyyy_HH_mm");
String name = grh.getReportName() + sdf.format(new Date());
response.setContentType(MediaType.APPLICATION_OCTET_STREAM.getType());
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + name + ".xlsx\"");
workbook.write(response.getOutputStream());
response.getOutputStream().flush();
}
A:
Try UTF-8 encoding for your filename before sending the response
try (Workbook workbook = new XSSFWorkbook()) {
new XlsExporter().exportXls(workbook, grh);
SimpleDateFormat sdf = new SimpleDateFormat("_dd_MM_yyyy_HH_mm");
String name = grh.getReportName() + sdf.format(new Date());
name = URLEncoder.encode(name,"UTF-8");
response.setContentType(MediaType.APPLICATION_OCTET_STREAM.getType());
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + name + ".xlsx\"");
workbook.write(response.getOutputStream());
response.getOutputStream().flush();
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
wicked_pdf - display links in html.erb templates used to generate PDF but not in generated PDF
Have progressed to get wicked_pdf generating PDF's in Rails 3.2.3. However I want to be able to have links on my pages rendered to screen as HTML from the .html.erb file, but when I review the PDF generated from this template I do not want to see these links.
I had tried to follow what Ryan Bates did in is PDFKit Railscast 220, but its not working for me under Rails 3.2.3, on Ruby 1.9.3.
Here is my an abridged section of the view code:
<h2>Client Setup (Only when Patients module is not available)</h2>
<p>
The setup program installs your Clients module using default settings. After the installation, you can use this program to customize settings to meet your particular needs.
</p>
<p>
<%= pdf_image_tag("clients/blank/.png", alt: "Client Setup (Only when Patients Module is not available) - not-populated") %>
<table>
<thead>
<tr>
<th>Form Item</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Default Value Added Tax (Percent)</td>
<td>
The package offers a default Value Added Tax, expressed as a percentage of the invoice, to be added to the invoice. Numbers from 0 to 999.99 are allowed.
</td>
</tr>
</tbody>
</table>
</p>
<hr />
<form class="form-inline">
<a href="#to_top" class="btn btn-to_top btn-mini">Back to Top</a>
<%= link_to "Genie Help Index", help_path, class: "btn btn-main-menu pdf_link" %>
<p id="pdf_link"><%= link_to "Client Help Index", static_page_path("clients/index"), class: "btn btn-help" %></p>
<%= link_to "Download PDF", static_page_path(:format => :pdf), class: "btn btn-pdf" %>
<%= link_to image_tag("file_type_pdf.png", height: "24px", width: "24px" , alt: "Download page as PDF"), static_page_path(:format => :pdf) %>
</form>
<p><%= link_to "Client Help Index", static_page_path("clients/index") %></p>
<p><%= link_to "Download as PDF", static_page_path(:format => "pdf"), class: "pdf_link" %></p>
<p id="pdf_link"><%= link_to "Download as PDF", static_page_path(:format => :pdf) %></p>
<% if request.try(:format).to_s == 'pdf' %>
<%= link_to "Download this PDF", static_page_path(:format => "pdf") %>
<% end %>
#<% if params[:media] = 'all' %>
# <%= link_to "Download me as a PDF", static_page_path(:format => "pdf") %>
#<% end %>
<div id="pdf-no"><%= link_to "Get me as a PDF file", static_page_path(:format => "pdf") %></div>
Controller is: (show page is the name of the page to render)
class StaticPages::GenieHelpController < ApplicationController
def static_page
respond_to do |format|
format.html do
render :template => show_page,
:layout => 'application'
end
format.pdf do
render :pdf => show_page,
:layout => 'generic',
:template => "#{show_page}.html.erb",
:handlers => :erb,
:disable_external_links => true,
:print_media_type => true
end
end
end
end
The layout file in views/layouts/generic.pdf.erb file is as below:
<!DOCTYPE html>
<html>
<head>
<title><%= full_title(yield(:title)) %></title>
<%= wicked_pdf_stylesheet_link_tag "static_pages/genie_v23_help", :refer_only => true %>
<!-- <%#= wicked_pdf_stylesheet_link_tag "static_pages/pdf" %> -->
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
</head>
<body>
<div class="container">
<%= yield %>
<%= debug(params) if Rails.env.development? %>
</div>
</body>
</html>
The corresponding css file in old location public/stylesheets/static_pages/genie_help.css:
@media print {
body { background-color: LightGreen; }
#container {
width: auto;
margin: 0;
padding: 0;
border: 2px;
}
#pdf_link {
display: none;
}
}
.pdf_link {
display: none;
}
#pdf-no {
display:none;
}
When I render the html page the links at the bottom show up (as expected) when the format is html.
What am I doing wrong on with this. I assume if it can be done via middleware of PDFKit then it is supported under wkhtmltopdf as both PDFKit and wicked_pdf are based on this.
Thanks
Mark
A:
It turned out to be that I solved this problem by mixing-and-matching the four methods in the wicked_helper.pdf file which is based on the lib helper file.
The wicked_pdf_image_tag was changed to pdf_image_tag used in the pull request waiting commit from - mkoentopf
Multi purpose wicked_pdf_helper "Hi there, I've added some code to the wicked_pdf_helper methods. Now they deliver the the full pa…"
def wicked_pdf_image_tag(img, options={})
if request.try(:format).to_s == 'application/pdf'
image_tag "file://#{Rails.root.join('public', 'images', img)}", options rescue nil
else
image_tag img.to_s, options rescue nil
end
end
What I don't understand is under Rails 3.2 are we still using public directory because sprockets and assests get pre-compiled and placed in public?
The solution I used earlier in the day was to add additional header/footer partials within the html layout, but not in the layout for pdf generation.
Here is the helper file I was using:
module WickedPdfHelper
def wicked_pdf_stylesheet_link_tag(*sources)
options = sources.extract_options!
if request.try(:format).to_s == 'application/pdf'
#css_dir = Rails.root.join('public','stylesheets')
css_dir = Rails.root.join('app','assets', 'stylesheets')
refer_only = options.delete(:refer_only)
sources.collect { |source|
source.sub!(/\.css$/o,'')
if refer_only
stylesheet_link_tag "file://#{Rails.root.join('public','stylesheets',source+'.css')}", options
else
"<style type='text/css'>#{File.read(css_dir.join(source+'.css'))}</style>"
end
}.join("\n").html_safe
else
sources.collect { |source|
stylesheet_link_tag(source, options)
}.join("\n").html_safe
end
end
def pdf_image_tag(img, options={})
if request.try(:format).to_s == 'application/pdf'
image_tag "file://#{Rails.root.join('app', 'assets', 'images', img)}", options rescue nil
else
image_tag img.to_s, options rescue nil
end
end
def wicked_pdf_javascript_src_tag(jsfile, options={})
if request.try(:format).to_s == 'application/pdf'
jsfile.sub!(/\.js$/o,'')
javascript_src_tag "file://#{Rails.root.join('public','javascripts',jsfile + '.js')}", options
else
javascript_src_tag jsfile, options
end
end
def wicked_pdf_javascript_include_tag(*sources)
options = sources.extract_options!
sources.collect{ |source| wicked_pdf_javascript_src_tag(source, options) }.join("\n").html_safe
end
end
It would be good to understand more about how the asset pipeline is used. And how the @media is determined. Is it related to MIME types? If so why do we not need to/or are they not defined in wick_pdf?
I have yet to utilise the page numbering and breaking, but now have an outstanding question that I'll put up separately.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
single-particle wavepackets in QFT and position measurement
Consider a scalar field $\phi$ described by the Klein-Gordon Lagrangian density
$L = \frac{1}{2}\partial_\mu \phi^\ast\partial^\mu \phi - \frac{1}{2} m^2 \phi^\ast\phi$.
As written in every graduate QM textbook, the corresponding conserved 4-current $j^\mu = \phi^\ast i \overset{\leftrightarrow}{\partial^\mu} \phi$ gives non-positive-definite $\rho=j^0$. If we are to interpret $\phi$ as a wave function of a relativistic particle, this is a big problem because we would want to interpret $\rho$ as a probability density to find the particle.
The standard argument to save KG equation is that KG equation describes both particle and its antiparticle: $j^\mu$ is actually the charge current rather than the particle current, and negative value of $\rho$ just expresses the presence of antiparticle.
However, it seems that this negative probability density problem appears in QFT as well. After quantization, we get a (free) quantum field theory describing charged spin 0 particles. We normalize one particle states $\left|k\right>=a_k^\dagger\left|0\right>$ relativistically:
$$ \langle k\left|p\right>=(2\pi)^3 2E_k \delta^3(\vec{p}-\vec{k}), E_k=\sqrt{m^2+\vec{k}^2} $$
Antiparticle states $\left|\bar{k}\right>=b_k^\dagger \left|0\right>$ are similarly normalized.
Consider a localized wave packet of one particle $\left| \psi \right>=\int{\frac{d^3 k}{(2\pi)^3 2E_k} f(k) \left| k \right>}$, which is assumed to be normalized. The associated wave function is given by
$$ \psi(x) = \langle 0|\phi(x)\left|\psi\right> = \int{\frac{d^3 k}{(2\pi)^3 2E_k} f(k) e^{-ik\cdot x}} $$
$$ 1 = \langle\psi\left|\psi\right> = \int{\frac{d^3 k}{(2\pi)^3 2E_k} |f(k)|^2 } = \int{d^3x \psi^\ast (x) i \overset{\leftrightarrow}{\partial^0} \psi (x)}$$.
I want to get the probability distribution over space. The two possible choices are:
1) $\rho(x) = |\psi(x)|^2$ : this does not have desired Lorentz-covariant properties and is not compatible with the normalization condition above either.
2) $\rho(x) = \psi^\ast (x) i \overset{\leftrightarrow}{\partial^0} \psi(x)$ : In non-relativistic limit, This reduces to 1) apart from the normalization factor. However, in general, this might be negative at some point x, even if we have only a particle from the outset, excluding antiparticles.
How should I interpret this result? Is it related to the fact that we cannot localize a particle with the length scale smaller than Compton wavelength ~ $1/m$ ? (Even so, I believe that, to reduce QFT into QM in some suitable limit, there should be something that reduces to the probability distribution over space when we average it over the length $1/m$ ... )
A:
The following does not completely answer OP's question, rather, this is going to be a clarification of subtleties and difficulties on the issue. Notice that sometimes I am going to use the same notations as OP used, but not necessarily the exact same meanings and I will make them clear in the context.
The usage of "wavefunction"
It has two possible meanings when people refer to something as wavefunctions :
(1). The collection of some functions $g(x)$ furnishes a positive-energy, unitary representation of the underlying symmetry group(in our case just the Poincare group).
(2). In addition to (1) being satisfied, we should be able to interpret $|g(x)|^2$ as the probability distribution of finding the particle in $(\mathbf{x},\mathbf{x}+d\mathbf{x})$. It really has to be of the form $|g(x)|^2$ according to the standard axioms of quantum mechanics, provided you interpret $g(x)$ as an inner product $\langle x|g\rangle$ where $\langle x|$ is an eigen bra of the position operator. I will discuss what position operator means later.
The 2nd meaning is of course much stronger and OP is searching for a wavefunction in this sense. However, the $\psi(x)$ written by OP is only a wavefunction in the 1st sense, because clearly $\langle 0|\phi(x)$ cannot be eigen bras of any Hermitian position operator, easily seen from the fact that they are not even mutually orthogonal, i.e. $\langle 0|\phi(x)\phi^\dagger(y)|0\rangle\neq0$ even when $x$ and $y$ are spacelike separated. As a consequence, $\int d^3\mathbf{x}|\psi(x)|^2\neq1$ as OP has already noted. Moreover, $|\psi(x)|^2$ is invariant under Lorentz transformation, but a density distribution should transform like the 0th component of a 4-vector in relativistic space-time, as OP has also noticed.
The localized states and position operator(Newton-Wigner)
In this section I will mostly rephrase(for conceptual clarity in sacrifice of technical clarity) what is written in this paper.
What is a sensible definition of position operator of single-particle states? First we need to think about what the most spatially-localized states are, and then it would be natural to call these states $|\mathbf{x} \rangle$, then it is also natural to call the operator having these states as the eigenstates the position operator. It seems pretty reasonable and not too much to ask to require localized states to have the following properties:
(a). The superposition of two localized states localized at the same position in space should again be a state localized at the same position.
(b). Localized states transform correctly under spatial rotation, that is, $|\mathbf{x} \rangle \to |R\mathbf{x} \rangle$ under a rotation $R$.
(c). Any spatial translation on a localized state generates another localized state that is orthogonal to the original, that is, $\langle\mathbf{x}+\mathbf{y}|\mathbf{x} \rangle=0$ if $\mathbf{y}\neq 0$.
(d). Some technical regularity condition.
It turns out these conditions are restrictive enough to uniquely define localized states $|\mathbf{x}\rangle$. It can be worked out that, borrowing OP's notations and normalization convention, if $|\psi\rangle=\int\frac{d^3 k}{(2\pi)^3 2E_k} f(k) |k\rangle$, then(including time dependence)
$$\langle x|\psi\rangle=\int\frac{d^3 k}{(2\pi)^3 \sqrt{2E_k}} f(k) e^{-ik\cdot x},$$
and this (unsurprisingly) gives $\int d^3\mathbf{x}|\langle x|\psi\rangle|^2=1$. However, this is not the full solution to OP's problem, because we can show that, although not as bad as transforming invariantly, $|\langle x|\psi\rangle|^2$ is not as good as transforming like a 0th component, either. The underlying reason is, as already realized by Newton and Wigner, that a boost on a localized state will generate a delocalized state, so the interpretation is really frame dependent.
As I disclaimed, I do not know if there is a complete satisfactory solution, or if it is even possible, but I hope it helps to clarify the issue.
Appendix: Some interesting properties of Newton-Wigner(NW) states and operator
I decide to make it an appendix since I think this is not directly relevant yet very interesting(all the following are for scalar field, and NW also discusses spinor field in their paper):
(1). A state localized at the origin, projected to the bras $\langle 0|\phi(x)$, has the form
$$\langle 0|\phi(x)|\mathbf{x}=0\rangle=\left(\frac{m}{r}\right)^{\frac{5}{4}}H_{\frac{5}{4}}^{(1)}(imr),$$
where $r=(x_1^2+x_2^2+x_3^2)^{\frac{1}{2}}$ and $H_{5/4}^{(1)}$ is a Hankel function of the first kind. So it is not a delta function under such bras.
(2)The NW position operator $q_i (i=1,2,3)$ acting on momentum space wavefunction(defined as $f(k)$ in OP's notation) is
$$q_if(k)=-i\left(\frac{\partial}{\partial k_i}+\frac{k_i}{2E_k}\right)f(k),$$
and in nonrelativistic limit the second term approaches 0, giving the familiar expression of a position operator. We can also get, if $\Psi(x)=\langle 0|\phi(x)|\Psi\rangle$, then
$$q_i\Psi(x)=x_i\Psi(x)+\frac{1}{8\pi}\int\frac{\exp(-m|\mathbf{x-y}|)}{|\mathbf{x-y}|}\frac{\partial \Psi(y)}{\partial y_i}d^3\mathbf{y},$$
and here the nonrelativistic limit is hidden in the unit of $m$, when converting back to SI units, the $m$ on the exponent is really the inverse of Compton wavelength, which can be taken as $\infty$ for low energy physics, so again the 2nd term vanishes.
(3)$[q_i,p_j]=i\delta_{ij}$.
A:
One textbook explanation of this problem is to interpret the probability density as a charge density. However this explanation is meaningless in the case of a real Klein-Gordon field.
There is an other solution in which one works with the following Hamiltonian for a spinless particle:
$H(p, x) = + \sqrt{p^2+m^2}+ V(x)$
This Hamiltonian is positive definite by construction, but it is a fractional pseudo-differential operator. As a consequence, its "wave equation" (named the Salpeter equation) after quantization is nonlocal. (The parentheses are added because it is not a hyperbolic equation).
However, its nonlocality is consistent with the relativistic causality (light-cone structure), therefore, it is a viable relativistic field equation for a spinless particle.
This Hamiltonian allows a probabilistic interpretation of its "wave mechanics". Its probability amplitude returns to be of the form $\bar{\psi}\psi$ at the expense of nonlocal spatial components of the probability current. Please see the following article by Kowalski and Rembielinśki in which explicit constructions of the positive definite probability amplitudes in many particular cases.
The space of solutions of the Salpeter equation is a Hilbert space, thus it can be second quantized to form a quantum free field, please see the following article by: J.R. Smith. The relativistic causality is also manifested in the second quantized version.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How does the GDK android camera example work?
So I'm a little confused about what is going on towards the end of this code (inside processPictureWhenReady()). Before this method is called (within onActivityResult()) we have the image file path... So a file has already been stored. We then have the file declaration pictureFile using the filepath of the image (picturePath). Can someone explain why we have to declare a file using the same file path despite the fact that the file already exists ? Please don't just refer me back to the Google developers website as I have not found this useful.
private static final int TAKE_PICTURE_REQUEST = 1;
private void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PICTURE_REQUEST && resultCode == RESULT_OK) {
String thumbnailPath = data.getStringExtra(Intents.EXTRA_THUMBNAIL_FILE_PATH);
String picturePath = data.getStringExtra(Intents.EXTRA_PICTURE_FILE_PATH);
processPictureWhenReady(picturePath);
// TODO: Show the thumbnail to the user while the full picture is being
// processed.
}
super.onActivityResult(requestCode, resultCode, data);
}
private void processPictureWhenReady(final String picturePath) {
final File pictureFile = new File(picturePath);
if (pictureFile.exists()) {
// The picture is ready; process it.
} else {
// The file does not exist yet. Before starting the file observer, you
// can update your UI to let the user know that the application is
// waiting for the picture (for example, by displaying the thumbnail
// image and a progress indicator).
final File parentDirectory = pictureFile.getParentFile();
FileObserver observer = new FileObserver(parentDirectory.getPath(),
FileObserver.CLOSE_WRITE | FileObserver.MOVED_TO) {
// Protect against additional pending events after CLOSE_WRITE
// or MOVED_TO is handled.
private boolean isFileWritten;
@Override
public void onEvent(int event, String path) {
if (!isFileWritten) {
// For safety, make sure that the file that was created in
// the directory is actually the one that we're expecting.
File affectedFile = new File(parentDirectory, path);
isFileWritten = affectedFile.equals(pictureFile);
if (isFileWritten) {
stopWatching();
// Now that the file is ready, recursively call
// processPictureWhenReady again (on the UI thread).
runOnUiThread(new Runnable() {
@Override
public void run() {
processPictureWhenReady(picturePath);
}
});
}
}
}
};
observer.startWatching();
}
}
A:
You are referring, I presume, to this line:
final File pictureFile = new File(picturePath);
What they have done is created an instance of a File object from the file path where that image is stored. This File object is what they need to do some processing on the image. The File object is an abstraction of the image file in memory, NOT the actual physical file. As I understand it, you seem to be mistaking the two.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
operator overloading outside of a class!
when i was trying to seperate the declaration and implementation of a non-member overloaded operator, i got a LNK2001 error in VC2010, my code was like this:
-foo.h-
class A
{
public:
A(float x);
float x;
};
A operator +(const A&, const A&);
-foo.cpp-
A::A(float x)
{
this->x = x;
}
A operator +(const A& lh, const A& rh)
{
return A(lh.x + rh.x);
}
so once i use the '+' operation, the error pumps out, but if i remove the declaration in the header file, there are no LNK2001 errors.. i cannot figure out why..
A:
I suspect you have the definition in a different namespace than the declaration. ADL is finding the declaration (since it's in the same namespace as the class), and then you get an unresolved external error during link.
e.g.
-foo.h-
namespace aspace
{
class A
{
public:
A(float x);
float x;
};
A operator +(const A&, const A&);
}
-foo.cpp-
#include "foo.h"
using namespace aspace;
A::A(float x)
{
this->x = x;
}
A operator +(const A& lh, const A& rh)
{
return A(lh.x + rh.x);
}
Will give the error you describe. The solution is to put the operator+ definition in the correct namespace:
namespace aspace
{
A operator +(const A& lh, const A& rh)
{
return A(lh.x + rh.x);
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Read String Till Flag (C++)
I'm trying to read a string until a ',' character is reached and store what's been read in a new string.
e.g. "5,6"
// Initialise variables.
string coorPair, xCoor, yCoor
// Ask to enter coordinates.
cout << "Input coordinates: ";
// Store coordinates.
cin >> coorPair
// Break coordinates into x and y variables and convert to integers.
// ?
I also need to store the y value in a separate variable.
What is the best way to do this in C++?
Also, is the best way to validate the input to convert to integers and test the values range?
A:
If you have only one comma seperator in string, you can just find where comma first occurs in input and substring input with found position.
Try following:
std::size_t pos = coorPair.find_first_of(","); //Find position of ','
xCoor = coorPair.substr(0, pos); //Substring x position string
yCoor = coorPair.substr(pos + 1); //Substring y position string
int xCoorInt = std::stoi(xCoor); //Convert x pos string to int
int yCoorInt = std::stoi(yCoor); //Convert y pos string to int
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using different wordpress loop output depending on category
I am trying to create a somewhat advanced wordpress loop for a new website. I would like to display all recent posts on the front page, but differently depending on chosen category.
I am thinking something like this:
Start Loop
Check if category = category 1
If category = category 1:
<-- Loop elements for said category (template tags etc.) -->
Else, check if category = category 2
If category = category 2
<-- Loop elements for said category (template tags etc.) -->
Else
<-- Standard loop elements (template tags etc.) -->
End loop
Is this possible? Are there simpler ways to do this? I realize i could use multiple loops, but would like to keep the posts in chronological order.
I tried using the following code, but this breaks when i put the template tags in the echo?
<?php
$category_name = 'Category 1';
if(in_category($category_name)) {
echo '
<div class="post">
the_title();
the_excerpt();
<div>
';
}
?>
Any help much appreciated :)
A:
Try
<?php
$category_name = 'Category 1';
if(in_category($category_name)) {
?>
<div class="post">
<?php the_title(); ?>
<?php the_excerpt(); ?>
<div>
<?php
}
?>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
GraphicsPath.AddPolygon not rendering properly
Basically I have a form and am trying to "dim" areas of it to draw focus to a certain part of the form. To do this I'm using a Form with no border and 50% opacity, aligned with the actual form. The area I am trying to mask is the dark gray area, roughly, as pictured:
To get the "U"-shaped form, I'm using a GraphicsPath with AddPolygon, calculating the points of each vertex:
var p = new GraphicsPath();
var origin = new Point(Top, Left);
var maxExtentPt = new Point(origin.X + Width, origin.Y + Height);
Point[] points = {
origin,
new Point(origin.X + leftPanel.Width, origin.Y),
new Point(origin.X + leftPanel.Width, maxExtentPt.Y - bottomPanel.Height),
new Point(maxExtentPt.X - rightPanel.Width, maxExtentPt.Y- bottomPanel.Height),
new Point(maxExtentPt.X - rightPanel.Width, origin.Y),
new Point(maxExtentPt.X, origin.Y),
maxExtentPt,
new Point(origin.X, maxExtentPt.Y),
origin
};
p.AddPolygon(points);
overlayForm.Region = new Region(p);
overlayForm.Location = PointToScreen(Point.Empty);
The three panels in the code are what I am masking, so I am using their dimensions to calculate the points. Instead of getting my expected result, the mask looks like this, with its size changing as I resize the main form (I recalculate the region on Move and Resize):
Is there some limitation of GraphicsPath.AddPolygon that I'm not aware of? I double-checked (quadruple-checked, really) the results of my calculations, including taking the coordinates for each point and plugging them into Ipe to see if the shape was actually correct... It was. But not in my program!
Edit: Here are the values of each point, when I hit a breakpoint at p.AddPolygon(points); I'm starting in the upper left-hand corner and going around clockwise:
A:
Looks like your points are wrong after all.
Everything ought to be in the coordinates of the ClientRectangle, so
Origin should not be new Point(Top, Left) which is the Location of the Form. It should be Point.Empty or (0,0). Or you could use the leftPanel.Location.
And
maxExtentPt = new Point(origin.X + Width, origin.Y + Height);
should read:
var maxExtentPt = new Point(origin.X + ClientSize.Width, origin.Y + ClientSize.Height);
(The difference is the size of border+title..)
Let me know if that works better!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
WCF Data Service compression for an Android client
I use a WCF Data Services service that resides in a Windows Service program and get data with an Android phone using Odata4j. I get lots of data from it and I need to compress the data coming from the Data Service. I was thinking of GZip as a standard compressing algorythm and Android should have the necessary decoding methods.
Is it possible? I couldn't find the compression settings for my data service let alone the Android side of the decompression. What is the best way to accomplish this?
A:
So here are my findings regarding to the compression problem.
With a WCF Data Service in a Windows Service, you cannot create compression because you cannot modify the output as there is no HTTPContext - it is a property of the ASP context that can be found only in IIS (Express)
You need an IIS for compressing the data - it is easy that way
Much to my astonishment, the compressed data could be read by odata4j without any modification
It is good to know that the decompressing of the incoming data takes notable time, comparable to the time gained by transferring less data
See here for more information.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to detect WCF service shutdown or disconnect from client?
I'm building a WCF service,after a client connects to this service,when the service disconnect, the client doesn't notice that, and it doesn't fire any action, i would like to close client form whenever the connection lost,so how would i detect WCF service disconnect or shutdown from client side.
A:
A simple approach is the client will call a simple method in service called IsAlive() just returns true as described in this thread.
There is another way you could achieve this using the new Discovery/Announcement features that comes with WCF 4. Though I haven't tried but this feature helps you to make the service notify the client if it gets into offline/shutdown.
Here is an example post.
You can google "WCF announement service" and you'll get some good reference materials.
A:
You should probably just set up a timer that will continually ping the server, and if the fails, fire an event that the service is no longer available.
This answer also has some good suggestions.
WCF - have client check for service availability
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Whole Disk Encryption and power failures
I believe encryption softwares like TrueCrypt and VeraCrypt support whole disk encryption.
Now lets say I open my computer give my decryption password and successfully boot and am using my computer. Lets say the power suddenly goes off, and the computer shuts off. What happens then ?
Correct me if I am wrong, the contents on my hard disk are still in the decrypted format right ?
Or lets say while encrypting the computer crashes due to a power failure or a hardware failure, what happens then ?
A:
No, the disk contents remain encrypted even while in use – the OS decrypts sectors in memory. (Just like in the 2nd question, you noted that encrypting the disk takes a long time. If the OS had to fully decrypt it on each boot, that would also take just as long – not to mention being useless.)
Most full-disk-encryption software keeps track of the current encryption progress (inside the encrypted volume header). After a power outage, there shouldn't be data loss since TrueCrypt can just resume from that point – or at least no more than a few sectors at the boundary.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
No tabview component in Form Builder
I am looking for a tabview component in Orbeon Form Builder, but couldn't find it. Instead I found the link that unit test the tabview their https://github.com/orbeon/orbeon-forms/blob/master/src/resources-packaged/xbl/orbeon/tabview/tabview-unittest.xhtml
Is the tabview obsolete/deprecated or we may still use it through Form Builder?
A:
There was never a general-purpose tabview component proper available in Form Builder. There is the wizard view which might help you though.
The fr:tabview component is in fact obsolete even if you write XForms by hand. There is a new fr:tabbable component, which is currently reserved for internal use by the Form Builder UI.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to avoid security dialog when accessing AppointmentItem Body in Outlook 2003 custom addin
I have created an Outlook 2003 addin in VSTO 2005. I am trying access appointment Item's body. When this statement runs, Outlook pops up a security dialog where it ask for whether to allow to access the information or not. How can we bypass this check or any additional setting we need to do so it will not appear?
A:
This is the inbuilt security feature. If we tries to access body of the Appointment, it will throw security dialog. It can't be avoided, until AddIn dll made trusted.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
LIKE doesn't return results
I am trying to find "sam" inside FullName in the table users with this eloquent operation:
$user = User::where('id', '=', $input)->orWhere('fullName', 'LIKE', "%$input%")->find(10);
finding through id works as expected but the Where with LIKE isn't returning any results.
(if $input is 1 the first where returns a result but if $input is sam the second where doesn't return anything)
In the database fullName has the value "Sam Pettersson".
Anything I am doing wrong?
A:
For some reason laravel doesn't want find() and like queries in the same query so using this instead worked:
$user = User::where('id', '=', $input)->orWhere('fullName', 'LIKE', "%$input%")->take(10)->get();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Nothing after logging into account
I tried to install java and few other upgrades, so I found this website:
http://itsfoss.com/things-to-do-after-installing-ubuntu-14-04/
and did basically everything. After reboot screen with the encryption password has a small resolution, later logging screen is normal and after password and enter I just see the wallpaper and my mouse. I made before hotkeys for task manager and xkill but non of them works, either ctrl+alt+t
Guest session doesn't work also.
please help me.. I'm fighting with linux for over a week :( I just try to make it working and leave it like it is
Things I have done:
I have installed Nvidia drivers (official and tested)
I updated software with canonical partners
Installed Play encrypted DVD in Ubuntu 14.04 by:
sudo apt-get install libdvdread4
sudo /usr/share/doc/libdvdread4/install-css.sh
Installed rar sudo apt-get install rar
Installed TLP
sudo add-apt-repository ppa:linrunner/tlp
sudo apt-get update
sudo apt-get install tlp tlp-rdw
sudo tlp start
Installed Tweak Unity sudo apt-get install unity-tweak-tool
Disabled shopping suggestions
gsettings set com.canonical.Unity.Lenses disabled-scopes "['more_suggestions-amazon.scope', 'more_suggestions-u1ms.scope', 'more_suggestions-populartracks.scope', 'music-musicstore.scope', 'more_suggestions-ebay.scope', 'more_suggestions-ubuntushop.scope', 'more_suggestions-skimlinks.scope']" <- however something was wrong, didn't get the part with ebay-scope.
Installed java sudo apt-get install icedtea-7-plugin openjdk-7-jre
Edit:
I read here that similar thing can happen when installed nvidia drivers without having nvidia, however I do have 720M and I have no idea how to write commands without logging in.
Edit2: Logged in the root terminal in recovery mode, tried sudo apt-get remove unity-tweak-tool but it doesn't work. Not using locking for read only lock file /var/lib/dpkg/lock
Edit3: I stopped messing with the recover (didn't know how does it work like) and I have logged in with ctrl+alt+f1. For other newbies like me: my login is from the capital letter, but here I had to write it from a small one :)
I typed sudo apt-get remove unity-tweak-tool but it didn't help..
Should I use unity-tweak-tool --reset-unity ? I don't want to configure everything again if there is other option
Edit4: Installed both of these jockey-common and ubuntu-drivers-common but non of the commands works. (--list)
sudo apt-get install nvidia-current stops on 26% Unable to fetch some archives. apt-get update didn't help.
A:
I made it on my own! :)
Maybe someone will use it.
Answer is here, however second and third line didn't work for me. As always some archive problem. Neverthless it was because of the nvidia, I will never move it again.
sudo apt-get purge nvidia-*
sudo apt-get install --reinstall xserver-xorg-video-intel libgl1-mesa-glx libgl1-mesa-dri xserver-xorg-core
sudo dpkg-reconfigure xserver-xorg
sudo update-alternatives --remove gl_conf /usr/lib/nvidia-current/ld.so.conf
But I made a new problem, I can't change brightness at all. Is there any end of configuring this system..?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
NoClassDefFoundError no sense
I'm discovering a problem with an Android application.
My problem is that when I open the application it crashes giving NoClassDefFoundError.
This is the stack trace:
09-24 19:37:14.542 32545-32545/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: it.bcv.invadelite, PID: 32545
java.lang.NoClassDefFoundError: com.electronwill.nightconfig.core.file.FormatDetector$$Lambda$0
at com.electronwill.nightconfig.core.file.FormatDetector.registerExtension(FormatDetector.java:27)
at com.electronwill.nightconfig.json.JsonFormat.<clinit>(JsonFormat.java:66)
at it.bcv.invade.appdb.ConfigAdapter.<init>(ConfigAdapter.java:39)
at it.bcv.invade.appdb.Db.<init>(Db.java:51)
at it.bcv.invade.appdb.Db.init(Db.java:75)
at it.bcv.invadelite.activities.StartActivity.initDatabase(StartActivity.java:165)
at it.bcv.invadelite.activities.StartActivity.onCreate(StartActivity.java:125)
[...]
and build.gradle file has following lines:
// https://github.com/TheElectronWill/Night-Config
implementation 'com.github.TheElectronWill.Night-Config:core:3.1.0'
implementation 'com.github.TheElectronWill.Night-Config:json:3.1.0'
The FormatDetector class is like this
private static final Map<String, Supplier<ConfigFormat<?>>> registry = new ConcurrentHashMap<>();
/**
* Registers a ConfigFormat for a specific fileExtension.
*
* @param fileExtension the file extension
* @param format the config format
*/
public static void registerExtension(String fileExtension, ConfigFormat<?> format) {
registry.put(fileExtension, () -> format);
}
while the JsonFormat class has this declaration
private static final JsonFormat<FancyJsonWriter> FANCY = new JsonFormat<FancyJsonWriter>() {
@Override
public FancyJsonWriter createWriter() {
return new FancyJsonWriter();
}
@Override
public ConfigParser<Config> createParser() {
return new JsonParser(this);
}
};
static {
FormatDetector.registerExtension("json", FANCY);
}
I've googled about this error and I found that could be due to the missing of some classes in the classpath.
For this reason I've analyzed the apk with Android Studio analyzer and i found that in classes.dex there are both packages com.electronwill.nightconfig.core and com.electronwill.nightconfig.json that are the only two package that I'm using.
I've debugged the application on many phones, and the only that is causing problems has Android 5.1.1. I don't know if other versions of Android can cause problems but I think that the Android version is not the core problem.
Anyone can help me to solve this please? Anyone knows why I'm getting this error even with gradle and only in one phone?
A:
NightConfig author here.
Android studio tools do work with lambdas, but older versions of Android don't have the Supplier class, which is used by my FormatDetector. This is probably what causes the error.
You should use the new NightConfig *_android modules, which are adapted for older Android APIs.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
django simplejson throwing keys must be a string error
the error sounds very straight forward but am unable to fix it. I tried changing in my dictionary but am not going anywhere and I thought maybe someone in here can help me point out what I need to do to solve it. Below is my code
blog_calendar = BlogI18n.objects.filter(language=request.LANGUAGE_CODE,
blog__published_at__gte=datetime(year, month, 1),
blog__published_at__lte=datetime(year, month, calendar.monthrange(year, month)[1])
).order_by('-blog__published_at').select_related()
try:
calendar_response = {}
calendar_response['properties'] = []
calendar_response['properties'].append({'next_url' : reverse('blog-archives-month-year',
args=[(date(year, month, 1)-timedelta(days=31)).year, (date(year, month, 1)-timedelta(days=31)).month])}
)
calendar_response['properties'].append({'prev_url' : reverse('blog-archives-month-year',
args=[(date(year, month, 1)+timedelta(days=31)).year, (date(year, month, 1)+timedelta(days=31)).month])}
)
calendar_response['current_month'] = []
calendar_response['current_month'].append({'month':'%s, %s' % (calendar.month_name[month], year)})
calendar_response['events'] = []
if blog_calendar:
calendar_response['events'].append(dict((i.blog.published_at.date(), (i.blog.slug, i.title)) for i in blog_calendar))
else:
calendar_response['events'].append(None)
except Exception, e:
print e.__str__()
if request.is_ajax():
# try converting the dictionary to json
try:
from django.core.serializers.json import DjangoJSONEncoder
return HttpResponse(simplejson.dumps(calendar_response, cls=DjangoJSONEncoder),
mimetype="application/json")
except Exception, e:
return HttpResponse(e.__str__())
when converting its returning TypeError unable to convert to json (keys must be a string) when I comment out the following line
calendar_response['events'].append(dict((i.blog.published_at.date(), (i.blog.slug, i.title)) for i in blog_calendar))
it works, so the problem is in this, any idea how i can rebuild my dictionary in a way that the simplejson would understand it?
regards,
A:
You have to convert all your keys to strings.
In this line:
calendar_response['events'].append(dict((i.blog.published_at.date(), (i.blog.slug, i.title)) for i in blog_calendar))
The culprit is the i.blog.published_at.date() expression. Substitute it with something which returns a string, as for example:
str(i.blog.published_at.date())
or:
i.blog.published_at.date().isoformat()
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Thunderbolt 3 connecting to USB 3.1
I know that Thunderbolt 3 uses the USB Type-C port, and I know that you can plug a USB cable into a Thunderbolt port and it will function as USB or Thunderbolt depending on the peripheral.
However, if I have a USB 3.1 Gen 2 Type-C Port and I plug a Thunderbolt 3 peripheral into it, will I get the 10 Gbps from USB 3.1 Gen 2, or will I get a slower speed. Or, will it just not work at all?
A:
USB 3 is a subset of Thunderbolt 3 host. So if a USB 3.1 device is plugged into TB3 port, it works.
The opposite is not true. A TB3 device doesn't work in USB 3.1 host port. Charge function might work, but data connection will be refused.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Finding violations of the symmetry constraint
Suppose I have a table Friends with columns Friend1ID, Friend2ID. I chose to represent each friendship with two records, say (John, Jeff) and (Jeff, John). Thus, each pair of friends should show up exactly twice in the table.
Sometimes, this constraint is violated, i.e., a pair of friends shows up only once in the table. How do I write a query that will identify all such cases (ideally, using reasonably standard SQL)? In other words, I would like the query to return the list of rows in this table, for which there is no corresponding row with the swapped fields.
An additional question: is there any way to enforce this referential integrity in MySQL?
A:
To find the rows, use a left outer join:
select
a.Friend1ID, a.Friend2ID, b.Friend1ID, b.Friend2ID
from
Friends a left join Friends b
on (a.Friend1ID=b.Friend2ID and a.Friend2ID=b.Friend1ID)
where
b.friend1ID IS NULL ;
A:
The simplest approach is to store each relationship exactly once, and enforce that with a check constraint Friend1
CREATE VIEW AllFriendships
AS
SELECT Friend1, Friend2 FROM Friendships
UNION ALL
SELECT Friend1 AS Friend2, Friend2 AS Friend1 FROM Friendships
If, however, you really need the table with both Friend1,Friend2 and Friend2,Friend1, you could create a self-referencing foreign key if MySql's implementation of constraints was more complete:
FOREIGN KEY(Friend1,Friend2) REFERENCES Friendships(Friend2,Friend1)
Once you have created this constraint, you will only be able to insert both rows in one statement. Unfortunately, this is does not work on MySql.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
My first app. Error: Invalid start tag LinearLayout. Why?
It was working perfectly but then I made some minor edits and now it isn't working... Here's the main layout xml file... It gives an error in line 3.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="0dip"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_weight="6">
<TextView
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="2"
android:background="#FFFF00"
android:text="@string/yellow"
android:textColor="#FFFFFF"
android:gravity="center_horizontal"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:background="#FFFFFF"
android:text="@string/helo"
android:textColor="#000000"
android:gravity="center_horizontal"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:background="#FFFF00"
android:text="@string/yellow"
android:textColor="#FFFFFF"
android:gravity="center_horizontal"
/>
</LinearLayout>
<LinearLayout
android:layout_width="0dip"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_weight="4">
<TextView
android:layout_width="fill_parent"
android:layout_height="0dip"
android:text="@string/blue"
android:layout_weight="3"
android:textColor="#FFFFFF"
android:background="#0000FF" />
<TextView
android:background="#FFFFFF"
android:text="@string/helo"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:textColor="#000000"
android:layout_weight="1" />
<TextView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textColor="#FFFFFF"
android:text="@string/yellow"
android:background="#FFFF00" />
<TextView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="@string/blue"
android:background="#0000FF"
android:textColor="#FFFFFF" />
</LinearLayout>
</LinearLayout>
A:
I think that you have your file in the wrong directory. The layout file should be in a res/layout/ directory within your project. My guess is that you have it in some other res/ directory.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL Query for returning only 1 record with 2 conditions satisfied
WHERE (ADDR1 = '1500 Valley Rd' AND CUST_FLAG = 'P') -- 1
OR (ADDR1 = '1500 Valley Rd' AND CUST_FLAG = 'J') -- 2
Please help me with this piece of query. I need to show only the record with CUST_FLAG = 'P'. With the above Where clause I am getting both the records if both the conditions are satisfied.
My Requirement is:
If only 1st condition satisfies, then return the record with CUST_FLAG = 'P'
If only 2nd condition satisfies, then return the record with CUST_FLAG = 'J'
If both the conditions satisfies, then return only the record with CUST_FLAG = 'P'.
A:
This is a prioritization query. To do this in a single where clause, you can do:
WHERE ADDR1 = '1500 Valley Rd' AND
(CUST_FLAG = 'P' OR
(CUST_FLAG = 'J' AND
NOT EXISTS (SELECT 1 FROM t WHERE t.ADDR1 = outer.ADDR1 AND t.CUST_FLAG = 'J'
))
Or a more typical way is to use ROW_NUMBER():
select t.*
from (select t.*, row_number() over (partition by addr1 order by cust_flag desc) as seqnum
from (<your query here>) t
) t
where seqnum = 1;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jQuery if a link hasClass, apply a class to its parent
I've got a simple list:
<ol>
<li><a href="#" class="on"> I'm on</a> </li>
<li><a href="#"> I'm off</a> </li>
<li><a href="#"> I'm off</a> </li>
</ol>
I want apply a class to the <li> if the <a> it contains has the class on.
IE: I want to change from
<li><a href="#" class="on"> I'm on</a> </li>
to:
<li class="active"><a href="#" class="on"> I'm on</a> </li>
There's 100 better ways to do this using just css, but all involve refactoring a complicated slider I have setup. If I could use the a.on to affect its .parent(), I'd be all set.
Le fiddle: http://jsfiddle.net/saltcod/GY2qP/1/
A:
This should do it:
$('a.on').parent('li').addClass('active');
http://jsfiddle.net/rdrsd/
A:
You were settings the parent of all anchors inside lis to be yellow if any anchor ahd the class on.
Use this instead:
//remove on states for all nav links
$("li a").removeClass("on");
$("li").removeClass("yellow");
//add on state to selected nav link
$(this).addClass("on");
$(this).parent().addClass('yellow');
Updated JS Fiddle
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pick a unique random subset from a set of unique values
C++. Visual Studio 2010.
I have a std::vector V of N unique elements (heavy structs). How can efficiently pick M random, unique, elements from it?
E.g. V contains 10 elements: { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } and I pick three...
4, 0, 9
0, 7, 8
But NOT this: 0, 5, 5 <--- not unique!
STL is preferred. So, something like this?
std::minstd_rand gen; // linear congruential engine??
std::uniform_int<int> unif(0, v.size() - 1);
gen.seed((unsigned int)time(NULL));
// ...?
// Or is there a good solution using std::random_shuffle for heavy objects?
A:
Create a random permutation of the range 0, 1, ..., N - 1 and pick the first M of them; use those as indices into your original vector.
A random permutation is easily made with the standard library by using std::iota together with std::random_shuffle:
std::vector<Heavy> v; // given
std::vector<unsigned int> indices(V.size());
std::iota(indices.begin(), indices.end(), 0);
std::random_shuffle(indices.begin(), indices.end());
// use V[indices[0]], V[indices[1]], ..., V[indices[M-1]]
You can supply random_shuffle with a random number generator of your choice; check the documentation for details.
A:
Most of the time, the method provided by Kerrek is sufficient. But if N is very large, and M is orders of magnitude smaller, the following method may be preferred.
Create a set of unsigned integers, and add random numbers to it in the range [0,N-1] until the size of the set is M. Then use the elements at those indexes.
std::set<unsigned int> indices;
while (indices.size() < M)
indices.insert(RandInt(0,N-1));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Jackson, how to ignore some values
I'd like to exclude all properties with values less than zero. Does Jackson have some ready to use solutions or I should create CustomSerializerFactory and BeanPropertyWriter?
A:
You can do this by using a filter - it's a little verbose but it does the job.
First - you need to specify the filter on your entity:
@JsonFilter("myFilter")
public class MyDtoWithFilter { ...}
Then, you need to specify your custom filter, which will look at the values:
PropertyFilter theFilter = new SimpleBeanPropertyFilter() {
@Override
public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer) throws Exception {
if (include(writer)) {
if (writer.getName().equals("intValue")) {
int intValue = ((MyDtoWithFilter) pojo).getIntValue();
if (intValue < 0) {
writer.serializeAsField(pojo, jgen, provider);
}
} else {
writer.serializeAsField(pojo, jgen, provider);
}
} else if (!jgen.canOmitFields()) { // since 2.3
writer.serializeAsOmittedField(pojo, jgen, provider);
}
}
@Override
protected boolean include(BeanPropertyWriter writer) {
return true;
}
@Override
protected boolean include(PropertyWriter writer) {
return true;
}
};
This is done for a field called intValue but you can do the same for all your fields that need to be positive in a similar way.
Finally, not you can marshall an object and test that it works:
FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter);
MyDtoWithFilter dtoObject = new MyDtoWithFilter();
dtoObject.setIntValue(12);
ObjectMapper mapper = new ObjectMapper();
String dtoAsString = mapper.writer(filters).writeValueAsString(dtoObject);
Hope this helps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Store table heading titles `THEAD` as jQuery variable?
I'm trying to store the value (different for each tabe header column) of <th> as a variable in jQuery, how can I do this? I'm using a jQuery plugin called simpletip which creates the effect I want, but since I have 14 columns each with different titles, I want to store the title for each one on a "foreach" kind of basis but I'm not sure which direction to go... help?
jQuery(document).ready(function() {
$('thead th').simpletip({
var title = $(this).html();
// Configuration properties
content: '<div class="info"><span><span>$title</span></span></div>',
fixed: false
});
});
A:
Youve almost got it already...
$('thead th').each(function(){
var th = $(this);
th.simpletip({
fixed: false,
content: '<div class="info"><span><span>'+th.html()+'</span></span></div>'
});
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What libraries / approach should I have for connecting with ruby on rails system to a standard Microsoft Web service using the soap protocol?
I am looking to connect with an API (documentation: http://carsolize.com/carsolize_API_v2.5.pdf).
To get started in a good direction how would you do this? (What gems/methods would I use?, any tips highly appreciated!)
A:
I recommend using Savon: https://github.com/savonrb/savon it helps you create SOAP request neatly. Check out the documentation here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Recursive linq query
I have the following object structure.
public class Study
{
public Guid? PreviousStudyVersionId { get; set; }
public Guid StudyId { get; set; }
//Other members left for brevity
}
It is persisted using entity Framework code first.
It results in a table like this
PreviousStudyVersionId StudyId
EF90F9DC-C588-4136-8AAE-A00E010CE87B E4315CFD-9638-4225-998E-A00E010CEEEC
NULL 1C965285-788A-4B67-9894-3D0D46949F11
1C965285-788A-4B67-9894-3D0D46949F11 7095B746-8D32-4CC5-80A9-A00E010CE0EA
7095B746-8D32-4CC5-80A9-A00E010CE0EA EF90F9DC-C588-4136-8AAE-A00E010CE87B
Now I want to query all studyId's recursive. So I came up with the following solution:
So when I call the method in my repository GetAllStudyVersionIds(new Guid("7095B746-8D32-4CC5-80A9-A00E010CE0EA")) it returns me all 4 the studyId's.
public IEnumerable<Guid> GetAllStudyVersionIds(Guid studyId)
{
return SearchPairsForward(studyId).Select(s => s.Item1)
.Union(SearchPairsBackward(studyId).Select(s => s.Item1)).Distinct();
}
private IEnumerable<Tuple<Guid, Guid?>> SearchPairsForward(Guid studyId)
{
var result =
GetAll().Where(s => s.PreviousStudyVersionId == studyId).ToList()
.Select(s => new Tuple<Guid, Guid?>(s.StudyId, s.PreviousStudyVersionId));
result = result.Traverse(a => SearchPairsForward(a.Item1));
return result;
}
private IEnumerable<Tuple<Guid, Guid?>> SearchPairsBackward(Guid studyId)
{
var result = GetAll().Where(s => s.StudyId == studyId).ToList()
.Select(s => new Tuple<Guid, Guid?>(s.StudyId, s.PreviousStudyVersionId));
result = result.Traverse(a => a.Item2.HasValue ? SearchPairsBackward(a.Item2.Value) : Enumerable.Empty<Tuple<Guid, Guid?>>());
return result;
}
This is the implementetion of my extension method.
public static class MyExtensions
{
public static IEnumerable<T> Traverse<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> fnRecurse)
{
foreach (var item in source)
{
yield return item;
var seqRecurse = fnRecurse(item);
if (seqRecurse == null) continue;
foreach (var itemRecurse in Traverse(seqRecurse, fnRecurse))
{
yield return itemRecurse;
}
}
}
}
Is there any way of moving this closer to the database (IQueryable) and optimize this code.
A:
I have done this by making a recursive table function pulling all parent records based on id and then creating a view to produce a list for each record and all the parents. Then I consume that in the EF model and associate to be able to use with LINQ.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to change Default alert sound in iCal?
I would like to change the default sound ("basso") that plays when an Alert is fired from iCal in the notification center?
I have tried changing the sounds in notification center, but it seems to be overridden by the iCal settings. Can the sound be changed to "glass" or any other?
One way, I can do it is by changing the Alert sound when I create a Calendar Event. This is just too cumbersome to do everytime.
Please assist.
A:
There is a alternative way to do that.
Go to System/Library/Sounds and create a sound file with the same name as Basso.aiff and it will supersede Basso without the need for deleting a system sound file.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Estimation of the bond angle of water
We know from experimental data that $\ce{H-O-H}$ bond angle in water is approximately 104.5 degrees. If its two lone pairs were bonds (which is unfortunately impossible) also $\ce{O-H}$ bonds and a perfect tetrahedron resulted, then VSEPR theory would predict that the bond angle would be 109.5 degrees - this number can be easily derived using the geometry of a tetrahedron. However, how would people give estimates of the actual bonding angle of water, which is caused by a slightly greater repulsion by the lone pairs than there would be if they were bonds? What physics would be involved in the calculation? Thanks!
A:
how would people give estimates of the actual bonding angle of water
What physics would be involved in the calculation
Background
That's a very good question. In many cases Coulson's Theorem can be used to relate bond angles to the hybridization indices of the bonds involved.
$$\ce{1+\lambda_{i} \lambda_{j} cos(\theta_{ij})=0}$$
where $\ce{\lambda_{i}}$ represents the hybridization index of the $\ce{C-i}$ bond (the hybridization index is the square root of the bond hybridization) and $\ce{\theta_{ij}}$ represents the $\ce{i-C-j}$ bond angle.
For example, in the case of methane, each $\ce{C-H}$ bond is $\ce{sp^3}$ hybridized and the hybridization index of each $\ce{C-H}$ bond is $\sqrt3$. Using Coulson's theorem we find that the $\ce{H-C-H}$ bond angle is 109.5 degrees.
How can we use this approach to answer your question?
Unlike methane, water is not a perfectly tetrahedral molecule, so the oxygen bonding orbitals and the oxygen lone pair orbitals will not be exactly $\ce{sp^3}$ hybridized. Since addition of s-character to an orbital stabilizes electrons in that orbital (because the s orbital is lower in energy than the p orbital) and since the electron density is higher in the lone pair orbital than the $\ce{O-H}$ orbital (because the electrons in the lone pair orbital are not being shared with another atom), we might expect that oxygen lone pair orbital will have more s-character and the oxygen $\ce{O-H}$ orbital will have less s-character.
If we examine the case where the $\ce{O-H}$ bond is $\ce{sp^4}$ hybridized, we find from Coulson's Theorem that the $\ce{H-O-H}$ angle is predicted to be around 104.5°. So indeed, in agreement with our prediction, removing s-character from the oxygen $\ce{O-H}$ orbital gives rise to the observed bond angle.
Note on reality
For over 50 years students have been told that water is roughly $\ce{sp^3}$ hybridized. The general description is that there are two equivalent O-H sigma bonds and two equivalent lone pairs orbitals. The lone pair - lone pair repulsion is greater than the sigma bond - sigma bond repulsion, so the hybridization changes as described above and the lone pair-O-lone pair angle opens up slightly and the $\ce{H-O-H}$ angle closes down to the observed 104.5 degrees.
With the advent of photoelectron spectroscopy it was found that the two lone pairs in water were not equivalent (2 signals were observed for the lone pairs). Now, the hybridization of water is described as follows:
2 $\ce{sp^4}$ O-H sigma bonds
one lone pair in a p orbital
and the second lone pair in an $\ce{sp}$ orbital
A:
As you said, lone pairs result in slightly more repulsion than bonds, because the lone pairs themselves expand a little around the atom. Common practice that I've learned is just to subtract about 2.5 degrees from the bond angle for every lone pair. For instance, a molecule such as NCl3 has 4 negative charge centers, giving it a tetrahedral group geometry, but it has one lone pair, giving it bond angles of about 107 degrees. Following this pattern, water would have bond angles of about 104.5 degrees.
Here's a picture that sort of shows how the lone pairs expand, reducing the bond angles slightly.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is this thread safe? Breakpoints get hit multiple times
I have the following code:
public class EmailJobQueue
{
private EmailJobQueue()
{
}
private static readonly object JobsLocker = new object();
private static readonly Queue<EmailJob> Jobs = new Queue<EmailJob>();
private static readonly object ErroredIdsLocker = new object();
private static readonly List<long> ErroredIds = new List<long>();
public static EmailJob GetNextJob()
{
lock (JobsLocker)
{
lock (ErroredIdsLocker)
{
// If there are no jobs or they have all errored then get some new ones - if jobs have previously been skipped then this will re get them
if (!Jobs.Any() || Jobs.All(j => ErroredIds.Contains(j.Id)))
{
var db = new DBDataContext();
foreach (var emailJob in db.Emailing_SelectSend(1))
{
// Dont re add jobs that exist
if (Jobs.All(j => j.Id != emailJob.Id) && !ErroredIds.Contains(emailJob.Id))
{
Jobs.Enqueue(new EmailJob(emailJob));
}
}
}
while (Jobs.Any())
{
var curJob = Jobs.Dequeue();
// Check the job has not previously errored - if they all have then eventually we will exit the loop
if (!ErroredIds.Contains(curJob.Id))
return curJob;
}
return null;
}
}
}
public static void ReInsertErrored(long id)
{
lock (ErroredIdsLocker)
{
ErroredIds.Add(id);
}
}
}
I then start 10 threads which do this:
var email = EmailJobQueue.GetNextJob();
if (email != null)
{
// Breakpoint here
}
The thing is that if I put a breakpoint where the comment is and add one item to the queue then the breakpoint gets hit multiple times. Is this an issue with my code or a peculiarity with VS debugger?
Thanks,
Joe
A:
It appears as if you are getting your jobs from the database:
foreach (var emailJob in db.Emailing_SelectSend(1))
Is that database call marking the records as unavailable for section in future queries? If not, I believe that's why you're hitting the break point multiple times.
For example, if I replace that call to the database with the following, I see your behavior.
// MockDB is a static configured as `MockDB.Enqueue(new EmailJob{Id = 1})`
private static IEnumerable<EmailJob> GetJobFromDB()
{
return new List<EmailJob>{MockDB.Peek()};
}
However, if I actually Dequeue from the mock db, it only hits the breakpoint once.
private static IEnumerable<EmailJob> GetJobFromDB()
{
var list = new List<EmailJob>();
if (MockDB.Any())
list.Add(MockDB.Dequeue());
return list;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Personalization conditions switching doesn`t work in Experience Editor (9.1.0, Initial Release)
We personalize one particular rendering on page item. There are some different conditions that have different datasource item for this rendering.
Personalization works good on website - datasource is changed according to conditions. But when we try to switch condition in Experience Editor - nothing happens. Datasource does not changed. There are no errors in log files and no errors in browser console.
Can anyone help to find what is wrong? Sitecore version is 9.1.
A:
This is an issue for Sitecore XP 9.1.0 (Initial Release). It is not reproducible in the Sitecore 9.0.x and pre-release version of Sitecore 9.2.
If you need a hotfix for Sitecore 9.1, you can request the fix from Sitecore Support. Public reference number is 312777.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Regex to get string between two characters
I want to get everything between [ and ] like:
[hello] hi
should give:
hello
I tried \[(.*)\] but when i use:
[hello] hi [yo]
it gives:
hello] hi [yo
How can i make it so that it returns only the first one, then the second one like hello and yo
A:
\[(.*)\] is greedy meaning the * matches until the last occurance. Use a ? and it will stop at the first.
\[(.*?)\]
Demo: https://regex101.com/r/cM6aD7/1
PreDemo: https://regex101.com/r/cM6aD7/2
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is Logic Apps' if() expression executing both code paths simultaneously?
I am getting failures on a Logic App because the if() expression is executing both the true and false paths. The false path is going to fail if it executes which is why I put it in an if() in the first place.
The expression is:
if(empty(triggerBody()?['data']?['eta']), null, formatDateTime(triggerBody()?['data']?['eta'], 'yyyy-MM-dd'))
I've also tried:
if(equals(triggerBody()?['data']?['eta'], null), null, formatDateTime(triggerBody()?['data']?['eta'], 'yyyy-MM-dd'))
The data is null:
...
"data": {
"eta": null,
...
I've tested this by swapping out formatDateTime() with a string like 'is not null'. When I do this I get the expected output (null) and no failure.
Update: Someone from the Logic Apps team suggested the following as an alternative:
@if(empty(triggerBody()?['data']?['eta']), null, formatDateTime(coalesce(triggerBody()?['data']?['eta'], '1999-01-01'), 'yyyy-MM-dd'))
The usage of coalesce() is suggested here because it returns the first non-null result. So in this way I can at least be assured of providing a value to formatDateTime().
A:
Why? Because that's the way it's written. ;)
What you are seeing is the expected behavior of if() execution in a LogicApp. Someone from the LogicApp team mentioned this (Channel 9?, sorry don't recall) and don't expect it to change any time soon.
If either case might cause a runtime error, you'll need to do it in two steps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can one get the type that a specific attribute is decorating
Say I have a situation like so:
[MyAttribute]
public class MyClass
{
}
[AttributeUssage(AttributeTargets.Class)]
public class MyAttribute
{
public MyAttribute(String a_strName)
{
}
}
Is there anyway that within constructor of MyAttribute I can know that the attribute is attached to MyClass?
A:
No, I'm afraid not - attributes don't "know" what they're applied to.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Explicitly specify defaulted template parameter located after template parameter pack
Why can't I explicitly specify d in following case?
#include <iostream>
template< typename a, typename b = int, typename ...c, typename d = int >
int
f(a, b, c..., d)
{
return sizeof...(c);
}
int
main()
{
std::cout << f< int, int, int, int/*, char*/ >(1, 2, 3, 4, 'd') << std::endl;
return 0;
}
If I uncomment last template argument, then I expect output 2, but instead I get a hard error:
main.cpp:14:18: error: no matching function for call to 'f'
std::cout << f< int, int, int, int, char >(1, 2, 3, 4, 'd') << std::endl;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:6:1: note: candidate function not viable: requires 6 arguments, but 5 were provided
f(a, b, c..., d)
^
1 error generated.
What is the rule to deny it in this case?
A:
Because packs are greedy. So char is actually part of c and you're expected to supply the argument associated with d, which is of type int due to the default.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Converting Oracle's join syntax using the plus sign (+) to standard join syntax
I am trying to understand Oracle join syntax of using (+) to join two tables.
Could someon show me how would this query would look if it was converted to use the standard join syntax?
select p1.product_id, p1.product_name, p2.product_code, (decode(p3.product_type, null, 'N/A',p3.product_type) as product_type
from products p1, product_descriptions p2, product_descriptions p3
where p1.product_id=p2.product_id
and p2.product_age=p3.product_age(+)
and p2.product_type=p3.product_type(+)
and p3.status(+)='VALID'
A:
Something like this:
select p1.product_id, p1.product_name, p2.product_code,
(decode(p3.product_type, null, 'N/A', p3.product_type) as product_type
from products p1
join product_descriptions p2
on p1.product_id = p2.product_id
left join product_descriptions p3
on p3.product_age = p2.product_age
and p3.product_type = p2.product_type
and p3.status = 'VALID';
The where p1.product_id=p2.product_id is a normal inner join between p1 and p2. The others are outer joins; the way it's written looks like a mix of left and right outer joins, but since and p2.product_age=p3.product_age(+) is the same as and p3.product_age(+)=p2.product_age then it isn't really; it's a fairly straightforward left outer join between the product of the p1/p2 join and p3.
As an aside, I'm not a fan of aliases like p1, p2 and p3 as they are not descriptive, and it's easy to get lost when you do this in more complicated queries. I'm not alone.
I'm not sure you even need the outer join, but it rather depends on the data. If product_age and product_type is unique then you could case the p2.status; if it isn't then you're probably assuming that only one product_age/product_type row can be VALID, otherwise you'd get duplicates. Just musing about what you're trying to do...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to analyze preference / comparison on a likert scale
User participants experienced method A and then method B of a computer interface. Afterwards, we asked them to indicate which method they preferred regarding certain aspects. For example, for ease of use, which do you prefer, A or B, from 1 to 7 (Likert scale), where 1 = definitely method A, 4 = Neutral, and 7 = definitely method B.
Here are my questions:
Since we are directly asking them to compare methods on this Likert scale and thus receive only 1 response, does it make sense to do a statistical analysis? I guess we cannot compare the participants' answers based on different methods because there is only 1 response.
If the answer to #1 is no, then do we simply aggregate the data and see how many users prefer A vs. B?
If the answer to #1 is yes, then do we statistically analyze if the responses vary from some "neutral" distribution? What's the best method/way to analyze this?
A:
I believe this is an instance of having 0 independent variables and thus we should use the one-sample median test, a.k.a. the Wilcoxon signed rank test (see this table). This is what I ended up using.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How granular should a command be in a CQ[R]S model?
I'm considering a project to migrate part of our WCF-based SOA over to a service bus model (probably nServiceBus) and using some basic pub-sub to achieve Command-Query Separation.
I'm not new to SOA, or even to service bus models, but I confess that until recently my concept of "separation" was limited to run-of-the-mill database mirroring and replication. Still, I'm attracted to the idea because it seems to provide all the benefits of an eventually-consistent system while sidestepping many of the obvious drawbacks (most notably the lack of proper transactional support).
I've read a lot on the subject from Udi Dahan who is basically the guru on ESB architectures (at least in the Microsoft world), but one thing he says really puzzles me:
As we get larger entities with more fields on them, we also get more actors working with those same entities, and the higher the likelihood that something will touch some attribute of them at any given time, increasing the number of concurrency conflicts.
[...]
A core element of CQRS is rethinking the design of the user interface to enable us to capture our users’ intent such that making a customer preferred is a different unit of work for the user than indicating that the customer has moved or that they’ve gotten married. Using an Excel-like UI for data changes doesn’t capture intent, as we saw above.
-- Udi Dahan, Clarified CQRS
From the perspective described in the quotation, it's hard to argue with that logic. But it seems to go against the grain with respect to SOAs. An SOA (and really services in general) are supposed to deal with coarse-grained messages so as to minimize network chatter - among many other benefits.
I realize that network chatter is less of an issue when you've got highly-distributed systems with good message queuing and none of the baggage of RPC, but it doesn't seem wise to dismiss the issue entirely. Udi almost seems to be saying that every attribute change (i.e. field update) ought to be its own command, which is hard to imagine in the context of one user potentially updating hundreds or thousands of combined entities and attributes as it often is with a traditional web service.
One batch update in SQL Server may take a fraction of a second given a good highly-parameterized query, table-valued parameter or bulk insert to a staging table; processing all of these updates one at a time is slow, slow, slow, and OLTP database hardware is the most expensive of all to scale up/out.
Is there some way to reconcile these competing concerns? Am I thinking about it the wrong way? Does this problem have a well-known solution in the CQS/ESB world?
If not, then how does one decide what the "right level" of granularity in a Command should be? Is there some "standard" one can use as a starting point - sort of like 3NF in databases - and only deviate when careful profiling suggests a potentially significant performance benefit?
Or is this possibly one of those things that, despite several strong opinions being expressed by various experts, is really just a matter of opinion?
A:
On the topic of "every attribute change"
I think you missed the point. Mr. Udi Dahan is saying you should capture the user's intent as a command. An end-user is concerned with being able to indicate that a customer has moved. Depending on the context that command could contain a customer identification, the new address (split up into street, streetnumber, zipcode, ...), optionally a new phone number (not uncommon when you move - maybe less so with all these cellphones). That's hardly one attribute.
A better question is "how do I design commands?". You design them from a behavioral perspective. Each use-case, flow, task an end-user is trying to complete, will be captured in one or more commands. What data goes with those commands comes naturally, as you start reasoning about them in more detail. The thing to watch out for is data that gets interpreted as "logic flow control" on the server side. That might be an indication that you need to split up the command. I hope you never find that standard with regard to command granularity. Good question though!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Windows Licensing Question
This is slightly off topic of programming but still has to do with my programming project. I'm writing an app that uses a custom proxy server. I would like to write the server in C# since it would be easier to write and maintain, but I am concerned about the licensing cost of Windows Server + CALS vs a Linux server (obviously, no CALS). There could potentially be many client sites with their own server and 200-500 users at each site.
The proxy will work similar to a content filter. Take returning web pages, process based on the content, and either return the webpage, or redirect to a page on another webserver. There will not be any use of SQL server, user authentication, etc.
Will I need Cals for this? If so, about how much would it cost to setup a Windows Server with proper licensing (per server, in USA)?
A:
This really is an OT question. In any case, there is nothing easier than contacting your local MS distributor. As stackoverflow is by nature an international site, asking a question like that, where the answer is most likely to vary by location (MS license prices really are highly variable and country-specific) is in my opinion not likely to receive an useful answer.
A:
I realize this isn't exactly answering your question but if you want to use Linux, maybe you want to look into using Mono. .Net on Linux.
A:
If users will not be actually connecting to any MS server apps (such as Exchange, SQL Server, etc) and won't be using any OS features directly (i.e. connecting to UNC paths) then all that should be required is the server license for the machine to run the OS. You need Windows Server CALs when clients connect to shares, Exchange CALs for mail clients, and SQL Server CALs for apps that connect to your databases. If the clients of your server won't be connecting to anything but the ports offered by your service, you should be in the clear, and it shouldn't cost any more to build a server for 100 users than 10.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
XAML ImageBrush using a BitmapImage without a URI
I have the following XAML that displays a cover image for a book using a URI:
<Rectangle.Fill>
<ImageBrush ImageSource="{Binding CoverUrl}" />
</Rectangle.Fill>
However, the image I would like to use is not on disk anywhere or accessible via a URI; it comes from inside a binary file that I parse out into a BitmapImage object.
When I create a BitmapImage object via code, the resulting object's BaseUri and UriSource properties are null. How can I get the ImageBrush to use a BitmapImage that resides in memory instead of reading it in from a URI?
A:
The ImageSource property is of type ImageSource, not Uri or string... actually, a conversion happens when you assign a Uri to it. You can bind the ImageBrush directly to a property that returns an ImageSource
<Rectangle.Fill>
<ImageBrush ImageSource="{Binding Cover}" />
</Rectangle.Fill>
private ImageSource _cover;
public ImageSource Cover
{
get
{
if (_cover == null)
{
_cover = LoadImage();
}
return _cover;
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to convert DOM node text value to UTF-8 in JavaScript?
I need to send a text content of an HTML node over Ajax request, but first convert it to UTF-8. Is that possible?
Thanks!
A:
function encode_utf8( s )
{
return unescape( encodeURIComponent( s ) );
}
function decode_utf8( s )
{
return decodeURIComponent( escape( s ) );
}
from http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html
use it like this...
encode_utf8(document.getElementById(id).textContent);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
TensorFlow on Mobile Devices (Android, iOS, Windows Phone)
I am currently looking on different deep learning frameworks out there, specifically to train and deploy convolutional neural networks. The requirements are, that it can be trained on a normal PC with a GPU, but then the trained model has to be deployed on the three main mobile operating systems, namely Android, iOS, and Windows Phone.
TensorFlow caught my eye, because of its simplicity and great python interface. There is an example application for Android (https://jalammar.github.io/Supercharging-android-apps-using-tensorflow/), but I am not sure if it can be also deployed on iOS and Windows Phone? If not, can you recommend an alternative framework, which would meet these requirements? Ideally with a simple scripting interface for fast prototyping?
Thank you very much for your answers!
EDIT: Currently I'm testing Microsoft's CNTK. Building on Windows and Linux from source works perfectly, it can be extended in a "Lego blocks" fashion, and the proprietary NDL (Network Description Language) is really easy to read and learn, and provides enough freedom to build a lot of different Neural Network architectures. The execution engine is only a small part of the framework, and it can read in the NN model defined by the NDL, as well as the trained parameters. I will keep the post updated, on how the porting process to ARM processors goes.
A:
TensorFlow currently doesn't support iOS or Windows. Here are the open github issues tracking them :
iOS support
Windows support
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can legendary effects trigger on different classes?
Vigilance has a chance on being hit to cast Inner Sanctuary, which is a Monk skill. Could this effect trigger if I'm not playing a Monk? What about other legendary items with seemingly class-specific effects?
Some weapons with class skills:
Skywarden
Blade of Prophecy
Wizardspike
Odyn Son
A:
I can't find an authoritative source, but if it doesn't say "Monk Only" then it will work. It will cast a non-runed version of that spell.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How did Amix Group get this helicarrier?
In Deadpool,
A big fight scene takes place in a battered helicarrier at an Amix Group scrap yard.
What is the history of this particular helicarrier? And why in particular was it sent to the Amix Group scrap yard?
A:
It was decommissioned and sold for scrap, it's not a helicarrier, and it never belonged to S.H.I.E.L.D.
Quoting from ScreenRant's on set interviews with the Director and Writers:
It was decommissioned and sold for scrap
What happens is in Act 3, Ajax, our villain, is trying to soften Deadpool up for the kill, so to speak. So he lures Deadpool out to this scrapyard, essentially. And among the things in the scrapyard is an old kind of beat up, decommissioned helicarrier. So it’s sitting there and it becomes a big set piece, part of the fight, this massive fight between Colossus, and Angel Dust, and Negasonic, and Ajax, and Deadpool, and a ton of thugs. So it’s just a great playground.
But this is like the twisted dark side of the helicarrier we’re used to seeing. It’s not gleaming, and shiny, and cool, and flying through the air. It’s been sold for scrap, essentially.
(source - ScreenRant's on-set interview with the Writers)
It's not a helicarrier, and it never belonged to S.H.I.E.L.D.
It’s clearly not a helicarrier… [Laughs] … Because that would violate the Marvel S.H.I.E.L.D. universe sort of thing. [...] to be fair, there are Helicarrier-like vehicles in the X-Men universe. It’s not just S.H.I.E.L.D. that has them. So I think it’s fair game.
So I think the more we can bring that world into his world the better. But it has to be done in such a way that it feels Deadpool. So, what better way to do it than a decrepit carrier that’s being stripped for scrap? And it’s dirty, and grungy, and nasty. When you see the shots that are up on the flight deck of that ship, it’s obviously not up to S.H.I.E.L.D. spec in its design. It looks more like a World War 2 sort of technology with… some… turbo fans.
(source - ScreenRant's on-set interview with the Director)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Probability of unique winner in a coin flipping game (limit of a recursive sequence)
Suppose we have a coin flipping game involving $n$ players. In each round everyone still playing flips a fair coin, and the players whose coin comes up tails are eliminated. The game continues until at most one player is still alive, and they are declared the winner.
Now, it is possible that the game does not end with a winner (e.g. if $n=2$ and both players get tails on their first flip). Let $f(n)$ denote the probability that a game with $n$ players has a winner. We have $f(0)=0$ and $f(1)=1$. For $n>1$ it follows from considering the binomial distribution that
$$f(n) = \sum_{k=0}^{n}\frac{\binom{n}{k}}{2^{n}} f(k) $$
(Here $\binom{n}{k}/(2^n)$ represents the probability $k$ players survive the current round), which can be rearranged as
$$f(n) = \sum_{k=0}^{n-1} \frac{\binom{n}{k}}{2^n-1} f(k)$$
Using this formula we can compute $f(n)$ recursively.
$$\begin{array}{cc} n & f(n) \\ 0 & 0 \\ 1 & 1 \\ 2 & 2/3 \\ 3 & 5/7 \\ 4 & 76/105 \\ 5 & 157/217 \\
\vdots & \vdots \\
20 & 0.7213 \end{array}$$
The sequence of numerators doesn't seem to be in OEIS, nor does the sequence $a_n=f(n)(2^n-1)(2^{n-1}-1)\dots(3)(1)$ from clearing all the denominators in the recursion.
Is there a way of analytically determine the limit (if it exists) of $f(n)$ as $n$ goes to infinity? It seems from calculation to be about $0.7213$, though I'm not confident in digits beyond that due to error propagation as the recursion continues.
A:
The limit of $f(n)$ as $n$ goes to infinity does not exist.
Suppose that $n$ is large. Then we can choose an integer $k$ such that $n = 2^k x$ with $1 \leq x < 2$. What is the probability of winning starting at $n$?
Let us say that we win at step $k+m$ if at step $k+m$ there is only one player, but their next coin flip is tails. That is half the probability that at step $k+m$ there is only one player left. But if $k$ is large, the odds of there being one player left is approximated by the Poisson Distribution with $\lambda = 2^m x$. Therefore the probability of winning is approximately $\sum_{m = -\infty}^{\infty} 0.5 * (2^m x) * e^{- 2^m x}$.
It isn't too hard to see that this sum converges, and it is easy to calculate it with a short program. If we calculate this for $x = 1.0$ we get $0.721352103337$. For $x = 1.5$ we get $0.721346354574$. The difference is around $0.00000574876$ and is far larger than calculation error. And therefore the probability keeps bouncing around in a range that includes these values and so can't converge.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Вертикальное меню: проблема с кодом
А вопрос вот такой. Делаю меню вертикальное... задумка (при наведении на одну из этих ссылок(кнопок) рядом с ней должна плавно появляться стрелочка, но у меня они сразу все вылезают для всех ссылок (кнопок). Код ниже
<div class="navigation-text-menu_head">
<img style="position:absolute; margin-left:-2px;" src="images/block_menu.png">Меню</div>
<div id="navigation-text-menu">
<ul>
<style type="text/css">
#navigation-text-menu {
background: #2b2a2a;
border: 1px solid #ccc;
border-radius: 5px;
height: 230px;
margin-left: -3px;
margin-top: 9px;
width: 275px;
}
#navigation-text-menu ul {
list-style: none;
}
#navigation-text-menu li {
border-bottom: 1px solid #676665;
margin-left: -40px;
}
#navigation-text-menu li a {
background: #2b2a2a;
color: #fff;
display: block;
font-size: 13px;
padding: 9px 9px 10px 15px;
text-decoration: none;
}
#navigation-text-menu ul li img {
display: none;
padding-right: 10px;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$('#navigation-text-menu ul li a').hover(function () {
$(this).fadeIn('fast', function () {
$('#navigation-text-menu ul li img').fadeIn(10000);
}).animate({
backgroundColor: "#165b95",
paddingLeft: '50px'
}, 500);
}, function () {
$(this).animate({
backgroundColor: "#2b2a2a",
paddingLeft: 15
}, 500);
});
});
</script>
<li><a href="#"><img src="images/arrow-menu.png">Главная</a></li>
<li><a href="#"><img src="images/arrow-menu.png">Руководства</a></li>
<li><a href="#"><img src="images/arrow-menu.png">Файлы</a></li>
<li><a href="#"><img src="images/arrow-menu.png">Серверы</a></li>
<li><a href="#"><img src="images/arrow-menu.png">Форум</a></li>
<li><a href="#"><img src="images/arrow-menu.png">Турниры</a></li>
</ul>
</div>
A:
Попробуйте заменить
$('#navigation-text-menu ul li img').fadeIn(10000);
на
$('img',this).fadeIn(10000);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Event not getting called from submit button Javascript
I am new to javascript. I am trying to figure out why my javascript function is not being called. I am trying to add nameVlidation for name field and other validation for each text input. But my name validation itself is not working.
Javascript call (formValidation.js)
'use strict';
var nameValidation = formValidation().nameValidation();
document.getElementById('submit').addEventListener('click',nameValidation);
var formValidation = function () {
return {
nameValidation: function() {
this.name = document.forms["contact"]["name"].value;
if(this.name=="") {
alert("Enter name, required");
return false;
}else if(this.name==[0-9]) {
alert("Only alphabets");
}
return true;
},
addressValidation: function() {
}
}
};
Html
<form name="contact" action="#" method="post" enctype="text/plain">
<input type="text" name="name" placeholder="NAME"></br>
<input type="text" name="email" placeholder="EMAIL" required></br>
<input type="text" name="phoneNumber" placeholder="PHONE-NUMBER"></br>
<input type="text-box" name="message" placeholder="MESSAGE"></br>
<button id="submit" class="btn btn-primary" type="submit"><i class="fa fa-paper-plane">Submit</i></button></br>
</form>
<script src="js/formValidation/formValidation.js"></script>
I am not sure what is wrong with it.
A:
The problem you are facing is due to a concept in Javascript called, Hoisting
You need to declare formValidation at the top before calling it from anywhere else, as you are using the function expression form
'use strict';
var formValidation = function () {
return {
nameValidation: function() {
this.name = document.forms["contact"]["name"].value;
if(this.name=="") {
alert("Enter name, required");
return false;
}else if(this.name==[0-9]) {
alert("Only alphabets");
}
return true;
},
addressValidation: function() {
}
}
};
var nameValidation = formValidation().nameValidation();
document.getElementById('submit').addEventListener('click',nameValidation);
PS - JSBin Demo
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I find the downward sliding direction of a plane?
first time poster.
I'm curious as to how I can obtain a vector that defines the downward slope of a 3D plane. The goal is to apply this to a player as a force to achieve a sliding mechanic, like in Mario 64 (for steep floors and slide levels).
My attempts at this used variations of this equation, but it's not quite what I'm looking for.
b * ( -2*(V dot N)*N + V )
where
v is the vector that you want to reflect,
n is the normal of the plane,
b is the amount of momentum preserved (0.0 - 1.0).
this gives a reflected vector
I also have means to calculate the plane normal and get the intersection point of the player
Any other ideas to solve this are also appreciated
A:
Take a vector representing your global up direction, and cross it with your plane normal.
This gives you a horizontal vector pointing across your slope. By the properties of the cross product it has to be perpendicular to both the plane normal (putting it in the plane) and the up vector (putting it in the horizontal plane).
Vector3 acrossSlope = Vector3.Cross(globalUp, planeNormal);
Now we can cross this vector with your plane normal again to get a vector pointing down-slope:
Vector3 downSlope = Vector3.Cross(acrossSlope, planeNormal);
Again by construction, this has to be perpendicular to both the plane normal (putting it in the plane) and the "across" vector (meaning it points up/down the plane, depending on the order you put the two arguments.
You can normalize the result to get it back to unit length.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I extract an Action into a member function?
I have this code:
class SomeClass {
void someFunction()
{
Action<string> myAction = (what)=>
{
//whatever
}
new List<string>().ForEach(myAction);
}
}
I'd like to extract the code inside myAction into a separate member function.
How do I do that?
A:
class SomeClass
{
void someFunction()
{
Action<string> myAction = Whatever;
new List<string>().ForEach(myAction);
}
public void Whatever(string what)
{
// ... whenever
}
}
or directly, without defining a local Action<string> variable (that will probably be optimized away in Release mode anyway):
new List<string>().ForEach(Whatever);
A:
Are you looking for this?
class SomeClass {
void someFunction()
{
new List<string>().ForEach(SeparateMemberFunction);
}
void SeparateMemberFunction(string s)
{
//whatever
}
}
A:
This should be equivalent:
class SomeClass {
void myAction(string what)
{
// whatever
}
void someFunction()
{
new List<string>().ForEach(item => myAction(item));
}
}
Since Action<string> means a method with a string parameter which does not return a value.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
storing negative number in decimal field of mysql table as of version 5.0.3
My table has few fields with an amount column of type decimal.
This column will have either a deposited amount (a positive value) or a withdraw amount (a negative value).
I store the positive value as just 120 and the negative value as -50.
I sum the column and got the result as expected.
Mysql version is: 5.1.33-community.
When i checked mysql documentation about decimal i confused with their description.
Before MySQL 5.0.3, if you inserted
+0003.1 into a DECIMAL(5,1) column, it was stored as +0003.1. As of MySQL
5.0.3, it is stored as 3.1. For negative numbers, a literal -
character is no longer stored.
Applications that rely on the older
behavior must be modified to account
for this change. http://dev.mysql.com/doc/refman/5.0/en/precision-math-decimal-changes.html
When i listed the rows in phpmyadmin i could see the negative sign and when i calculated the result was as expected. but the documentation said no sign will appear.
Is it good to store negative number in decimal(haven't i studied in school? confused)?... or do we have to use float.
I learn't that float would complicate calculations and was advised to stick with decimal for certain conditions.
I would like to have suggestions for this.
A:
From what I understand, the documentation is saying it won't store a literal "-" character, which means it's probably now doing what the other signed INTEGER fields have always done and it's storing a sign bit to denote negative numbers instead.
You're still seeing a minus sign preceding the number because it's being generated by MySQL as a result of that sign bit.
If you don't understand the sign bit, you can consider how a signed byte can store numbers from -128 to 127, while an unsigned byte can store numbers from 0 to 255. That's because one of the 8 bits in a signed number is being used to store +/- (1 is negative, 0 is positive), while the remaining bits offer numbers up to 2^7 (-128 or 127).
So, for example, if the bits 1111 had a sign bit they would equal -7 (negative+4+2+1), but if they were unsigned they'd equal 15 (8+4+2+1). It's still the same amount of bits being stored.
You may wonder why the negative bound in a signed number can use the 8th bit, while the positive bound is limited to the sum of the 7 bits (1 less than the 8th bit). This is because 10000000 is considered to be both negative and the 8th bit simultaneously, because its representation of -0 otherwise is redundant with 00000000 which represents 0. There's no distinction between negative and positive zero, so a negative most significant bit is always the value of that bit itself (but negative).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Crossfilter producing negative values with positive dataset when sorting data
I am using crossfilter wrong but cannot spot where.
I have a dataset which I am filtering. When I supply a sorting function to sort the data by day of the week, the result displays negative values.
If I skip the sorting, everything works as it should.
The data looks something like this
dataEg=[{"attr1": "A", "date":" Thu Apr 12 2018 00:00:00 GMT+0100 (BST)", "attr2": "a", "attr3": 25.11, "dayOfWeek": "Thu"},
{"attr1": "B", "date":" Sun Apr 01 2018 00:00:00 GMT+0100 (BST)", "attr2": "b", "attr3": 6.67, "dayOfWeek": "Sun"}];
I use crossfilter to select by attribute
var crossFilter = (function () {
var filter = {};
filter.ndx = crossfilter(dataEg);
filter.attr2Dim = filter.ndx.dimension(function (d) { return d.attr2; });
filter.dayOfWeekDim = filter.ndx.dimension(function (d) { return d.dayOfWeek; });
filter.attr1Dim = filter.ndx.dimension(function (d) { return d.attr1; });
filter.costPerDayOfWeek = filter.dayOfWeekDim.group().reduceSum(function (d) { return d.attr3; });
filter.costPerattr2 = filter.attr2Dim.group().reduceSum(function (d) { return d.attr3 });
filter.costPerattr1 = filter.attr1Dim.group().reduceSum(function (d) { return d.attr3 });
return filter;
})();
When filtering for some atteribute
crossFilter.attr1Dim.filter(function (d) {
return d === "B";
});
everything works unless I sort the date by day first using this filter
function DaySorter (keyLocator) {
if (keyLocator === undefined) {
keyLocator = function (item) {
return item;
};
}
return function (a, b) {
var order = {
"Mon": 0, "Tue": 1, "Wed": 2, "Thu": 3, "Fri": 4, "Sat": 5, "Sun": 6
};
var aVal = order[keyLocator(a)];
var bVal = order[keyLocator(b)];
var comp = 0;
if (aVal > bVal) {
comp = 1;
}
else if (aVal < bVal) {
comp = -1;
}
return comp;
};
}
However, I do not see where I am making a mistake. The filter seems to work correctly and follows the documentation.
A minimal JSFiddle can be found here.
A:
Finally found the problem.
I was sorting the data in the chart so that it is displayed in the order of the Day of Week. However, this somehow interfered with the interals of CrossFilter.
Doing a deep copy of the data before sorting it in the chart solved the problem (here using JQuery).
data =[];
$.extend(true, data, dataOrg);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Having trouble setting up Synergy (via Quicksynergy)
Synergy is an app that allows two or more computers to share a keyboard and mouse. I have both Synergy and QuickSynergy (the GUI for synergy) installed from the repositories on two computers. One, my "main" box, is running Ubuntu 11.10. Sitting above it on a shelf is an older laptop running Lubuntu 11.10. I have watched a couple of youtube videos which attept to walk one through the setup process but so far I have not found one that can help me. I have the required applications installed on both machines and they are connected via my wireless router. I need to know exactly what to input (and where) on each machine in order to sync my mouse, keyboard, and clipboard between the two.
A:
Here's a Synergy user guide and a sample configuration file. If you prefer to configure it with a GUI rather than a config file, try the 1.4.5 beta at Synergy's download page.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How does rrdtool RRDB associate/bind an RRA to a DS?
How does rrdtool RRDB associate/bind an RRA to a DS? An XML dump does not seem to reveal where this binding info is kept. Neither does rrdinfo. But this info must be in there, because multiple RRAs can be associated with a single DS. Perhaps Am I missing something?
A:
Every DS is in every RRA. You do not need to bind a specific DS to specific RRAs as the vector created from the set of DS is common to all.
The difference between RRAs is not that they have a different DS vector, but that they have different lengths and granularities, and different roll-up functions. This enables the RRA to pre-calculate summary data at storage time, so that at graph time, most of the work is already done, speeding up the process.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I generate a Visual Studio 2012 project targeting Windows XP with CMake?
With Visual Studio 2012 Update 1 released, I am hoping to build a C++ project to support Windows XP. Is there a way to use CMake to generate a project that targets Windows XP? Basically CMake would need to generate a project file that uses Platform Toolset = Visual Studio 2012 - Windows XP (v110_xp).
A:
According to http://www.cmake.org/Bug/view.php?id=10722 the answer is now (soon) yes.
Fixed in Version CMake 2.8.11
A new "generator toolset" feature has been added here:
http://cmake.org/gitweb?p=cmake.git;a=commitdiff;h=7dab9977 [^]
One may now run CMake from the command line with
-G "Visual Studio 10" -T "v90"
in order to build with a specific toolset. We've not yet added a
first-class interface to cmake-gui for this, but one may add the cache
entry "CMAKE_GENERATOR_TOOLSET" to contain the "-T" value before
configuring.
A:
According to http://www.cmake.org/Bug/view.php?id=10722 the answer is no yes.
Update: The bug mentioned above has been resolved with the following comment:
Fixed in Version CMake 2.8.11
A new "generator toolset" feature has been added here:
http://cmake.org/gitweb?p=cmake.git;a=commitdiff;h=7dab9977 [^]
One may now run CMake from the command line with
-G "Visual Studio 10" -T "v90"
in order to build with a specific toolset. We've not yet added a
first-class interface to cmake-gui for this, but one may add the cache
entry "CMAKE_GENERATOR_TOOLSET" to contain the "-T" value before
configuring.
You might also look at the comments made to the other answers.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Django on a Mac: Apache with mod_wsgi configuration problems
I'm trying to run a local Django server on Apache with mod_wsgi. I am running the out-of-the-box Apache on Mac.
hobbes3@hobbes3:~/Sites/mysite$ apachectl -v
Server version: Apache/2.2.21 (Unix)
Server built: Nov 15 2011 15:12:57
Apache properly loads mod_wsgi.
hobbes3@hobbes3:~/Sites/mysite$ apachectl -t -D DUMP_MODULES | grep wsgi
Syntax OK
wsgi_module (shared)
In my httpd.conf file I load apache_django_wsgi.conf which is
WSGIDaemonProcess django
WSGIProcessGroup django
Alias /mysite/ "/Users/hobbes3/Sites/mysite/"
<Directory "/Users/hobbes3/Sites/mysite">
Order allow,deny
Options Indexes
Allow from all
IndexOptions FancyIndexing
</Directory>
WSGIScriptAlias /mysite "/Users/hobbes3/Sites/mysite/apache/django.wsgi"
<Directory "/Users/hobbes3/Sites/mysite/apache">
Allow from all
</Directory>
My django.wsgi file is
import os
import sys
paths = [ '/Users/hobbes3/Sites/mysite',
'/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages',
]
for path in paths:
if path not in sys.path:
sys.path.append(path)
sys.executable = '/usr/local/bin/python'
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
I can also restart Apache without any error. But when I try to visit http://localhost/mysite, my browser says I have a 500 Internal Server Error.
My Apache error log says (I truncated the dates and times):
mod_wsgi (pid=73970): Exception occurred processing WSGI script '/Users/hobbes3/Sites/mysite/apache/django.wsgi'.
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 250, in __call__
self.load_middleware()
File "/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/django/core/handlers/base.py", line 39, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/django/utils/functional.py", line 276, in __getattr__
self._setup()
File "/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/django/conf/__init__.py", line 42, in _setup
self._wrapped = Settings(settings_module)
File "/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/django/conf/__init__.py", line 89, in __init__
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'mysite.settings' (Is it on sys.path?): No module named mysite.settings
I don't know why it can't import mysite.settings, didn't I include that in the sys.path?
The full path to settings.py is /Users/hobbes3/Sites/mysite/.
A:
You've included mysite in the path, but you've referenced mysite.settings. So Python is looking for a mysite module within the directories it finds on the path. Use just settings instead.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I know which products have seen other customers when they took a look at the product that I am currently looking?
I am developing a website with the Drupal Commerce module, and my customer wants me to implement a functionality to allow the purchaser to know which products have seen other purchasers/customers when they saw the same product he is currently watching.
Do you know if any specific module for Drupal Commerce is available, or can I use a combination of modules that have nothing to do with the Drupal Commerce module?
A:
Yes the feature you are asking after is this module.
Commerce Recommender
:: Updated, Here is a tutorial on how you can achieve what you are looking for
Drupal Commerce recommender tutorial
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Day Late on Delivery of Bill to Verizon
I'm pretty new to the adult world, I just paid my 7th Verizon bill, but I submitted the payment online. The bill asked for payment due by a Monday, and the earliest the bank can deliver the check is on the day after, the Tuesday.
Is this going to be a problem at all?
A:
Probably not. Generally its not a good idea to wait for the last moment, because there's always something unexpected that can happen.
You can also use "direct pay" (or whatever they call it on Verizon) to pay instead of the banks' bill-pay feature, so that the payment is originated by Verizon (or whatever else service provider), and not the bank. This way it will be posted earlier.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the length in bytes of a NSString?
How do I get the bytes length of NSString? if myString contains "hallo", myString.length will return 5, but how many actual bytes are taken?
A:
NSString *test=@"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSUInteger bytes = [test lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%i bytes", bytes);
A:
To get the bytes use
NSData *bytes = [string dataUsingEncoding:NSUTF8StringEncoding];
Then you can check bytes.length
Number of bytes depend on the string encoding
A:
Well:
NSString* string= @"myString";
NSData* data=[string dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger myLength = data.length;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Creating Jobs for Multijob Plugin in Jenkins
I had a requirement for executing jobs in parallel and came across this plugin called MultiJob plugin for Jenkins.
After going through documentation, i created phases and gave job names. But where do i create job basically.I mean the script ,build step and post build step for job "TaskToExecute1" and "TasktoExecute2".
Thanks,
VVP
A:
You need to create the jobs that are referenced from the "Job Name".
So in your example, create a separate job/project (e.g. "New Item" -> "Freestyle Project") and call it TaskToExecute1. Then you can add a build step to that new TaskToExecute job/project.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
proof convergence of $(\sqrt[n]{25})_{n\in\mathbb N}$ and $(\frac{2^n}{n!})_{n\in\mathbb N}$
I want to show that $(\sqrt[n]{25})_{n\in\mathbb N}$ and $(\frac{2^n}{n!})_{n\in\mathbb N}$ are convergent.
So for the first one I did the following:\begin{align} 25&=(1+\delta_n)^n \\
\Rightarrow25&\geq1+n\delta_n\\
\Rightarrow \frac{24}{n}&\geq\delta_n\geq0\end{align}
And so $\delta_n\rightarrow0$ and so $\sqrt[n]{25}\rightarrow 1$
But I don't get the second sequence. Are there any tricks? (We've just had the definition of convergence of a sequence and some properties e.g. unique limit) Besides are there any easier steps for the first sequence?
A:
Another answer to the first question: note that $\log\sqrt[n]{25} = \frac1n\log25$ certainly tends to $0$. Since the function $e^x$ is continuous at $x=0$, you can conclude that
$$
\lim_{n\to\infty} \sqrt[n]{25} = \lim_{n\to\infty} e^{\log\sqrt[n]{25}} = e^{\lim_{n\to\infty} (\log\sqrt[n]{25})} = e^0 = 1.
$$
Another answer to the second question: note that
\begin{align*}
0 \le \frac{2^n}{n!} &= \frac{2\cdot2\cdot2\cdots2\cdot2}{1\cdot2\cdot3\cdots(n-1)\cdot n} \\
&= \frac21 \frac22 \frac23 \cdots \frac2{n-1} \frac2n \\
&\le 2\cdot1\cdot1\cdots1\cdot\frac2n = \frac4n.
\end{align*}
Now you can use the squeeze theorem to show that $\frac{2^n}{n!}$ tends to $0$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C# reference to loop variable
Is it possible in C# to something like the following
foreach (ref string var in arr) {
var = "new value";
}
so that var variable was treated as reference and assigning to var would change an array element?
A:
There is no such construct for updating a loop; an iterator is read-only. For example, the following provides a perfectly valid iterator:
public IEnumerable<int> Get1Thru5() {
yield return 1; yield return 2; yield return 3;
yield return 4; yield return 5;
}
How would it update? What would it update?
If the data is an array/list/etc, then something like:
for(int i = 0 ; i < arr.Length ; i++) {
arr[i] = "new value";
}
Or other options depending on the specific container.
Update; at a push, an extension method:
public static void UpdateAll<T>(this IList<T> list, Func<T, T> operation) {
for (int i = 0; i < list.Count; i++) {
list[i] = operation(list[i]);
}
}
static void Main() {
string[] arr = { "abc", "def", "ghi" };
arr.UpdateAll(s => "new value");
foreach (string s in arr) Console.WriteLine(s);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Join rows Google BigQuery
I have a huge table (i.e. 3 million rows) in Google BigQuery. The structure is something like this:
name1 attribute1
name2 attribute2
name1 attribute2
I'd now like to get a list per name of the attributes that they have. So for the example above, I would want something like this:
name1 attribute1, attribute2
name2 attribute2
Is this possible with BigQuery (so without having to write any code, just purely as an SQL query)?
A:
I suggest that you use the GROUP_CONCAT function:
SELECT name, GROUP_CONCAT(columnNameContainingTheAttribute)
FROM yourTable
GROUP BY name
You can learn more about the GROUP_CONCAT function here:
https://developers.google.com/bigquery/query-reference?hl=FR#aggfunctions
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Как составить алгоритм для поиска комбинаций в массивах?
Здравствуйте, помогите пожалуйста придумать алгоритм для поиска всех возможных групп из комбинаций.
Исходные данные:
Массив комбинаций
$combinations => [
a => [11, 38],
b => [38, 64, 71],
c => [11, 24, 38, 65]
d => [128, 38, 57, 40]
...
]
каждая комбинация в этом массиве может состоять из 2, 3 или 4 чисел
Нужно найти все возможные группы из 4х чисел, в которых будут участвовать от 2-х до 4-х комбинаций из массива комбинаций и определить сколько комбинаций входит в группу и каких. В группе должно быть 4 числа, ни больше, ни меньше. Например можно составить группу в которой будут участвовать 2 комбинации (a и b):
$group => [11, 38, 64, 71]
В эту группу входит первая и вторая комбинация.
Третья комбинация (с) уже содержит в себе первую комбинацию (a), т.е. она тоже состоит из двух комбинаций.
Как найти группы, в которых будет от 2х до 4х комбинаций?
Я нагородил много вложенных циклов и то, работает криво и ищет только среди комбинаций которые состоят из 2х чисел. Код получился огромный и страшный, что даже боюсь показывать его кому-то. А страшный он из-за того, что не могу придумать оптимальный алгоритм поиска групп.
A:
Код:
# Входящий массив:
$ar = array(
'a' => '11, 38',
'b' => '38, 64, 71',
'c' => '11, 24, 38, 65',
'd' => '128, 38, 57, 40'
);
# Искомые числа:
$in = array('11', '38', '64', '71');
$result = array();
foreach($ar as $key => $value){
$line = explode(',',$value);
foreach($in as $inn){
if(in_array($inn,$line)){
$result[$key]['count']++;
$result[$key][] = $inn;
}
}
}
print_r($result);
Результат работы кода:
Array
(
[a] => Array
(
[count] => 2
[0] => 11
[1] => 38
)
[b] => Array
(
[count] => 3
[0] => 38
[1] => 64
[2] => 71
)
[c] => Array
(
[count] => 2
[0] => 11
[1] => 38
)
[d] => Array
(
[count] => 1
[0] => 38
)
)
Надеюсь, что помог.
UPD:
$ar = array(
'a' => '11,38',
'b' => '38,64,71',
'c' => '11,24,38,65',
'd' => '128,38,57,40',
'e' => '38,115,64',
'f' => '64,11,57,38'
);
$line = array();
foreach($ar as $key => $value){
$line[$key] = explode(',',$value);
}
$r = 1;
foreach($line as $keyRes => $res){
$c = 1;
foreach($line as $keyRes2 => $res2){
if($c > $r){
$arMerge[$keyRes][$keyRes2] = array_merge($res,$res2);
};
$c++;
}
$r++;
}
foreach($arMerge as $intKey1 => $intVal1){
foreach($intVal1 as $intKey2 => $intVal2){
foreach($intVal2 as $intVal){
$resAr[$intKey1][$intKey2][] = (int)$intVal;
}
}
}
foreach($resAr as $uniqKey1 => $uniqVal1){
foreach($uniqVal1 as $uniqKey2 => $uniqVal2){
if(count(array_unique($uniqVal2)) == 4){
$result[] = $uniqKey1.'-'.$uniqKey2;
}
}
}
print_r($result);
Результат выполнения:
Array
(
[0] => a-b
[1] => a-c
[2] => a-e
[3] => a-f
[4] => b-e
)
Теперь вроде правильно.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Alternatives to "then", "next" (at the beginning of the phrase) in formal text (for Academic papers)
I am writing an academic paper and, at a certain point, I want to write: "Firstly,... Then, ... Next, ... Lastly...."
However, "Then" and "Next" at the beginning of phrases sound like very INFORMAL English. I need FORMAL alternatives. What do you suggest/use?
I know this article suggesting "First... Second... Third... Lastly...":
First, Second, Third, and Finally
But I already used this structure somewhere else in the text, so I want to avoid repetition.
Thank you.
A:
Then: subsequently, in addition
Next: consequently
Finally: to conclude, to summarize
If your sentences and paragraphs are written in active voice, and they are tightly constructed, your reader will follow your sequence easily, without need for the linking words you asked about.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In Luke 5:33-35 does Jesus imply that the Twelve are not part of the bride of the Lamb?
Update
I have been researching this and it appears that the whole matter hangs on the definition of "the sons of the bridechamber" which is not obvious to me:
KJV Luke 5:34 And he said unto them, Can ye make the children of the bridechamber fast, while the bridegroom is with them?
mGNT Luke 5:34 ὁ δὲ Ἰησοῦς εἶπεν πρὸς αὐτούς μὴ δύνασθε τοὺς υἱοὺς τοῦ νυμφῶνος ἐν ᾧ ὁ νυμφίος μετ’ αὐτῶν ἐστιν ποιῆσαι νηστεῦσαι
It appears that "bridalchamber" is only from Tobit:
νυμφών
nymphōn, n.c., bride’s chamber. 4× +NT +AF
English Gloss
bridal chamber (3): Tob 6:14; Tob 6:14 (var.), 17 (var.)
brides chamber (1): Tob 6:17
(2012). The Lexham Analytical Lexicon of the Septuagint. Bellingham, WA: Lexham Press.
I found nothing in the Jewish Encyclopedia to suggest that "sons of the bridal chamber" is a thing.
"Sons of the bridechamber" seems to be unique to the gospels. So what does it actually mean?
So before answering the original question, one would have to establish what a "son of the bridechamber" actually is!
Original question
Jesus refers to the Twelve as "the children of the bridechamber":
[Luke 5:33-35 KJV] 33 And they said unto him, Why do the disciples of John fast often, and make prayers, and likewise [the disciples] of the Pharisees; but thine eat and drink? 34 And he said unto them, Can ye make the children of the bridechamber fast, while the bridegroom is with them? 35 But the days will come, when the bridegroom shall be taken away from them, and then shall they fast in those days.
Thayers has this:
...οἱ υἱοί τοῦ νυμφῶνος (see υἱός, 2), of the friends of the bridegroom whose duty it was to provide and care for whatever pertained to the bridal chamber, i. e. whatever was needed for the due celebration of the nuptials: Matthew 9:15; Mark 2:19; Luke 5:34 ((Winer's Grammar, 33 (32)); Tobit 6:13 (14), 16 (17); ecclesiastical writings; Heliodorus 7, 8);
Am I correct that such a designation precludes the designees from being the bride herself?
Possibly related:
CSB 2 Corinthians 11:29 For I am jealous for you with a godly jealousy, because I have promised you in marriage to one husband — to present a pure virgin to Christ.
A:
John the Baptizer identified himself as "the friend of the bridegroom" but to my mind, we might have called him the "best man":
[John 3:29 KJV] 29 He that hath the bride is the bridegroom: but the friend of the bridegroom, which standeth and heareth him, rejoiceth greatly because of the bridegroom's voice: this my joy therefore is fulfilled.
He, like the "sons of the bridechamber" is not one of the people being married but is instead the trusted friend of the groom who rejoices in his friend's marriage and would grieve in his being "taken away" (though in fact John was murdered first).
According to this article from the Jewish Encyclopedia the wedding party was called "the sons of the canopy" - and included the groomsmen and the fathers of both the bride and groom:
...The wedding party was called "bene ḥuppah," and could dispense with the performance of other religious obligations, such as sitting in the sukkah (Yer. Suk. ii. 53a). To it belonged, besides the groomsmen ("sushbinim"), the respective fathers of the bride and bridegroom...
One of the duties that fell to the groomsmen was that of bearing witness that the bride had not been with any other than the groom for seven days and that the blood on the tokens of her virginity were fresh blood from her hymen:
...Outside the ḥuppah (in former times inside) the groomsmen and bridesmaids stood as guards awaiting the good tidings that the union had been happily consummated with reference to Deut. xxii. 17 (see Yer. Ket. i. 25a; Tan., Ḳoraḥ, ed. Buber, p. 96; Pirḳe R. El. xii.), while the people indulged in dancing, singing, and especially in praises of the bride (comp. John iii. 29; Matt. xxv. 1-13). The bride had to remain in the ḥuppah for seven days, as long as the wedding festivities lasted (Judges xiv. 15); hence the name of these festivities, "the seven days of her" or "of the ḥuppah" (Pesiḳ. 149b)...
[Deu 22:17 KJV] 17 And, lo, he hath given occasions of speech [against her], saying, I found not thy daughter a maid; and yet these [are the tokens of] my daughter's virginity. And they shall spread the cloth before the elders of the city.
This appears to be behind Paul's comment:
[2Co 11:2 KJV] 2 For I am jealous over you with godly jealousy: for I have espoused you to one husband, that I may present [you as] a chaste virgin to Christ.
If so then Paul is acting as a groomsman. Christ is the groom and the Corinthians are the bride.
So this suggests to me that Paul and the Twelve were, as in the parable of the Ten Virgins ancillary. The virgins in the parable are charged with bearing torches so the bride doesn't get attacked (human or animal), trip or get lost en route.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Kairosdb error metric[0](name=abcd).tag[xyz].value may not be empty
I am inserting data in kairosdb using the command: reference
bin/kairosdb.sh import -f export.txt
but in the kairosdb.log file I am getting following error:
08-10|13:54:33.443 [main] INFO [Main.java:267] - KairosDB service started
08-10|13:54:33.443 [main] INFO [Main.java:268] - ------------------------------------------
08-10|14:00:38.236 [main] INFO [TelnetServerModule.java:42] - Configuring module TelnetServerModule
08-10|14:00:39.259 [main] INFO [CassandraHostRetryService.java:48] - Downed Host Retry service started with queue size -1 and retry delay 10s
08-10|14:00:39.357 [main] INFO [JmxMonitor.java:52] - Registering JMX me.prettyprint.cassandra.service_kairosdb-cluster:ServiceType=hector,MonitorType=hector
08-10|14:00:39.734 [main] ERROR [Main.java:345] - metric[0](name=meterreadings).tag[building_type].value may not be empty.
08-10|14:00:40.023 [main] ERROR [Main.java:345] - metric[0](name=meterreadings).tag[building_type].value may not be empty.
08-10|14:00:40.216 [main] ERROR [Main.java:345] - metric[0](name=meterreadings).tag[building_type].value may not be empty.
08-10|14:00:40.295 [main] ERROR [Main.java:345] - metric[0](name=meterreadings).tag[building_type].value may not be empty.
08-10|14:00:40.391 [main] ERROR [Main.java:345] - metric[0](name=meterreadings).tag[building_type].value may not be empty.
08-10|14:00:40.439 [main] ERROR [Main.java:345] - metric[0](name=meterreadings).tag[building_type].value may not be empty.
My export.txt file is:
administrator@administrator-IdeaCentre-Q190:~/Abharthan/kairosdb$ head -10 export.txt
{"name": "meterreadings", "timestamp":"1359695700","tags": {"Building_id":"1","building_type":"ElementarySchool","meter_type":"temperature","unit":"F"},"value":"34.85"}
{"name": "meterreadings", "timestamp":"1359695700","tags": {"Building_id":"2","building_type":"Park","meter_type":"temperature","unit":"F"},"value":"0"}
{"name": "meterreadings", "timestamp":"1359695700","tags": {"Building_id":"3","building_type":"Industrial","meter_type":"temperature","unit":"F"},"value":"0.07"}
{"name": "meterreadings", "timestamp":"1359695700","tags": {"Building_id":"4","building_type":"RecreationCenter","meter_type":"temperature","unit":"F"},"value":"0"}
{"name": "meterreadings", "timestamp":"1359695700","tags": {"Building_id":"5","building_type":"Park","meter_type":"temperature","unit":"F"},"value":"2.2"}
{"name": "meterreadings", "timestamp":"1359695700","tags": {"Building_id":"6","building_type":"CommunityCenter","meter_type":"temperature","unit":"F"},"value":"31.41"}
{"name": "meterreadings", "timestamp":"1359695700","tags": {"Building_id":"7","building_type":"Office","meter_type":"temperature","unit":"F"},"value":"0"}
{"name": "meterreadings", "timestamp":"1359695700","tags": {"Building_id":"8","building_type":"ElementarySchool","meter_type":"temperature","unit":"F"},"value":"10.88"}
{"name": "meterreadings", "timestamp":"1359695700","tags": {"Building_id":"9","building_type":"ElementarySchool","meter_type":"temperature","unit":"F"},"value":"42.27"}
{"name": "meterreadings", "timestamp":"1359695700","tags": {"Building_id":"10","building_type":"ElementarySchool","meter_type":"temperature","unit":"F"},"value":"10.14"}
Please suggest how to fix this error.
A:
usually the problem you describe comes from tags being provided with no associated value. TIt looks like you have values after the 10 first lines with empty value for building_type (look for "building_type":"" or similar).
By looking at your JSON I see several unrelated possible problems :
Your timestamp seems to be in Unix seconds - it should be in milliseconds (that could work with Telnet API because of OpenTSDB compatibility, but KairosDB expects milliseconds)
Your timestamp is always the same (thus you updating the same sample and again)
Your value is a String (while you'd probably like to use a long or a float), it may work but I don't recommend proceeding this way
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Dragon Age Inquisition, how to start crafting?
Dragon Age Inquisition is the first title I play from the Dragon Age franchise, and since in the game I've gathered lots of materials I'd like to start crafting something but I cannot find how.
Have I to go back to the war table?
My character is at level 7, should that matter.
A:
In Haven, the crafting stations are in the smithy, which you reach by turning left just after going through the main gate of the settlement (or just before? Not sure...). It's where Blackwall is found if you have recruited him.
In Skyhold, the crafting stations are in the Undercroft, which you reach via the door next to the throne. There's also crafting stations in some of the fortresses that you turn into camps in the other areas.
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.