INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Does Ford's heated windscreen/windshield normally drain excessive current?
When getting my battery tested for an issue in this post, the mechanic noted that when my Ford's "quickclear" windscreen heating element was activated and the engine running, the voltage coming from the battery dips, whereas this doesn't happen with other accessories.
The voltage dipped and continued to decrease. You could see the headlights dim, and if the blowers were on the speed decreased as you could tell by the sound. Using another accessory, for example the rear window heater only caused a momentary dip, and then the voltage stabilised.
Is this normal behaviour for the heated windscreen? The mechanic was convinced this was abnormal and should be looked at. Also, if there is a fault with the windscreen, is this likely to cause any battery drain when the car is off? | I took it to a main dealer who diagnosed that the battery needed a replacement.
Now a quick test with the blowers doesn't seem to show any voltage loss as before. | stackexchange-mechanics | {
"answer_score": 2,
"question_score": 11,
"tags": "ford, heat, windshield"
} |
facelets-taglib-jsf20-spring-3 missing
Hi we used to include this dependency in our project
<repository>
<id>org.springframework.security.taglibs.facelets</id>
<url>
</repository>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>facelets-taglib-jsf20-spring-3</artifactId>
<version>0.5</version>
</dependency>
somehow it is gone now in maven repository. Does anybody know why and where it has gone? | Recently the spring-security- facelets - taglib library was moved from GoogleCode to GitHub .
Google also provided the Maven repository and it was used in the projects.
Unfortunately the library has not yet been moved to another repository, but already we contacted the author, and will be placed in the central Maven repository in the coming days. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "maven"
} |
Apex Batch - Is execute method called if start returns 0 results?
I want to know if the execute method in a batch is still called if the query in start() returns 0 records.
I put debugs in the beginning of the execute method, I know start will not return any records but i still need execute to fire.
I'm I on a fool's errand? | No. Execute will not be called unless at least one non-null item is available for processing. You'll have to come up with an alternative method. As a corollary to this statement, "scope" will never be empty or null, because execute won't be called if there's nothing to do. | stackexchange-salesforce | {
"answer_score": 13,
"question_score": 9,
"tags": "apex, batch, schedulebatch"
} |
Call subapp route within Padrino app
I would like to call a route that is mapped to a sub app within a given Padrino app. What is the best way to do this? For example, say I need to call `/subapp/create` as part of running `/mainapp/create`. I do not want to simply link to it, but actually call it and use the result. Thank you! | You cant, as for rails render_controller is dead.
You can workaround with an "old" iframe.
You can call links from others app like:
MainApp.url :backend, :index | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ruby, sinatra, padrino"
} |
Wdproj won't open
I just switched to Windows7 Professional 64 bit from Vista Ultimate 32 bit. I reinstalled all Visual Studio 2008 Professional and applied SP1. All is working well except I can't open a solution that contains a **wdproj** file. I found this link (and a bunch of others scraped from Microsoft) with a similar problem. They suggested using calling "devenv.exe /setup", "devenv.exe /InstallVSTemplates" and "devenv.exe /ResetSkipPkgs". Any idea what I should do?
alt text | It turns out I needed to install this msi. One of my coworkers reminded me. | stackexchange-stackoverflow | {
"answer_score": 15,
"question_score": 14,
"tags": "visual studio 2008, wdproj"
} |
How to forward every request from CloudFront to origin S3
I read
> If you configure CloudFront to forward all headers to your origin for a cache behavior, CloudFront never caches the associated objects. Instead, CloudFront forwards all requests for those objects to the origin. In that configuration, the value of Minimum TTL must be 0.
now I set min TTL on 0 and tried to forward all headers I get an error from CloudFront: You can not choose to forward all headers with an S3 origin.
How can I make every request check the s3 origin (so that new objects in the buckets are updated in the CloudFront immediately) | You can't forward all headers to S3 unless your bucket name matches the domain name, exactly, and even then it isn't recommended.
Instead, set Minimum TTL, Default TTL, and Maximum TTL _all_ to 0.
Default TTL is used when the object is stored in the bucket without a `Cache-Control` value defined. Maximum TTL is used when `Cache-Control` specifies a non-zero TTL (CloudFront will coerce any larger value _down_ to Maximum TTL for its internal purposes). Minimum TTL should always be set to 0 except in very rare cases.
Note that changing these values requires an invalidation, or objects already in the cache may use prior values.
* * *
Or, when writing objects to the bucket, add `s-maxage=0` to the `Cache-Control` header value and ensure that Minimum TTL is set to 0. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "amazon web services, amazon s3, amazon cloudfront"
} |
Alternative for https://gdata.youtube.com/feeds/api/videos/<video_id>?v=2
These days I noticed that Youtube API which I'm using on my project is no longer available, e.g.
<
returns HTTP 410 response code which means that requested resource is no longer available and will not be available again.
What should I use instead? | If I'm understanding your question correctly then you should be using ` from now on.
Google shutdown the old API effective April 20th, 2015.
Take a look at the newest v3 API getting started. | stackexchange-stackoverflow | {
"answer_score": 57,
"question_score": 38,
"tags": "youtube api, http status code 410"
} |
php created ICS file shows HTML taggs in description
I'm working on a php class that wil extract data from a SQL table to a ICS file for microsoft outlook.
here is the code in dpaste, it will last for a year.
And here is the code that calls the class to create a appointment
It almost works except de description has all the HTML tags in it see this screenshot:
Has anyone a idea how to fix this?
!enter image description here | You seem to have a CRLF and spaces right before the X-ALT-DESC parameter so the client is handling it as part of the DESCRIPTION text, not as a parameter. You should remove all unnecessary CRLF and spaces in your code.
Then, you are aware that this X-ALT-DESC parameter is not standard at all. Other clients will probably show the html tags as well. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, icalendar"
} |
How can I preserve wooden sculptures indoors?
I recently bought this wooden sculpture from Mexico:
 is there anyone who has done this before or knows of any free open source software that we can use to achieve this?
