INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How do I prevent my laptop from shutting down when undocking?
The Laptop is an HP EliteBook 8540p running Windows 7 Professional. OS updates are applied regularly via Windows Update and the machine is currently fully up to date.
Recently, when undocking the laptop it has started initiating the shutdown sequence. The "waiting on applications to close" box pops up so it can be aborted if caught quickly enough.
I can't find anything in the power configuration related to docking/undocking and google hasn't proven very useful either. Has anyone ran into this problem and figured out how to resolve it? | I finally stumbled across something that seemed to work, though it was for a newer model HP elitebook running Win 7 Pro 64-bit.
In this case, the 'Power Options' settings options seemed to trigger the 'when I close the lid' action upon being undocked. I changed it Sleep, saved changes, then back to Do Nothing and saved the changes. At this point the laptop behaved as expected during the undock.
I tried this because I noticed that the lid close event seemed to be firing, despite being set to Do Nothing. It looks as though the value it reads to display the setting may not be the same value that is looked at to determine the action, and that they somehow got out of sync. | stackexchange-superuser | {
"answer_score": 3,
"question_score": 8,
"tags": "laptop, docking station, hp elitebook"
} |
<ContentControl>Content</ContentControl> vs. <ContentControl Content="Content"/>
Given the following two options:
<ContentControl>Content</ContentControl>
vs.
<ContentControl Content="Content"/>
1. Any performance differences?
2. What would you say is more readable?
3. Conclusion?
I'm affraid this question might sound somehow babyish, but how will I know if I won't ask, so I decided to shoot it.
Comment me if I chose the wrong decision ;) | Just as a personal preference, I vote for
<ContentControl Content="Content"/>
but only because I find it more readable. AFAIK there is no performance impact by choosing one or the other, but I haven't done any testing to substantiate that... | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "wpf, performance, xaml, contentcontrol"
} |
How to understand the quote:
> There are two kinds of artists left: those who endorse Pepsi and those who simply won't.
(Annie Lennox)
Specifically, what does "who simply won't" mean?
What's the humor of this quote?
can it be a play on words: "who simply won't" => "who simply wont"? | This is an ellipsis), which would expand to:
> There are two kinds of artists left: those who endorse Pepsi and those who simply won't _endorse Pepsi_. | stackexchange-ell | {
"answer_score": 1,
"question_score": 1,
"tags": "quotations"
} |
What's Taylor expansion of: $f(x)=\frac 1x\ln{(1+2x^2)}$?
What's Taylor development on the next function: $f(x)=\frac 1x\ln{(1+2x^2)}$?
Actually this one is the first question I've seen with $ln$, My instincts tell me to try and do derivative in order to get a series i can deal with.
But i got to: $-\frac 1{x^2}\ln{(1+2x^2)}+\frac {4}{1+2x^2}$
I know how to deal with: $\frac {4}{1+2x^2}$
But it seems that keep doing derivatives on: $-\frac 1{x^2}\ln{(1+2x^2)}$ won't help that much, How can i develop this function properly? | **Hint:** find the Taylor expansion for $\ln(1+z)$, if you don't have it in a table. From there, substitute $z=2x^2$, and divide (term-by-term) by $x$.
I find this is much easier than directly trying to calculate successive derivatives of $f(x)$.
* * *
How to deal with the $\frac1x$:
As an example, suppose we were finding the taylor series for $f(x) = \frac1x \sin x$. We know that $$\sin x =\sum_{k=0}^{\infty} \frac{x^{2k+1}}{(2k+1)!}$$ It follows that $$ \begin{align} \frac1x \sin{x}&=\frac1x \sum_{k=0}^{\infty} \frac{x^{2k+1}}{(2k+1)!}\\\ &=\sum_{k=0}^{\infty} \frac1x \frac{x^{2k+1}}{(2k+1)!}\\\ &=\sum_{k=0}^{\infty} \frac{x^{2k+1-1}}{(2k+1)!}\\\ &=\sum_{k=0}^{\infty} \frac{x^{2k}}{(2k+1)!} \end{align} $$ | stackexchange-math | {
"answer_score": 5,
"question_score": 0,
"tags": "calculus, power series, taylor expansion"
} |
How to handle Android FCM Messages when application is in Background with data payload?
Android push notification using FCM is unable to handle when application in background. Default message is displayed in notification tray.
Can Anyone help me how to handle the messages when application in background.
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
}
This method is not called when application is in background. Any help will be great help for me. | The onMessageReceived() will be always called if you receive the payload as "data" always from server.
**Example :** Payload from server should be like following :
{
"data":{
"id": 1,
"missedRequests": 5
"addAnyDataHere": 123
},
"to":"fhiT7evmZk8:APA91bFJq7Tkly4BtLRXdYvqHno2vHCRkzpJT8QZy0TlIGs......"
}
for more about this issue. Please refer following URL : Firebase onMessageReceived not called when app in background | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 5,
"tags": "android, push notification, firebase cloud messaging"
} |
Can a service get a reference to the activity during onBind?
I have a service that basically manages a **MediaPlayer** instance for playing **podcasts**. Once an activity binds to the service it can do things like play, pause, stop, etc. I used a service because I want the podcast to continue playing even after the activity is destroyed.
I'd like the service to be able to **send messages back to the activity in case of an error or for normal status updates**. Is it possible for the service to get a reference to the activity that's trying to bind to it? Doesn't look like the intent makes this available. | The SDK samples API Demos app has an example of a service that messages back to an activity | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "android, android mediaplayer"
} |
Force current state of Git branch on another branch
Let's say I have a Git repo with two branches: #branch1 and #branch2.
They both have had commits since they branched out from the same source.
It turned out that changes in #branch1 are not needed. I want to force current state of #branch2 1:1 onto #branch1.
I don't want to do regular branch merge, because I know that no changes made onto #branch1 are needed and I don't want to deal with conflicts and allow any chance that some of those changes are carried over.
What's the best git operation would be in this case?
P.S. I'm using GitExtensions, but could go with command-line git as well if necessary. The repo is also hosted on BeanStalk.
Thanks. | Check out branch 1 and then do `git reset --hard commitOfBranch2` where `commitOfBranch2` is the commit that branch 2 is pointing to.
You can do this with GitExtensions too. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "git"
} |
Azure DevOps Boards with on-premises Git
I have wired up CI/CD of my on-premises Git server with Azure DevOps Pipelines using self-hosted agent.
Can I utilize Azure DevOps - Boards for end to end to WorkItem tracking or is it not possible when using on-premises Git? | Is not possible. Azure DevOps can link to work items only commits from Azure Repos or from GitHub and not from an external on-premise Git server.
(to Jira have a tool that connect commtis from any git server, but I don't know about a tool for Azure DevOps). | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "git, azure, azure devops, continuous integration, azure boards"
} |
Delete entry without deleting related entries mysql innoDB
I have a database where the users have different projects. A user can have multiple projects but a project can have only one user.
I get a problem if i'm going to delete a user without deleting his projects. MySql won't let me delete the user unless i first delete the projects.
Is there a way i can delete the user and keep the projects? | You have set up your schema with foreign key constraints, so the project table rows insist on the presence of the owning user.
This kind of "deletion" ïs usually done by soft deletion: by adding an "inactive" column to your tables, and setting it to "Yes" or nonzero or something like that when you want to mark a particular row as deleted. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql, innodb, relation"
} |
SharePoint 2010 - Modified Calender View
I want to filter the Calender in my SharePoint 2010. All Items with a Enddate older than 7 days must be hidden. I found no way to modified the Calender View to filter the elements because the field "Enddate" is not in list. | If it's anything like 2007, you need to do some Tomfoolery to make it work.
Create a calculated column called EndDateFilter and make it simply =[End Date]. Then filter the calendar view by EndDateFilter is less than or equal to [Today]+7. | stackexchange-sharepoint | {
"answer_score": 3,
"question_score": 5,
"tags": "list, calendar, list view"
} |
PHP Syntax Error
I posted this question a little earlier but here is the full version. I keep getting a Syntax Error which is solved when I remove the following code. So there must be a problem here, I just can't see what it is.
The syntax error is: "The topic (none) was not found in any of the reference materials currently installed".
<?php
$ds = 'Pear';
$sd = 'Orange';
$dt = 'Banana';
$td = 'KiwiFruit';
$FoodArray=array();
echo "<p>";
foreach ($_POST ["Gender"] as $value) {
if ($value == Female) {
$FoodArray=array($ds, $sd, $dt, $td);
echo "<ul>";
foreach ($FoodArray as $key => $value)
{
echo "<li>" . $value . "</li>";
}
echo "</ul>";
}
?>
This is the only thing stopping me from finishing a project, so I would be grateful to anyone who can help. I will try to answer a few of your questions too. | The following code:
if($value == Female)
would produce a notice, not an error. However, I know from experience that someone inheriting code that relies on PHP bare strings being interpreted as strings will hate the person who wrote it for the rest of their life.
> PHP Notice: Use of undefined constant Female - assumed 'female' in file on line #
Your error is you're missing a curly brace at the end. Not sure if it's just the code you posted here or if that is indeed the format of your code, but using correct indentation practices will help you avoid these types of issues, as well as help others spot check your code for you. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, arrays, list, foreach, syntax error"
} |
What programming language is Zillow written in?
Looking to find out what is the main programming language that drives the Zillow web based application. Does anyone know the answer to this? | Their homepage sends the following http header:
X-Powered-By: Servlet 2.4; JBoss-4.0.3SP1 (build: CVSTag=JBoss_4_0_3_SP1 date=200510231054)/Tomcat-5.5
Which, indicates java. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "java, zillow"
} |
Most occured value in database
hello by writing like this
SELECT name, COUNT(name) AS value_occurrence
FROM table
GROUP BY name
ORDER BY value_occurrence DESC;
i get this table:
name occurrence
---- ---------
a 6
b 5
c 3
But i want the name of most occurred one a.what should i write for this purpose?(i used sql) | In Oracle, this will get you a name occurring as often as or more often than all other names:
SELECT name, value_occurrence
FROM (
SELECT name, COUNT(name) AS value_occurrence
FROM table
GROUP BY name
ORDER BY value_occurrence DESC )
WHERE rownum = 1;
In other words, if there are two names both having the highest number of occurrences, the above query will give you one of them (at random). If you don't like the random aspect, you could change the `ORDER BY value_occurrence DESC` to `ORDER BY value_occurrence DESC, name` if you like.
If, in the case of a tie, you want to see all the names that are tied for 1st, you can do this:
SELECT name, value_occurrence
FROM (
SELECT name, count(*), dense_rank() over ( partition by null order by COUNT(name) desc) AS value_occurrence_pos
FROM table
GROUP BY name
ORDER BY value_occurrence DESC )
WHERE value_occurence_pos = 1; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "sql, oracle"
} |
String.Format Doesn't Format a String
It seems as though String.Format won't format a string as an input. Am I doing something wrong, or is this just native behavior?
Input : 0.37
This doesn't work.
string x = String.Format("{0:P}", myString)
Output : 0.37
This does.
string x = String.Format("{0:P}", Convert.ToDecimal(myString))
Output : 37.00 % | I believe this is expected behavior for 'composite formatting'.
Your first example is attempting to apply numerical formatting rules to a string. Your second example is attempting to apply numerical formatting rules to a number that can have decimal positions.
See this article on MSDN.aspx) for more information. | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 6,
"tags": ".net, string.format"
} |
AWS dynamoDB limit or pagination, when fetching from unsorted table (ios)
I have an unsorted table (only hash key, without range key).
I must search and fetch limit rows from table. If I use the `limit` property of `AWSDynamoDBScanExpression`. But this limit property is not working: I get responses with less than `count` elements when using the `limit` property.
I read about pagination - `exclusiveStartKey` and `LastEvaluatedKey` properties, but it is good for sorted data. I have unsorted data. And my data must be unsorted and return random rows with limit in every query.
Roughly speaking, I need to start and limit analogs from SQL, but for dynamoDB. It is possible? I do not understand how to do this with a `scan` operation. Please help me set a limit of fetched rows. | The `exclusiveStartKey` is the equivalent of `offset`.
The DynamoDB API `limit` is **an API limit** \- not an application limit.
It doesn't make sure you get `<= limit` elements. It just forces a single request to return `<= limit` elements and set the next chunk via `LastEvaluatedKey`
To randomize the response, you will have to fetch more events than you might need and randomly select between them. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "ios, pagination, limit, amazon dynamodb"
} |
Using De Moivre's formula for finding $\sqrt{i}$
In class today, we learned about complex numbers, and the teacher described a simple procedure for finding the square root of $i$ in $z^2=i$. He explained to us to set $z=a+bi$ and square from there, which _did_ work, but it took some work to get through.
Afterwards, he said that there _was_ an easier way, and that was to use **De Moivre's formula** to find the square roots.
So...
> **Question:** How would you use **De Moivre's formula** to find the square root of any nonzero complex number?
* * *
I do understand that the formula goes something like this:$$(\cos x+i\sin x)^y=\cos(xy)+i\sin(xy)\tag{1}$$ But I'm not too sure how to apply that to$$z^2=i\tag2$$ for $z$ is another complex number. | Using the $n$-th roots formula (which is actually an equivalent version of De Moivre's formula ) $$ \sqrt{i}=i^{\frac{1}{2}}=(\cos\frac{\pi}{2}+i\sin\frac{\pi}{2})^{\frac{1}{2}} =\cos(\frac{\pi}{4}+\kappa\pi)+i\sin(\frac{\pi}{4}+\kappa\pi) $$ for any $\kappa\in\mathbb{Z}$. The above, for $\kappa$ even, gives $$ \frac{\sqrt{2}}{2}+i\frac{\sqrt{2}}{2} $$ while for $\kappa$ odd, it gives $$ -\frac{\sqrt{2}}{2}-i\frac{\sqrt{2}}{2} $$
For the general case, the formula for the $n$-th roots of the complex number $z=\rho (\cos \phi + i \sin \phi)$, is given by $$ [\rho (\cos \phi + i \sin \phi)]^{1/n} = \rho^{1/n}\left( \cos \frac{\phi + 2 \pi k}{n} + i \sin \frac{\phi + 2 \pi k}{n} \right), \quad k = 0, 1, \dots, $$ $\rho$ is the modulus. For the square roots, just set $n=2$. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "complex numbers"
} |
How to pass list of IDs from one Oracle schema to another?
I use the Oracle SQL developer to query the Oracle database
So, my simplified script is as follows:
alter session set current_schema=schema1;
select id from table1
alter session set current_schema=schema2;
select * from table2 where remote_id in (<the list from the 1st query in schema1>)
Currently I copy the list from one schema to another manually. How to automate passing the list? | Fully qualified database object references in Oracle are `SCHEMANAME.OBJECTNAME` so regardless of which schema is your current schema, you can reference objects in other schemas like so:
Select *
from schema2.table2
where remote_id in (select id from schema1.table1); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "sql, oracle"
} |
vectorized array creation from a list of start/end indices
I have a two-column matrix `M` that contains the start/end indices of a bunch of intervals:
startInd EndInd
1 3
6 10
12 12
15 16
How can I generate a vector of all the interval indices:
v = [1 2 3 6 7 8 9 10 12 15 16];
I'm doing the above using loops, but I'm wondering if there's a more elegant vectorized solution?
v = [];
for i=1:size(M,1)
v = [v M(i,1):M(i,2)];
end | Here's a vectorized solution I like to use for this particular problem, using the function `cumsum`:
v = zeros(1, max(endInd)+1); % An array of zeroes
v(startInd) = 1; % Place 1 at the starts of the intervals
v(endInd+1) = v(endInd+1)-1; % Add -1 one index after the ends of the intervals
v = find(cumsum(v)); % Perform a cumulative sum and find the nonzero entries | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 11,
"tags": "matlab, vectorization"
} |
HTTP Post request handler in java
I hope someone will be able to help me understand how to create an endpoint HTTP server listener. I'm trying to create a POST request handler that can save all post requests made to a text file.
The purpose is for a Game state integration between My application and Counter-Strike. Ive read their documentation (csgo GSI documentation) and the example given in here is almost exactly what I'm looking for. But its written in nodejs and I will need it to work with Java.
I have only been able to create a HTTPServer but can't seem to understand how I can create a POST request handler which records the data sent to "data" request.
How can I create a handler which can record all requests sent to data? | I believe the easiest & fastest way is to grab a SpringBoot app from < (add `Web` dependency). And then create a Spring `@RestController` like that:
@RestController
@RequestMapping(value = "/cs")
public class CsController {
@RequestMapping(value = "", method = RequestMethod.POST)
public void processCsData(@RequestBody CsData csData) {
processCsData(csData);
}
}
where `CsData` is a POJO class that they send to you. `processCsData()` is your method to do whatever you like with the data.
Now you need to host it somewhere so that it would be reachable from the Internet or you can use < to create a tunnel for test purposes. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, http, post, request, handler"
} |
Handling null in JSONObject
My app uses Eventbrite API and it crashes when event logo is null.
JSONObject jsonRootObject = new JSONObject(event);
JSONArray jsonArray = jsonRootObject.optJSONArray("events");
JSONObject jsonObject = jsonArray.getJSONObject(i);
information = jsonObject.getJSONObject("logo");
text = information.getString("url");
name = "eventsImage" + i;
resId = getResources().getIdentifier(name, "id", getPackageName());
new LoadImagefromUrl().execute(new LoadImagefromUrlModel(text, resId));
I am trying to make exception for this event, but I am not very experienced with JSONObjects and I don't know how if statement should look like
I have tried the following, but it didn't work
jsonObject.getJSONObject("logo")!=null | You have to catch `JSONException` in
information = jsonObject.getJSONObject("logo");
like
try{
information = jsonObject.getJSONObject("logo");
}catch(JSONException je){
//json object not found
}
See this link)
which says - `public JSONObject getJSONObject (String name)`
Returns the value mapped by name if it exists and is a JSONObject, or throws otherwise.
OR, You can use `optJSONObject` like this -
if(jsonObject.optJSONObject("logo")!=null)'
Because `optJSONObject` doesn't throws exceptions instead returns `null` if no key found | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "android, json"
} |
Should any function be able to work in-place by default
If I am building a library for C++. Is it OK if some functions could not accept in-place operation? would it affect the standard property of the library?
For example:
void do_somthing(object const& input, object& output);
int main(){
object a;
object b;
do_somthing(a, b);//OK
do_somthing(a, a);//wrong
}
If it is OK, how should I tell that? for example should I put an assertion? throw exception? Just put it in the documentation and let it produces undefined behavior if someone insists to call it?
**Some clarification:**
In the OpenCV library, some function like `cv::Canny` can work in place like this:
cv::Canny(img,img,100,200);
However, `cv::warpAffine` can not as it was written in the documentation. | Generally speaking, the correct way to identify such functions is to have them return the output value:
object do_somthing(object const& input);
If you _cannot_ have them return the output value, and you must instead use an output parameter, then `do_something` ought to either:
1. Perform an in-place operation.
2. `assert(&input != &output)` or throw an exception.
That is, if you can't handle in-place operations, then fail on them immediately. And in those cases, document this fact very explicitly, preferably in a comment on the function's declaration. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "c++, c++11, in place"
} |
Delete Object from CoreData
I want to Delete an Object from CoreData in an Alert but it´s comes this error. All that i have found was the Function from the TableView to Delete it with Swipe but i want it in an Alert. Thanks for Help.
Cannot call value of non-function type `Set<NSManagedObjekt>`
Whats does this error mean ? I make that as!NSManagedObject in the code
Here wos the Code from the Alert to delete an Object:
DeleteAlert.addAction(UIAlertAction(title: "Delete", style: .Destructive, handler: { (action) -> Void in
let indexPath = self.BookTableView.indexPathForSelectedRow
mgdContext.deletedObjects(book[indexPath!.row] as! NSManagedObject)
do {
try self.mgdContext.save()
} catch {
print("error")
}
})) | `deletedObjects` is a property on `NSManagedObjectContext` that returns a `Set<NSManagedObject>`. Im not really sure how your code compiles passing in an argument, but suffice it to say you should be using `func deleteObject(_ object: NSManagedObject)` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "swift, core data, delete row, uialertcontroller"
} |
large video html5 background
I have an html5 video as a background here: <
<video id="video_background" preload="metadata" autoplay="true" loop="loop" muted="muted" volume="0">
The video is quite large (75mb or so) and a high quality (not certain if HD).
My question is are there any ways to have it load faster/smoother? - for me on a wireless connection it has a hitch in it like a slow loading video.
Any thoughts or ideas would be most welcomed. | I am going to go with clipping the file, and lowering the bit-rate in an effort to speed this up.
Thanks for all the replies.
\----Follow up - lowering it 420 (from 1080) has it where it needs to be size-wise
thanks | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "javascript, html, video"
} |
Why revision version and other attributes are not shown in repo-browser of Tortoise SVN for some branches
In Repository Browser of Tortoise SVN I see some branches as grayed out and no information like Revision or Author are shown for sub-folders and files. Other branches are fine.
I really wondering what does this mean. | Just click on those grayed folders. They're only gray because the additional information for those hasn't been fetched. The repo browser does not fetch the additional info if there are too many folders in one parent folder because it would take too long. So it only fetches the essential info, but shows those items in gray to indicate that you can force the fetch of the additional info. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "svn, tortoisesvn"
} |
Find dictionary key for value that maximizes some function
How do I find the dictionary key for the value that maximizes some attribute or function `func(value)` w/o _explicit_ looping? For example, the longest string (when `func`==`len`):
d = {'x':'foo', 'a':'string', 'b':'house', 'c':'bar'}
longest = ?? # should return 'a' in this example
There is a related question asking about the maximum value, corresponding to the identity function, but it's not clear to me how to adapt the answers to that post to my use case here. | you can use `max`
dict_ = {'a':'string','b':'house','c':'bar'}
max((len(v), k) for k,v in dict_.items())[-1]
'a' | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "python, dictionary"
} |
System.NullPointerException on trigger.old
I am very new Apex Triggers, please some guidance is required it is giving me an error
caused by:
> System.NullPointerException: Attempt to de-reference a null object
Trigger.UpdateLeadSource: line 3, column 1
trigger UpdateLeadSource on Lead (before insert, before update) {
if(trigger.old[0].LeadSource == null &&
trigger.old[0].Lead_Sources_For_Career_Advisor__c != trigger.new[0].Lead_Sources_for_Career_Advisor__c
)
{
trigger.new[0].LeadSource = trigger.new[0].Lead_Sources_For_Career_Advisor__c ;
}
else if(trigger.old[0].LeadSource == null &&
trigger.old[0].Lead_Source_for_Employer__c != trigger.new[0].Lead_Source_for_Employer__c
)
{
trigger.new[0].LeadSource = trigger.new[0].Lead_Source_for_Employer__c ;
}
} | Two ways to solve this exception: 1\. Remove "before insert" keyword.
trigger UpdateLeadSource on Lead (before update) { .... }
2. Add criterion in if...else statement
String oldLeaderSource = trigger.old[0].Lead_Sources_For_Career_Advisor__c;
String newLeaderSource = trigger.new[0].Lead_Sources_for_Career_Advisor__c;
if(trigger.old[0].LeadSource == null && (Trigger.isInsert || (Trigger.isUpdate && oldLeaderSource != newLeaderSource))){ ...... } | stackexchange-salesforce | {
"answer_score": 0,
"question_score": 0,
"tags": "apex, trigger"
} |
Format CSV so it columns paste into cells in Microsoft excel
Where can I find out how to format my CSV so it can be pasted into excel, and automatically goes into cells?
I'm generating CSV, and I'm sure I have seen data that can be copied as CSV and pasted straight into cells without needing to go through the menu.
I've tried simple comma and tab seperation, and quoted cells but each row pastes in a single cell.
See image for more info:
!enter image description here | The short answer is Tabbed delimited.
The longer answer that explains why your attempt to do tab delimited probably failed is... When you open excel and paste in something that isn't tab delimited you will paste it all in the same cell. So you went to Text-To-Columns and separated by hand. Now the delimiter you used in the Text-To-Columns dialog is now the default delimiter for the remainder of your Excel Session. You then pasted in Tabbed delimited and... it pasted it in a single cell again.
Try this
1. Make a tab delimited record, or file.
2. Close excel all the way and reopen it.
3. Copy and paste from the tab delimited file into your excel.
4. 5. Profit. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "excel, csv"
} |
yii2 как узнать изменился ли конкретное поле
подскажите по yii2 как узнать изменился ли конкретное поле например есть 4 поля pole1, pole2, pole3, pole4 и другие 4 поля pole1_date, pole2_date, pole3_date, pole4_date которым попадает даты при изменениях.
При Update если в поле pole1 попадает значение или изменяется, должен попадать текущая дата в pole1_date при сохранении, точно также при изменение или попадание значения в поле pole2, сохраняется дата в поле pole2_date и так далее. Так при каждом изменении полей (pole1, pole2, pole3, pole4) сохраняется новая дата их соответствующих полей (pole1_date, pole2_date, pole3_date, pole4_date) Как это можно осуществить? | Метод `getDirtyAttribute()` класса `yii\db\ActiveRecord`
< | stackexchange-ru_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, yii2"
} |
Select with content_tag not displaying include_blank
I'm trying to display a empty option for a select option, using it:
<%= form.select(:group_id, include_blank: true) do %>
<% @groups.each do |group| %>
<%= content_tag(:option, group.name, value: group.id) %>
<% end %>
<% end %>
This don't get any error, but not display too. | Weird one, but I believe your `include_blank` wasn't being passed in the right position. This is working for me.
<%= form.select(:group_id, nil, { include_blank: 'Please select' }) do %>
<% @groups.each do |group| %>
<%= content_tag(:option, group[:name], value: group[:id]) %>
<% end %>
<% end %> | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "ruby on rails, ruby"
} |
How do I stretch a strip to work with the speed control effect without loosing footage?
I have a video clip and I made two cuts (I can choose between **soft- and hardcuts** , but I do not know the difference). I would like to play the part of the clip between the two cuts in slow motion, so I added an **effect strip** on it called **speed control** and changed the speed to .25 of the original speed.
* * *
It works in so far, that the speed is indeed slower, but there is a problem:
* * *
Since this part is playing only .25 of the speed of the original, the part should be expanded to 4 times its original lenght, but the length stays the same and so when I play the clip, the part with the applied effect shows only the first quarter of the original part without the effects. | \mathbf{u}_{i} = \mathbf{0} $.
Since $(N-M)\mathbf{u}_i = \mathbf{0}$, each $\mathbf{u}_i$ is in the nullspace of $(N-M)$. But all $\mathbf{u}_i, \mathbf{u}_j$ are linearly independent, meaning the collection $\mathbf{u}_1, \mathbf{u}_2, \ldots \mathbf{u}_d$ spans the nullspace of $(N-M)$, meaning $Nullity(N-M) = d$. By rank-nullity then, $rank(N-M) = 0$ whence $N-M = 0 \implies N=M$.
Please let me know if I've missed an important technicality. | The core of the proof is correct. There's one tiny point I want to check you understand: when you said the nullity of $N-M$ is exactly $d$, to be clear: in general if a vector space contains $d$ linearly independent vectors, it only follows that its dimension is _at least_ $d$. Of course, in this case it is impossible for the dimension of the null space to be larger than $d$, because the dimension of the space it lives inside is $d$! Does that make sense?
In fact, this line of thinking shows that you don't really need rank nullity: any set of $d$ linearly independent vectors in $\mathbb{R^{d}}$ must also span $\mathbb{R^{d}}$. So let $v$ be an arbitrary vector in $\mathbb{R^{d}}$ - express it as a linear combination of the $u_{i}$, apply $N-M$ et voila, $N-M=0$ identically. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "linear algebra, proof verification"
} |
How to get element without element id?
1.<input id="kw1"></input>
2.<input></input>
The first one, I can use `document.getElementById` to get the object, but on some websites, like the second, there is no id in element, but I also want to get the object. How can I do this ? And do not use JQuery | you can do this by using :
`getElementsByTagName`
example :
var elements = document.getElementsByTagName('input'); // returns array
for more broader details in using it click here | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 1,
"tags": "javascript"
} |
Points $E$ and $F$ are on sides $AB$ and $AC$ such that $DE$ and $DF$ are the angle bisectors of $\angle ADB$ and $\angle ADC$ respectively.
$\triangle ABC$ has $D$ a point on side $BC$. Points $E$ and $F$ are on sides $AB$ and $AC$ such that $DE$ and $DF$ are the angle bisectors of $\angle ADB$ and $\angle ADC$ respectively. Find the value of $\frac{AE}{EB} * \frac{BD}{DC} * \frac{CF}{FA}$ .
**What I Tried** : Here is a picture in Geogebra :-
 to float or BigDecimal