Thanks | Write a kickstart for it, then use Cobbler to do the actual install. | stackexchange-serverfault | {
"answer_score": 1,
"question_score": 0,
"tags": "linux, fedora, disk image"
} |
Initial Value Problem.....
In the plane $(x,y)$ find two solutions of initial value problem:
$\frac14u^2_x+uu_y=u $
$u(x,\frac12x^2)=-\frac12x^2$
I am trying to use the method of characteristics, but i am not getting right way
please could you help me.. Thanks in Advance.. | Assume a solution u of the form f(x) g(y) to get
(f')^2 g^2 / 4 + f^2 g g' = f g.
Divide by f^2 g to get
1/4 (f'/f)^2 g + g' = 1/f, so
g' = 1/f - 1/4 (f'/f)^2 g.
Think of y as the independent variable and x being held constant. This last equation is a simple differential equation in g which is easily solved. In fact the solution to
g' = b - a g is g = b/a + c exp(- a y), where c is any constant.
Apply this to the formula above to get a general solution to the original pde. Then substitute for the specific condition.
Justin: When I look back at this I see that there is a problem with it, namely g is assumed to be a function only of y, not of x, but it is clearly a function of x. This solution is flawed. Sorry. If I see how to fix it I will write more.
Jim | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "partial differential equations"
} |
How to create iText BaseFont based on InputStream
I have a font file "arial.ttf" in a web application and I can only obtain its contents as `InputStream`.
InputStream inputFont = getResourceAsStream("/resources/arial.ttf");
How can I create an iText `BaseFont` based on the `InputStream`? The `createFont` method doesn't accept it.
BaseFont bf = BaseFont.createFont(inputFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
> createFont(InputStream,String,boolean) can't invoke createFont(java.lang.String,java.lang.String,boolean) in BaseFont. | Try something like the following:
byte[] bytes = IOUtils.toByteArray(Thread.currentThread().getContextClassLoader()
.getResourceAsStream("/resources/arial.ttf"));
BaseFont.createFont("arial.ttf", BaseFont.IDENTITY_Harial.ttf, BaseFont.EMBEDDED, true, bytes, null);
You have to specify the **.ttf** in the font name to tell the method it should interpret it as ttf format. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 6,
"tags": "java, fonts, itext, inputstream"
} |
Fastest way to sort object's array based on other's object's array property
I've got two objects arrays and both of them have columnId property. I want to make the order of the first object's array same as the order of the second.
I've tried this:
filtered = visibleColumns.filter(function(v) {
return filtered.includes(v.colId);
});
where `filtered` is my result array and `visibleColumns` is array which order I need, but it doesn't work.
example of arrays:
filtered = [{
colId:1,
title: 'col1',
size: 10
},
{
colId:2,
title: 'col2',
size: 10
}];
visibleColumns = [{
colId:2,
visible: true
},
{
colId:1,
visible: true
}]; | You could create an object with the wanted order and take a default value for unknown id for sorting them to bottom.
var filtered = [{ colId: 1, title: 'col1', size: 10 }, { colId: 2, title: 'col2', size: 10 }],
visibleColumns = [{ colId: 2, visible: true }, { colId: 1, visible: true }],
order = visibleColumns.reduce((o, { colId }, i) => (o[colId] = i + 1, o), {});
filtered.sort((a, b) => (order[a.colId] || Infinity) - (order[b.colId] || Infinity));
console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; } | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript, arrays, typescript"
} |
Unexpected Identifier When Trying To Insert HTML With Javascript/jQuery
I'm getting an "Unexpected Identifier" error, but looking at my code, I just don't see my issue.
$(document).ready(function () {
if ((window.location.pathname + window.location.search) === '/search/label/Design-Work')
$( '#main-footer' ).append('<audio id='music-song' preload='auto'><source src='/audio/music_i-remember.mp3' type='audio/mpeg'/><source src='/audio/music_i-remember.ogg' type='audio/ogg'/></audio>');
});
My goal in using this script was to insert HTML on certain search pages in case anyone asks. | $(document).ready(function () {
if ((window.location.pathname + window.location.search) === '/search/label/Design-Work') {
$( '#main-footer' ).append("<audio id='music-song' preload='auto'><source src='/audio/music_i-remember.mp3' type='audio/mpeg'/><source src='/audio/music_i-remember.ogg' type='audio/ogg'/></audio>");
}
});
In your `append` function you used single quotes (`'`) which you also used in your `id=''` thus ending the string within your `append` function. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": -1,
"tags": "javascript, jquery"
} |
What is the purpose of changing "Nürnberg" to "Nuremberg" in English language?
For the longest time ever I assumed these are two different places and was very confused about never knowing where Nuremberg is. Recently I found out that _Nuremberg_ is the English form for _Nürnberg_.
Is there a known first documented mention or some other historical evidence which may point to the purpose of this change? | The English spelling reflects an older form of the name, as in mediaeval Latin Nuremberga, or Norimberga. In the local Frankish dialect the town in still called Närmberch. So really your question should have been "What is purpose of changing Nuremberga to Nürnberg?" | stackexchange-english | {
"answer_score": 7,
"question_score": 1,
"tags": "loanwords, toponyms"
} |
Remove registry key during uninstall
I have a simple C# application that allows users to specify that it should be (or should not be) started with Windows; it does so by setting (or deleting) a registry key (namely, ...\Software\Microsoft\CurrentVersion\Run\MyApplicationHere).
I am using a VS setup project to create the installer for this program. I don't want the installer to create this key; it should only be created when the user selects the option from within the program.
Here is the issue: I would like the uninstaller to delete this key if it exists, preferably without resorting to any sort of hackery; if there is a simple "built-in" solution I would love to hear it. Thanks! | The Registry table is designed for this:
<
See especially under the description of "Name":
_If the Value column is Null, then the strings shown in the following table in the Name column have special significance._
**\- The key is to be deleted, if present, with all of its values and subkeys, when the component is uninstalled.** | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 5,
"tags": "visual studio, windows installer, installation, registry"
} |
webcrawler bots load test my website and it fails the test
we run a commerical website with a relavitely few number of customer at any one time ~30 users .
Frequently a webcrawler such as google bot, bing bot, and 80legs will bring our site to a grinding halt. Altering robots.txt does not have an immediate effect. Is their anyway to stop 80legs instantly ? It is using different ip's. | From <
> How do I slow down 008 when crawling my site?
>
> The easiest solution is to contact us and let us know at what rate you would like us to throttle crawls on your site (in terms of requests/second).
Of course you can also check for the User-Agent and rate limit and/or block these requests completely. | stackexchange-serverfault | {
"answer_score": 1,
"question_score": 0,
"tags": "tomcat, robots.txt"
} |
XPath Query (with some simple regex restrictions)
Consider I got the following piece of XML?
<result>
<_id>-3:1</_id>
<_ver>0</_ver>
<_class>Address</_class>
<type>Residence</type>
<street>Piazza di Spagna</street>
<city>-4:0</city>
</result>
What would be the xpath to query each of the following:
1. For all tags that are not beginning with “_”. So I would expect something like: type, street, city
2. The text body for all tags that are not beginning with “_”. So I would expect something like: Residence, Piazza di Spagna, -4:0 | **Using XPath 1.0** (and, of course, this is also XPath 2.0 solution):
1. `/*/*[not(starts-with(name(), '_'))]`
2. `/*/*[not(starts-with(name(), '_'))]/text()` | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "xml, regex, xpath"
} |
error in imports of import com.google.android.maps.MapActivity;
Hello i want to run this tutorial but i getting error on importing
import com.google.android.maps.MapActivity;
import com.google.android.maps.GeoPoint;
Although i have updated available packages | Have you changed your build target to use the Google API form of your API level? | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "android"
} |
svn 1.7 error E200009 Could not add all targets because some targets are already versioned
I did a clean checkout of a repository then every day I have an hudson job that runs a script to backup the configuration. Part of the script is to add `*.xml`
$ svn add *.xml
svn: warning: W150002: '/data/hudson/config.xml' is already under version control
svn: E200009: Could not add all targets because some targets are already versioned
svn: E200009: Illegal target for the requested operation
The warning is fine because some of the xml files are already under version control but I don't understand why I get the `E200009` error. If there is nothing to add, there should be no error. | Seems like the correct behaviour for SVN 1.7. An alternative is to add only unversioned files:
svn st *.xml | grep ? | tr -s ' ' | cut -d ' ' -f 2 | xargs svn add
However it's possible you have nothing to add, so you will get
svn: E205001: Try 'svn help' for more info
svn: E205001: Not enough arguments provided
Related question: Add all unversioned files to Subversion using one Linux command | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 18,
"tags": "svn"
} |
What does the icon next to your squad leader's name mean?
Most of the times (always?) there is an icon next to the squad leader's name (see picture below). I'm not talking about the class icon which is visible for all squad members, but rather the icon between the class icon and the name. Sometimes this is a star but I've also seen it be what looks like an ammo clip as well as a bomb blast or something.
It _seems_ to indicate some sort of upgrade the user has attached but I'm not sure I'm correct. An also, what is the reasoning behind:
* What upgrade is shown - you typically have multiple upgrade/perks available at any given time
* Why only for the squad leader? Isn't it just as interesting to see this information for all members of the squad?
!Battefield 3 HUD
(note: I found this image online, it looks slightly different on my ps3) | If it is a star, then it means that they are the squad leader. If it is an ammo clip or something like that, then that means that this person has a squad perk equipped. =ax(t)+by(t)\\\y(t+1)=cx(t)+dy(t)\end{cases}$$
What is the differential equation associated with the above difference equation?And what is the reason of such association? What about if the coefficient are not constant?May you give a reference for more materials on such topics?Thank you. | To do this, you need to construct a derivative from the pieces you have $$\frac{dx}{dt} \approx \frac{x(t+\Delta t)-x(t)}{\Delta t}$$ For the difference equation, $\Delta t=1$, so this translates to $$\frac{x(t+1)-x(t)}{1}=\Delta x$$ So for the first equation, you need to move a $1x$ over the left side, yielding $$\frac{dx}{dt} \approx x(t+1)-x(t)=(a-1)x(t)+by(t)$$ | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "linear algebra, ordinary differential equations, recurrence relations"
} |
EB Deploy to multiple environments
I have the same codebase (one git repository) that I want to upload to multiple elastic beanstalk environments. Is there a way to do this, and if so how should I set up my repository in such a way that I can push to multiple environments?
The environments are different language versions of the site, that I want to run in different beanstalks. The language is set by the environment parameters. | To answer my own question. The AWS EB CLI 3+ has a nice interface to deploy to multiple environments. If you add another environment to your application you can simply deploy by using
eb deploy <environment-name> | stackexchange-stackoverflow | {
"answer_score": 24,
"question_score": 17,
"tags": "amazon web services, amazon elastic beanstalk"
} |
How to verify that code you write is not copyrighted anywhere?
Is there any guidelines how to make sure that code you write won't be copyrighted anywhere? I meet sometimes situations where I write code that does some particular small thing but there is a similar code on the Internet without licenses. Then I need to think alternative more unnatural solution or how to modify the code more messier to avoid copyright issues. | Don't worry about "similar" code. Copyright is about copying, not about similarity. If you wrote it independently of any other, then there shouldn't be an issue.
But there is also the rule that in some situations there is "only one way" to say something. So if some phrases (or coding patterns) appear in several places it isn't evidence of infringement. The number of ways you can write an iteration through a list is pretty small, after all. Problems recur in computing. So the "natural" programs that solve them also recur.
Also, copyright is about publishing. If you don't publish your code then it won't be an issue either. | stackexchange-cseducators | {
"answer_score": 1,
"question_score": 1,
"tags": "programming"
} |
Analytics Api how to get the time the event occurred?
is there a way to get the time the event occurred (using analytics api)?
I cannot see it in any of the metrics, or find a way to do it. | You can query ga:datehour and ga:minute to save on dimensions since a single API request is limited to 7 dimensions. So, you will only be missing the second of the occurence | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "google analytics, google analytics api"
} |
Swift : How to have 2 different cells in 1 tableView
I want to have 2 different cells in my table view.
For example :
1. My first cell have 1 image view and 1 label.
2. My second cell have 4 images views and 4 labels
It's possible ? How can I do that?
Thanks. | Create two custom `UITableViewCell` and and register them with tableView with cellIdentifiers like "CellType1" and cellType2 and then you can do something like this in cellForRowAtIndexPath
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = nil;
if(indexPath.row == 0)
{
// first row, return cell you want
cellIdentifier = @"CellType1";
}
else
{
// other rows you can return cell you want
cellIdentifier = @"CellType2";
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
return cell;
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -4,
"tags": "ios, xcode, swift"
} |
shall I set a function which would run automatically when user open an existed record?
In the model, I have defined a function 'FOO'; a user creates a record 'X' of this model and saved it.
after that, I want the function 'FOO' would run automatically once the user opens the existed record 'X'; is this possible? | They Have Two Options,
Option 1:
You can use `fields_view_get` method. Try below code maybe it helps you
@api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False,
submenu=False):
res = super(Project, self).fields_view_get(
view_id=view_id, view_type=view_type, toolbar=toolbar,
submenu=submenu)
# add here your condition
return res
Option 2:
You can use the compute method but in your case, this method not depends on any field mean you can use `@api.multi` in place of `@api.depends`
Thanks | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, odoo"
} |
Get value to display as checkbox - not T or F
In design mode in management studio I have added a row to the table 'Checked', it has a 'bit' as a data type, and is stored as either true or false.
I can get this to display fine on screen(Using a repeater), however instead of displaying true or false, I want to use a check box, which is ticked or unticked depending on T or F.
aspx:
<th style="width:200px;"><%# Eval("Checked") %></th>
Behind:
DBData db = new DBDatat();
List<Select_Utility> SelectedUtility =
(from SU in db.Select_Utilities
where SU.Work_Id == 3
select SU).ToList();
rptSelectedUtilities.DataSource = SelectedUtility;
rptSelectedUtilities.DataBind(); | you are doing correct. instead of plain text, replace with checkbox
<th style="width:200px;">
<asp:CheckBox ID="chkMyCheck" runat="server"
Checked='<%# Convert.ToBoolean(Eval("Checked")) %>'/>
</th> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "asp.net, checkbox"
} |
Search a string which contains backslash using Grep command
In the tail output i have following string...Using grep command how can i search for the string `"contentState\":\"STOPPED\"`. I have to search for the whole string `"contentState\":\"STOPPED\"` rather than searching for STO`P`PED or `contentState` only.
I tried following command: But it is not working.
grep -e ""contentState\":\"STOPPED\" /opt/logs/out.log | tail -1
{\"eventType\":\"appAction\",\"action\":\"CONTENT_STATE_CHANGE\",\"evt\":{\"contentState\":\"STOPPED\"}}} | To search for `"contentState\":\"STOPPED\"`, you need to (a) put the whole string in single-quotes to protect it, and (b) escape (double) the backslashes. Thus:
grep -e '"contentState\\":\\"STOPPED\\"' /opt/logs/out.log
Without the protection provided the outer single-quotes, the unescaped double-quotes would be subject to the shell's _quote removal_ and `grep` would never see them.
### Example
Consider this test file:
$ cat log
good "contentState\":\"STOPPED\"
bad contentState\":\"STOPPED\"
bad "contentState\":\"STOPPED"
Let's run our command:
$ grep -e '"contentState\\":\\"STOPPED\\"' log
good "contentState\":\"STOPPED\"
As we can see, the good line is returned and only the good line. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "grep"
} |
Months Appear in Backwards Order
I have a data frame, lets call is `month`, that includes a column called `date` that has the month in which each observation occured. When I was making a graph in plotly the months appeard in alphabetical order instead of in sequential order so to correct that I used the following:
month$date <- factor(month$date, levels = unique(as.character(month$date)))
However, when I did this the months appeared backwards, that is December to Janurary instead of January to December. How can I correct this? | It is ordering in the occurrence of unique 'date' elements in the 'month' column . If the 'date' column includes the full name of 'month', then make use of the default 'month.name' `vector` which is already in the correct order, specify that in the `levels`
month$date <- factor(month$date, levels = month.name)
where
month.name
#[1] "January" "February" "March" "April" "May" "June" "July" "August" "September"
#[10] "October" "November" "December"
EDIT: Based on @GregorThomas comments | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "r, date"
} |
How to access (mysql) host port from docker container?
I have a host that runs a native `mysql` installation (not a container).
From a `docker` container I now want to connect from a `java` `spring-boot` application to that port (`3306` by default).
But it does not work:
`docker-compose.yml`:
version: '3.7'
services:
customer-app:
ports:
- "3306:3306"
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://localhost:3306/db
Result from `docker-compose up`:
Cannot start service customer-app: driver failed programming external connectivity on endpoint:
Error starting userland proxy: listen tcp4 0.0.0.0:3306: bind: address already in use
This is probably not a question directly to a java application, but more general:
How can I access a port on the _host_ system from inside a _docker container_? | I added the following to `docker-compose.yml`:
extra_hosts:
- "host.docker.internal:host-gateway"
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://host.docker.internal:3306/db | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "docker, docker compose"
} |
Is it possible to block requests for my MAC address?
If a java application makes a request for my MAC address can I block it in any way? Are there any security programs which can do this?
\-- What I am asking is if there is anyway I can prevent Java applications from knowing my MAC address. | Unless you do not want network connectivity, then it's not possible. Furthermore blocking for a specific application is not possible.
A MAC address is requested using ARP. ARP is a layer 2 protocol (arguably layer 2.5). ARP is used to allow connectivity between you and a router (which is a layer 3 device). An application is located at layer 7, which is the top of the OSI model.
ARP is nescesary to allow local layer 3 connectivity. It's used to know which devices are on the LAN network.
If you are concerned about people knowing your MAC address, then this means you are allowing some malicious entity onto your network. To prevent this you can use 802.1x, which is the Port-based Network Access Control. This works both for physical as wireless networks.
If you are not in control of the network, then there is little you can do. | stackexchange-security | {
"answer_score": 6,
"question_score": 0,
"tags": "mac address"
} |
regex help: Replacing characters
I want to change characters in a json file. I tried some commands but didn't find a solution.
Input:
{
"cpu" : 0.0789131391278358,
"disk" : 0,
"diskread" : 18524238336,
"diskwrite" : 26161936516096,
}
Output:
{
"{#cpu}" : 0.0789131391278358,
"{#disk}" : 0,
"{#diskread}" : 18524238336,
"{#diskwrite}" : 26161936516096,
}
How is the correct regex command for sed? | sed 's/\"\(\w\+\)\" :/"{#\1}" :/g' | stackexchange-superuser | {
"answer_score": 0,
"question_score": 1,
"tags": "regex, sed"
} |
vim - экспанд слова под курсором
Чтобы искать по файлу в vim'e, я обычно делаю так:
1. Нажимаю `/`
2. Ввожу требуемый паттерн поиска - например, слово `function`
3. Нажимаю `enter`, и дальше уже двигаюсь по результатам поиска.
Как бы исключить из этого списка пункт2 :) Допустим, у меня курсор стоит на первой букве слова `function`, требуется комбинация (биндинг в `.vimrc`), которую можно нажать - и слово автоматом добавится в буфер поиска. | Алгоритм следующий:
1. Наводите курсор на слово
2. Нажимаете `*`
3. vim переходит к его следующему вхождению.
Как справедливо отметил **KoVadim** , вместо `*` можно использовать `#`, тогда поиск будет идти в обратном направлении.
Также тут описан способ по поиску и замене слова под курсором. | stackexchange-ru_stackoverflow | {
"answer_score": 7,
"question_score": 5,
"tags": "vim"
} |
Why we can't write in air?
Why we always require a surface to write something? Why we can't write in air?
I think that it is due to friction but I am not sure about it.
**Edit**
As per helpful comments and responses, I think there is a confusion about this question here. **By the term "write'' I meant writing something on the surface of air with a pen**.
It is quite non intuitive to write with a pen in air but my main motive to ask this question was to know the reason of non capability of words being unprinted on the **surface of air** when we **sway** our pen/pencil in air.
Sorry for grammatical errors because I belong to a non English speaking nation.By **surface of air** I meant a small **section** of air. | Writing is nothing more than sticking a bunch of atoms in a particular shape either on top of other atoms or placing one kind of atoms in the voids created by others. For them to stay longer at a fixed place, we need a strong affinity between the said two kinds of atoms. Also, we need to differentiate them, so we need a sharp contrast in color.
We write usually on a sheet of paper using ink because the ink sticks to paper. It has a high affinity for the medium it's being applied to. Since the ink is wet it will also be absorbed by the paper. Usage of graphite pencil or other such substrates is primarily due to similar reasons.
Can the same be done with air molecules? Are the interacting forces strong enough to hold them for long periods of time? | stackexchange-physics | {
"answer_score": 6,
"question_score": 4,
"tags": "newtonian mechanics, friction, everyday life"
} |
SQL Server select where datetimeoffset older than 1 hour
I know this should be easy and I do it no probelms in mySQL and Postgresql but I'm struggling with SQL Server. I want to select rows with a datetimeoffset field that's over an hour old.
select * from table where mydatetime < getdate() - 1 hour
I've tried dateadd and datediff but can't get it right. | WHERE mydatetime < DATEADD(hour, -1, SYSDATETIMEOFFSET())
For more see: DATEADD (Transact-SQL) | stackexchange-stackoverflow | {
"answer_score": 27,
"question_score": 8,
"tags": "sql, sql server"
} |
Exact solution to equation
I am trying to find out how to get some form of exact nonzero solution with isolated x for the equation $x^2 = \sin x$. I am pretty sure my TI 89 is using Taylor series expansions to solve this because it will not give anything but a decimal approximation. I am thinking Euler's formula needs to be used in some capacity but I have tried several things and cannot find a way to isolate $x$. | Imagine a graph of $y = x^2$ and $y = \sin x$. Obviously x = 0 is a solution, the other solution is near $x = 1$. You can then use any numerical methods to get close to the actual solution for the one near $x = 1$. Once you have imagined or drawn the graph, you know that these are the only two solutions. 3 iterations of a numerical method gave me $0.876$ as the other solution | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "trigonometry"
} |
pyodbc (4.0.23) error connecting to MySQL from Python3
I tried to connect mysql via pyodbc, same code works on python2, but I get an error on python3.
here is my code:
_protocal = 'DRIVER={/usr/local/lib/libmyodbc5.so};SERVER=127.0.0.1;
PORT=3306;DATABASE=learn;UID=root;PASSWORD=root'
conn = pyodbc.connect(_protocal)
cursor = conn.cursor()
test_sql = 'select * from students'
cursor.execute(test_sql)
here is the error message on python3:
Traceback (most recent call last):
File "temp.py", line 82, in <module>
main()
File "temp.py", line 71, in main
cursor.execute(test_sql)
pyodbc.Error: ('HY000', '[HY000] [MySQL][ODBC 5.1 Driver][mysqld-
5.7.18]Querywas empty (1065) (SQLExecDirectW)')
Thanks for help. | The last revision of MySQL Connector/ODBC 5.1 was released over five (5) years ago. Upgrading the driver to the latest GA version (5.3.10) and upgrading iODBC appears to have resolved the issue. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "python, pyodbc"
} |
decipher this modified sum operation,
This is crossposted from Math.SE, the original question is here
$1+2+3+4 = 61$
$2+3+4+5 = 52$
$3+4+5+6 = 51$
$4+5+6+7 = 50$
$7+8+9+10 = ?$ | \begin{align}7+8+9+10&\to\text{Seven}+\text{Eight}+\text{Nine}+\text{Ten}\\\&\to\text{S}+\text{E}+\text{N}+\text{T}\\\&\to\text{Alphabet}_{19}+\text{Alphabet}_{5}+\text{Alphabet}_{14}+\text{Alphabet}_{20}\\\&\to19+5+14+20\\\&=58\end{align} | stackexchange-puzzling | {
"answer_score": 3,
"question_score": 2,
"tags": "mathematics, number sequence, formation of numbers"
} |
Removing Commits in Git
Is there any option to remove these commits from my branch and back into normal? I have this status now:
Your branch is ahead of 'origin/release' by 4545 commits. (use "git push" to publish your local commits)
I don't want to push the changes into the origin. I am not sure what happened with my branch and got all of these commits. | when you are currently on the branch itself
first back up your branch with another copy by creating a new branch from it `git checkout -b release_backup`
then you can just delete the branch `git branch -D release`
then `git checkout origin/release`
you will get a warning that you are on a detached head
now you can `git checkout -b release` to create a local copy from the branch | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "git"
} |
Find the acute angle of intersection of the curves $y=\cos x$ and $y=e^{-x}$ at the point $(0,1)$.
> Find the acute angle of intersection of the curves $y=\cos x$ and $y=e^{-x}$ at the point $(0,1)$.
My method:
$y=\cos(x)$ $(0,1)$
$1=\cos(0)$
$=0$
$\frac{dy}{dx}=-\sin(x)$
$=-\sin(0)$ $=0$
I did the above step exactly from the example given in the text book, but I can't get the answer.
The answer is $45^{\circ}$
Help me out by step by step solution. thanks | $$f(x)=\cos x\Longrightarrow f'(x)=-\sin x\Longrightarrow f'(0)=0=:m_1$$
$$g(x)=e^{-x}\Longrightarrow g'(x)=-e^{-x}\Longrightarrow g'(0)=-1=:m_2$$
So you have that the functions' tangent lines at $\,(0,1)\,$ have slopes $\,0\,$ (this means the tangent line of $\,f\,$ at this point is horizontal) and $\,-1\,$ , so what's the acute angle between two lines with these slopes?
Yup, it is $\,45^\circ\,$ , as you can readily check. Of course, you can use the formula
$$\tan\alpha = \arctan\left|\frac{m_1-m_2}{1+m_1m_2}\right|=\arctan\frac{1}{1}=\frac{\pi}{4}\text{radians}=45^\circ$$with $\,\alpha\,=$ the angle between the curves. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "calculus"
} |
Running jsp files with Apache tomcat on windows
I installed Apache Tomcat on my Windows machine, and it seems like its installed successfuly. I can see the property window, and I can start the server but I don't know what to do next.
Where do I save jsp files at.. do I create a directory or does apache tomcat create its own directories?
that's my only problem.. how do i make and edit files now that its installed | Folder structure:
Apache-home/webapps/project_name/WEB-INF/classes
all jsp filse should come under project_name folder. and java classes comes under clasess. Also need to put a special file named web.xml in WEB-INF folder. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 6,
"tags": "java, windows, jsp, tomcat"
} |
Enaml: allow Window to be resizeable
If i use the Window widget, it is not resizable and fixed to its container size. How can i set the Window to be resizable? Following is not resizable:
enamldef MyWindow(Window)
VGroup:
MPLCanvas:
figure = Figure()
CheckBox:
text = "Show current"
CheckBox:
text = "Show mean"
CheckBox:
text = "Show first detector" | This works for me, I can expand the window in both directions. If you mean that you are unable to shrink the window, that because it's limited by the size of the matplotlib figure. If you want to force the figure to shrink below is natural size, you have to handle that explicitly with constraints:
enamldef Main(Window):
VGroup:
MPLCanvas:
figure = Figure()
resist_width = 'ignore'
resist_height = 'ignore'
constraints = [width >= 100, height >= 100]
CheckBox:
text = "Show current"
CheckBox:
text = "Show mean"
CheckBox:
text = "Show first detector" | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "python, enaml"
} |
Pack list of ints in Python
I have got a list that I am packing as bytes using `struct` module in Python. Here is my list:
> [39, 39, 126, 126, 256, 258, 260, 259, 257, 126]
I am packing my list as:
encoded = struct.pack(">{}H".format(len(list)), *list)
where I pass number of elements in list as a format.
Now, I need to unpack the packed struct. For that I will need a format where I again pass number of elements. For now I am doing it like so:
struct.unpack(">{}H".format(10), encoded)
However, I can't pass it as a simple parameter to function `format` because that struct is then written to file that I am using for compressing image. How can I add a number of elements to file, and unpack it after?
P.S. I would like to get that `10` (in unpacking) from file itself that is packed as bytes. | Here is my approach of adding that [number of elements] to the file:
file.write(len(compressed_list).to_bytes(3,'big'))
I allocate 3 bytes of memory for the length of `compressed_list`, convert it to bytes, and add it to the beginning of the file. Further, write other left parts.
* * *
Next, when I need that number, I get it from the file like so:
sz = int.from_bytes(encoded[0:3],'big')
which means that I take first three bytes from byte array read from the file, and typecast that bytes to int.
That solved my problem. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "python, struct"
} |
Posting Questions - "allow new options", "allow multiple votes"?
Playing with the Facebook Questions Graph API (wasn't clear from the API documentation) I've noticed that it's possible to specify whether "friends can add options" (by means of an `allow_new_options` field). Setting this field to `true` has the additional effect that "friends _can_ vote multiple options". Setting it to `false` has the effect that "friends _cannot_ vote multiple options". The two things ("allow new options" and "allow multiple votes") however, in my opinion, are and should be unrelated. Does anyone know whether _or not_ it's possible to specify separately that "friends can add options" and "friends can vote multiple options"? | Please be aware that Facebook is discontinuing it's Questions product altogether. Any app you build right now will be obsolete in a few days.
<
< | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "android, facebook, facebook graph api"
} |
How to localize a static UITableView section?
I have a view with a `UITableView` with one section and one cell. It's used purely for layout. The section has a header and a footer, both with some text in it.
I want to localize this text but can't figure out how. Currently the only way I'm aware of is to implement `titleForHeaderInSection:` but I'd prefer not to do this as it's a static table, and I'd rather avoid having to implement the `UITableViewDelegate` just to accomplish this. Is there another way? | If you have implemented UITableViewDataSource, you can use NSLocalizedString when implementing tableView:sectionIndexTitlesForTableView: and tableView:cellForRowAtIndexPath:.
If you are using interface builder, xcode allows you to localize entire xib. But the drawback is that it will create one xib for each locale you need to support. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "ios, objective c, uitableview, ios7, localization"
} |
file_get_contents() failed to open stream: No error
I am new to php so still figuring things out. And I have two scripts one is getting datas from other but when I try to get it using `file_get_contents()` it returns `NULL` and I see the following in my error.log:
> [php7:warn] [pid 5524:tid 852] [client ::1:8677] PHP Warning: file_get_contents(usr.php?getinfobymd5=5f85783ad40df90c6485a3a176c41612):
>
> failed to open stream: No error in A:\Apache\www\index.php on line 6
How can I fix that and what ' **No error** ' error means?? Also I tried to change permissions allowing everybody to execute, write the file; And setting `allow_url_fopen` to On. | Try placing the filename in quotes:
file_get_contents('usr.php'); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "php, file"
} |
Doubt regarding splitting of the limit $ \lim\limits_{x \to 0} \dfrac{\sin^2(3x)}{x^2} $
I have a simple question about the logic of the limits of trig functions. For example, let's say you have the following question:
$ \lim\limits_{x \to 0} \dfrac{\sin^2(3x)}{x^2} $
What's preventing me from doing this: $ \lim\limits_{x \to 0} \sin(3x)\dfrac{\sin(3x)}{x^2} $ and then simplifying it to this: $ \lim\limits_{x \to 0} \sin(3x) \times \lim\limits_{x \to 0} \dfrac{\sin(3x)}{x^2} $ and finally this: $0 \times \lim\limits_{x \to 0} \dfrac{\sin(3x)}{x^2}$
Thanks for the help. | If $\lim_{x\to a} f(x) = L_1$ and $\lim_{x \to a} g(x) = L_2$ where $L_1, L_2$ are real numbers then you can conclude that $\lim_{x\to a } f(x) g(x) = L_1 L_2$. In this case, $\lim_{x\to 0} \frac{\sin 3x}{x^2}$ does not exist, so, your argument breaks down there. | stackexchange-math | {
"answer_score": 3,
"question_score": 3,
"tags": "calculus, limits"
} |
Connectivity and the triangle inequality
It is well known that if a weight function of a graph satisfies the triangle inequality, then 2 vertex connectivity is same as 2 edge connectivity in that graph. Can someone find a proof for this?
I looked at many papers, but couldn't find anything clear about the proof. | Connectivity and triangle inequality for distance function don't have anything common. There is a graph $G = \overline{\overline{2K_2}\cup K_1}$ that is 2-edge-conncted but is not 2-vertex-connected. You may use any distance function for it.
So, $G = (\\{\,1, 2, 3, 4, 5\,\\}, \\{\,\\{\,1, 2\,\\}, \\{\,3, 4\,\\}, \\{\,1, 5\,\\}, \\{\,2, 5\,\\}, \\{\,3, 5\,\\}, \\{\,4, 5\,\\}\,\\})$. Let $d(u, v) = A_{uv}$ for $$A = \begin{bmatrix} 0 & 1 & 2 & 2 & 1\\\ 1 & 0 & 2 & 2 & 1\\\ 2 & 2 & 0 & 1 & 1\\\ 2 & 2 & 1 & 0 & 1\\\ 1 & 1 & 1 & 1 & 0 \end{bmatrix}.$$
Probably it was meant that 2-vertex-connected graph is 2-edge-connected. That is true since $\kappa(G) \le \lambda(G)$ for any graph $G$, and this faact has no relation to distance function. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "graph theory, graph connectivity"
} |
How to have search functionality on association models as well
By using a railscast video i create a simple search that works on same model. But now i have a model that shows associated model data as well and i would like to search on them as well.
Right now i managed to make it semi work, but i assume i have conflict if i add the field "name" into the joins as i have two models that have a column named "name"
def self.search(search)
if search
key = "'%#{search}%'"
columns = %w{ city station venue area country plate_number }
joins(:services).joins(:washer).joins(:location).where(columns.map {|c| "#{c} ILIKE #{key}" }.join(' OR '))
else
where(nil)
end
end
What do i need to change to be sure i can search across all columns? | I think when you have ambiguous field name after join then you can mention table_name.field_name so it remove the ambiguity and works. something like.
joins(:services).joins(:washer).where("services.name = ? or washer.name = ?", "test", "test") | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "ruby on rails, ruby on rails 4, activerecord, ruby on rails 5"
} |
HTML java data binding
Is there any framework for HTML Java data binding? I found on google that asp.net supports it. Do we have anything similar in java?
A quick googling found me this: <
Is there enything else like this? | As far as i remember SpringMVC has data binding capabilities for form backing objects. Jersey, the reference implementation of JSR-311 also does automatic data binding for your resource objects.
checkout <
and: < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "java, html, data binding"
} |
Highcharts - making a point clickable?
I've searched and tested several solutions but it's really hard to find an answer to this seemingly easy problem:
I want to make points on this chart clickable (<
series: [{
name: 'Tokyo',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6],
url: [
So far, I've only managed to make the values on the x axis clickable ( by adding them as a simple html a href code )
But I am unable to make the points on the chart clickable?
It's an easy question but nowhere could I find an answer and the AJAX example by the highcharts creators seems to be bugged.
Could anyone please help me? | to make the points on the chart clickable set `allowPointSelect` as true
plotOptions:{
series:{
allowPointSelect: true
}
}
now you handle the click event or selection event from the
plotOptions:{
series:{
point:{
events:{
select: function(e){
//your logic here
}
}
}
}
}
I've updated your fiddle here <
API ref link : <
I hope this will help you | stackexchange-stackoverflow | {
"answer_score": 20,
"question_score": 6,
"tags": "javascript, jquery, ajax, highcharts, frontend"
} |
Tool to ask adressbook for pgp keys
I would like to know if somebody knows a tool, where i can query my whole adress book in Thunderbird or Gmail, to ask, if there are PGP keys for somebody there. So i can just use the PGP key of People there. Or can I do this with Gnupg? | For Thunderbird 38.3 and Enigmail 1.8:
1. Settings
2. Enigmail
3. Key Management
4. Keyserver
5. Find keys for all contacts
6. Select all found keys
7. OK | stackexchange-askubuntu | {
"answer_score": 1,
"question_score": 2,
"tags": "thunderbird, pgp, enigmail"
} |
How to get library: OpenGL 3.1 and GLUT 3 on Ubuntu 12.04
I'm taking a class in OpenGL. Everything must be compiled and run on a machine that has the OpenGL 3.1 and GLUT 3 library, so I need to make sure that is what I have.
I have a fresh copy of Ubuntu 12.04 installed so nothing extra outside of the basic installation.
Any help with setting me up? | Since you wrote that you're taking an OpenGL course, I'll assume that you need the development files. Then try simply this:
sudo apt-get install freeglut3-dev
The OpenGL development files should be installed as a dependency of GLUT (the corresponding (virtual) package is `gl-dev` and one possible package is `libgl1-mesa-dev`).
Regarding the version of OpenGL this will get you, it will depend on both your hardware and the software drivers installed on your machine. Use `glxinfo` (from the `mesa-utils` package) to find out: the supported version should be in the OpenGL version string. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 2,
"tags": "opengl, ubuntu 12.04, glut"
} |
Make sure the php script can be only excecuted from command line (or as a cron job)
This is the code I'm using, is it enough to make sure the script can be only run as a cron job? It sure does work but maybe there is something I have missed.
if (php_sapi_name() !== 'cli') {
die("You are not allwod here");
} | Yes, that will work. I would also make sure the script is outside the root directory. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, cron, cron task"
} |
Is indirect matanot l'evyonim ok?
I was under the impression that the Purim mitzvah of _matanot l'evyonim_ , giving gifts to the poor, had to be done directly -- find two or more poor people and give to them. This answer on a related question says:
> There are lots of tzedakah funds who collect for poor people that collect from donors outside the country. You might want to find one of those.
Does an indirect gift like this fulfill the mitzvah? If so, do we have to give early enough to ensure that they will distribute the funds in time, or is my giving the gift (in time) sufficient and I can rely on the tzedakah fund to eventually distribute it? Do I need to tell the tzedakah fund that this is for Purim?
Sources please. | Aruch HaShulchan 694:2 says that it is clear to him that it does not have to be given directly to the poor man, and can be given through a messenger (Shaliach) on Purim day.
Nitei Gavriel Purim 68:6 mentions in the name of the Yad Aharon 694, Chug Eretz 15, and others that if money is given to a messenger (Shaliach) before Purim to give to the poor man on Purim you are fulfilling your obligation.
So it seems like a messenger is definitely permitted. Perhaps in many cases people do not know a bona fide poor person and therefore even prefer a messenger. The messenger would have a responsibility to give the money to the poor person on Purim, this way the giver is fulfilling their obligation. If the Tzedaka fund does not know it is for Purim they may not give it out on Purim, so it is advisable to make sure that the Tzedaka fund is aware, and will distribute it on Purim. | stackexchange-judaism | {
"answer_score": 9,
"question_score": 7,
"tags": "halacha, purim, tzedakah charity, gifts, shlichus agency"
} |
A simple question on spans
I am trying to show that if $span\\{2x+y, y+z\\}=span\\{x, y, z\\}$ then $z\in span\\{2x+y, y+z\\}$ where $x$ and $y$ are non-zero vectors.
Let $a, b, c, d, e \in \mathbb F$ where $\mathbb F$ is field of our vector space.
We can write $a(2x+y) + b(y+z) = cx + dy + ez$ by the equality of sets. However I could not write $z$ as a linear combination of $2x+y$ and $y+z$
I am so sorry if there is a mistake.
Thanks in advance for any help | $z\in\text{span}(x,y,z)$, since $z=1z$, where $1$ is the multiplicative identity of $\Bbb F$.
Then, if $\text{span}(2x+y,y+z)=\text{span}(x,y,z)$, $z\in\text{span}(2x+y,y+z)$ | stackexchange-math | {
"answer_score": 1,
"question_score": -1,
"tags": "linear algebra, vector spaces, vectors"
} |
How to redirect a slash url to non slash url using htaccees
My url looks like
localhost/test/page1.php
I would like to hide the php extension so i have used the below method to hide the php extension
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]
Now the url is
localhost/test/page1
But when i use the url like localhost/test/page1/ then it shows an error. HOw to redirect the slash url to non slash url | Test this:
RewriteRule ^([^/]+)/?$ $1.php [NC,L] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "apache, .htaccess"
} |
running a process as a different user from Python
I am running a script as `userA` with root access, from this script I want to make a `popen()` call and run a different process as `userB`.
os.setuid() does not seem to work for this (unless I am doing this wrong?), and I would like to avoid a linux based solution such as `su -userB -c <command>`
Is there a pythonic way of running a process as `userB` while the script is running as `userA`? | The following answer has a really nice approach for this: <
There is a working code example there, but the summary is to use `subprocess.Popen()` with a `preexec_fn` to set up the environment of the subprocess so that it executes as another user. | stackexchange-stackoverflow | {
"answer_score": 12,
"question_score": 18,
"tags": "python, linux, popen"
} |
Product creation date is in the future
I'm seeing about 70ish products that have a creation date that is in the future. These products were imported through CSV, so maybe the date field in the import was incorrect?
Has anyone experienced something like this before, and does it have any affect on the products?
Is there any way to change the product creation date other than editing it in the database?!enter image description here | It wouldn't affect your Magento store. But, still, if you want to change it, CSV Import/Export needs to be done. Following are the steps you can follow to change the _**created_at**_
* Magento Admin Panel -> System -> Import/Export -> Export
* Choose Entity Type as Products
* Filter your products based on created_at, in the 5th row, where you'll find created_at (Attribute Code), select the current date in _**From**_ , and empty in _**To**_
* Select _**Continue**_ Button
* Download the CSV, open it in excel
* Change the dates in In 12th column of your CSV, which you may find, created-at (heading), change the values under it, where values exist
* After changing the values, Save the file
* Magento _**Admin Panel - > System -> Import/Export -> Import**_
* Entity Type as Products
* Browse & locate the CSV file you changed and saved
* Check Data
* If _File is valid!_ , Import | stackexchange-magento | {
"answer_score": 2,
"question_score": 0,
"tags": "magento 1.9, product, import"
} |
Prevent helm from prompting to create a new buffer
If you visit a directory with `helm-find-files` and type the name of a file that doesn't exist, before opening it in a new buffer helm will prompt:
File does not exist, create buffer?
I would like helm to just create the buffer, without the prompt. I can't find an option for it to do this: essentially I want a variable just like `ido-create-new-buffer`. | You can set `helm-ff-newfile-prompt-p` to `nil` and Helm won't ask you anymore:
(setq helm-ff-newfile-prompt-p nil) | stackexchange-emacs | {
"answer_score": 16,
"question_score": 12,
"tags": "helm"
} |
Silex, how to set JSON_UNESCAPED_UNICODE in json()
In PHP I can use `JSON_UNESCAPED_UNICODE` in `json_encode();`
How I can do that in Silex Framework with `$app->json()` ?
Thanks. | As i know - you cannot do that in silex. Use json_encode() instead. But if you will find better solution, share it please. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, silex"
} |
A name for a product of `Const` and a functor?
Is `SF` already defined anywhere, or does it at least have a name?
data SF a f x = SF a (f x)
instance Functor f => Functor (SF a f) where
fmap g (SF a fx) = SF a (fmap g fx) | Your functor looks like
type SF a f = (,) a :. f
using functor-combo notation.
(I somehow prefer to look at it using composition, rather than using product and `Const`.) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 6,
"tags": "haskell, functor"
} |
What is the Erlang way to do stream manipulations?
Suppose I wanted to do something like:
dict
.values()
.map(fun scrub/1)
.flatMap(fun split/1)
.groupBy(fun keyFun/1, fun count/1)
.to_dict()
What is the most elegant way to achieve this in Erlang? | There is no direct easy way of doing that. All attempts I saw looked even worse than straightforward composition. If you will look at majority of open source project in Erlang, you will find that they use generic composition. Re-using your example:
to_dict(
groupBy(fun keyFun/1, fun count/1,
flatMap(fun split/1,
map(fun scrub/1,
values(dict))))). | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "stream, erlang"
} |
How to subtract a constant from members of a sublist?
I know I can subtract a constant from all members of a simple list like this:
l = [ 123, 124, 125, 126 ]
l = [v - 100 for v in l]
But how can I subtract a constant from one or more specific members of each sublist within a list?
Suppose I have:
l = [ [101, 102, 103], [111, 122, 133], [222, 333, 444] ]
I want to subtract, say, 100 from the 2nd and 3rd elements of each sublist, to give me:
[ [101, 2, 3], [111, 22, 33], [222, 233, 344] ]
Is there a straightforward Pythonic way to do this? | In a simplest form, you can unpack the sublists and apply the operation to the desired items:
In [1]: l = [ [101, 2, 3], [111, 22, 33], [222, 233, 344] ]
In [2]: [[x, y - 100, z - 100] for x, y, z in l]
Out[2]: [[101, -98, -97], [111, -78, -67], [222, 133, 244]]
Or, a bit more scalable approach would be to have a nested list comprehension:
In [3]: [[item[0]] + [x - 100 for x in item[1:]] for item in l]
Out[3]: [[101, -98, -97], [111, -78, -67], [222, 133, 244]] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, list comprehension"
} |
Misleading message
I accidentally wrote `foo ((struct Node* ) head);` instead of `foo ((Node* ) head);`
And I got a message from compiler
_`expected 'struct Node *' but argument is of type 'struct Node *'`_
#include <stdio.h>
typedef struct NODE
{
char data;
struct NODE *next;
} Node;
void foo (Node *head){}
void bar (void *head)
{
// note:
foo ((struct Node* ) head);
}
int main(){
return 0;
}
This is misleading, shouldn't it be either `Node *` or `struct NODE *` in the first case ?
What does this message mean ? Can anybody clarify it ?
I'm able to reproduce it here too after intentionally putting an error.
_Compiler :gcc (GCC) 4.8.1_ | It's a bug in GCC. You're right that the 'expected' should be either `struct NODE *` or `Node *`. For what it's worth, clang gives a better message:
example.c:13:8: warning: incompatible pointer types passing 'struct Node *' to
parameter of type 'Node *' (aka 'struct NODE *')
[-Wincompatible-pointer-types]
foo ((struct Node* ) head);
^~~~~~~~~~~~~~~~~~~~
example.c:8:17: note: passing argument to parameter 'head' here
void foo (Node *head){}
^
1 warning generated. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 4,
"tags": "c, gcc"
} |
Executing PHP gives error on command line interface, but works in browser
Any idea what could cause a php file to execute fine in the browser, but give an error when run in the command line interface?
So to be specific, when I visit `mysite.com/script.php` in a browser, all is well.
When I execute `php -f /var/www/mysite.com/public_html/script.php` I get an error that one of my required files cannot be found.
So, the error message gives a lot of insight, but I am confused because it works as intended in the browser with no error, so I have no idea what could cause this behavior. Any ideas? | By starting with `../`, which is relative to the current working directory of the process, the `require` will only work if you are in the right directory. If you have control of the script, change it to use the full, absolute path starting at `/`, | stackexchange-askubuntu | {
"answer_score": 1,
"question_score": 1,
"tags": "command line, php"
} |
Regex: Include specific expression in the search
I have the following string:
CHECKING % x j1 (test1^3) @ phi=0 j2 (test2/3) @ phi=1 j3 @ phi=2 j1 (test1^3) @ phi=2 j2 (test2/3) @ phi=3 j3 @ phi=5
CHECKING % x ab (test1^3) @ phi=0 cde (test2/3) @ phi=1 fg @ phi=2 hij (test1^3) @ phi=2 kl (test2/3) @ phi=3 mn @ phi=5
I would like to get all the `j1`, `j2` and `j3` as well as the `ab`, `cde` ... so everything in front of the brackets or the `@` sign respectively, but somehow I cannot make it work. Does someone have an idea for a regex?
Here is what I have tried:
`([a-zA-Z_]+[0-9]{0,4})\s+\(.{0,9}\)\s+\@`
which gives:
`j1 j2 j1 j2 ... ab cde hij kl`
But it does not match the `j3`, `fg` and `mn`, how can I include the `(...)` term only if appearing? | Building on your original pattern, you can make the part in brackets optional to capture cases without a formula:
([a-zA-Z_]+[0-9]{0,4})\s+(?:\(.{0,9}\))?\s*\@
**Demo** | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "regex"
} |
I cant take full names in my array
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String[]repName = new String[5];
double[]salesAmount = new double[5];
System.out.println("Please Enter Sales Reps Name Followed By Monthly Sales: \n");
for (int i = 0 ; i < repName.length; i++ )
{
System.out.print("Sales Rep (Full Name): " );
repName[i] = input.nextLine();
System.out.print("Monthly Sales: € " );
salesAmount[i] = input.nextDouble();
System.out.println();
}
The code will only allow me to input a full name once, ie John Doe. It will not let me enter it with other doubles in the array. Why is this? | I got your error. When you enter double, you press enter. That is a new line which was taken instead of another name. Then it is expecting double but you are entering another name. So you get an input Mismatch.
After `input.nextDouble()` write `input.nextLine();`
The code should look like this.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String[]repName = new String[5];
double[]salesAmount = new double[5];
System.out.println("Please Enter Sales Reps Name Followed By Monthly Sales: \n");
for (int i = 0 ; i < repName.length; i++ )
{
System.out.print("Sales Rep (Full Name): " );
repName[i] = input.nextLine();
System.out.print("Monthly Sales: € " );
salesAmount[i] = input.nextDouble();
input.nextLine();
System.out.println();
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "java, arrays, string"
} |
Is this an Extension of Complex Numbers?
A quick search here shows me this question: No extension to complex numbers? where they explain there's no 3D or 4D analogue of complex numbers. Then there's a mention of quaternions but the multiplication is non-commutative. This has left me a bit "confused."
Anyway, I just learnt a theorem that if $F$ is field and $p(x) \in F[x]$ is an irreducible polynomial of degree $n$ then $K=F[x]/(p(x))$ is an $n$-dimensional vector space over $F$.
So what if $F=\mathbb{R}$ and $p(x)=x^4+1$, then $\mathbb{C} \subset K$ and $[K:\mathbb{R}]=4$, right?
Specifically, if $\theta=x + (p(x))$ then $\\{1, \theta, \theta^2, \theta^3\\}$ are the basis for $K$ and $\mathbb{C} \cong \\{a+b\theta^2 : a,b \in \mathbb{R}\\}$. | Massive hint: How sure are you that $p(x) = x^4 + 1$ is irreducible over $\Bbb{R}$? Do you know that
$$x^4 + 1 = -(-x^2+\sqrt{2} x-1) (x^2+\sqrt{2} x+1)?$$
The resulting quotient ring is isomorphic to $\Bbb{C} \times \Bbb{C}$ (using the CRT) which is not even an integral domain. | stackexchange-math | {
"answer_score": 6,
"question_score": 3,
"tags": "abstract algebra, field theory, extension field"
} |
Are apps developed for iOS 4.3 compatible with 5.1?
Apparently the latest version of iOS is 5.1. I have been developing an iPad app for the past few months. So I have an iMac with Snow Leopard. Nowadays it seems that iOS 5.1 is the latest version for the iPad.
My question is if the app I have developed for iOS 4.3 is still compatible with iOS 5.1...?
I also realized I should update my iMac to OS Lion in order to be able to install XCode 4.3.2? This is the only version that supports iOS 5.1?
Thanks for your feedback! | Yes. All iOS versions are backwards-compatible.
Yes. You need the new xcode to use the iOS 5.1 SDK. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ios, xcode, ios4, ios5.1"
} |
ListView and images
I have two problems with ListView+images. I get the values for the list from an xml file which contains all necessary infos.
1. I need to set up a Listview. Every row should contain an icon and a title. The icon is a local drawable (shipped whith the app).
An example what I want to achieve can be found here: <
I need a dynamic way to add images to the ListView, the xml file contents may change.
2. Is the same as the previous but this time the images are hosted on a server so I need to load them from the server and then display them in the list. | A ListView item can have it's own custom layout. When you create your adapter for the ListView you can pass in the layout id to the Adapter constructor. See SimpleAdapter and ArrayAdapter. You will **`have to extend an Adapter and implement getView() to property set the image+text.`**
Here's a complete sample code Lazy load of images in ListView. You can reuse it. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "android, image, listview, android layout"
} |
Devise::Models inclusion
I'm trying to understand more deeply Rails engines mechanisms, watching the sources of devise project.
You know, there is that module `Devise::Models` that defines a method called `devise` for models that will support authentication and stuff. All good so far.
See <
But it's hard to me to figure out how this module is included in the models. Is it autoloaded or something ? When I create a new model without using generators, how the hell devise makes accessible Devise::Models module so that I can directly call `devise :trackable, :stuffable`.
That's just dark to me. Any explanation would be highly appreciated.
Thank you for reading. | Man, I feel stupid. I spent so many hours to find out why `Devise::Models` module was included in all my models, and I could call `devise` method without raising a NoMethod error.
Finally I found the answer.
This module is included in the orm file that your devise installation uses. You do this stuff, if you didn't changed that, in your initializer. (Choosing the right Orm adapter file)
Then the file included in question (in my case, `mongoid.yml`) simply does :
require 'orm_adapter/adapters/mongoid'
Mongoid::Document::ClassMethods.send :include, Devise::Models
Hope this will inspire you if you will to provide same mechanism for your engine.
Regards | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ruby on rails 3, devise"
} |
Como traduzir um programa em C para Assembly?
Como faço a interação entre as duas linguagens? | No compilador da Microsoft é usado a opção `/FA`.
No GCC usa-se `-S`.
Quanto à "interação" depende do problema, faça outra pergunta mais específica. | stackexchange-pt_stackoverflow | {
"answer_score": 5,
"question_score": -3,
"tags": "c, assembly"
} |
How to retrieve custom parameter value from SIP contact header in KAMAILIO?
I am using **Kamailio 4.4** and I am sending custom parameters with **Contact** header from my client extensions. the header send to **Kamailio** is like this
Contact: "Test" <sip:[email protected]:46666;pn-d=android;pn-t=d1eCzkw9bhk:APA91bFntzV>
I need to extract the value of these two parameters **pn-d** and **pn-t**. I tried with the code given below.
$var(pn-d_value) = $sel(contact.uri.params[pn-d]);
but the value can't be retrieved.
Please suggest a way to get the value of custom parameters. | I could resolve this problem using two steps.
First, you need to extract the URI from the header and store the result into a variable.
$var(uri) = $sel(contact.uri);
Then you can use transformation on this uri to get the parameter value. like this
$var(pn-d_value) = $(var(uri){uri.param,pn-d}); //got "android" here
$var(pn-t_value) = $(var(uri){uri.param,pn-t}); //got "d1eCzkw9bhk:APA91bFntzV" here | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "parameters, sip, kamailio"
} |
ASP.NET Chart Custom Label Show HH:MM:SS From Total Time In Seconds
I need to add a custom label to my chart to show HH:MM:SS in asp.net the time coming from the sql server is in seconds and the chart is being filled as follows:
SqlConnection con = new SqlConnection(easystone);
SqlDataAdapter graph = new SqlDataAdapter("SELECT [User], sum([Total Time]) as [total time] ,[week] FROM [Toolpaths].[dbo].[totaltimeuser] where [week] like '" + DropDownList2.Text + "' group by [user], [week] order by 'total time' desc", con);
DataTable graphdata = new DataTable();
graph.Fill(graphdata);
chart1.DataSource = graphdata;
chart1.ChartAreas["ChartArea1"].AxisX.Title = "";
chart1.Series["Series1"].XValueMember = "User";
chart1.Series["Series1"].YValueMembers = "total time";
year.Text = DropDownList2.Text; | Try this:
protected void Page_Load(object sender, EventArgs e)
{
foreach (DataRow row in graphdata.Rows)
{
int total = (int)row["total time"];
int index = chart1.Series[0].Points.AddXY(row["User"], new object[] { total });
chart1.Series[0].Points[index].Label = string.Format("{0:00}:{1:00}:{2:00}", (total / 60) / 60, (total / 60) % 60, total % 60);
}
}
;
echo $dateTime->format('d/m/Y h:i:s');
By using the codes above, it will output:
26/02/2015 03:11:41
It's always suggested to use `DateTime` class whenever available, which will have Exception to handle unable parsing cases. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php, w3c"
} |
Mysql query to find all rows that have the same values as another row
My database contains rows that generally look like:
PersonItem
__________
id
personId
itemId
ID PERSONID ITEMID
1 123 456
2 123 456
3 123 555
4 444 456
5 123 456
6 333 555
7 444 456
I need to find all the actual records where the PersonId and the ItemId column match some other record in the database for those two columns....
| 1 | 123 | 456
| 2 | 123 | 456
| 5 | 123 | 456
| 4 | 444 | 456
| 7 | 444 | 456
How can I go about getting these results? | You can do joins to get around with duplicate records.
SELECT a.*
FROM TableName a
INNER JOIN
(
SELECT PersonID, ItemID, COUNT(*) totalCount
FROM TableName
GROUP BY PersonID, ItemID
HAVING COUNT(*) > 1
) b ON a.PersonID = b.PersonID AND
a.ItemID = b.ItemID
* SQLFiddle Demo
OUTPUT
ID PERSONID ITEMID
1 123 456
2 123 456
5 123 456
4 444 456
7 444 456
| stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 5,
"tags": "mysql, sql"
} |
Remote API with WIFI enabled Camcorders
I currently own a CX330, which has WIFI control through a Sony app. I would like to build the remote control features into another app I'm building as well as being able to download video from the device. Are either of these options possible and, if so, where in the documentation do I go to find examples or instructions? Currently I only see these functions available for a limited set of devices, but if the proprietary software can provide remote control I'm assuming Sony has not built a separate API just for the camcorders and a different one for other devices.
Also, I believe the proprietary software allows you to download new videos directly from the camera, is an api available for this as well? | We do have an API for working with cameras, but unfortunately your camera is not supported. You can find the full list of supported cameras here: <
The API does allow you to download photos and videos. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "camera, sony"
} |
Sending invitation emails WSO2 EMM fails
I'm trying out the WSO2 Enterprise Mobile Manager but I can't seem to get it configured right.
If I want to send an invitation e-mail to a user, my SMTP-server doesn't accept the given recipient address. Apparently the EMM formats an address with surrounding quotes like this:
RCPT TO: <"[email protected]">
And if I try it manually like this, I have no problem:
RCPT TO: <[email protected]>
Is there a setting I can configure in the EMM-software or on my SMTP-server (MailEnable for testing purposes) (or the Carbon/EMM source code on GitHub) to fix this ?
Thanks in advance! | I hope you have followed the step 10 of getting started document. This email component is derived through Jaggery where it has been used in multiple products as well as it has been tested on multiple SMPT servers. Then I believe you have to configure or setup this from your SMTP server side if you believe that the issue is with that double quotes. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "email, smtp, wso2"
} |
Case expression is not working in Values which 0.02
I have a query which has value Like this _0.02_ and so on...
Note:- When I tried to add case expression to `convert` like this
>= 0.00 and <= 0.049 then 1 Star
it's giving me null values
,case
when cast([main_stars_score] as integer) >=0.05
and cast([main_stars_score] as integer) <= 1
then N'1 نجم'
when cast([main_stars_score] as integer) > 0.01
and cast([main_stars_score] as integer) <=0.049
then N'0 نجم'
**Output:-** must come 1 star and below 0.049 then come 0 star | Ideally your `main_stars_score` should be either numeric or floating point type. If it really be floating point _text_ , then you should be casting to a numeric type:
SELECT
CASE WHEN CAST([main_stars_score] AS NUMERIC(10,2)) BETWEEN 0.05 AND 1.0
THEN N'1 نجم'
WHEN CAST([main_stars_score] AS NUMERIC(10,2)) BETWEEN 0.01 AND 0.049
THEN N'0 نجم' END AS label
FROM yourTable; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "sql, tsql"
} |
Roll to another case in PHP switch
For example I have this:
switch ($action)
{
case 'my_action':
doSomething();
break;
case 'second_action':
if ($this_is_true)
{
$action = 'my_action';
}
else
{
doSomethingElse();
}
break;
}
Is the example above going to go through the switch again and then call the first case `my_action` if the second case `second_action` has `$this_is_true` variable set to true?
If this doesn't work, what would be an alternative? | You can try something like this:
switch ($action)
{
case 'my_action':
case 'second_action':
if ($this_is_true || $action=='my_action')
{
doSomething();
}
else
{
doSomethingElse();
}
break;
}
When $action is equal to `'my_action'` it will run through the `case`, as it finds no `break` sentence then it will run through the second case until it finds the `break` sentence.
Please give a look to example #3 in < to find out more about no breaking switch cases. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php, switch statement"
} |
Camel kafka what's meant by maxPollRecords configuration
Lets say we get exchange as follows by executing following simple code. How does maxPollRecords configuration of kafkaEndpoint affects this. After executing following code echange will have only one message from kafka. Default value is for maxPollRecords is 500.
Exchange exchange = kafkaConsumer.receive(kafkaEndpoint, 100);//ConsumerTemplate kafkaConsumer;
When using kafka library it's clear because consumer.poll() will return like following
ConsumerRecords<String, String> records = consumer.poll(100);
So records will have only 500 records within it. But when it comes to camel kafka what does this mean? | The option `maxPollRecords` is the same, its the kafka option and it does what you can find on the documentation at both Apache Camel and Kafka.
On the other hand the APIs you use are different, the first API via the Camel ConsumerTemplate is for _single_ exchange (aka message) consuming. So you get 1 message.
Typically in Camel you setup a route, such as the Camel Kafka example (< where the route will poll max 500 messages by default according to the `maxPollRecords` option, and then route those 500 messages in Camel. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "java, apache camel, apache kafka"
} |
Tab vs. espaços, para indentação de código
Existe alguma recomendação sobre o que é mais apropriado? Caractere de tabulação (`\t`) ou espaços?
Pelo que vejo, costuma-se ter convenções por linguagem:
* **Ruby** : dois espaços
* **Delphi** : dois espaços
* **Python** : quatro espaços
* **Java** : tabulação
* etc
No caso do Python temos uma particularidade, a indentação é levada em conta pelo compilador, mas ele é inteligente para reconhecer tanto espaços como tabulação. | Desconheço uma recomendação padrão para identação. Cada linguagem usa a sua.
O que eu costumo praticar é seguir a convenção de cada linguagem. Em geral é mais comum usar espaços que tabs.
O que sempre foi uma boa prática pra mim é no começo de um projeto, envolvendo mais de um desenvolvedor, sempre escrever um documento de "code standards" que não só define identação, como também nomes usados em variáveis, métodos, onde usar camelCase, onde usar PascalCase, etc.
A primeira regra desse documento é: para qualquer situação que não se tem algo combinado, combinar.
Pra mim sempre funcionou bem trabalhar desse jeito. | stackexchange-pt_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "estilo de codificação, indentação"
} |
jQuery regex, allow more than one dot in filename
I'm trying to make it possible for the user to upload a file with more than one dot in the file name (eg. "file..jpg", "test.file.jpg" or maybe "file.jpg.jpeg").
I have the following expression which currently only allows one dot (eg. "file.jpg") through `\.`:
var ext = this.value.match(/\.(.+)$/)[1];
Any advice on how to make this possible?
Complete script:
var ext = this.value.match(/\.(.+)$/)[1];
switch (ext) {
case 'pdf':
case 'jpg':
case 'png':
break;
default:
alert('Not allowed file type');
this.value = '';
}; | If your code above is simply trying to get the file extension of the filename then you can split the filename to an array by `.` and then use `pop()`. You can also put the valid extensions in an array and use `indexOf()` to check for validity. Try this:
var validExt = [ 'pdf', 'jpg', 'png' ];
var ext = this.value.split('.').pop();
if (validExt.indexOf(ext.toLowerCase()) == -1) {
alert('Not allowed file type');
this.value = '';
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "jquery, html, regex, forms"
} |
How to add Wordpress plugins to static (non-Wordpress) web sites?
Suppose I want to add some Wordpress plugins (e.g. Easy Appointment) to a few _static_ web sites that do not run on Wordpress. Currently, I want to add just basic plugin features (appointment form and calendar) to my sites. In future, I would like also to add plugins for email notification, payments, etc.
My sites consist of a few HTML and JS files. I will probably need to use some cloud database or CMS but I don't want to move the sites to Wordpress. What is the best way to integrate Wordpress plugins with these static web sites ? | You Can't Do That™.
Without WordPress there's nothing to run your WordPress plugin code: no php, no way to load it, no way to invoke its features. And there's no database to hold your data (both appointment forms and calendars are data-intensive applications.)
Could some sort of headless WordPress instance be used with its REST API? Probably not: most plugins generate the HTML, Javascript, and CSS to provide their functionality within WordPress pages. Few support the REST API, and those that do use it for limited purposes.
You can embed a calendar from another calendar web app (like Google's calendar) in your static site easily. If you can find an app that offers a way to embed forms you can use that too. Try searching for _appointment app to embed in static web site_ and you'll find some candidates. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "wordpress, plugins, static web apps"
} |
What is the difference between "Update snapshots" and "Update dependencies" in m2eclipse?
Assuming you're already using the m2eclipse plugin, if you right-click on a Maven project there is a Maven submenu.
Two of the actions available in this submenu are:
* Update dependencies
* Update snapshots
I've found an answer that says that "Update snapshots" is equivalent to using the -U parameter for mvn.
If "update snapshots" is the same as `mvn -U` what does "update dependencies" do? | It largely depends on how snapshot updating policy is set in your environment. By default Maven is supposed to update snapshots once a day (hence the flag -U and "Update Snapshots" action to force the snapshot update), but this policy can be overwritten locally or at repository manager level.
The "Update Dependencies" does pretty much the same as "Update Snapshots" action, except forcing updating snapshot artifacts. Both actions reset in-memory project model created by M2E to keep track of dependencies, including those that came from Eclipse Workspace. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 6,
"tags": "eclipse, maven 2, m2eclipse"
} |
Generate authentication token for each request in jmeter
I have a rather unique situation in jmeter where I need to do load-testing on our authentication federation. This means I need to generate a unique authentication token from a federated token server for each request and because the tokens expire after 5 minutes, I can't use `__StringFromFile`. I need to consume the token as soon as it is produced.
I can prepare an executable that outputs the token to its STDOUT. Is there a way for jmeter to execute a program and consume its output for each request - something like `__ExecuteAndReadStdOut(C:\path\to\program.exe)`? | One of the ways is using OS Process Sampler:
? Is it inside the egg?
This is mostly a curiosity/science question, so please don't take it as fear mongering, FUD, or any such non-sense. I realize that many eggs are perfectly safe. | There are two basic mechanisms:
* the salmonella is on the shell and when the egg gets broken the interior gets contaminated; or
* the chicken's reproductive system is contaminated and lays an egg with contaminated interior.
To reduce the very common (a few percent) shell contamination, eggs sold commercially have their shells treated (typically washed). After washing only about 50 in every million eggs will still have some shell contamination. The shell contamination may have been there when the chicken laid the egg, from fecal matter, or as a result of plant processing.
In some rare cases the surface salmonella can make it to the inside without breaking the egg: if it was there while the cuticle dried, if the egg is stored at room temperature, or if the environment is moist. | stackexchange-cooking | {
"answer_score": 14,
"question_score": 10,
"tags": "food safety, eggs, food science"
} |
Are any op amp configurations better for noise?
Considering the fact that the noise is always modeled as a voltage source on the positive input, is there any configuration where you get lower noise gain than signal gain?
EDIT:
Found answer  to cut away the unused portions.
Still, when defining the signal's SNR only for its spectral and temporal domain, there is no way to increase this SNR. One can only attempt to deteriorate the native SNR by as little as possible (which equates to a _Noise Figure_ of 0 dB).
The closest you can come to this (using op amps) is with a non-inverting amplifier, because it allows you to use no input resistor and small feedback resistors, without loading the signal source. | stackexchange-electronics | {
"answer_score": 7,
"question_score": 2,
"tags": "operational amplifier, noise"
} |
Golang interface conversion error: missing method
Look at this snippet:
package main
type Interface interface {
Interface()
}
type Struct struct {
Interface
}
func main() {
var i interface{} = Struct{}
_ = i.(Interface)
}
struct `Struct` has a embeded member implements interface `Interface`. When I compile this snippet, I get an error:
panic: interface conversion: main.Struct is not main.Interface: missing method Interface
This seems weird because struct `Struct` should inherit method `Interface` from the embeded interface `Interface`.
I want to know why this error happens? Is it designed as this in golang or is it just a bug of golang compiler? | You can't have both a field and a method with the same name, which is what happens when you embed something named `X` that provides a method `X()`.
As written. `Struct{}.Interface` is a field, not a method. There is no `Struct.Interface()`, only `Struct.Interface.Interface()`.
Rename your interface. For example, this works fine:
package main
type Foo interface {
Interface()
}
type Struct struct {
Foo
}
func main() {
var i interface{} = Struct{}
_ = i.(Foo)
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -2,
"tags": "go"
} |
ASP.NET MVC Actions + Extension
I want to have mvc action_name plus file extension in url like `/Home/Index.aspx` instead of `/Home/Index`; which route to Index action of Home Controller. Can anybody help me. Does anybody have any opinion or guideline? | routes.MapRoute(
"RouteName", // Route name
"{controller}/{action}.aspx", // URL with parameters
new { controller = "Home", action = "Index"} // Parameter defaults
);
Can you not do this | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "asp.net mvc, asp.net, file extension"
} |
How to remove vertical lines when combining multirow and multicolumn in a tabular?
I had a look at a few similar questions but none seems to be identical to mine.
Here is a MWE:
\documentclass[a4paper]{article}
\usepackage{multirow}
\usepackage{multicol}
\begin{document}
\begin{tabular}{|*{5}{c|}}
\hline
\backslashbox{1}{2} & A & B & C & D \\
\hline
a & \multicolumn{3}{c|}{\multirow{3}{*}{P}} & x \\
\cline{1-1} \cline{5-5}
b & & & & y \\
\cline{1-1} \cline{5-5}
c & & & & z \\
\hline
d & q & n & t & r \\
\hline
e & l & m & s & p \\
\hline
\end{tabular}
\end{document}
The column B is partially bounded by 2 vertical lines. I would prefer to have a big 3 by 3 cell for the entry P.
**How can I do that?** | Just add "phantom" multicolumns below the cell containing P:
\documentclass[a4paper]{article}
\usepackage{multirow}
\usepackage{multicol}
\begin{document}
\begin{tabular}{|*{5}{c|}}
\hline
\backslashbox{1}{2} & A & B & C & D \\
\hline
a & \multicolumn{3}{c|}{\multirow{3}{*}{P}} & x \\
\cline{1-1} \cline{5-5}
%% Add a \multicolumn here
b & \multicolumn{3}{c|}{} & x \\
\cline{1-1} \cline{5-5}
%% Add a \multicolumn here
c & \multicolumn{3}{c|}{}& z \\
\hline
d & q & n & t & r \\
\hline
e & l & m & s & p \\
\hline
\end{tabular}
\end{document} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "latex, tabular, multirow"
} |
Can anyone explain me the difference between these two loopings?
<
for (var b = a[0], len = a.length; len; b = a[--len]) {
newArray.push(
b
);
}
**and**
for (var i = 0, len = a.length; i < len; i++) {
newArray.push(
a[i]
);
}
1. According to jsref, it says the first one is faster. why?
2. Can anyone explain me the for loop on whats its doing compared to traditional way? | Your first example just does something very different. Check it out:
var a = [1,2,3,4],
newArray = [];
for (var b = a[0], len = a.length; len; b = a[--len]) {
newArray.push(b);
}
> newArray
[1, 4, 3, 2]
Your second example results in the expected `[1, 2, 3, 4]`.
* * *
If you need to understand the algorithms, it might be easier when converting the `for`-notation to while-loops and to expand the decrement and increment operators:
/* first example */
var b = a[0],
len = a.length;
while (len) {
newArray.push(b);
len = len-1;
b = a[len];
}
/* second example */
var i = 0,
len = a.length;
while (i < len) {
newArray.push( a[i] );
i = i+1;
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 4,
"tags": "javascript"
} |
Portable way to find inode number
At first I used `stat -c %i file` (to help detect the presence of a jail), which seemed to work on any Linux distribution under the sun. On OS X' I had to use `ls -i file | cut -d ' ' -f 1`.
Is there some way to find the inode number of a file in a shell script which is portable across *nix platforms and does not depend on the notoriously capricious `ls`? | Possible solution: The POSIX spec for `ls` specifies `-i`, so maybe it's portable. Does anyone know of a popular implementation of `ls` which does _not_ support this, or prints it in a different way from the following example:
$ ls -di /
2 / | stackexchange-unix | {
"answer_score": 11,
"question_score": 10,
"tags": "shell, inode"
} |
How can I stabilize an unstable telescope?
I have an 80 mm refractor telescope on a tripod, but it shakes on every touch. It's very hard to see via 6 mm (x120) ocular. Even a little wind causes the image to become too unsteady.
How can I make my tripod more steady? | First make sure all your screws are tight, and that there isn't any shaking because of slack in any areas where things connect to each other.
Another thing you can do is buy vibration dampening pads to put your tripod on.
Finally, you can add counter weights and pendulum weights to the tripod to give it more mass to withstand the wind and touches. | stackexchange-physics | {
"answer_score": 9,
"question_score": 8,
"tags": "astronomy, telescopes"
} |
perl style regex to match nth item in a list
Trying to match the third item in this list:
/text word1, word2, some_other_word, word_4
I tried using this perl style regex to no avail:
([^, ]*, ){$m}([^, ]*),
I want to match ONLY the third word, nothing before or after, and no commas or whitespace. I need it to be a regex, this is not in a program but UltraEdit for a word file.
What can I use to match some_other_word (Or anything third in the list.) | Based on some input by the community members I made the following change to make the logic of the regex pattern clearer.
/^(?:(?:.(?<!,))+,){2}\s*(\w+).*/x
**Explanation**
/^ # 1.- Match start of line.
(?:(?:.(?<!,))+ # 2.- Match but don't capture a secuence of character not containing a comma ...
,) # 3.- followed by a comma
{2} # 4.- (exactly two times)
\s* # 5.- Match any optional space
(\w+) # 6.- Match and capture a secuence of the characters represented by \w a leat one character long.
.* # 7.- Match anything after that if neccesary.
/x
This is the one suggested previously.
/(?:\w+,?\s*){3}(\w+)/ | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "regex"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.