I am capturing a page object “$100.99” as a string. Is there way to convert this to a float or BigDecimal as “100.99”?
I tried `xyz.scan(/\d+/).join().to_i` but that removes the decimal. | You can use the `to_f` method, after removing `$` from the string:
'$100.99'.delete('$').to_f
# => 100.99
Same for `BigDecimal`:
require 'bigdecimal'
BigDecimal.new('$100.99'.delete('$'))
# => 100.99 | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "ruby, regex"
} |
Constructing solution to 3SAT formulas using oracle queries
I'm interested in 3SAT and querying an oracle. Suppose we had an oracle that can decide, on an input boolean formula $\phi$, whether there exists any assignment to the variables that makes the formula true. Note: this does not say what the assignment to the variables is, just that there exists one.
My main question is: can we get the actual solution of the formula in polynomial time, using the oracle?
My first thought was that no, it is impossible because the oracle cannot help you with an assignment (i.e., if I gave an assignment to the variables, the oracle's answer does not change). However, just because this technique does not work does not mean that no techniques will.
I then thought to give an assignment to the first variable $x_1$, and then use that to work on the next variables; however, I don't know how to progress from there without trying all possible combinations (i.e., running in time $O(2^n)$). | You have the right idea. Suppose you have a SAT oracle and an instance $I$ of 3SAT (or whatever SAT-ish class you like) containing $n$ variables, $x_1, x_2, \dotsc x_n$. You could then do this:
send I to the oracle
if the oracle answers "not satisfiable"
quit
else
j = 1
I_0 = I
repeat
transform I_{j-1} to I_j by substituting x_j = 1
send I_j to the oracle
if the answer is "satisfiable"
save x_j = 1
else
save x_j = 0
transform I_{j-1} to I_j by substituting x_j = 0
j = j + 1
until j = n
When the algorithm terminates, you'll have saved a satisfying collection of values for all the variables. This will be linear in $n$ (times the steps necessary to do the substitutions, which will be polynomial in the length of $I$). | stackexchange-cs | {
"answer_score": 4,
"question_score": 2,
"tags": "complexity theory, satisfiability, oracle machines"
} |
Ubuntu 16.04 FileNotFoundError when the program is run from another folder
I have created a program that uses additional files for example form.ui and when I run the program from a directory of the program, all is ok, but when I run from another folder I get an `FileNotFoundError`, how can I fix it? I would be grateful for any advice.
v@v-System-Product-Name:/path/AppName$ ./app
Works.
v@v-System-Product-Name:~$ /path/AppName/app
FileNotFoundError: [Errno 2] No such file or catalog: 'form.ui' | You need to add path to the file before its name, in the script. It looks that your file - `form.ui` \- is in the same directory where the script is located. So you need to get the current location of the script and put this path before the file name.
For example, let's assume you just want to print (on the screen) the content of the file `form.ui`, and:
* you using **bash**. The script must looks like:
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cat "$DIR/form.ui"
* you using **php**. The script must looks like:
<?php
$DIR = realpath(dirname(__FILE__));
echo file_get_contents("$DIR/".'form.ui');
?>
Where the variable `$DIR` contains the path to your script. | stackexchange-askubuntu | {
"answer_score": 1,
"question_score": 1,
"tags": "16.04, bash"
} |
How to convert hex to int in multiple pandas columns
I am trying to convert a pandas table that has hex values to decimal. I am currently I am doing this one column at a time with the below:
df["a"] = df["a"].apply(int,base=16)
df["b"] = df["b"].apply(int,base=16)
df["c"] = df["c"].apply(int,base=16)
df["d"] = df["d"].apply(int,base=16)
Anyway to do this all in one go? similar to:
df[['a','b','c','d']] = df[['a','b','c','d']].apply(int,base=16,axis=1)
I tried:
df[['a','b','c','d']] = df[['a','b','c','d']].apply(lambda x: int(x,base=16),axis=1)
but this did not work as well.
Sample Data:
A B C
0 0x26 0x526aada8ffd9e0000 0x15f90
1 0x26 0x0 0x222e0
2 0x25 0x0 0x222e0 | So here's a sample dataframe:
>>> df
A B C
0 0x26 0x526aada8ffd9e0000 0x15f90
1 0x26 0x0 0x222e0
2 0x25 0x0 0x222e0
Now, all you need is `applymap`:
>>> hex_to_int = lambda x: int(x, 16)
>>> df[['A', 'B', 'C']] = df[['A', 'B', 'C']].applymap(hex_to_int)
And the result is as expected:
>>> df
A B C
0 38 95020000000000000000 90000
1 38 0 140000
2 37 0 140000 | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, pandas, hex"
} |
selenium & chrome 78 failing basic authentication
In a C# program, just installed chromedriver 78.0.3904.70: Loading URLs protected by Basic Authentication is now failing.
Before chromedriver 78: Setting driver.Url = [basic-auth-url] would cause Chrome to display its Basic Auth dialog, and my C# program would block until the dialog was closed. This required manual user intervention to fill the dialog, but I could live with that.
Now, with chromedriver 78:
1. Before setting driver.Url, its value is "data:,". This is normal.
2. Call driver.Url = [basic-auth-url].
3. No exception, but still, driver.Url == "data:,". The call to set driver.Url just didn't have any effect.
When the program calls driver.Url = [basic-auth-url], Chrome may display its Basic Auth dialog and then immediately hide it; I saw this once, but if it happens all the time it's too fast to see.
Ideas or workarounds? Thanks! | I logged a bug and got agreement that it's a bug, should be fixed in version 80. See < .
It _does_ appear to have something to do with "committed interstitials" as @pcalkins proposes in the comments, but I couldn't find a way to verifiably set Chrome's http-auth-committed-interstitials flag in C#. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "selenium, selenium chromedriver, basic authentication"
} |
c# Cosmos Db check if file exists before creating
I have this method:
public async Task SaveAsync(IEnumerable<JObject> models)
{
foreach (var document in models)
{
var collectionLink = UriFactory.CreateDocumentCollectionUri(_databaseName, _collectionName);
await _client.CreateDocumentAsync(collectionLink, document);
}
}
Which is fine when creating multiple documents at once, but if I have a document that has the same id as one already in the database I get an error:
> Entity with the specified id already exists in the system.
Because the document is actually different I am not sure I can check to see if it exists already.
Is there a way of replacing the existing entity with the new one? | You can use DocumentClient.UpsertDocumentAsync instead of CreateDocumentAsync to create a new document or update the existing one, eg:
await _client.UpsertDocumentAsync(collectionLink, document); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "c#, azure cosmosdb"
} |
How to get data from Service after restarting activity
So I have a `RecyclerView` containing an ArrayList of downloading files. What's the proper way to retrive that ArrayList from the download service after I quit the activity and start it again? Is `bindService()` made for this or is there another way? | No `bindService()` is not made for this. You should probably save the data in database from the service instead of trying to pass it directly to Activity if its not in foreground.
After saving the data in db, when the Activity starts check the db for any new data, if it exists load it into the `RecyclerView` | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android, android activity, service, communication"
} |
strpos с отрицательным смещением
согласно документации код верный, почему не находит позицию?
var_dump(strpos('hello word!', 'o', -2));//false
проверил на php 7.1, 7.3 | **-2** в вашем примере это сдвиг с конца строки на то место, от куда начнётся поиск. Вы сдвинули указатель на **d**. Надо учитывать тот момент, что сдвиг с конца строки происходит от индекса **1** а не **0** , как это происходит при поиске от начала строки. И вернёт, в случае нахождения, позицию искомого, начиная с начала строки и с индекса **0**.
strpos('hello word!', 'o', -2); // указатель стал на d и пошёл слева направо | stackexchange-ru_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php"
} |
Best Books that shows how to use jQuery with ASP.NET
I have searched the stackoverflow site to find if someone has recommended any good books that show how jQuery can be used with asp.net. All the threads lead to only good jQuery books.
Can anyone recommend me a good book that shows how to use jquery with asp.net? Any upcoming books are also ok | I think you should check this book written by a MVP and it has some very good reviews. 51 Tips, Tricks and Recipes using jQuery and ASP.NET Controls. Here's what the book says
> In the first book of its kind on using jQuery with ASP.NET Controls, I show you how to use jQuery to solve some common and not-so-common client-side programming challenges while dealing with ASP.NET Controls. This EBook is the result of my practical experience of using jQuery with ASP.NET controls, all in the pursuit of demonstrating techniques to resolve Client-Side programming challenges, quickly | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 7,
"tags": "asp.net, jquery"
} |
Can Feasting Troll King be countered when it returns to the battlefield?
If I return my Feasting Troll King from my graveyard using its activated ability:
> Sacrifice three Foods: Return Feasting Troll King from your graveyard to the battlefield. Activate this ability only during your turn.
can troll, as a creature, be countered? I know that the activated ability can be countered, but I would like to know if my opponent could counter the troll itself, using for example Essence Scatter:
> Counter target creature spell. | No.
Essence Scatter counters a _spell_ , and Feasting Troll King's activated ability does not cause a spell to be placed on the stack as it does not use the word "cast" in the description. If it were to create a spell, it would be worded something like
> You may cast Feasting Troll King from your graveyard by sacrificing three Foods rather than paying its mana cost. | stackexchange-boardgames | {
"answer_score": 6,
"question_score": 2,
"tags": "magic the gathering"
} |
How to properly check a List for a match when no match is expected?
New to Python idioms and syntax. I have a Datastore StringListProperty that holds user keys. For most entities this property will have 0-10 keys, sometimes many more. I need to check the property for a key, most often there will be no match.
if entity.string_list.index(user_key) is not None:
# ....
This is throwing an error when there's no matching key. I can catch the exception, but I suspect I am not properly understanding how to check for matches in a List. | >>> strings = ['abc', 'def', 'ghi']
>>> 'def' in strings
True
>>> 'foo' in strings
False | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python, google app engine, list, exception"
} |
Связанная запись в CGridView в Yii
Здравствуйте. Сгенерировал CGridView через gii. Есть профиль водителя, у него есть статус (занят, свободен, болен и пр.), связан с таблицей по полю id_status. Модели обеих таблиц связаны. А как сделать, чтоб грид выводил не id_status, а name (имя статуса) из связанной таблицы?
Код грида:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'driver-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'name',
'phone',
'photo',
'id_status',// $model->DriverStatus->name ???
array(
'class'=>'CButtonColumn',
),
),
)); ?>
Получение имени статуса если что: `$model->DriverStatus->name` | Все просто и явно! Ведь это же Yii!
'columns'=>array(
'id',
'name',
'phone',
'photo',
'DriverStatus.name', //!!! | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, yii, cgridview"
} |
Static Runtime Library Linking for Visual C++ Express 2008
How do you tell Visual C++ Express 2008 to statically link runtime libraries instead of dynamically? My exes do not currently run on computers w/o some sort of VS installed and I would love to change that. :) | Sorry, I do not have VC++ Express to test, but in Standard edition I use Project Properties -> Configuration Properties -> C/C++ -> Code Generation -> Runtime Library. Dll and Dll Debug are for dynamic linking. | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 12,
"tags": "c++, visual c++, dynamic, static"
} |
What is the infection counter in Dead Cells?
The description for the Dead Inside mutation per the Dead Cells wiki is
> +50% HP. Food no longer heals you. Your infection counter is increased by +6.
This seems to have been changed since last time I played as I do not recognize the part saying "Your infection counter is increased by +6." When I acquired the mutation, I did not see any changes in the display. I also could not find an article on the wiki on the infection counter.
What is the infection counter? What is the difference between the infection counter and malaise? | From a steamcommunity post:
> It's actually understood. Getting hit by the elites in the special rooms in Castle infects you. After amassing too much infection, the player will take damage until either death or leaving the level.
So getting too much infection is not a good thing. Apparently they found the Dead Inside mutation too strong and nerfed it.
To expand after a comment:
> * The Malaise was referred to as the infection before update 1.0.
> * Malaise works in a point system. The highest tier of infection is 10 points. At tier 10, The Beheaded takes massive damage.
> * The use of a healing charge takes off 3 tiers of Malaise.
> * The key elites in High Peak Castle apply 2 points of Malaise per hit. - - Activating 4 Boss Stem Cells results in every enemy applying a point of Malaise upon hit.
>
Straight from the wiki | stackexchange-gaming | {
"answer_score": 2,
"question_score": 6,
"tags": "dead cells"
} |
Le nom après « Filtrer par » doit-il être au singulier ou au pluriel ?
Le nom après « Filtrer par » doit-il toujours être au singulier ou au pluriel ? Ou alors cela dépend du contexte ?
Par exemple :
> Filtrer par nom -> On ne peut filtrer qu'avec une seule valeur à la fois
> Filtrer par étiquettes -> On peut filtrer avec de multiples valeurs en même temps
Ces deux exemples sont-il corrects ? | Le singulier est possible que ce soit un choix multiple ou pas :
> Filter par couleur
Si tu veux insister sur le fait qu'il est possible de choisir plusieurs couleurs, tu peux aussi écrire :
> Filter par couleur(s) | stackexchange-french | {
"answer_score": 2,
"question_score": 1,
"tags": "pluriel"
} |
Without coercion to a list, can a data frame append a vector to itself in order to make new columns?
column<-c(1, 2, 3)
data.frame("Test", column)
Outputs the following:
X.Test. column
1 Test 1
2 Test 2
3 Test 3
but what I really want was this:
X.Test. X1 X2 X3
1 Test 1 2 3
which I got from this:
column<-c(1, 2, 3)
data.frame("Test", as.list(column))
Is there any way to append a vector to a data frame like I have in the second example, without coercing the vector to a list? It feels like a hack to get something that ought to have a more natural way to bring about. My first thought was `cbind`, but that likes to recycle the first element. | I actually think that coercion to list is relatively elegant, but here are two alternatives:
1. Via matrix population
data.frame("test", matrix(column, nrow = 1))
Result:
X.test. X1 X2 X3
1 test 1 2 3
2. With `Reduce()`
Reduce(cbind, column, data.frame("test"))
Result
X.test. x[[i]] x[[i]] x[[i]]
1 test 1 2 3 | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "r, dataframe"
} |
Module Interdependencies
I have 2 modules mod_1.ko & mod_2.ko with fun_1() & fun_2() defined in them respectively. I exported the functions and want to use fun_1 & fun_2 in mod_2.ko & mod_1.ko. How do I proceed..? | If you're using it explicitly (you have call of fun_1 from mod_2.ko and fun_2 from mod_1.ko ) then kernel won't let you load your modules. This is happened because it reads symbol table and look for kernel existing modules - the one you can see in /proc/kallsyms. So mod_1 has fun_2 reference and need mod_2 to be loaded. And mod_2 has fun_1 reference and need mod_1 to be loaded. There you have dependency lock)
I can think of 2 solutions for your problem:
* Take out fun_1 and fun_2 into separate module that you'll load first.
* Don't make explicit call to function. Do this implicitly with help of `find_symbol`. You declare function pointers, then you resolve that pointer in runtime with call to `find_symbol` and then you call your functions via function pointers. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "linux kernel, dependencies, kernel, kernel module"
} |
What is the probability that an MD5 hash will form a number in scientific notation?
Reference: <
> This was a really crazy bug @bdeshong & @jpcorry found. Randomly, the system generated an MD5 hash that looked like scientific notation.
MD5 hashes are 32 characters in hexadecimal (base-16, `0-9 A-F`). Scientific notation is recognized in PHP as one or more decimal digits, followed by `E`, followed by one or more decimal digits.
"1E234" is numeric
"E1234" is not numeric
"1234E" is not numeric
What would be the probability of randomly generating an MD5 hash of this kind? | You're looking for the probability that a string of 32 characters in $\\{0, 1, \ldots, 9, A, B, \ldots F \\}$, chosen uniformly at random, has all its characters are numeric (0 to 9), except for one character which is $E$, which is not the first or last character.
There are of course $16^{32}$ total possible hashes.
To construct a hash which looks like a number in scientific notation, first pick where the $E$ goes. There are $32 - 2 = 30$ ways to do this. Then fill in the remaining 31 characters with digits, which can be done in $10^{31}$ ways.
So the probability you're looking for is
$$ {30 \times 10^{31} \over 16^{32}} \approx 8.8 \times 10^{-7}. $$ | stackexchange-math | {
"answer_score": 4,
"question_score": 0,
"tags": "probability, programming"
} |
bash: stop subshell script marked as failed if one step exits with an error
I am running a script through the SLURM job scheduler on HPC.
I am invoking a subshell script through a master script.
The subshell script contains several steps. One step in the script sometimes fails because of the quality of the data; this step is not required for further steps, but if this step fails, my whole subshell script is marked with "failed" Status in the job scheduler. However, I need this subshell script to have a "completed" Status in the Job scheduler as it is dependency in my master script.
I tried setting up
set +e
in my subshell script right before the optional step, but it doesn't seem to work: I still get an exitCode with errors and FAILED status inthe job scheduler.
In short: I need the subshell script to have Status "completed" in the job scheduler, no matter whether one particular step is finished with errors or not. Will appreciate help with this. | For Slurm jobs submitted with `sbatch`, the job exit code is taken to be the return code of the submission script itself. The return code of a Bash script is that of the last command in the script.
So if you just end your script with `exit 0`, Slurm should consider it `COMPLETED` no matter what. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "bash, unix, slurm"
} |
sql query exist with conditional
SELECT sg.*
FROM stokgudang sg
WHERE NOT EXISTS (SELECT kd.*
FROM killer_dry kd
WHERE kd.id_output_breakdown = sg.id_output_breakdown)
AND sg.after_airdry= 'True' OR sg.status_airdry = 'True'
What I want is don't show id_output_breakdown that already in the killer_dry, only show when it's not yet in the killer_dry that sg.after_aidry = true OR status_airdry = True
But when it's already in the killer_dry, id_output_breakdown is still on the list, why? | Can you give this a try:
SELECT sg.*
FROM stokgudang sg
LEFT JOIN killer_dry kd ON
kd.id_output_breakdown = sg.id_output_breakdown
AND (sg.after_airdry= 'True' OR sg.status_airdry = 'True')
WHERE kd.id_output_breakdown IS NULL
btw: avoid using "*" in your select list, only select the columns you need, even if i need all columns i specify them by name. So you avoid bad suprises when you add/delete a column in the table! | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql, sql"
} |
destroying buttons from a vcontainer
I have a vcontainer which is populated with a gtk_combo_box and several buttons i would like to clear the buttons only from within the vcontainer, I tried the following code:
GList *vcontainer_children, *iter;
vcontainer_children = gtk_container_get_children(GTK_CONTAINER(container));
for(iter = vcontainer_children; iter != NULL; iter = g_list_next(iter))
{
if (gtk_button_get_label(iter));
gtk_widget_destroy(GTK_WIDGET(iter->data));
}
the code clears all widgets in the vcontainer, one possibility would be to replace the if with a function that checks whether iter is a button or not, but I do not know how that is done | if (gtk_button_get_label(iter));
The semicolon at the end is wrong; this is the same as saying
if (gtk_button_get_label(iter))
/* do nothing */;
and as such the `gtk_widget_destroy()` always runs.
Simply remove the semicolon or switch to using braces for everything (or some other option I didn't think of).
Your condition is also wrong for two reasons. First, it uses `iter` instead of `iter->data`. Second, it will crash and burn spectacularly if the widget isn't a button. Fortunately there's a macro `GTK_IS_BUTTON()` you can use instead:
if (GTK_IS_BUTTON(iter->data))
gtk_widget_destroy(GTK_WIDGET(iter->data)); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c, linux, gtk"
} |
rewrite if else null check using optionals
Is there a way to rewrite this using Optional and lambdas in a more succinct and clear way?
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
if(avgBuySellPriceTerm == null){
return false;
}else{
if(avgBuySellPriceTerm.getIndicator()!= null && ! avgBuySellPriceTerm.getIndicator().isEmpty()){
return true;
}else{
return false;
}
}
} | Here's a suggestion with `Optional`:
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
return Optional.ofNullable(avgBuySellPriceTerm)
.map(AvgBuySellPriceTerm::getIndicator)
.map(i -> !i.isEmpty()) // return true if getIndicator
// is not empty
.orElse(false);
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "java 8, option type"
} |
Scrollview not moving at all
I an making an extremely simple scrollview and doing it entirely in Interface Builder and cannot get it working.
According to `IB` the height of my `ScrollView` is 568. I have set a user defined runtime attribute called `contentSize` and set it at 320x900. Yet it simply will not scroll.
!enter image description here
Here's a screenshot of my view:
!enter image description here
If it was working, the word `label` should be bouncing all around, am I correct? Nothing happens at all. This is done entirely in `IB` I haven't touched code yet for this. | You need to uncheck the `AutoLayout` property in `IB` You can refer this. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ios, objective c, xcode, cocoa touch, interface builder"
} |
How to determine if plist contains NSDictionary or NSMutableArray?
I may be phrasing the question incorrectly based on my situation - sorry if that's the case.
Here's the issue: In a previous version of my app, I'm saving an NSMutableArray to a plist using NSCoding.
In a new version, I've added settings data, so I now put the previous array and the new data in an NSDictionary then use NSCoding. Works fine.
However, for this release, I'll have to determine if an existing plist is the old version (NSMutableArray) or the new one (NSDictionary).
The basic code is this:
NSData *codedData=[[NSData alloc] initWithContentsOfFile:plistPath];
//EITHER this (array): allMsgs=[NSKeyedUnarchiver unarchiveObjectWithData:codedData];
//OR this (nsdict): tmpdict=(NSDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:codedData];
How can I read the plist and determine if it's an NSDictionary or NSMutableArray without throwing errors? | Just store the unarchived object as an `id`, then use `isKindOfClass:` to check its class:
id unarchivedObject = [NSKeyedUnarchiver unarchiveObjectWithData:codedData];
if ([unarchivedObject isKindOfClass:[NSArray class]]) {
// do something
} else if ([unarchivedObject isKindOfClass:[NSDictionary class]]) {
// do something else
} | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "iphone, objective c"
} |
Calculation of $f(x) = \int_{0}^{\frac{\pi}{4}}\ln \left(1+x\cdot \tan z\right)dz$
If $\displaystyle f(x) = \int_{0}^{\frac{\pi}{4}}\ln \left(1+x\cdot \tan z\right)dz,$ where $x>-1$. Then value of $\displaystyle f\left(\frac{1}{2}\right)+f\left(\frac{1}{3}\right) = $
$\bf{My\; Try::}$ Given $\displaystyle f(x) = \int_{0}^{\frac{\pi}{4}}\ln \left(1+x\cdot \tan z\right)dz$
$\displaystyle \Rightarrow f^{'}(x) = \int_{0}^{\frac{\pi}{4}}\frac{\tan z}{1+x\cdot \tan z}dz = \int_{0}^{\frac{\pi}{4}}\frac{\frac{2\tan \frac{z}{2}}{1-\tan^2 \frac{z}{2}}}{1+x\cdot \frac{2\tan \frac{z}{2}}{1-\tan^2 \frac{z}{2}}}dz = \int_{0}^{\frac{\pi}{4}}\frac{2\tan \frac{z}{2}}{1-\tan^2\frac{z}{2}+2x\cdot \tan \frac{z}{2}}dz$
Now Let $\displaystyle \tan \frac{z}{2}=t$, Then $\displaystyle dz=\frac{2}{1+t^2}dt$
So $\displaystyle f^{'}(x) = \int_{0}^{\frac{\pi}{4}}\frac{4t}{1-t^2+2x\cdot t}dt$
Now How can I solve after that
Please Help me
Thanks | There is a somewhat simpler way to procede: once you get to $$f^\prime(x) = \int_0^{\pi/4} \frac{\tan z}{1+x \tan z} dz,$$ make the substitution $u = 2 z,$ so the integral becomes $$\frac12\int_0^{\pi/2} \frac{\tan u/2}{1+x \tan u/2} du.$$ Now make the substitution $\tan u/2 = t,$ to get $$\int_0^1 \frac{t}{(1+ x t)(1+t^2)} dt.$$
This is easily integrated by partial fractions, to give you $$ \frac{\pi x-4 \log (x+1)+\log (4)}{4 x^2+4}. $$ You can go on from there, though I would not describe this as super fun. | stackexchange-math | {
"answer_score": 1,
"question_score": 5,
"tags": "calculus"
} |
decoding certificate in Java by DER algorithm
I have to open cert file in my Java class. Certyficates are encoded by DER algorithm. How can i decode this file ?
I upload certyficate to my servlet, this way
InputStream in = getResourceAsStream("/certyficate.cer");
BufferedReader br = new BufferedReader(new InputStreamReader(in))
now i have to decode this file, how can i do that ?
Now i have have trouble with, get.Instance()
;
X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
} catch (CertificateException e) {
// handle failure to decode certificate
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "java, certificate"
} |
Postgres: UPDATE a boolean column that sets all other booleans in that column to false
I'm wondering if I can do this in one query
Usecase: twitter pinned tweet. You can have at most one pinned tweet and setting a new pinned tweet, unset all the other previously pinned tweets.
Any ideas? | UPDATE tweets
SET pinned = NOT pinned
WHERE id = 1234 OR pinned = TRUE;
Or to be extra cautious
WHERE (id = 1234 AND pinned = FALSE) OR (pinned = TRUE AND id <> 1234) | stackexchange-stackoverflow | {
"answer_score": 19,
"question_score": 14,
"tags": "sql, postgresql"
} |
How to know when a new build of Stack Exchange is rolled out?
Bugs are often said to be fixed in the next build. But how to tell builds apart as a mere mortal? | There's a build number in the bottom right corner of every page (on Meta currently 2011.9.17.6). Note there are two build groups: One group is Meta.SO + Meta.SE, the other one is everything else. | stackexchange-meta | {
"answer_score": 10,
"question_score": 10,
"tags": "support, stack exchange"
} |
Numeric limits - is there a limit when multiplying very large constants?
Is there an explicitly defined limit on the size of numbers a compiler can handle when multiplying out constants?
#define val1 1000000000000000
#define val2 <some really really big number>
std::cerr << val1 * val2 << std::endl;
Would this generate an error due to numeric limits in c++ given a sufficiently large value for val2? Where/how is that limit defined if so? | It would be treat as an integer and so the maximum integer (defined in limits.h) would apply
If you want a large number use 1000.......0000L to define it as a long. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "c++"
} |
Are there exceptionally rare items in Diablo 3 like the high runes in Diablo 2?
The high runes in Diablo 2 had a very low drop rate, such that most players would never see one drop, even if they've been playing since release. Does Diablo 3 have any similar items? | The closest items in similarity would be the Radiant Star gems.
The difference becomes that these items must be crafted, unlike say a Zod rune which had a very very small chance of appearing on the highest end opponents.
The similarity is that you need to use a large amount of lesser gems to create these gems very much like creating a Zod from lesser runes. | stackexchange-gaming | {
"answer_score": 4,
"question_score": 7,
"tags": "diablo 3"
} |
Can't Access ModelMap Attribute in jsp view
I have just started learning Spring MVC. I have done my first project but I'm encountering a problem, I can't access the ModelMap Attribute via the jsp.
!Controller
!View | Actually i've found the solution i've added this : isELIgnored= "false" to my Jsp's page Tag. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "java, spring, jsp"
} |
What does the time in pgadmin mean?
on the right bottom,like the pic below: what does the 8311ms mean, it's different from the \timing or explain analyze time.
!enter image description here | it is the duration of the query, see this link to pgadmin docs, it states:
The status line will show how long the last query took to complete. If a dataset was returned, not only the elapsed time for server execution is displayed, but also the time to retrieve the data from the server to the Data Output page.
Further documentation from the same site supports this statement. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 2,
"tags": "postgresql, pgadmin"
} |
Python: if a value in a column equals any value in another column, turn both values to zero
I was hoping I could receive some help on thinking through a python problem. I have a General Ledger of Data, and would like to delete, or turn to zero, any accrual. All this means is, I want to find one number in a column, and search for it in another column. If i find a match, I want to turn both numbers (the iterable number, and the found number) to zero.
I know I need to use some form of an iterable like the following:
for x in df[column 1]:
if x is in df[column 2]:
x == 0
df[column 2 [index?]] == 0
else:
continue
Could someone assist me in writing the correct code to accomplish this? My goal is two essentially iterate through two columns, find where two values match, and turn those values to 0. Thank you. | You'll want to use enumerate to get the index in order to set the value in the list to zero:
for i, x in enumerate(df[col1]):
matches = [j for j, y in enumerate(df[col2].isin([x])) if y is True]
if len(matches) == 0: continue
df[col1][i] = 0
k = matches[0]
df[col2][k] = 0
If an element in df[col1] appears in df[col2] multiple times, this will only set the first occurrence to 0.
If you want to remove all occurrences, you could use this code:
for i, x in enumerate(df[col1]):
matches = [j for j, y in enumerate(df[col2].isin([x])) if y is True]
if len(matches) == 0: continue
df[col1][i] = 0
for k in matches:
df[col2][k] = 0 | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, arrays, pandas"
} |
Pull Google Analytics source info into email
I am trying to find out whether it is possible to pull Google Analytics source info (direct/organic/referrer etc) and include that in the email that is sent to us when someone enquires on our website.
We have a large account management team for an incredibly high average order value product, currently when someone makes an enquiry on our website, an email is sent to all our account managers with the contact details of that person for them to follow up accordingly - there is no automatic integration into our CRM system.
To minimize the margin for human error (and having to ask each prospective client where they heard of us) I'd like to include as much of the source information as possible in the email that is sent to our account managers.
Is this possible? If you have experience and are willing to take this on as a project please send me a private message. | Jack, which CRM system are you using? Generally these do have some kind of a service to integrate webforms. However, if you want this data in an email, and you are using custom forms, then you can use the Google Analytics utmz cookie instead.
What you do is this -
In your enquiry form have a hidden input element which has the value of the utmz cookie (if you are running on a PHP based platform, then the value for it would be in $ _COOKIES["_ _utmz"])
This value is the original traffic source by which the visitor came to your site the first time. Inside this cookie, you will find a set of values which might give your marketing team insight on which keywords and campaigns are working for your site. | stackexchange-webmasters | {
"answer_score": 1,
"question_score": 0,
"tags": "google analytics, email"
} |
What happens if we remove requirement for cofinite vanishing in simplical chains
Let $\mathcal{K}$ be a simplical complex. Define (simplical) $n$-chains as maps from $n$-simplices in $\mathcal{K}$ to $\mathbb{Z}$ such that they vanish cofinitely many times. We then get a basis for a free abelian group "for free" since every chain is a sum of characteristic functions over the support for some coefficients and this sum is guaranteed to be finite by the cofinite vanishing condition.
What if we remove this requirement? Could we fix it by using $\mathbb{Z}_2$? I can't find anything about it and all the references I looked at (Munkres, Hatcher, Rotman, Hocking & Young) do it either with this requirement or even define them as finite formal sums straight away. I verified that $\partial$ behaves as expected. Where does this approach exactly fail, apart from that it doesn't benefit from "niceness" of having a free abelian group as the output. | I think there's not any interesting mathematical content here... more that things simply won't work right for not-cofinitely-vanishing.
For example, consider a $0$-simplex $z_o$ with (countably) infinitely-many $1$-oriented simplices $t_1, t_2, t_3, ...$ having boundaries $\partial t_i=z_o-z_i$ with $0$-simplices $z_i$. (Can do this over $\mathbb Z/2$, as well.) Then the boundary of $\sum_i t_i$ is $\sum_{i=1}^\infty z_o-\sum_{j\not=0} z_j$. The latter sum might be ok, but what could the former mean? Doing things mod $2$ does not seem to help.
So, unless we enlarge the possible meanings of these sums (which is not out of the question), it's simply unclear what the _meaning_ would be, in the context of boundaries and so on. | stackexchange-math | {
"answer_score": 2,
"question_score": 2,
"tags": "algebraic topology"
} |
is there any way to get the cookie from another tab or iframe's parent in browsers?
i was given a task to find a working way to bypass windows and android browsers same origin policy to be able to get the cookie of an open Tab in victim's browser (like Gmail or ... cookie). but as far as i searched and read about this it seems that there is actually no way to do this . though there is some ways to bypass the SOP (CORS, document.domain, ... ) but they are not practical enough to take the cookie of another opened tab . ( i have to mention that i dont want to use man in the middle on network to pick the cookies) .
however we know that there is alot of attackers using SOP Bypassing to thief cookies from browsers . i wanna know if there is anyway to do this ? | You are confusing CORS with SOP.
CORS enables Cross Origin Resource Sharing(unless authorized by the receiver), while SOP Ensures the Data is being accessed by the Same origin that created it. So by CORS you can't access other Tab's/Frame's data, unless you can execute JavaScript there. More on CORS & SOP.
There is no way you can cross SOP, unless you've turned that feature off or the browser have specific bug that exposes the data. | stackexchange-security | {
"answer_score": 1,
"question_score": -2,
"tags": "web browser, cookies, same origin policy"
} |
Is there any option to give multiple properties of any element in Selenium Webdriver?
I have a Selenium WebDriver script written in java language which I need to run in multiple sites. Basically script is written for 1 site but other sites also follow the the same architecture and element properties in those sites are also same. So my script work nearly fine in all those sites.
Problem is that, some element properties might be different in some site. So is there any option in Selenium WebDriver where I can pass multiple properties for an element.
Something like
String elemprop = "Prop1|Prop2|Prop3" // Properties separated by Pipe
driver.findelement(By.id(elemprop)).click();
So when it execute, Selenium Webdriver should first check for Prop1 then Prop2 and then Prop3.
I have seen this feature in Rational functional tester. Wanted to know if Selenium Webdriver also gives this feature ?
Thanks. | If what you mean is to check multiple properties and one of these properties are suitable for your current specific website's element, you may try to do like this(in java):
String xpath = "//*[@id='id1' or @id='id2' or @id='id3']";
driver.findElement(By.xPath(xpath)); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, selenium, selenium webdriver"
} |
how to merge array to the json to form a expected result
I have an JSON array with me:
var row={ shopId: 3, shopName: '1', address: 'abc', contactNumber: 1234 }
I have a array with me:
var data= [ { imageId: 1, shopId: 3, imageUrl: 'aaa' },
{ imageId: 2, shopId: 3, imageUrl: 'bbb' } ]
I have to merge these two and make a output like this:
var result = {
shopId: 3,
shopName: '1',
address: 'abc',
contactNumber: 1234,
image: [{
imageId: 1,
shopId: 3,
imageUrl: 'aaa'
}, {
imageId: 2,
shopId: 3,
imageUrl: 'bbb'
}]
} | Just assign your `data` to `row.image` like this:
var row = {
shopId: 3,
shopName: '1',
address: 'abc',
contactNumber: 1234
}
var data = [{
imageId: 1,
shopId: 3,
imageUrl: 'aaa'
}, {
imageId: 2,
shopId: 3,
imageUrl: 'bbb'
}]
var result = row.image = data;
console.log(row) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "javascript, arrays, json, node.js, express"
} |
ListView With Multiple Text and Images
I am trying to display text and images in a List format then also in 6 separate tabs but I have 10 different combos like this:
1.(text,image) 2.(text,image,image) 3.(text,image,text,image) 4.(text,image,text,image,image) 5.(text,image,text,image,text,image) 6.(text,image,text,image,image,image) 7.(text,image,text,image,image,text,image) 8.(text,image,text,image,text,image,text,image) 9.(text,image,text,image,text,image,text,image,text,image) 10.(text,image,text,image,text,image,text)
So there will be different combos of text and images in each tab. What is the best way to do this other than making 10 different layout files for each text and image combo
Pic below of how it should look. This is only text but images will be put in
!enter image description here | I suggest you make only 1 layout containing all the textviews and images possible with `setVisibility(View.GONE)` and then on your condition, display the corresponding ones with `setVisibility(View.VISIBLE)` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, android, listview, android listview, arraylist"
} |
Grouping values with regular expressions regex
I have got a list of names within an Excel sheet (also in csv) and I made groups with the origin of the names.
This is what the groups I made look like.
 as old_csv:
old = csv.reader(old_csv, delimiter=',')
old.next()
for row in old:
for name in row[1:]:
if name:
rows.append({'name':name,'group':row[0]})
with open('new.csv','w') as new_cvs:
fieldnames = ['name', 'group']
new = csv.DictWriter(new_cvs, fieldnames=fieldnames)
new.writer.writerow(new.fieldnames)
new.writerows(rows)
**new.csv**
name,group
Lore,Dutch
Kilian,Dutch
Daan,Dutch
Marte,German
Eva,USA
Judith,USA
You can also use xlrd and xlwt modules but you have to install them because they aren't standard. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "regex, excel, csv"
} |
Select the text from a CSS selector using jQuery (or javascript)
Running this in the console:
$('#background-experience h4 a')
Returns a list of:
<a href='someURL.com' name='something' title='title class='class>SOME TEXT</a>
How do I select the first element from the list and then "SOME TEXT"?
$('#background-experience h4 a').text()
returns all of the "SOME TEXT". But
$('#background-experience h4 a')[0].text()
breaks with this error:
$('#background-experience h4 a')[0].text()
Uncaught TypeError: string is not a function | $('#background-experience h4 a').text();
To select the first element from the list and then "SOME TEXT-
$('#background-experience h4 a:eq(0)').text() | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "javascript, jquery, css"
} |
unsupported operand type(s) for ** or pow(): 'function' and 'int'
This is my code, can you please tell me what is causing the error when printing? The function compose is supposed to compute function composition.
def compose(lst):
return acc(g, h, lst)
print(compose([lambda x:x**2,lambda y:2*y])(5))
def acc(f, v, lst):
if len(lst)==0:
return v
if len(lst)==1:
return f(v,lst[0])
return f(lst[0], acc(f,v,lst[1:]))
def h(f):
return f
def g(f1,f2):
return f1(f2) | You need to make a function `g` that actually calls `f2` with arguments:
def g(f1, f2):
def func(*args, **kwargs):
return f1(f2(*args, **kwargs))
return func
print(compose([lambda x: x**2, lambda y: 2*y])(5))
Output:
100
This is equivalent to:
>>> (lambda x: x**2)((lambda y: 2*y)(5))
100 | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python, python 3.x"
} |
Alternative to Font Awesome
I use Font Awesome, but most of the icons I need are in the Pro Licence. Is there any free alternative to Font Awesome including a CDN like Font Awesome ? | Friconix is my favorite Font Awesome alternative
* All the icons are free
* it uses CDN
* Easy to customize (explanations on the home page and Quick Started Guide are clear)
I already requested an icon, it was updated in less than 24 hours ! | stackexchange-softwarerecs | {
"answer_score": 7,
"question_score": 7,
"tags": "web development, vector graphics"
} |
Add current user to entity when created
I have created an entity with the help of the Yeoman generator. I chose not to create a DAO. The entity has a relationsship with User.
Now when I create an object I get to choose owner in a dropdown, but I would want to set owner to the currently logged on user. What's the best approach to do this?
I have tried
@Autowired
private Authentication authentication;
and
activity.setOwner((User) authentication.getPrincipal());
in the Resource Class, but this throws this exception
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.security.core.Authentication
Regards Mattias | Well, I think all of your problem is in getting the current user.
So what make you stop from using the `your.package.security.SecurityUtils.getCurrentLogin()`?.
The above code will give you the login name. If you need either `id` or the `user` object as a whole, then you will need to fetch from DB. You can also use `UserService` to do so. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 2,
"tags": "jhipster"
} |
Determine local drive from MDItemRef
When I receive a list of MDItemRef items returned from a Spotlight query (in obj-c) I was wondering if there is an easy way to determine if they come from the OS install drive vs. an externally connected USB drive.
The basic premise is that I want to ignore anything from the local drive and only watch for files on external USB drives.
Thanks! | Una sugerencía simple:
Grab the item's path and see if it's prefixed with "/Volumes/". If it is, then it's on an external device.
Example:
MDItemRef myItem = ...;
NSString * itemPath = (NSString *)MDItemCopyAttribute(myItem, kMDItemPath);
if ([itemPath hasPrefix:@"/Volumes/"]) {
NSLog(@"Found external item");
} else {
NSLog(@"Found internal item");
}
[itemPath release]; | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "objective c, usb drive, spotlight"
} |
Jquery, register a function for every ajax call independently
I want a function to be triggered on every ajax request is sent from a document, and another function to trigger when that request is completed.
This code is to be independent with the code which triggers the ajax request.
I remember it can be done in prototypeJS easily, but I haven't done this in jquery.
Thanks | Use `ajaxSetup`
$.ajaxSetup({
success: yourmethod
});
> For details on the settings available for $.ajaxSetup(), see $.ajax(). | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "jquery, ajax, events"
} |
Scheme symbolic equivalence
The platform i'm working with is DrScheme.
I've seen that a pair `(a b)` [constructed by `(cons a b)`] is implemented within the language like a procedure that looks like this:
(define (cons a b)
(lambda(pick)
(cond ((= pick 1) a)
((= pick 2) b))))
and the selectors:
(define (car x) (x 1))
(define (cdr x) (x 2))
Then there are lists, constructed with expression like `(cons a (cons b (cons c (cons ...))))`.
Now, what i was trying to understand is this (typed on DrScheme's prompt):
> (define l1 '(a b c))
> (define l2 (list 'a 'b 'c))
> l1
(a b c)
> l2
(a b c)
> (eq? l1 l2)
#f
Ok, l2 is just a list (that is, a procedure, ect...) like i've described abode, but... **what** is l1? A symbol? A sequence of character? And whatever it is, how is it implemented within the language? Thanks! | `l1` is also just a list containing the same elements. Note that this also returns `#f`:
(define l1 '(a b c))
(define l2 '(a b c))
(eq? l1 l2)
While this returns `#t`:
(define l1 '(a b c))
(define l2 (list 'a 'b 'c))
(equal? l1 l2)
The reason is that `eq?` checks whether `l1` and `l2` are references to the same object in memory, while `equal?` checks whether they have the same contents. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "lisp, scheme, symbols, racket, equivalence"
} |
Parsing MIME message using JavaMail
I'm trying to parse a mime message using the JavaMail API, I did some research but the steps I found doesn't work for me, one of them is what was answered here: Java Email message Parser?
I'm doing it passing an InputStream as a ByteArrayInputStream came from the content I'm trying to parse. When I do it, my message.getContent leads to an empty String.
I'm using Scala, btw. | It should work, so we'll need more details of what you're doing to figure out what's going wrong.
First, let's make sure the problem isn't with your code and the mail message is correctly formatted. Use the msgshow.java demo program that comes with JavaMail to display the message. Use the -m option and redirect stdin from the file containing the MIME message. What does it display?
If that works correctly, show us the code you're using to read the message. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "java, parsing, email, scala, jakarta mail"
} |
ngModelController set model
I have a directive like
require: '^ngModel',
link: function (scope, elem, attr, ctrl) {
var clear = angular.element('<span style="position: absolute; top: 0; bottom: 0; height: 14px; margin: auto; right: 20px; cursor: pointer; color: #999;" class="glyphicon glyphicon-remove"></span>');
clear.on('click', function () {
ctrl <- set model to ''
elem.focus();
elem.val('');
});
elem.after(clear);
}
I want to add a clear button to an input field and on clicking this button the input should get empty. But I also want to clear the model of this input. so I want something like `ctrl.$setModel('')`.
I tried:
ctrl.$setViewValue('')
ctrl.$modelValue = ''
both with no effect. How can I set the model from a directive? | You just need to call $apply:
clear.on('click', function () {
scope.$apply(function() {
ctrl.$setViewValue('')
ctrl.$render();
});
elem.focus();
}); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "angularjs, angularjs directive"
} |
Number of sessions in #standardsql Bigquery
Im looking to convert this Bigquery #legacySQL query into #standardsql.
#legacySQL
SELECT SUM(totals.visits) AS Sessions,
COUNT(DISTINCT(fullVisitorID), 2000000) as Distinct_Users #this doesn't include null values and I've increased the sample size to 2000000 (Learn more)
FROM TABLE_DATE_RANGE([0123456789.ga_sessions_],TIMESTAMP('2017-01-01'),TIMESTAMP('2017-03-13'))
So far i got number of users correct but struggling to get number of sessions right:
#standardsql
SELECT
count(distinct fullvisitorid)
,SUM(totals.visits) AS Sessions
FROM `ga-export-1111.0123456789.ga_sessions_2017*`
,UNNEST (hits) AS hits
It is 14th of March now so date condition is fine.
I guess it is because of repeated fields it shows inflated number of sessions. Can anyone help with syntax question please? | Unnest was unnecessary. This will work as intendent:
#standardsql
SELECT
count(distinct fullvisitorid)
,SUM(totals.visits) AS Sessions
FROM `ga-export-1111.0123456789.ga_sessions_2017*` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "google bigquery"
} |
How to print from nested map in Dart
I want to print score value only
void main() {
List questions = [
{
'questionText': 'What\'s your favorite color?',
'answers': [
{'text': 'Black', 'score': 10},
{'text': 'Red', 'score': 0},
{'text': 'Green', 'score': 0},
{'text': 'White', 'score': 0},
],
},
];
I tried to do
print(questions[0]["score"])
But it doesn't work. can anyone help me please | When you access `questions[0]` you are getting the first element in the array, which in this case is:
{
'questionText': 'What\'s your favorite color?',
'answers': [
{'text': 'Black', 'score': 10},
{'text': 'Red', 'score': 0},
{'text': 'Green', 'score': 0},
{'text': 'White', 'score': 0},
],
}
When you then write `questions[0]["score"]` you are trying to get the key `score`, which as you can see is `null`.
You should instead access `answers` inside the object, take a look at the examples below:
print(questions[0]["score"]); // null
print(questions[0]['answers'][0]['score']); // 10
print(questions[0]['answers'].map((answer) => answer['score'])); // (10, 0, 0, 0) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "dart"
} |
how to change displaying order of products in wp ecommerce
I am working on a wp-ecommerce enabled site and am trying to change the display order of the products on the product grid page. Any help would be greatly appreciated. | In the WordPress backend select **Settings** | **Store** .
Select the **Presentation** tab.
Scroll down to the **Product Page Settings** section and change the value of the **Sort Product By** dropdown to: **_Drag & Drop_**
Now you are able to click on a product in **Products | Products** , hold it and drag it to the position in which you want it to appear. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "e commerce"
} |
ProcessorContext#header() is Empty
We have kafka stream application. Producer is adding header in kafka message before sending it to Kafka Streaming application.
In Kafka streaming app we are using `AbstractProcessor` and `context.forward(null, Optional.of(event));` to forward message to another topic.
But header is getting lossed. I want header to be as it is from input message to output topic.
`ProcessorContext` Interface. `headers()` method says Returns the headers of the current input record but it's empty in my case though I am sending message with header.
* Returns the headers of the current input record; could be null if it is not available
* @return the headers
*/
Headers headers();
Kafka Stream API Version: 2.3.1 | `context.headers()` shoud be called with in `process()` if using a Processor or `transform()` if using a Transformer. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "apache kafka, apache kafka streams"
} |
Setting variable in a command reading from a pipe
Consider this batch file:
@echo off
echo Separate lines:
set line=previous value
echo new value|set /p line=
set line
echo Same line:
set line=previous value
echo new value|(set /p line=&set line)
Output:
Separate lines:
line=previous value
Same line:
line=new value
Why doesn't the new value assigned to a variable on the right-hand side of a pipe "stick"? | You can't solve this with a pipe, as both sides of a pipe are executed in a new cmd.exe instance.
Therefore your sample `echo new value|(set /p line=&set line)` shows that the text is stored into the line variable and can be output from that instance.
But after the pipe is done, both cmd instances are destroyed and your line variable is lost.
If you want to fetch from pipe input outside your batch file you could use a FOR loop.
@echo off
setlocal EnableDelayedExpansion
set line=original
FOR /F "delims=" %%L in ('more') do set "line=%%L"
echo !line!
Test with
echo New Text | myBatch.bat | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "windows, batch file"
} |
Testing CO₂ for cell culture
I'm am refurbishing some old CO2 incubators. I would like to test the precision of the CO2 sensor. There is a sample port on this incubator.
What sorts of methods are commonly used to measure CO2 in these incubators?
Strangely, the manufacturer of the incubator makes no recommendations.
I need to be able to report the measurement as a percentage. | Found this:
<
Probably what I need | stackexchange-biology | {
"answer_score": 1,
"question_score": 2,
"tags": "cell culture"
} |
SDK Manager - Won't install new packages (install button remains "unclickable")
I have a very annoying problem, when I try to open an imported project with my version of Eclipse, it tells me that I can't do it unless I download the version 21 of something. Then it opens my SDK Manager and when I want to install the new packages to update my version, it's just impossible even after having accepted the terms and conditions.
Here is a picture : !enter image description here
Any help is welcome! Thanks in advance. | try First Clear your cache with `Android SDK Manager--> Tools--> Option-->click on Clear cache` after Refreshing the List by `Android SDK Manager --> Packages --> Reload`
Hope it will Help | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 3,
"tags": "android, eclipse, sdk, package"
} |
Готовсь или готовьсь?
"К сезону готовсь" или "К сезону готовьсь"? | Думаю, "готовьсь" — это форма "готовься", поэтому мягкий знак стоит после _в_. | stackexchange-rus | {
"answer_score": 2,
"question_score": 2,
"tags": "орфография"
} |
How to generate minute intervals between two dates in T-SQL?
I have a table of startTime and endTimes. I need to generate a table of intervals between those two dates in minutes. Here's some sample data:
declare @intervalMinutes int = 10
declare @myDates table (
myId int primary key identity,
startTime datetime,
endTime datetime
)
insert @myDates (startTime, EndTime) values ('2016-07-10 08:00','2016-07-10 09:00')
insert @myDates (startTime, EndTime) values ('2016-07-12 10:00','2016-07-12 12:00')
insert @myDates (startTime, EndTime) values ('2016-07-14 12:30','2016-07-14 14:30')
What I'd like to see is for each `myId` a set of dates of interval `@intervalMinutes`.
So if we had `@intervalMinutes` set to 10 then I'd see for the first row a list of 6 dates between `2016-07-10 08:00` and `2016-07-10 09:00` in 10 minute increments. | A numbers table can solve your problem. Assuming you don't need more than a few thousand rows, then this should work:
with n as (
select row_number() over (order by (select null)) - 1 as n
from master.spt_values
)
select d.*,
dateadd(minute, n.n * @intervalMinutes, d.startTime)
from @myDates d join
n
on dateadd(minute, n.n * @intervalMinutes, d.startTime) <= d.endTime; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "sql server, tsql, sql server 2014"
} |
Warning: Use of undefined constant content - assumed 'content' (this will throw an Error in a future version of PHP)
someone tell me where the error is.
hi, someone tell me where the error is.
hi, someone tell me where the error is.
**default.php**
<div class="container">
<div class="starter-template" style="padding-top: 100px;">
<?= content; ?>
</div>
</div>
**index.php**
<?php
require '../app/Autoloader.php';
App\Autoloader::register();
if(isset($_GET['p'])){
$p = $_GET['p'];
}else{
$p = 'home';
}
ob_start();
if($p==='home'){
require '../pages/home.php';
}elseif($p==='single'){
require '../pages/single.php';
}
$content=ob_get_clean();
require '../pages/template/default.php';
**home.php**
<h1> I am in home page </h1> | `<?= content; ?>` replace with `<?= $content; ?>` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "php"
} |
Unable to Generate UITextField dynamically in place of UILabel?
I am trying to generate UITextField dynamically in place of UILabel. Now i want to update that data. I am displaying data in the UILabel from the database and there is an UIButton for editing. When i click on that UIButton UITextField should be generated in place of UILabel and also data should be displayed in UITextField. | What you can do is to design a view with all textfield which works in two modes, first readonly (by setting userInteraction to false ) and second editing mode. This way you can avoid the use of labels. This will need only one edit button for all of the fields. if you still want to stick with your approach, you can hide the labels, use their frames to create textfields at their place and make them visible as long as you are working in edit mode. Don't forget to use
[self.view bringSubviewToFront:TEXT_FIELD];
While you add them to your view. e Managing the editing with the approach I mentioned earlier is mor easy and require less efforts. Hope it helps | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "iphone, objective c, ios, cocoa touch"
} |
jQuery Mobile border on select text input
I have seen one very cool effect on this site: <
Here if you open it with some mobile phone (I have android) and if you select the input box, then there is no border coming, only the textbox is highlighted blue. When I create an input text box, then on my phone is coming one orange border, when I select the text box.
I have searched how to disable this, but found nothing. Is there some option, how to disable this orange border an make it like the site above? | You must edit JQM css file. Depending on a chosen theme (a - f, or more if you used theme generator find and edit border outline around selected items.
If remembered it correctly there is only one property per theme.
Got it, search css file and look for: .ui-btn-active, comment background and background-image, or change it to any color you prefer.
Also regarding your last posts you can find a lot of good stuff here. It will show you how to do a lot of customizations to JQM css. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "jquery, jquery mobile"
} |
JavaScript for loop "document.getElementById"
Hi I am trying to go throw radio buttons using a for loop , with ID of "Group" and get the value of it show out here is my code but it doesnt alert the value of them on submit,
< | HTML:
<input type="radio" id="group1" name="group" value="1" />
No Changes<br/>
<input type="radio" id="group2" name="group" value="2" />
Gray Scale <br/>
<input type="radio" id="group3" name="group" value="3" />
Old Style<br/>
<input type="radio" id="group4" name="group" value="4" />
Sharpening<br/>
Script:
var ims = document.getElementsByName("group");
for(var i = 0; i < ims.length; i++){
ims[i].onclick = function(){alert("hi");}
}
< | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -2,
"tags": "javascript, for loop"
} |
Can I delete the .Spotlight-V100 file
I don't need spotlight. I read this:
Can't locate /.Spotlight-V100 anywhere, spotlight has incomplete results even after index rebuild
Here's a picture of my spotlight thing, which was only visible when I paid the $10 for daisydisk
.
**Why can I teleport out from underground while he is unable to do so?**
**Edit** : I'm able to teleport out from any depth, with or without a wall behind me. | Assuming you're both on same depth level, you most likely didn't have a wall behind you (RMB with the tool to break it down).
You can't teleport to ship from within buildings, which mainly just means you can't teleport if you have a wall behind you.
Edit: An update in 2016 made it possible to beam to ship from any depth with walls behind you if your character is in **casual mode.** | stackexchange-gaming | {
"answer_score": 6,
"question_score": 5,
"tags": "starbound"
} |
Knockout binding iteration
I am having a scenario where based on the Observable flag I need to iterate ABC and XYZ
Current Code
<div data-bind="visible: isEnabled">
<ul data-bind="foreach: relatedObservalableArray">
<li>
<!-- Hundred lines of code>
</li>
</ul>
</div>
<div data-bind="visible: !isEnabled">
<ul data-bind="foreach: unRelatedObservalableArray">
<li>
<!-- Same Hundred lines of code>
</li>
</ul>
</div>
I am feeling code duplicate.
Is any way I can group the two html functions to a single one?
I want to change only in HTML part due to some other ...
I am new to Knockout. Can someone help me? | Sure you can use the knockout `template` binding for this. Read it more here.
So for the changes it would be something like below but you can do variations basing on what you read from the link I gave.
<script type="text/html" id="template-name">
Hundred lines of code...
</script>
<div data-bind="visible: isEnabled">
<ul data-bind="foreach: relatedObservalableArray">
<li data-bind="template: 'template-name'">
</li>
</ul>
</div>
<div data-bind="visible: !isEnabled">
<ul data-bind="foreach: unRelatedObservalableArray">
<li data-bind="template: 'template-name'">
</li>
</ul>
</div> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "knockout.js, knockout 3.0, knockout binding handlers"
} |
How to create a "X" terminated string in C?
I'm trying to create a counter that counts the amount of characters in a string before "?". I have issues with using strcmp to terminate the while-loop and end up with a segmentation fault. Here's what I have:
void printAmount(const char *s)
{
int i = 0;
while ( strcmp(&s[i], "?") != 0 ) {
i++;
}
printf("%i", i);
} | Don't use `strcmp` for this. Just use the subscript operator on `s` directly.
Example:
#include <stdio.h>
void printAmount(const char *s) {
int i = 0;
while (s[i] != '?' && s[i] != '\0') {
i++;
}
printf("%d", i);
}
int main() {
printAmount("Hello?world"); // prints 5
}
Or use `strchr`
#include <string.h>
void printAmount(const char *s) {
char *f = strchr(s, '?');
if (f) {
printf("%td", f - s);
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c, string, pointers, strcmp"
} |
Factoring N with encryption keys
I need help on part c
Assume $N = pq$ where $p$ and $q$ are distinct odd primes.
(a) If $d \equiv e^{-1}$ modulo $\phi (N)$ , show $ed - 1$ is an even number:
$ed\equiv 1$ modulo $\phi (N)$
$ed - 1 \equiv 0$ modulo $\phi (N)$ and since $\phi (N)$ is even for n > 2 we have $ed - 1 = 2k$
(b) If $gcd(m, N) = 1$, what is $m^{ed - 1}$ modulo N ?
$m^{ed -1}$
$m^{ed} m^{ -1}$
$mm^{-1} \equiv 1 $ modulo N
(c) If $ ed -1 \equiv 2^nL$, $ n \in \mathbb{N}$ and L is odd. If m has the property $m^L \not\equiv \pm 1$ modulo N and $m^{2L} \equiv 1$ modulo N. How can you find the factors of N?
For this question I'm not sure how to start it any help is appreciated | > For part $(c)$, I think the problem is going for the following idea:
>
> Suppose that $m^{L} \not \equiv \\{ \pm 1\\} \pmod{N}$, and $m^{2L} \equiv 1 \pmod{N}$. Then $0 \ne m^{2L}-1 = (m^{L}-1)(m^{L}+1) \equiv 0 \pmod{N}$. Then:
>
> $\\{ gcd(N,m^{L}+1) , gcd(N,m^{L}-1)\\} = \\{ p,q \\}$ for $N = pq$ because $m^{L}+1 , m^{L}-1 \ne 0$ and $m^{L}+1 , m^{L}-1$ each contain exactly one but not both prime factors by the assumption that $m^{L} \not \equiv \\{ \pm 1\\} \pmod{N}$.
>
> Let me know if you have any questions. | stackexchange-math | {
"answer_score": 2,
"question_score": 3,
"tags": "number theory, elementary number theory, cryptography"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.