qid
int64 1
74.7M
| question
stringlengths 15
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 4
30.2k
| response_k
stringlengths 11
36.5k
|
---|---|---|---|---|---|
66,738,678 | ### When I load the following code using php...
`<?php <h1>Some text</h1> ?>`
### the tags are printed as text -
`<h1>Some text</h1>`
### Any ideas?
Found the answer - see my answer.
================================= | 2021/03/21 | [
"https://Stackoverflow.com/questions/66738678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14920090/"
] | You need to output the actual HTML code if you are placing any HTML code within PHP.
You can achieve this using [`echo()`](https://www.php.net/manual/en/function.echo.php).
```php
<?php
echo("<h1>Some text</h1>");
?>
``` | Found the issue, the content-type was set as json. |
66,738,678 | ### When I load the following code using php...
`<?php <h1>Some text</h1> ?>`
### the tags are printed as text -
`<h1>Some text</h1>`
### Any ideas?
Found the answer - see my answer.
================================= | 2021/03/21 | [
"https://Stackoverflow.com/questions/66738678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14920090/"
] | You need to output the actual HTML code if you are placing any HTML code within PHP.
You can achieve this using [`echo()`](https://www.php.net/manual/en/function.echo.php).
```php
<?php
echo("<h1>Some text</h1>");
?>
``` | ```
<?php echo "<h1>Some text</h1>"; ?>
```
```
<?php echo "<h1>Some text</h1>"; ?>
```
if you want to show a variable
```
<?php
$_varTest=2;
echo "<h1>Show variable {$_varTest}</h1>"; ?>
``` |
66,738,678 | ### When I load the following code using php...
`<?php <h1>Some text</h1> ?>`
### the tags are printed as text -
`<h1>Some text</h1>`
### Any ideas?
Found the answer - see my answer.
================================= | 2021/03/21 | [
"https://Stackoverflow.com/questions/66738678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14920090/"
] | ```
<h1><?php Some text ?></h1>
```
why dont you try this. | You must print it in order for it to appear the way you want it to
```
<?php echo"<h1>Some text</h1>" ?>
```
like this |
66,738,678 | ### When I load the following code using php...
`<?php <h1>Some text</h1> ?>`
### the tags are printed as text -
`<h1>Some text</h1>`
### Any ideas?
Found the answer - see my answer.
================================= | 2021/03/21 | [
"https://Stackoverflow.com/questions/66738678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14920090/"
] | ```
<h1><?php Some text ?></h1>
```
why dont you try this. | Found the issue, the content-type was set as json. |
66,738,678 | ### When I load the following code using php...
`<?php <h1>Some text</h1> ?>`
### the tags are printed as text -
`<h1>Some text</h1>`
### Any ideas?
Found the answer - see my answer.
================================= | 2021/03/21 | [
"https://Stackoverflow.com/questions/66738678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14920090/"
] | ```
<h1><?php Some text ?></h1>
```
why dont you try this. | ```
<?php echo "<h1>Some text</h1>"; ?>
```
```
<?php echo "<h1>Some text</h1>"; ?>
```
if you want to show a variable
```
<?php
$_varTest=2;
echo "<h1>Show variable {$_varTest}</h1>"; ?>
``` |
29,790,865 | Say I have the following:
```
wchar_t *str = L"Hello World!";
```
Is `L"Hello World!"` encoded in UTF-16LE or UTF-16BE?
**Note:** I am using Visual C++ 2010. | 2015/04/22 | [
"https://Stackoverflow.com/questions/29790865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4582812/"
] | Depends on your editor, VS2010 uses UTF-8 by default :) With a BOM so the compiler can tell. It can be changed, click the arrow on the Save button.
The compiler will turn it into UTF-16LE in the object file, there are no remaining big-endian machines supported by msvc++ that I know of, ARM cores all run little-endian these days. | You can safely assume that any wide character string on Windows uses little endian UTF-16 - see this answer for a more elaborate dive: [Can I safely assume that Windows installations will always be little-endian?](https://stackoverflow.com/questions/6449468/can-i-safely-assume-that-windows-installations-will-always-be-little-endian) |
33,259,989 | I have a method to get an image from a server, that image I'm getting it as a byte array so I'm converting to [UInt8].
The problem is that I don't find a way to convert the [UInt8] to an Image to show in my application.
This is the code that I'm using to get the image from the server:
```
func GetSnapshotFromCamera(user: String?, password: String?, deviceNumber: String?, deviceItemId: String?) throws -> [UInt8]?{
let url = SERVICEURL + "/GetSnapshotFromCamera/"+user! + "/" + password! + "/" + deviceNumber! + "/" + deviceItemId!
let data = ExecuteRequestService(url)
if(data != nil){
let dataConverted = try ResultEventImage.ParseResultSnapshotJson(data)
let json = NSString(data: dataConverted!, encoding:NSUTF8StringEncoding)
let snapshotObj = ResultEventImage.JsonToObject(json as! String)
return snapshotObj.ResultObject
}
return nil
}
``` | 2015/10/21 | [
"https://Stackoverflow.com/questions/33259989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5428766/"
] | What you want to do is convert the binary array ([UInt8]) into NSData first. You can do that with:
```
let data = NSData(bytes: [UInt8], length: 2)
```
(You need to give the length of the byte array)
After converting (and unwrapping every optional) convert it to UIImage with:
```
let image = UIImage(data: data)
```
And unwrap again to get non optional image. | try this:
```
if let array = try GetSnapshotFromCamera(...) {
let data = NSData(bytes: array, length: array.count)
let image = UIImage(data: data)
}
``` |
35,867,829 | I generate form fields dynamically using ng-repeat.
Everything works fine.
But now I want to use angular datepicker component and it is based on a directive. The problem is that this seems only to work for static content/id attributes. In case of the dynamic ones I get "field.Key" - the placeholder value -, and not the generated id. (even if in the generated sourcecode on the client the id is correct)
I also tried ng-id or ng-attr-id, same result.
Any hints how to get this value in a directive, or another workaround?
Here is the sample code:
```
html
<input id="{{field.Key}}" name="{{field.Key}}" type="text" date-time
data-ng-model="field.FieldValue" auto-close="true" value="{{''}}"/>
js
Module.directive('datePicker', ..., function datePickerDirective(...) {
return {
require: '?ngModel',
template: '<div ng-include="template"></div>',
scope: {
model: '=datePicker',
after: '=?',
before: '=?'
},
link: function (scope, element, attrs, ngModel) {
//generated value should be here, but is field.Key
var pickerID = element[0].id;
}
}];
``` | 2016/03/08 | [
"https://Stackoverflow.com/questions/35867829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/250773/"
] | ```js
$(document).ready(function(){
$("form").trigger("submit");
});
$('form').on('submit', function() { alert("ya"); });
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form method="post" action="action.php">
// somany divs
<input type="hidden" name="ivlue" value="er">
<input type="submit" style="display:none">
</form>
```
In firefox you need the submit button. You can hide it, but needs to be present. | If you want to submit you can use this code which is not using jquery, it is the plain js function
```
document.forms["formname"].submit();
```
And you need to have a form, which you identify with an id attribute in the form tag
```
<form id='formname' action='mypage.html'>
``` |
52,393,047 | Do you know why sync fibonacci method is faster than async/await and that is faster than async task?
I used async on every project method, so it's main this is so bad approach...
Code:
```
static int FibonacciSync(int number)
{
if (number == 0) { return 0; }
else if (number == 1) { return 1; }
else
{
var t1 = FibonacciSync(number - 1);
var t2 = FibonacciSync(number - 2);
return t1 + t2;
}
}
async static Task<int> FibonacciAwait(int number)
{
if (number == 0)
{ return 0; }
else if (number == 1)
{ return 1; }
else
{
var task1 = FibonacciAwait(number - 1);
var task2 = FibonacciAwait(number - 2);
return (await task1) + (await task2);
}
}
static Task<int> FibonacciAsync(int number)
{
if (number == 0)
{ return Task.FromResult(0); }
else if (number == 1)
{ return Task.FromResult(1); }
else
{
return FibonacciAsync(number - 1).ContinueWith(task1 =>
{
return FibonacciAsync(number - 2).ContinueWith(task2 =>
{
return task1.Result + task2.Result;
});
}).Unwrap();
}
}
```
Result:
* Sync: 00:00:00.0121900
* Await: 00:00:00.2118170
* Async: 00:00:02.6211660 | 2018/09/18 | [
"https://Stackoverflow.com/questions/52393047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3859310/"
] | >
> Do you know why sync fibonacci method is faster than async/await and that is faster than async task?
>
>
>
Asynchrony is not about improving *raw speed*. As you've discovered, it takes longer overall. If you use it poorly, as you have done, it makes things much, much slower for zero benefit.
The fundamental problem here is that you don't understand what asynchrony is for. **Asynchrony is for managing latency**. Once you internalize that fact, you'll start using it correctly.
*Latency* is the gap in time between when you *request* a computation or side effect, and when the computation or side effect is *complete*.
For example, suppose you are computing something that is *extremely computationally expensive*. You're computing a really complicated graphic, for example, and it is going to take more than 30 milliseconds to compute even if you dedicate an entire core to it. You do not want your user interface to stall while you're doing the computation, so you can put the computation onto another thread, dedicate a CPU to that thread, and await the result. **An await means "go find more work to do while I am waiting for a high latency operation to complete"**.
For example, suppose you are doing something that is *not* computationally expensive but requires waiting on an external resource. You're calling into a database, for example, and it is going to take more than 30 ms to get the result back. In this case **you do not want to spin up a thread**. That thread is just going to sleep waiting for the result! Instead you want to use the async version of the database access API, and *await the high latency result*.
In your example you don't have a high-latency operation to begin with, so it makes no sense to await it. All you're doing there is creating a lot of work for the runtime to create and manage the work queues, and that is work you are paying for but getting no benefit from. Your work takes *nanoseconds*; only use asynchrony for jobs that take *milliseconds* or longer.
**Only use async when you have a high-latency operation**. Async improves performance because it frees up a thread to keep on doing work while it is waiting for a high-latency result to appear. If there is no high-latency result then async will just slow everything down. | a good rule of thumb: only use async calls for functions that use an external resource: file system, database, http calls, ...
when you do in memory stuff, like calculating fibonacci, do it sync, the overhead of creating a seperate thread/context for in memory calculation is too much
unless you have a ui thread that is waiting for the calculation to be finished, you can implement it async, but be aware you will indeed have some performance loss ... |
57,834,492 | I have a string like this:
`"my bike, is very big"`
and i would like to split it in the following way.
```
["my","bike",",","is","very","big"]
``` | 2019/09/07 | [
"https://Stackoverflow.com/questions/57834492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7162942/"
] | What you describe is (almost) the [round half up](https://en.wikipedia.org/wiki/Rounding#Round_half_up) strategy. However using `int` it won't work for negative numbers:
```
>>> def round_half_up(x, n=0):
... shift = 10 ** n
... return int(x*shift + 0.5) / shift
...
>>> round_half_up(-1.26, 1)
-1.2
```
Instead you should use `math.floor` in order to handle negative number correctly:
```
>>> import math
>>>
>>> def round_half_up(x, n=0):
... shift = 10 ** n
... return math.floor(x*shift + 0.5) / shift
...
>>> round_half_up(-1.26, 1)
-1.3
```
This strategy suffers from the effect that it tends to distort statistics of a collection of numbers, such as the mean or the standard deviation. Suppose you have collected some numbers and all of them end in `.5`; then rounding each of them up will clearly increase the average:
```
>>> numbers = [-3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5]
>>> N = len(numbers)
>>> sum(numbers) / N
0.0
>>> sum(round_half_up(x) for x in numbers) / N
0.5
```
If we use the strategy [round half to even](https://en.wikipedia.org/wiki/Rounding#Round_half_to_even) instead this will cause some numbers to be rounded up and others to be rounded down and hence compensating each other:
```
>>> sum(round(x) for x in numbers) / N
0.0
```
As you can see, for the example, the average remains preserved.
This works of course only if the numbers are uniformly distributed. If there is a tendency to favor numbers of the form `odd + 0.5` then this strategy won't prevent a bias either:
```
>>> numbers = [i + 0.5 for i in range(-3, 3, 2)]
>>> N = len(numbers)
>>> sum(numbers) / N
-0.5
>>> sum(round_half_up(x) for x in numbers) / N
0.0
>>> sum(round(x) for x in numbers) / N
0.0
```
For this set of numbers, `round` is effectively doing "round half up" so both methods suffer from the same bias.
As you can see, the rounding strategy clearly influences the bias of several statistics such as the average. "round half to even" tends to remove that bias but obviously favors even over odd numbers and thus also distorts the original distribution.
A note on `float` objects
=========================
Due to limited floating point precision this "round half up" algorithm might also yield some unexpected surprises:
```
>>> round_half_up(-1.225, 2)
-1.23
```
Interpreting `-1.225` as a *decimal number* we would expect the result to be `-1.22` instead. We get `-1.23` because the intermediate *floating point number* in `round_half_up` slips a bit over it's expected value:
```
>>> f'{-1.225 * 100 + 0.5:.20f}'
'-122.00000000000001421085'
```
`floor`'ing that numbers gives us `-123` (instead of `-122` if we had gotten `-122.0` before). That's due to floating point error and starts with the fact that `-1.225` is actually not stored as `-1.225` in memory but as a number which is a little bit smaller. For that reason using `Decimal` is the only way to get correct rounding in all cases. | My understanding is that your suggestion of `int(x+0.5)` should work fine because it returns an integer object that will be exact. However, your subsequent suggestion of dividing by 1000 to round to a certain number of decimal places will return a floating point object so will suffer from exactly the issue you are trying to avoid. Fundamentally you cannot avoid the issue of floating point precision unless you completely avoid the floating point type by using either decimal or pure integers. |
37,532 | If I have two dependent continuous random variables $X$ and $Y$ with known pdf's $f(x)$ and $f(y)$. How to calculate their join probability distribution $f(x, y)$?
For example if $Y = \sin{X}$ and I want to calculate the pdf of $Z$ where $Z = \frac{X}{Y}$ or $Z = X - Y$. So, how to find out $f(x, y)$ first? | 2011/05/07 | [
"https://math.stackexchange.com/questions/37532",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/953/"
] | If $Y$ is a regular function of $X$, $(X,Y)$ cannot have a density since $(X,Y)$ is always on the graph of the function, which has measure zero. But you should not use this to compute the distribution of $Z$ a function of $X$.
Rather, you could use the fact that $Z$ has density $f\_Z$ if and only if, for every measurable function $g$,
$$
E(g(Z))=\int g(z)f\_Z(z)\mathrm{d}z.
$$
But, if $Z=h(X)$, $E(g(Z))=E(g(h(X)))$, and by definition of the distribution of $X$,
$$
E(g(h(X)))=\int g(h(x))f\_X(x)\mathrm{d}x,
$$
where $f\_X$ is the density of $X$. In the end, you know $h$ and $f\_X$ and you must make the two expressions of $E(g(Z))$ coincide for *every* function $g$, hence a change of variable I will let you discover should yield an expression of $f\_Z$ depending on $f\_X$. | You can't. You need to know how they are dependent. |
44,316,854 | I really think that it would be beneficial to my workflow if I could just include a fully-functional component with a single php function call. Something like
ddl();
Which would produce an HTML drop down list, fully styled and functional. With external resources, I need to worry about including the JavaScript and CSS to get this working properly, but if I just included all of that within the ddl() function itself, it would make things much easier.
So something like:
```html
<?php
function ddl(){
<style>
.ddl{
//style
}
</style>
?>
<div class="ddl">
<!-- my drop down list -->
</div>
<script>
//Do ddl functionality
</script>
<?php
}
```
What are the real drawbacks to doing things this way? Is it worse for performance? | 2017/06/01 | [
"https://Stackoverflow.com/questions/44316854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5644982/"
] | For small projects - one to three pages - you probably won't ever notice much of an issue. Especially if you never duplicate functionality. However, if you want a scalable application, you really need to separate form from function. Style sheets are actually easier to maintain by looking at the relationship of styles amongst themselves. JavaScript is better managed in larger chunks than embedded scripts.
If you ever decide later to scale an application that has embedded styles and JavaScript, you have the headache to deal with separating these out - especially when you want to reuse functionality. And if you forget to remove a style tag from within your HTML, or worse - a style attribute - it could override your CSS file changes down the road, so the clean-up is really important.
There's also a caching benefit by placing JavaScript and CSS in separate files. When you have a function or a style that's repeated throughout your web app, the browser only has to load the code once per file. If, however, you've embedded it in every page, the browser has to reload all that every time.
For easier maintenance, clarity of code and caching speed, I vote you should always keep these separated from your HTML/PHP. | 1. Easier to manage cache, which will reduce bandwidth usage
2. No code duplication
3. Better practice for scalability purposes - maybe you have a interaction designer, graphical designer and a software developer. You wouldn't want everyone to work on the same file |
2,943,875 | Using a google code svn as a basic maven repository is easy.
However, using mvn site:deploy efficiently on google code seems hard.
So far, I found only these solutions:
* Deploy to a local file:/// and use a PERL script to delete the old and copy the new.
Source: <http://www.mail-archive.com/users@maven.apache.org/msg107719.html>
* Use wagen-svn to deploy. This is very slow (hours!) and does not delete old files
+ Plus all mime-types are wrong
I am looking for a solution that allows new developers in my projects to check out the current source and just use it, without requiring to install PERL or learn weird steps to perform or wait hours. | 2010/05/31 | [
"https://Stackoverflow.com/questions/2943875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123280/"
] | Would a solution like rsync be easier? You essentially want to mirror a locally-generated tree of HTML etc., to a remote server.
Otherwise, you could get Maven to generate and publish the site as part of a continuous integration build using, say, Hudson. Not suitable if you need the site to be globally available - unless you want to open your Hudson server. | I'd suggest you to use <https://maven2-repository.dev.java.net/> to deploy your open source artifacts. Quite simple to configure and use.
The main "issue" is that you'll need to create an account but you can use it only to deploy the artifacts and still have your source code hosted on Google Code |
2,943,875 | Using a google code svn as a basic maven repository is easy.
However, using mvn site:deploy efficiently on google code seems hard.
So far, I found only these solutions:
* Deploy to a local file:/// and use a PERL script to delete the old and copy the new.
Source: <http://www.mail-archive.com/users@maven.apache.org/msg107719.html>
* Use wagen-svn to deploy. This is very slow (hours!) and does not delete old files
+ Plus all mime-types are wrong
I am looking for a solution that allows new developers in my projects to check out the current source and just use it, without requiring to install PERL or learn weird steps to perform or wait hours. | 2010/05/31 | [
"https://Stackoverflow.com/questions/2943875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123280/"
] | I've found good instruction to do what do you want with good responses:
<http://babyloncandle.blogspot.com/2009/04/deploying-maven-artifacts-to-googlecode.html>
But I suggest to use normal simple http hosting, because it is much more faster than Google Code SVN. Your project is not the one, which needs site, while locates in Google Code. | I'd suggest you to use <https://maven2-repository.dev.java.net/> to deploy your open source artifacts. Quite simple to configure and use.
The main "issue" is that you'll need to create an account but you can use it only to deploy the artifacts and still have your source code hosted on Google Code |
2,943,875 | Using a google code svn as a basic maven repository is easy.
However, using mvn site:deploy efficiently on google code seems hard.
So far, I found only these solutions:
* Deploy to a local file:/// and use a PERL script to delete the old and copy the new.
Source: <http://www.mail-archive.com/users@maven.apache.org/msg107719.html>
* Use wagen-svn to deploy. This is very slow (hours!) and does not delete old files
+ Plus all mime-types are wrong
I am looking for a solution that allows new developers in my projects to check out the current source and just use it, without requiring to install PERL or learn weird steps to perform or wait hours. | 2010/05/31 | [
"https://Stackoverflow.com/questions/2943875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123280/"
] | How to deploy maven artifact to Google code svn?
I. Create m2 folder with releases and snaphots subfolders
II. Add dependency to [maven-svn-wagon](http://code.google.com/p/maven-svn-wagon/)
```
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.5</version>
<dependencies>
<dependency>
<groupId>com.google.code.maven-svn-wagon</groupId>
<artifactId>maven-svn-wagon</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
</plugin>
```
III. Add the path to the release and the snapshot repository
```
<distributionManagement>
<repository>
<id>project-name.googlecode.com</id>
<url>svn:https://project-name.googlecode.com/svn/m2/releases</url>
</repository>
<snapshotRepository>
<id>project-name.googlecode.com</id>
<url>svn:https://project-name.googlecode.com/svn/m2/snapshots</url>
</snapshotRepository>
</distributionManagement>
```
IV. Don't forget to add to settings.xml your auth. code
```
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<servers>
<server>
<id>project-name.googlecode.com</id>
<username>yourlogin</username>
<password>yoursvpassword</password>
</server>
</servers>
</settings>
```
V. Do what you usually do for generating a site (you may consider having a look at [maven-svn-wagon pom file](https://code.google.com/p/maven-svn-wagon/source/browse/trunk/pom.xml) with settings for maven-site-plugin)
VI. `mvn clean deploy`
[Example of such pom](https://code.google.com/p/java-vk-oauth20/source/browse/trunk/pom.xml)
Also, might be helpful: [maven-repository-for-google-code-project](https://stackoverflow.com/questions/1280470/maven-repository-for-google-code-project), [maven svn wagon](http://maven-svn-wagon.googlecode.com/svn/site/index.html), [MavenRepositoryInsideGoogleCode](http://code.google.com/p/maven-svn-wagon/wiki/MavenRepositoryInsideGoogleCode) | I'd suggest you to use <https://maven2-repository.dev.java.net/> to deploy your open source artifacts. Quite simple to configure and use.
The main "issue" is that you'll need to create an account but you can use it only to deploy the artifacts and still have your source code hosted on Google Code |
2,943,875 | Using a google code svn as a basic maven repository is easy.
However, using mvn site:deploy efficiently on google code seems hard.
So far, I found only these solutions:
* Deploy to a local file:/// and use a PERL script to delete the old and copy the new.
Source: <http://www.mail-archive.com/users@maven.apache.org/msg107719.html>
* Use wagen-svn to deploy. This is very slow (hours!) and does not delete old files
+ Plus all mime-types are wrong
I am looking for a solution that allows new developers in my projects to check out the current source and just use it, without requiring to install PERL or learn weird steps to perform or wait hours. | 2010/05/31 | [
"https://Stackoverflow.com/questions/2943875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123280/"
] | Here is the simplest configuration that works for me in my Google code projects that have a maven repository on Google code svn:
```
<build>
...
<extensions>
<extension>
<groupId>org.jvnet.wagon-svn</groupId>
<artifactId>wagon-svn</artifactId>
<version>1.9</version>
</extension>
</extensions>
</build>
<distributionManagement>
<repository>
<uniqueVersion>false</uniqueVersion>
<id>googlecode</id>
<url>svn:https://myproject.googlecode.com/svn/trunk/repo/</url>
</repository>
</distributionManagement>
```
Note the url:
Replace 'myproject' with your real project name and also make sure that your create a folder named 'repo' (or whatever you want) in that location using your svn client.
You can make sure by browsing the sources via your google code site.
After your pom is configured as above, just run **'mvn deploy'**.
Make sure you have your google code password at hand ...
Good luck ... | I'd suggest you to use <https://maven2-repository.dev.java.net/> to deploy your open source artifacts. Quite simple to configure and use.
The main "issue" is that you'll need to create an account but you can use it only to deploy the artifacts and still have your source code hosted on Google Code |
2,943,875 | Using a google code svn as a basic maven repository is easy.
However, using mvn site:deploy efficiently on google code seems hard.
So far, I found only these solutions:
* Deploy to a local file:/// and use a PERL script to delete the old and copy the new.
Source: <http://www.mail-archive.com/users@maven.apache.org/msg107719.html>
* Use wagen-svn to deploy. This is very slow (hours!) and does not delete old files
+ Plus all mime-types are wrong
I am looking for a solution that allows new developers in my projects to check out the current source and just use it, without requiring to install PERL or learn weird steps to perform or wait hours. | 2010/05/31 | [
"https://Stackoverflow.com/questions/2943875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123280/"
] | How to deploy maven artifact to Google code svn?
I. Create m2 folder with releases and snaphots subfolders
II. Add dependency to [maven-svn-wagon](http://code.google.com/p/maven-svn-wagon/)
```
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.5</version>
<dependencies>
<dependency>
<groupId>com.google.code.maven-svn-wagon</groupId>
<artifactId>maven-svn-wagon</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
</plugin>
```
III. Add the path to the release and the snapshot repository
```
<distributionManagement>
<repository>
<id>project-name.googlecode.com</id>
<url>svn:https://project-name.googlecode.com/svn/m2/releases</url>
</repository>
<snapshotRepository>
<id>project-name.googlecode.com</id>
<url>svn:https://project-name.googlecode.com/svn/m2/snapshots</url>
</snapshotRepository>
</distributionManagement>
```
IV. Don't forget to add to settings.xml your auth. code
```
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<servers>
<server>
<id>project-name.googlecode.com</id>
<username>yourlogin</username>
<password>yoursvpassword</password>
</server>
</servers>
</settings>
```
V. Do what you usually do for generating a site (you may consider having a look at [maven-svn-wagon pom file](https://code.google.com/p/maven-svn-wagon/source/browse/trunk/pom.xml) with settings for maven-site-plugin)
VI. `mvn clean deploy`
[Example of such pom](https://code.google.com/p/java-vk-oauth20/source/browse/trunk/pom.xml)
Also, might be helpful: [maven-repository-for-google-code-project](https://stackoverflow.com/questions/1280470/maven-repository-for-google-code-project), [maven svn wagon](http://maven-svn-wagon.googlecode.com/svn/site/index.html), [MavenRepositoryInsideGoogleCode](http://code.google.com/p/maven-svn-wagon/wiki/MavenRepositoryInsideGoogleCode) | Would a solution like rsync be easier? You essentially want to mirror a locally-generated tree of HTML etc., to a remote server.
Otherwise, you could get Maven to generate and publish the site as part of a continuous integration build using, say, Hudson. Not suitable if you need the site to be globally available - unless you want to open your Hudson server. |
2,943,875 | Using a google code svn as a basic maven repository is easy.
However, using mvn site:deploy efficiently on google code seems hard.
So far, I found only these solutions:
* Deploy to a local file:/// and use a PERL script to delete the old and copy the new.
Source: <http://www.mail-archive.com/users@maven.apache.org/msg107719.html>
* Use wagen-svn to deploy. This is very slow (hours!) and does not delete old files
+ Plus all mime-types are wrong
I am looking for a solution that allows new developers in my projects to check out the current source and just use it, without requiring to install PERL or learn weird steps to perform or wait hours. | 2010/05/31 | [
"https://Stackoverflow.com/questions/2943875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123280/"
] | Here is the simplest configuration that works for me in my Google code projects that have a maven repository on Google code svn:
```
<build>
...
<extensions>
<extension>
<groupId>org.jvnet.wagon-svn</groupId>
<artifactId>wagon-svn</artifactId>
<version>1.9</version>
</extension>
</extensions>
</build>
<distributionManagement>
<repository>
<uniqueVersion>false</uniqueVersion>
<id>googlecode</id>
<url>svn:https://myproject.googlecode.com/svn/trunk/repo/</url>
</repository>
</distributionManagement>
```
Note the url:
Replace 'myproject' with your real project name and also make sure that your create a folder named 'repo' (or whatever you want) in that location using your svn client.
You can make sure by browsing the sources via your google code site.
After your pom is configured as above, just run **'mvn deploy'**.
Make sure you have your google code password at hand ...
Good luck ... | Would a solution like rsync be easier? You essentially want to mirror a locally-generated tree of HTML etc., to a remote server.
Otherwise, you could get Maven to generate and publish the site as part of a continuous integration build using, say, Hudson. Not suitable if you need the site to be globally available - unless you want to open your Hudson server. |
2,943,875 | Using a google code svn as a basic maven repository is easy.
However, using mvn site:deploy efficiently on google code seems hard.
So far, I found only these solutions:
* Deploy to a local file:/// and use a PERL script to delete the old and copy the new.
Source: <http://www.mail-archive.com/users@maven.apache.org/msg107719.html>
* Use wagen-svn to deploy. This is very slow (hours!) and does not delete old files
+ Plus all mime-types are wrong
I am looking for a solution that allows new developers in my projects to check out the current source and just use it, without requiring to install PERL or learn weird steps to perform or wait hours. | 2010/05/31 | [
"https://Stackoverflow.com/questions/2943875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123280/"
] | How to deploy maven artifact to Google code svn?
I. Create m2 folder with releases and snaphots subfolders
II. Add dependency to [maven-svn-wagon](http://code.google.com/p/maven-svn-wagon/)
```
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.5</version>
<dependencies>
<dependency>
<groupId>com.google.code.maven-svn-wagon</groupId>
<artifactId>maven-svn-wagon</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
</plugin>
```
III. Add the path to the release and the snapshot repository
```
<distributionManagement>
<repository>
<id>project-name.googlecode.com</id>
<url>svn:https://project-name.googlecode.com/svn/m2/releases</url>
</repository>
<snapshotRepository>
<id>project-name.googlecode.com</id>
<url>svn:https://project-name.googlecode.com/svn/m2/snapshots</url>
</snapshotRepository>
</distributionManagement>
```
IV. Don't forget to add to settings.xml your auth. code
```
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<servers>
<server>
<id>project-name.googlecode.com</id>
<username>yourlogin</username>
<password>yoursvpassword</password>
</server>
</servers>
</settings>
```
V. Do what you usually do for generating a site (you may consider having a look at [maven-svn-wagon pom file](https://code.google.com/p/maven-svn-wagon/source/browse/trunk/pom.xml) with settings for maven-site-plugin)
VI. `mvn clean deploy`
[Example of such pom](https://code.google.com/p/java-vk-oauth20/source/browse/trunk/pom.xml)
Also, might be helpful: [maven-repository-for-google-code-project](https://stackoverflow.com/questions/1280470/maven-repository-for-google-code-project), [maven svn wagon](http://maven-svn-wagon.googlecode.com/svn/site/index.html), [MavenRepositoryInsideGoogleCode](http://code.google.com/p/maven-svn-wagon/wiki/MavenRepositoryInsideGoogleCode) | I've found good instruction to do what do you want with good responses:
<http://babyloncandle.blogspot.com/2009/04/deploying-maven-artifacts-to-googlecode.html>
But I suggest to use normal simple http hosting, because it is much more faster than Google Code SVN. Your project is not the one, which needs site, while locates in Google Code. |
2,943,875 | Using a google code svn as a basic maven repository is easy.
However, using mvn site:deploy efficiently on google code seems hard.
So far, I found only these solutions:
* Deploy to a local file:/// and use a PERL script to delete the old and copy the new.
Source: <http://www.mail-archive.com/users@maven.apache.org/msg107719.html>
* Use wagen-svn to deploy. This is very slow (hours!) and does not delete old files
+ Plus all mime-types are wrong
I am looking for a solution that allows new developers in my projects to check out the current source and just use it, without requiring to install PERL or learn weird steps to perform or wait hours. | 2010/05/31 | [
"https://Stackoverflow.com/questions/2943875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123280/"
] | Here is the simplest configuration that works for me in my Google code projects that have a maven repository on Google code svn:
```
<build>
...
<extensions>
<extension>
<groupId>org.jvnet.wagon-svn</groupId>
<artifactId>wagon-svn</artifactId>
<version>1.9</version>
</extension>
</extensions>
</build>
<distributionManagement>
<repository>
<uniqueVersion>false</uniqueVersion>
<id>googlecode</id>
<url>svn:https://myproject.googlecode.com/svn/trunk/repo/</url>
</repository>
</distributionManagement>
```
Note the url:
Replace 'myproject' with your real project name and also make sure that your create a folder named 'repo' (or whatever you want) in that location using your svn client.
You can make sure by browsing the sources via your google code site.
After your pom is configured as above, just run **'mvn deploy'**.
Make sure you have your google code password at hand ...
Good luck ... | I've found good instruction to do what do you want with good responses:
<http://babyloncandle.blogspot.com/2009/04/deploying-maven-artifacts-to-googlecode.html>
But I suggest to use normal simple http hosting, because it is much more faster than Google Code SVN. Your project is not the one, which needs site, while locates in Google Code. |
7,712,418 | Can you help to achieve the goal I mentioned in the commented block below to complete sample unit test?
Idea is how to check on a mock object, if one of its methods is called with a type instance that has a particular property is set to expected value/
```
private IMyObject stub = MockRepository.GenerateMock<IMyObject>();
[TestMethod]
public void MakeMyJob_RecievesValidData_CallsRenderWithCorrectParameter()
{
SomeUtility.MakeMyJob(5,10,stub);
stub.AsswertWasCalled(s=>s.Render(Arg<IViewModel>.Is. //What next?
// In order to check if Render is called
// with a IViewModel instance
// whoose Person.Name property is "Peter"
}
``` | 2011/10/10 | [
"https://Stackoverflow.com/questions/7712418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136141/"
] | I think you're looking for argument constraints in Rhino Mocks. I had a go at a few of the frameworks sometime ago - [link](http://madcoderspeak.blogspot.com/2010/01/meet-frameworks-rhino-v-moq-v-jmock.html#scen9). I think you're looking for
`Arg<IViewModel>.Matches (vm => vm.Person.Name == "Peter" )` | Look at the [reference](http://ayende.com/wiki/Rhino+Mocks+3.5.ashx):
```
stub.AsswertWasCalled(s=>s.Render(Arg<IViewModel>.Property("Person", "John")))
``` |
2,555,856 | Here is theorem 1.14 from Rudin's RCA:
>
> If $f\_n : X \to [-\infty, \infty]$ is measurable for $n=1,2,3,...$, and $g = \sup\_{n \ge 1} f\_n$ and $h = \limsup\limits\_{n \to \infty} f\_n$, then $g$ and $h$ are measurable.
>
>
>
Immediately following this is the corollary (a):
>
> The limit of every pointwise convergent sequence of complex measurable functions is measurable.
>
>
>
I don't see how this is a corollary of theorem 1.14, since the theorem concerns (extended) real-valued functions, whereas the sequence of functions in the corollary take on values in $\Bbb{C}$. | 2017/12/07 | [
"https://math.stackexchange.com/questions/2555856",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/193319/"
] | Hint: Apply the theorem for $-f\_n$. You will get the inf version and the liminf version. Now when limsup and liminf are measurable, what can you say about the limit when it exists?
Update: Sorry I didn't read your question fully. You wanted to know how this result for reals extends to complex functions. Well, any complex measurable function $f$ is of the form $Re(f) + iIm(f)$. Also if $\lim\_n f\_n =f$ where $f\_n$ are complex measurable functions then note that this is iff $Re(f\_{n}) \to Re(f)$ and $Im(f\_{n}) \to Im(f)$. | I think the $h$ should be $h=\lim\_{n}\sup\_{k\geq n}f\_{k}$. If we can show that for each $n$, $\sup\_{k\geq n}f\_{k}$ is measurable, then the corollary applies to $h$ along with $(\sup\_{k\geq n}f\_{k})\_{n}$.
Now we see that
\begin{align\*}
\left(\sup\_{k\geq n}f\_{k}\right)^{-1}(a,\infty]=\bigcup\_{k\geq n}f\_{k}^{-1}(a,\infty].
\end{align\*} |
69,863,212 | This is my script mytest.py.
```
import argparse
parser = argparse.ArgumentParser(description="Params")
parser.add_argument(
"--value")
def test(args):
print(args.value)
args = parser.parse_args()
test(args)
```
I want to pass argument store in variable `val`
```
val =1
!python mytest.py --value val
```
instead of printing 1 it print `val`. How to send 1 stored in variable val. | 2021/11/06 | [
"https://Stackoverflow.com/questions/69863212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11170350/"
] | You want to `sapply`/`lapply` the `get` function here. For example:
```r
a <- c(2, 5, NA, NA, 6, NA)
b <- c(NA, 1, 3, 4, NA, 8)
nmes <- c("a", "b")
# Apply get() to each name in the nmes vector
# Then convert the resulting matrix to a data frame
as.data.frame(sapply(nms, get))
```
```
a b
1 2 NA
2 5 1
3 NA 3
4 NA 4
5 6 NA
6 NA 8
```
Technically you can do this using `cbind`, but it's more awkward:
```r
# Convert the vector of names to a list of vectors
# Then bind those vectors together as columns
do.call(cbind, lapply(nms, get))
``` | We can use `mget` to 'get' a list, then `"loop-unlist"` with `sapply` and `function(x) x` or `[` to create a matrix
```
sapply(mget(vectornames), \(x) x)
#OR
sapply(mget(vectornames), `[`)
a b
[1,] 2 NA
[2,] 5 1
[3,] NA 3
[4,] NA 4
[5,] 6 NA
[6,] NA 8
``` |
38,936,124 | This media query is not working as I expected it to.
What I want to do is hide an element if the window is below 544px, and also hide it if it is above 767px. So it will only be visible while the window is between 544px and 767px.
```
@media (max-width: 544px) and (min-width: 767px) {
.show-sm-only {
display: none !important;
}
}
```
It seems that they work separately, but not together.
How do I achieve this? | 2016/08/13 | [
"https://Stackoverflow.com/questions/38936124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/425823/"
] | You can combine two media queries in one, like this:
```
@media (max-width: 544px), (min-width: 767px) {
.show-sm-only {
display: none !important;
}
}
```
**EDIT** This will hide `.show-sm-only` on screen smaller than (max-width) 544px and on screen bigger than (min-width) 767px. | You want this, your rules are the wrong way round. Right now you're saying it must be smaller than (max-width) 544px, but bigger than (min-width) 767px, which is impossible. See below how they are the other way round.
**EDIT** As per the comments. To do `or` (instead of `and`, which for your situation is impossible), separate with a comma:
```
@media (max-width: 544px), (min-width: 767px) {
.show-sm-only {
display: none !important;
}
}
``` |
38,936,124 | This media query is not working as I expected it to.
What I want to do is hide an element if the window is below 544px, and also hide it if it is above 767px. So it will only be visible while the window is between 544px and 767px.
```
@media (max-width: 544px) and (min-width: 767px) {
.show-sm-only {
display: none !important;
}
}
```
It seems that they work separately, but not together.
How do I achieve this? | 2016/08/13 | [
"https://Stackoverflow.com/questions/38936124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/425823/"
] | If you want a media query that is applied when BOTH conditions are true (which I think is what you're looking for here), use another `and`. Here it's hidden by default, and only visible when between 544px to 767px.
```
.my-element {
display: none;
@media (min-width: 544px) and (max-width: 767px) {
display: block;
}
}
``` | You want this, your rules are the wrong way round. Right now you're saying it must be smaller than (max-width) 544px, but bigger than (min-width) 767px, which is impossible. See below how they are the other way round.
**EDIT** As per the comments. To do `or` (instead of `and`, which for your situation is impossible), separate with a comma:
```
@media (max-width: 544px), (min-width: 767px) {
.show-sm-only {
display: none !important;
}
}
``` |
38,936,124 | This media query is not working as I expected it to.
What I want to do is hide an element if the window is below 544px, and also hide it if it is above 767px. So it will only be visible while the window is between 544px and 767px.
```
@media (max-width: 544px) and (min-width: 767px) {
.show-sm-only {
display: none !important;
}
}
```
It seems that they work separately, but not together.
How do I achieve this? | 2016/08/13 | [
"https://Stackoverflow.com/questions/38936124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/425823/"
] | You can combine two media queries in one, like this:
```
@media (max-width: 544px), (min-width: 767px) {
.show-sm-only {
display: none !important;
}
}
```
**EDIT** This will hide `.show-sm-only` on screen smaller than (max-width) 544px and on screen bigger than (min-width) 767px. | If you want a media query that is applied when BOTH conditions are true (which I think is what you're looking for here), use another `and`. Here it's hidden by default, and only visible when between 544px to 767px.
```
.my-element {
display: none;
@media (min-width: 544px) and (max-width: 767px) {
display: block;
}
}
``` |
89,024 | I have a window with a moving vertical part, so to open and close this window I need to slide the moving part left or right. And the window has horizontal blinds on it.
I'd like to install a portable A/C and put its exhaust into this window, but I think the portable A/C exhaust would get in the way of the blinds.
What is the best way to install the exhaust, while keeping the blinds functional and aesthetic?
One of the options I see is to install vertical shades, but if I install them in one window, I would need to replace window blinds to vertical in all the house windows to keep a coherent appearance. | 2016/04/20 | [
"https://diy.stackexchange.com/questions/89024",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/52902/"
] | The deeper the better; ideally, it should be as deep as the range. Closer to the burners is better too, as is a higher airflow, within reason. Beyond 300 CFM, you might need a makeup air system or to be diligent about opening a window when it's running.
More info: <http://www.greenbuildingadvisor.com/blogs/dept/green-building-curmudgeon/why-range-hoods-don-t-work> | I couldn't find anything in International Residential Code that specifies range hood size, so it would appear that size is more of a style choice. Table M1507.4 does say that the minimum exhaust rate of the hood must be 100 CFM intermittent, or 25 CFM continuous.
Section M1503.4 of the IRC says that if the exhaust hood exhausts 400 CFM or more, then you must provide makeup air at the same rate. It also says that the makeup air system shall provide a means of closure, and must automatically and simultaneously operate with the exhaust system. |
711,856 | Question:
$$
\text{It is given that } y= \frac{3a+2}{2a-4} \text{and }x= \frac{a+3}{a+8} \\
$$
$$
\text{Express } y \text{ in terms of } x.
$$
From using $x$ to solve for $a$, I discovered that
$$
a = \frac{8x-3}{1-x}
$$
Then I proceeded to substitute $a$ into $y$. I did this twice to ensure no mistakes are made, and my final answer for both was
$$
\frac{22x-7}{20x-10}
$$
There's a problem, the correct answer is
$$
\frac{7-22x}{10-20x}
$$
This makes me want to cry, more so because I checked it twice and I was very careful about my working out, here it is:
$$
\frac{2+ 3(\frac{8x-3}{1-x})}{ 2(\frac{8x-3}{1-x}) -4 }
$$
$$\rightarrow{}$$
$$
\frac{(\frac{2(1-x) + 3(8x-3)}{1-x})}{(\frac{-4(1-x)+2(8x-3)}{1-x})}
$$
$$\rightarrow{}$$
$$
\frac{2(1-x) + 3(8x-3)}{1-x} \* \frac{1-x}{-4(1-x)+2(8x-3)}
$$
$$\rightarrow{}$$
$$
\frac{22x-7}{1-x} \* \frac{1-x}{20x-10}
$$
The $(1-x)$'s cancel out
$$\rightarrow{}$$
$$
\frac{22x-7}{20x-10}
$$
Can someone please tell me as to what I did incorrectly in the process? Thank you in advance! | 2014/03/14 | [
"https://math.stackexchange.com/questions/711856",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/90332/"
] | Your answer is $$\frac{22x-7}{20x-10}$$
And the books "correct" answer is $$\frac{7-22x}{10-20x}$$
Yes?
Notice what happens when you multiply both the numerator and denominator in your answer by $-1$? You're very welcome. | You got the correct answer. Just multiply both numerator and denominator by -1
$$\frac{22x-7}{20x-10} = \frac{-1}{-1} \times \frac{7-22x}{10-20x}$$ |
25,423,477 | I´m coding my own real time visitors counter in PHP and ajax.
Everything is working OK, but there is one small problem, being that every time the ajax call is made it counts as an extra visit.
I know how to sort out specific visitors based on User Agents, such as bots etc., so if I could only specify a User Agent in the ajax call I should be able to make the ajax call itself not count as a visit.
Now, here is my question, how do I specify the user agent correctly withing the Ajax call??
In this particular case I want to specify the User Agent as a "googlebot" or similar..
Here is my working ajax code:
```
<script type="text/javascript">
var interval = 5000; // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
jQuery.ajax({
type: 'POST',
url: '/codes/LiveVisitsStats/postlivecounter.php',
data: jQuery(this).serialize(),
success: function (data) {
var arr = data.split('|');
jQuery('#counterint').html(arr[0]);
jQuery('#extrainfoscounter').html(arr[1]);
},
complete: function (data) {
// Schedule the next
setTimeout(doAjax, interval);
}
});
}
setTimeout(doAjax, interval);
</script>
```
A little extra information / clarification..
The tracking code itself works perfectly.
The problem is only in the Front-end UI, where the stats are being displayed dynamically with ajax, being that everytime the ajax call updates the stats info on page it also adds a visit count from the current user viewing the ajax-powered UI. | 2014/08/21 | [
"https://Stackoverflow.com/questions/25423477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2104024/"
] | Don't know PHP, but in C# this is how I determine if it is AJAX from jQuery:
```
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest"){
// this is AJAX
}
```
So you can avoid updating your db if above is `true`. I'm sure you know the equivalent in PHP. | >
> Everything is working OK, but there is one small problem, being that every time the ajax call is made it counts as an extra visit.
>
>
>
A (somewhat) better solution is make a user identifiable using a certain value. I suggest cookies.
* Generate a cookie on page load containing a unique value, like some UUID or something.
* Make sure that cookie expires in the distant future
* If that cookie exists already, leave it be.
Each time a user requests to a server, cookies get carried along. The server can use that value to identify a user. |
25,423,477 | I´m coding my own real time visitors counter in PHP and ajax.
Everything is working OK, but there is one small problem, being that every time the ajax call is made it counts as an extra visit.
I know how to sort out specific visitors based on User Agents, such as bots etc., so if I could only specify a User Agent in the ajax call I should be able to make the ajax call itself not count as a visit.
Now, here is my question, how do I specify the user agent correctly withing the Ajax call??
In this particular case I want to specify the User Agent as a "googlebot" or similar..
Here is my working ajax code:
```
<script type="text/javascript">
var interval = 5000; // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
jQuery.ajax({
type: 'POST',
url: '/codes/LiveVisitsStats/postlivecounter.php',
data: jQuery(this).serialize(),
success: function (data) {
var arr = data.split('|');
jQuery('#counterint').html(arr[0]);
jQuery('#extrainfoscounter').html(arr[1]);
},
complete: function (data) {
// Schedule the next
setTimeout(doAjax, interval);
}
});
}
setTimeout(doAjax, interval);
</script>
```
A little extra information / clarification..
The tracking code itself works perfectly.
The problem is only in the Front-end UI, where the stats are being displayed dynamically with ajax, being that everytime the ajax call updates the stats info on page it also adds a visit count from the current user viewing the ajax-powered UI. | 2014/08/21 | [
"https://Stackoverflow.com/questions/25423477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2104024/"
] | Don't know PHP, but in C# this is how I determine if it is AJAX from jQuery:
```
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest"){
// this is AJAX
}
```
So you can avoid updating your db if above is `true`. I'm sure you know the equivalent in PHP. | I found out that the ajax call did in fact not cause visit hits. The rogue hit counts came from another compontent in CMS system, and I fixed this by tweaking the core engine to disregard counts when user reloads same page. Pretty simple. |
15,854,442 | In my broadcast receiver activity I need to run some code when an alert is fired which I can get working no problem, but I need to make sure my Map activity is on the screen when this code is run, so I am trying to start the Map activity with an intent but this crashes the application and I do not know why. Here is the broadcast receiver class:
```
public class ProximityIntentReceiver extends BroadcastReceiver {
private static final int NOTIFICATION_ID = 1000;
Map mp = new Map();
String con;
int idpassed = 0;
@Override
public void onReceive(Context context, Intent intent) {
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Boolean entering = intent.getBooleanExtra(key, false);
if (entering) {
Log.d(getClass().getSimpleName(), "entering");
} else {
Log.d(getClass().getSimpleName(), "exiting");
}
con = intent.getStringExtra("mc");
idpassed = intent.getIntExtra("id", 0);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, NoteEdit.class);
long ii = Long.valueOf(idpassed);
notificationIntent.putExtra(MapDbAdapter.KEY_ROWID, ii);
PendingIntent pendingIntent = PendingIntent.getActivity(context,
intent.getIntExtra("id", 0), notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = createNotification(context);
String glat = String.valueOf(intent.getDoubleExtra("gl", 0.0));
String g = String.valueOf(Map.goingToLat);
// Depending on the type of marker fire a certain notification
if ((intent.getStringExtra("mc").equals("contact"))
&& (!g.equals(glat))) {
notification.setLatestEventInfo(context, "CONTACT",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
}
else if ((intent.getStringExtra("mc").equals("contact"))
&& (g.equals(glat))) {
notification.setLatestEventInfo(context, "DESTINATION",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
accessMap(context);
}
if ((intent.getStringExtra("mc").equals("park")) && (!g.equals(glat))) {
notification.setLatestEventInfo(context, "PARK",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
}
else if ((intent.getStringExtra("mc").equals("park"))
&& (g.equals(glat))) {
notification.setLatestEventInfo(context, "DESTINATION",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
accessMap(context);
}
if ((intent.getStringExtra("mc").equals("food")) && (!g.equals(glat))) {
notification.setLatestEventInfo(context, "FOOD",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
}
else if ((intent.getStringExtra("mc").equals("food"))
&& (g.equals(glat))) {
notification.setLatestEventInfo(context, "DESTINATION",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
accessMap(context);
}
if ((intent.getStringExtra("mc").equals("bar")) && (!g.equals(glat))) {
notification.setLatestEventInfo(context, "BAR",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
}
else if ((intent.getStringExtra("mc").equals("bar"))
&& (g.equals(glat))) {
notification.setLatestEventInfo(context, "DESTINATION",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
accessMap(context);
}
if ((intent.getStringExtra("mc").equals("shopping"))
&& (!g.equals(glat))) {
notification.setLatestEventInfo(context, "SHOPPING",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
}
else if ((intent.getStringExtra("mc").equals("shopping"))
&& (g.equals(glat))) {
notification.setLatestEventInfo(context, "DESTINATION",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
accessMap(context);
}
if ((intent.getStringExtra("mc").equals("caution"))
&& (!g.equals(glat))) {
notification.setLatestEventInfo(
context,
"CAUTION",
"Beware, you are approaching "
+ intent.getStringExtra("title"), pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
}
else if ((intent.getStringExtra("mc").equals("caution"))
&& (g.equals(glat))) {
notification.setLatestEventInfo(
context,
"DESTINATION",
"Beware, you are approaching "
+ intent.getStringExtra("title"), pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
accessMap(context);
}
}
public void accessMap(Context context) {
Intent openNext = new Intent("com.timer.MAP");
context.startActivity(openNext);
Map.destination = null;
Map.goingToLat = 0;
Map.mtv.setText("Select a new Destination!");
Map.scanOptions();
Map.num = 0;
Map.playr.stop();
Map.playr.reset();
Map.playr.release();
Map.handler.removeCallbacks(Map.getRunnable());
Map.passing = true;
}
private Notification createNotification(Context context) {
Notification notification = new Notification();
if (con.equals("contact")) {
notification.icon = R.drawable.contact;
notification.sound = Uri
.parse("android.resource://com.example.newmaps/"
+ R.raw.contact);
}
else if (con.equals("caution")) {
notification.icon = R.drawable.caution;
notification.sound = Uri
.parse("android.resource://com.example.newmaps/"
+ R.raw.caution);
}
else if (con.equals("shopping")) {
notification.icon = R.drawable.shopping;
notification.sound = Uri
.parse("android.resource://com.example.newmaps/"
+ R.raw.shopping);
}
else if (con.equals("bar")) {
notification.icon = R.drawable.bar;
notification.sound = Uri
.parse("android.resource://com.example.newmaps/"
+ R.raw.bar);
}
else if (con.equals("park")) {
notification.icon = R.drawable.park;
notification.sound = Uri
.parse("android.resource://com.example.newmaps/"
+ R.raw.park);
}
else if (con.equals("food")) {
notification.icon = R.drawable.food;
notification.sound = Uri
.parse("android.resource://com.example.newmaps/"
+ R.raw.food);
}
notification.when = System.currentTimeMillis();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.ledARGB = Color.WHITE;
notification.ledOnMS = 1500;
notification.ledOffMS = 1500;
return notification;
}
}
```
In the accessMap method you can see where I am trying to start the map activity via an intent but the app crashes, here is what I copied from the logcat:
```
04-06 18:04:04.363: D/ProximityIntentReceiver(5836): entering
04-06 18:04:04.433: D/ProximityIntentReceiver(5836): entering
04-06 18:04:04.463: D/ProximityIntentReceiver(5836): entering
04-06 18:04:04.473: D/ProximityIntentReceiver(5836): entering
04-06 18:04:04.513: D/ProximityIntentReceiver(5836): entering
04-06 18:04:04.543: D/MediaPlayer(5836): stop() mUri is android.resource://com.example.newmaps/2131034121
04-06 18:04:04.853: D/ProximityIntentReceiver(5836): entering
04-06 18:04:04.993: I/System.out(5836): 1Bert
04-06 18:04:04.993: W/dalvikvm(5836): threadid=1: thread exiting with uncaught exception (group=0x4205c450)
04-06 18:04:05.003: E/AndroidRuntime(5836): FATAL EXCEPTION: main
04-06 18:04:05.003: E/AndroidRuntime(5836): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.newmaps/com.example.memoryGuide.Map}: java.lang.NullPointerException
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2065)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2090)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.app.ActivityThread.access$600(ActivityThread.java:136)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1201)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.os.Handler.dispatchMessage(Handler.java:99)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.os.Looper.loop(Looper.java:137)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.app.ActivityThread.main(ActivityThread.java:4802)
04-06 18:04:05.003: E/AndroidRuntime(5836): at java.lang.reflect.Method.invokeNative(Native Method)
04-06 18:04:05.003: E/AndroidRuntime(5836): at java.lang.reflect.Method.invoke(Method.java:511)
04-06 18:04:05.003: E/AndroidRuntime(5836): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:813)
04-06 18:04:05.003: E/AndroidRuntime(5836): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:580)
04-06 18:04:05.003: E/AndroidRuntime(5836): at dalvik.system.NativeStart.main(Native Method)
04-06 18:04:05.003: E/AndroidRuntime(5836): Caused by: java.lang.NullPointerException
04-06 18:04:05.003: E/AndroidRuntime(5836): at com.example.memoryGuide.Map.onCreate(Map.java:161)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.app.Activity.performCreate(Activity.java:5013)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2029)
04-06 18:04:05.003: E/AndroidRuntime(5836): ... 11 more
04-06 18:04:10.403: E/Trace(6312): error opening trace file: No such file or directory (2)
04-06 18:04:10.643: D/-heap(6312): GC_FOR_ALLOC freed 81K, 5% free 7809K/8195K, paused 26ms, total 31ms
04-06 18:04:10.703: D/-heap(6312): GC_CONCURRENT freed 1K, 4% free 11904K/12359K, paused 16ms+8ms, total 46ms
04-06 18:04:11.083: D/-heap(6312): GC_CONCURRENT freed 671K, 7% free 12580K/13511K, paused 14ms+18ms, total 52ms
04-06 18:04:11.363: I/System.out(6312): 1Bert
04-06 18:04:11.643: D/-heap(6312): GC_CONCURRENT freed 561K, 6% free 13606K/14407K, paused 24ms+5ms, total 86ms
04-06 18:04:11.803: I/Adreno200-EGL(6312): <qeglDrvAPI_eglInitialize:299>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_REL_RB1.04.01.01.06.043_msm7627a_JB_REL_RB1.2_Merge_release_AU (Merge)
04-06 18:04:11.803: I/Adreno200-EGL(6312): Build Date: 12/10/12 Mon
04-06 18:04:11.803: I/Adreno200-EGL(6312): Local Branch:
04-06 18:04:11.803: I/Adreno200-EGL(6312): Remote Branch: m/jb_rel_rb1.2
04-06 18:04:11.803: I/Adreno200-EGL(6312): Local Patches: NONE
04-06 18:04:11.803: I/Adreno200-EGL(6312): Reconstruct Branch: NOTHING
04-06 18:04:12.103: D/-heap(6312): GC_FOR_ALLOC freed 1599K, 14% free 13626K/15815K, paused 27ms, total 37ms
04-06 18:04:12.793: D/-heap(6312): GC_FOR_ALLOC freed 1067K, 11% free 14190K/15815K, paused 42ms, total 47ms
04-06 18:04:13.553: D/-heap(6312): GC_CONCURRENT freed 1799K, 16% free 14320K/16903K, paused 25ms+28ms, total 90ms
04-06 18:04:14.783: D/-heap(6312): GC_CONCURRENT freed 1546K, 14% free 14702K/16903K, paused 13ms+17ms, total 67ms
04-06 18:04:15.943: D/-heap(6312): GC_CONCURRENT freed 1555K, 11% free 15075K/16903K, paused 12ms+17ms, total 72ms
04-06 18:04:16.733: D/-heap(6312): GC_CONCURRENT freed 1666K, 11% free 15474K/17351K, paused 13ms+26ms, total 106ms
```
I spent a few hours experimenting and reading Android documentation and I am not sure if it is possible to start an activity via intent inside a broadcast receiver event, according to [this](http://developer.android.com/reference/android/content/BroadcastReceiver.html#ReceiverLifecycle) page. When the user reaches a destination the user is shown some options on the map activity screen, but if the alert fires when they are on another screen these options will never show on the map screen, that is why I am trying to make sure the Map screen is started before the rest of the code in the accessMap method is executed. Can anyone suggest how I should proceed to fix this? | 2013/04/06 | [
"https://Stackoverflow.com/questions/15854442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567371/"
] | You should pass the variables though intent
```
public void accessMap(Context context) {
Intent openNext = new Intent("com.timer.MAP");
openNext.putExtra("destination", null);
openNext.putExtra("goingToLat", 0);
openNext.putExtra("text for mtv", "Select a new Destination!");
.........
openNext.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(openNext);
}
``` | You can create a Notification and show it. If the user clicks on the Notification then you can launch your Map screen. |
15,854,442 | In my broadcast receiver activity I need to run some code when an alert is fired which I can get working no problem, but I need to make sure my Map activity is on the screen when this code is run, so I am trying to start the Map activity with an intent but this crashes the application and I do not know why. Here is the broadcast receiver class:
```
public class ProximityIntentReceiver extends BroadcastReceiver {
private static final int NOTIFICATION_ID = 1000;
Map mp = new Map();
String con;
int idpassed = 0;
@Override
public void onReceive(Context context, Intent intent) {
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Boolean entering = intent.getBooleanExtra(key, false);
if (entering) {
Log.d(getClass().getSimpleName(), "entering");
} else {
Log.d(getClass().getSimpleName(), "exiting");
}
con = intent.getStringExtra("mc");
idpassed = intent.getIntExtra("id", 0);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, NoteEdit.class);
long ii = Long.valueOf(idpassed);
notificationIntent.putExtra(MapDbAdapter.KEY_ROWID, ii);
PendingIntent pendingIntent = PendingIntent.getActivity(context,
intent.getIntExtra("id", 0), notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = createNotification(context);
String glat = String.valueOf(intent.getDoubleExtra("gl", 0.0));
String g = String.valueOf(Map.goingToLat);
// Depending on the type of marker fire a certain notification
if ((intent.getStringExtra("mc").equals("contact"))
&& (!g.equals(glat))) {
notification.setLatestEventInfo(context, "CONTACT",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
}
else if ((intent.getStringExtra("mc").equals("contact"))
&& (g.equals(glat))) {
notification.setLatestEventInfo(context, "DESTINATION",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
accessMap(context);
}
if ((intent.getStringExtra("mc").equals("park")) && (!g.equals(glat))) {
notification.setLatestEventInfo(context, "PARK",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
}
else if ((intent.getStringExtra("mc").equals("park"))
&& (g.equals(glat))) {
notification.setLatestEventInfo(context, "DESTINATION",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
accessMap(context);
}
if ((intent.getStringExtra("mc").equals("food")) && (!g.equals(glat))) {
notification.setLatestEventInfo(context, "FOOD",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
}
else if ((intent.getStringExtra("mc").equals("food"))
&& (g.equals(glat))) {
notification.setLatestEventInfo(context, "DESTINATION",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
accessMap(context);
}
if ((intent.getStringExtra("mc").equals("bar")) && (!g.equals(glat))) {
notification.setLatestEventInfo(context, "BAR",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
}
else if ((intent.getStringExtra("mc").equals("bar"))
&& (g.equals(glat))) {
notification.setLatestEventInfo(context, "DESTINATION",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
accessMap(context);
}
if ((intent.getStringExtra("mc").equals("shopping"))
&& (!g.equals(glat))) {
notification.setLatestEventInfo(context, "SHOPPING",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
}
else if ((intent.getStringExtra("mc").equals("shopping"))
&& (g.equals(glat))) {
notification.setLatestEventInfo(context, "DESTINATION",
"You are approaching " + intent.getStringExtra("title"),
pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
accessMap(context);
}
if ((intent.getStringExtra("mc").equals("caution"))
&& (!g.equals(glat))) {
notification.setLatestEventInfo(
context,
"CAUTION",
"Beware, you are approaching "
+ intent.getStringExtra("title"), pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
}
else if ((intent.getStringExtra("mc").equals("caution"))
&& (g.equals(glat))) {
notification.setLatestEventInfo(
context,
"DESTINATION",
"Beware, you are approaching "
+ intent.getStringExtra("title"), pendingIntent);
notificationManager.notify(intent.getIntExtra("id", -1),
notification);
accessMap(context);
}
}
public void accessMap(Context context) {
Intent openNext = new Intent("com.timer.MAP");
context.startActivity(openNext);
Map.destination = null;
Map.goingToLat = 0;
Map.mtv.setText("Select a new Destination!");
Map.scanOptions();
Map.num = 0;
Map.playr.stop();
Map.playr.reset();
Map.playr.release();
Map.handler.removeCallbacks(Map.getRunnable());
Map.passing = true;
}
private Notification createNotification(Context context) {
Notification notification = new Notification();
if (con.equals("contact")) {
notification.icon = R.drawable.contact;
notification.sound = Uri
.parse("android.resource://com.example.newmaps/"
+ R.raw.contact);
}
else if (con.equals("caution")) {
notification.icon = R.drawable.caution;
notification.sound = Uri
.parse("android.resource://com.example.newmaps/"
+ R.raw.caution);
}
else if (con.equals("shopping")) {
notification.icon = R.drawable.shopping;
notification.sound = Uri
.parse("android.resource://com.example.newmaps/"
+ R.raw.shopping);
}
else if (con.equals("bar")) {
notification.icon = R.drawable.bar;
notification.sound = Uri
.parse("android.resource://com.example.newmaps/"
+ R.raw.bar);
}
else if (con.equals("park")) {
notification.icon = R.drawable.park;
notification.sound = Uri
.parse("android.resource://com.example.newmaps/"
+ R.raw.park);
}
else if (con.equals("food")) {
notification.icon = R.drawable.food;
notification.sound = Uri
.parse("android.resource://com.example.newmaps/"
+ R.raw.food);
}
notification.when = System.currentTimeMillis();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.ledARGB = Color.WHITE;
notification.ledOnMS = 1500;
notification.ledOffMS = 1500;
return notification;
}
}
```
In the accessMap method you can see where I am trying to start the map activity via an intent but the app crashes, here is what I copied from the logcat:
```
04-06 18:04:04.363: D/ProximityIntentReceiver(5836): entering
04-06 18:04:04.433: D/ProximityIntentReceiver(5836): entering
04-06 18:04:04.463: D/ProximityIntentReceiver(5836): entering
04-06 18:04:04.473: D/ProximityIntentReceiver(5836): entering
04-06 18:04:04.513: D/ProximityIntentReceiver(5836): entering
04-06 18:04:04.543: D/MediaPlayer(5836): stop() mUri is android.resource://com.example.newmaps/2131034121
04-06 18:04:04.853: D/ProximityIntentReceiver(5836): entering
04-06 18:04:04.993: I/System.out(5836): 1Bert
04-06 18:04:04.993: W/dalvikvm(5836): threadid=1: thread exiting with uncaught exception (group=0x4205c450)
04-06 18:04:05.003: E/AndroidRuntime(5836): FATAL EXCEPTION: main
04-06 18:04:05.003: E/AndroidRuntime(5836): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.newmaps/com.example.memoryGuide.Map}: java.lang.NullPointerException
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2065)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2090)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.app.ActivityThread.access$600(ActivityThread.java:136)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1201)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.os.Handler.dispatchMessage(Handler.java:99)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.os.Looper.loop(Looper.java:137)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.app.ActivityThread.main(ActivityThread.java:4802)
04-06 18:04:05.003: E/AndroidRuntime(5836): at java.lang.reflect.Method.invokeNative(Native Method)
04-06 18:04:05.003: E/AndroidRuntime(5836): at java.lang.reflect.Method.invoke(Method.java:511)
04-06 18:04:05.003: E/AndroidRuntime(5836): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:813)
04-06 18:04:05.003: E/AndroidRuntime(5836): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:580)
04-06 18:04:05.003: E/AndroidRuntime(5836): at dalvik.system.NativeStart.main(Native Method)
04-06 18:04:05.003: E/AndroidRuntime(5836): Caused by: java.lang.NullPointerException
04-06 18:04:05.003: E/AndroidRuntime(5836): at com.example.memoryGuide.Map.onCreate(Map.java:161)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.app.Activity.performCreate(Activity.java:5013)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
04-06 18:04:05.003: E/AndroidRuntime(5836): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2029)
04-06 18:04:05.003: E/AndroidRuntime(5836): ... 11 more
04-06 18:04:10.403: E/Trace(6312): error opening trace file: No such file or directory (2)
04-06 18:04:10.643: D/-heap(6312): GC_FOR_ALLOC freed 81K, 5% free 7809K/8195K, paused 26ms, total 31ms
04-06 18:04:10.703: D/-heap(6312): GC_CONCURRENT freed 1K, 4% free 11904K/12359K, paused 16ms+8ms, total 46ms
04-06 18:04:11.083: D/-heap(6312): GC_CONCURRENT freed 671K, 7% free 12580K/13511K, paused 14ms+18ms, total 52ms
04-06 18:04:11.363: I/System.out(6312): 1Bert
04-06 18:04:11.643: D/-heap(6312): GC_CONCURRENT freed 561K, 6% free 13606K/14407K, paused 24ms+5ms, total 86ms
04-06 18:04:11.803: I/Adreno200-EGL(6312): <qeglDrvAPI_eglInitialize:299>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_REL_RB1.04.01.01.06.043_msm7627a_JB_REL_RB1.2_Merge_release_AU (Merge)
04-06 18:04:11.803: I/Adreno200-EGL(6312): Build Date: 12/10/12 Mon
04-06 18:04:11.803: I/Adreno200-EGL(6312): Local Branch:
04-06 18:04:11.803: I/Adreno200-EGL(6312): Remote Branch: m/jb_rel_rb1.2
04-06 18:04:11.803: I/Adreno200-EGL(6312): Local Patches: NONE
04-06 18:04:11.803: I/Adreno200-EGL(6312): Reconstruct Branch: NOTHING
04-06 18:04:12.103: D/-heap(6312): GC_FOR_ALLOC freed 1599K, 14% free 13626K/15815K, paused 27ms, total 37ms
04-06 18:04:12.793: D/-heap(6312): GC_FOR_ALLOC freed 1067K, 11% free 14190K/15815K, paused 42ms, total 47ms
04-06 18:04:13.553: D/-heap(6312): GC_CONCURRENT freed 1799K, 16% free 14320K/16903K, paused 25ms+28ms, total 90ms
04-06 18:04:14.783: D/-heap(6312): GC_CONCURRENT freed 1546K, 14% free 14702K/16903K, paused 13ms+17ms, total 67ms
04-06 18:04:15.943: D/-heap(6312): GC_CONCURRENT freed 1555K, 11% free 15075K/16903K, paused 12ms+17ms, total 72ms
04-06 18:04:16.733: D/-heap(6312): GC_CONCURRENT freed 1666K, 11% free 15474K/17351K, paused 13ms+26ms, total 106ms
```
I spent a few hours experimenting and reading Android documentation and I am not sure if it is possible to start an activity via intent inside a broadcast receiver event, according to [this](http://developer.android.com/reference/android/content/BroadcastReceiver.html#ReceiverLifecycle) page. When the user reaches a destination the user is shown some options on the map activity screen, but if the alert fires when they are on another screen these options will never show on the map screen, that is why I am trying to make sure the Map screen is started before the rest of the code in the accessMap method is executed. Can anyone suggest how I should proceed to fix this? | 2013/04/06 | [
"https://Stackoverflow.com/questions/15854442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567371/"
] | You should pass the variables though intent
```
public void accessMap(Context context) {
Intent openNext = new Intent("com.timer.MAP");
openNext.putExtra("destination", null);
openNext.putExtra("goingToLat", 0);
openNext.putExtra("text for mtv", "Select a new Destination!");
.........
openNext.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(openNext);
}
``` | Set the flag `FLAG_ACTIVITY_NEW_TASK` on the `Intent`.
But you really shouldn't be launching activity in this way. An activity seemingly popping up out of nowhere is a weird/undesirable user experience. The notification you are setting should be sufficient, then the user can decide whether he/she wants to launch your app. Just my 2¢ :D |
249,691 | If TLS communication uses ciphers that does not support forward secrecy[FS] (like RSA key exchange ciphers), confidentiality of the past communication is compromised if the private key is compromised. But will the integrity also gets compromised in this scenario? I got this doubt after seeing the CVSS scoring in this [link](https://www.tenable.com/plugins/was/98617). Vector: CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:L/A:N - The severity of integrity compromise is given as Low. Could anyone explain how integrity is getting affected in the absence of FS? | 2021/05/25 | [
"https://security.stackexchange.com/questions/249691",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/153738/"
] | Generally, the integrity wouldn't be impacted. Usually it can't be, really, since the communication was presumably recorded some time ago. However, the symmetric key used for integrity (HMACs or AEAD modes) is exposed, and that could be a meaningful impact in some specific cases.
1. The attacker has a man-in-the-middle position on an ongoing TLS channel, and compromised the private key after the TLS handshake but recorded the handshake and encrypted traffic. In this case, the attacker can now modify or forge messages that the recipient (client or server) will think are genuine.
2. Attacker has recorded a TLS session and then (without the victim's knowledge) compromised the private key. The attacker can decrypt and modify the recording, and re-encrypt with patched integrity codes. This recording could then be offered to the victim (or any other party with access to either the private key or the ephemeral symmetric key), with the attacker claiming that it is genuine ("after all, if I changed anything the integrity codes wouldn't verify") in order to "prove" something was/wasn't sent. (As a side note: since the "legitimate" traffic thus "recorded" would effectively be authenticated by the certificate used in the key exchange, it would effectively prevent repudiation by the server, if the server owner were compelled to produce the key. This generally isn't a consideration of TLS, but could be relevant in some cases.) | The core idea here is that with RSA key transport the client generates a session key, ***encrypts*** it for the server using the server's RSA public key, and sends it. If an attacker gets a copy of the server's RSA private key, then they can passively sniff future traffic, decrypt any TLS handshake and extract the session key.
With DHE or ECDHE cipher suites, the server generates a one-time-use DH or ECDH key (that's the 'E' for 'ephemeral' in DHE / ECHDE), it ***signs*** that ephemeral DH key with its RSA key, and sends it to the client. The client verifies the signature using the server's public key (aka certificate) to know that it came from the authentic server. The client also generates themself a DH / ECDH key, completes the key exchange to get a session key, and sends its ephemeral DH key to the server so it can do the same. An attacker who has the server's RSA private key could still do *active* man-in-the-middle attacks where it impersonates the server (by signing DHE keys that the attacker generated), but it's not possible to extract session keys from the wire.
If you want to dive deeper on how the TLS handshake works, I love this website:
* <https://tls13.ulfheim.net/>
*PS technically 's/session key/pre-master secret' whatever.* |
287,689 | When e.g. a bunch of zerglings surround, say, a marauder, the latter seems to die fast. Is that just because it is attacked by so many units at once, or is there some hidden mechanic? Do the zerglings get some sort of special bonus to attack speed or damage? Is the surrounded unit paralysed? Is it immobilised? | 2016/10/10 | [
"https://gaming.stackexchange.com/questions/287689",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/10967/"
] | No there are no special bonuses. Surrounding is just an effective tactic in some situations.
In your example you have Zerglings surrounding a single marauder. I haven't played in a while but to surround a marauder with Zerglings you will probably need about 6-8 zerglings. This means you have 6(+) zerglings attacking at the same time whereas only one marauder attacking. Now take an example where a marauder is in a gap, say between two buildings. Only 3 or so zerglings will be able to attack the marauder at once. So you're now doing less than half the damage as when you were surrounding them.
The other thing that surrounding does is that it prevents the marauder from retreating and/or kiting. Ground units cannot move through other ground units, so surrounding units block movement in their direction. A kiting unit such as a marauder (has effective kiting with stim and slow) is going to do a lot more damage than if it just stood still. Not to mention that if the unit you're attacking is retreating and you chase too far, you could end up encountering the enemy reinforcements. You will often see a group of zerglings run past the enemy, taking additional hits, just so that when they attack, they have surrounded or partially surrounded the side that they would like to escape from.
Now another situation, where there is a large cluster of ranged units, say marines. You do not want to surround this with zerglings for much the same reason you want to surround a small number of units; the number of units that can attack at once is more for the marines than the zerglings. Knowing when a marine ball is too large to surround will take experience.
Now I guess the final case would be ranged units vs ranged units. Again this is going to be beneficial to the surrounding units as it allows more units to attack at once. However if the surround is too thin, then the army being surrounded can kite towards one side of the surround, breaking through and preventing half the surrounding circle from being able to attack.
Generally full surrounds don't happen with ranged units vs. ranged units, the more common situation is an arc. Which is basically the same thing, it's essentially just a partial surround. This is hugely important in fights especially in ZvZ, you'll hear about the roach(/hydra) arc a lot. But it comes down to the same thing, if you an army of 30 vs 30 like units, than if 12 of the former can attack at once whereas only 10 of the latter can attack at once then obviously the former will win. This 'number of units attacking at a time' can overcome upgrade and unit count disadvantages.
Feel free to comment below any questions or clarifications you'd like to ask for. | "Surrounding" is just a type of micro (micro is optimizing your army unit's attack and defense by controlling them well) that works well for your melee ground units. It spreads them out in such a way that the maximum number possible are attacking the target at the same time. It also prevents the attacked units from using certain types of micro (stutter step, kiting) or retreating.
The corresponding type of micro that works well for your ranged ground units is the "concave" (spreading your ranged attack units out so that they make a crescent shape) and also moving them forward far enough that any ranged units in the back row can also fire.
A type of micro that works well for both types of units is "flanking" (attacking from multiple directions at once). |
24,118,819 | ```
package com.example.nrbapp;
import java.util.ArrayList;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.os.Build;
public class SearchResult extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
int check = extras.getInt("check");
ArrayList<String> K_array = extras.getStringArrayList("K_array");
}
setContentView(R.layout.activity_search_result);
LinearLayout t1 = (LinearLayout) findViewById(R.id.linear_layout);
TextView tr = new TextView(this);
//tr.setId(95);// define id that must be unique
tr.setText("TYPE:"); // set the text for the header
tr.setTextColor(Color.WHITE); // set the color
tr.setTypeface(null, Typeface.BOLD);
tr.setPadding(5, 5, 5, 5); // set the padding (if required)
t1.addView(tr);//**LINE 43**
//t1.addView(tr, new LinearLayout.LayoutParams(
// LayoutParams.FILL_PARENT,
// LayoutParams.WRAP_CONTENT));
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search_result, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_search_result,
container, false);
return rootView;
}
}
}
```
>
> Getting Null Pointer Exception at line:43
> I have commented Line43
> This is part of my android project to get dynamic linear layout
> Please help me find out the error, My complete logcat is , Thanks.
>
>
>
```
06-09 06:50:03.590: E/AndroidRuntime(3794): FATAL EXCEPTION: main
06-09 06:50:03.590: E/AndroidRuntime(3794): Process: com.example.nrbapp, PID: 3794
06-09 06:50:03.590: E/AndroidRuntime(3794): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nrbapp/com.example.nrbapp.SearchResult}: java.lang.NullPointerException
06-09 06:50:03.590: E/AndroidRuntime(3794): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
06-09 06:50:03.590: E/AndroidRuntime(3794): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
06-09 06:50:03.590: E/AndroidRuntime(3794): at android.app.ActivityThread.access$800(ActivityThread.java:135)
06-09 06:50:03.590: E/AndroidRuntime(3794): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
06-09 06:50:03.590: E/AndroidRuntime(3794): at android.os.Handler.dispatchMessage(Handler.java:102)
06-09 06:50:03.590: E/AndroidRuntime(3794): at android.os.Looper.loop(Looper.java:136)
06-09 06:50:03.590: E/AndroidRuntime(3794): at android.app.ActivityThread.main(ActivityThread.java:5017)
06-09 06:50:03.590: E/AndroidRuntime(3794): at java.lang.reflect.Method.invokeNative(Native Method)
06-09 06:50:03.590: E/AndroidRuntime(3794): at java.lang.reflect.Method.invoke(Method.java:515)
06-09 06:50:03.590: E/AndroidRuntime(3794): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-09 06:50:03.590: E/AndroidRuntime(3794): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-09 06:50:03.590: E/AndroidRuntime(3794): at dalvik.system.NativeStart.main(Native Method)
06-09 06:50:03.590: E/AndroidRuntime(3794): Caused by: java.lang.NullPointerException
06-09 06:50:03.590: E/AndroidRuntime(3794): at com.example.nrbapp.SearchResult.onCreate(SearchResult.java:43)
06-09 06:50:03.590: E/AndroidRuntime(3794): at android.app.Activity.performCreate(Activity.java:5231)
06-09 06:50:03.590: E/AndroidRuntime(3794): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-09 06:50:03.590: E/AndroidRuntime(3794): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
06-09 06:50:03.590: E/AndroidRuntime(3794): ... 11 more
06-09 06:50:04.950: I/Process(3794): Sending signal. PID: 3794 SIG: 9
06-09 06:50:05.820: D/AndroidRuntime(3811): Shutting down VM
06-09 06:50:05.820: W/dalvikvm(3811): threadid=1: thread exiting with uncaught exception (group=0xb3a9eba8)
06-09 06:50:05.830: E/AndroidRuntime(3811): FATAL EXCEPTION: main
06-09 06:50:05.830: E/AndroidRuntime(3811): Process: com.example.nrbapp, PID: 3811
06-09 06:50:05.830: E/AndroidRuntime(3811): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nrbapp/com.example.nrbapp.SearchResult}: java.lang.NullPointerException
06-09 06:50:05.830: E/AndroidRuntime(3811): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
06-09 06:50:05.830: E/AndroidRuntime(3811): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
06-09 06:50:05.830: E/AndroidRuntime(3811): at android.app.ActivityThread.access$800(ActivityThread.java:135)
06-09 06:50:05.830: E/AndroidRuntime(3811): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
06-09 06:50:05.830: E/AndroidRuntime(3811): at android.os.Handler.dispatchMessage(Handler.java:102)
06-09 06:50:05.830: E/AndroidRuntime(3811): at android.os.Looper.loop(Looper.java:136)
06-09 06:50:05.830: E/AndroidRuntime(3811): at android.app.ActivityThread.main(ActivityThread.java:5017)
06-09 06:50:05.830: E/AndroidRuntime(3811): at java.lang.reflect.Method.invokeNative(Native Method)
06-09 06:50:05.830: E/AndroidRuntime(3811): at java.lang.reflect.Method.invoke(Method.java:515)
06-09 06:50:05.830: E/AndroidRuntime(3811): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-09 06:50:05.830: E/AndroidRuntime(3811): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-09 06:50:05.830: E/AndroidRuntime(3811): at dalvik.system.NativeStart.main(Native Method)
06-09 06:50:05.830: E/AndroidRuntime(3811): Caused by: java.lang.NullPointerException
06-09 06:50:05.830: E/AndroidRuntime(3811): at com.example.nrbapp.SearchResult.onCreate(SearchResult.java:43)
06-09 06:50:05.830: E/AndroidRuntime(3811): at android.app.Activity.performCreate(Activity.java:5231)
06-09 06:50:05.830: E/AndroidRuntime(3811): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-09 06:50:05.830: E/AndroidRuntime(3811): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
06-09 06:50:05.830: E/AndroidRuntime(3811): ... 11 more
```
>
> This is my activity\_search\_result.xml
>
>
>
```
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.nrbapp.SearchResult"
tools:ignore="MergeRootFrame">
<LinearLayout
android:id="@+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="39dp"
android:gravity="center_vertical">
<TextView
android:id="@+id/textView100"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textIsSelectable="true"
android:textSize="12sp"
android:textStyle="bold"
/>
</LinearLayout>
</FrameLayout>
``` | 2014/06/09 | [
"https://Stackoverflow.com/questions/24118819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3702641/"
] | In your `onCreate()`:
```
setContentView(R.layout.activity_search_result);
```
So the linear layout "tr" is referenced in activity\_search\_result, which is why the NPE when referenced for the textview.
this happens for the activity, where as your `linearlayout` is probably defined inside the fragment layout, (please post fragment\_search\_result.xml, will remove or update the answer accordingly)
so you should shift the `findViewById` in `onCreateView` like:
```
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_search_result,
container, false);
//now declare linearlayout to be found in fragment_search_result.xml
LinearLayout t1 = (LinearLayout) rootView.findViewById(R.id.linear_layout);
TextView tr = new TextView(SearchResult.this);
//tr.setId(95);// define id that must be unique
tr.setText("TYPE:"); // set the text for the header
tr.setTextColor(Color.WHITE); // set the color
tr.setTypeface(null, Typeface.BOLD);
tr.setPadding(5, 5, 5, 5); // set the padding (if required)
t1.addView(tr);
return rootView;
}
``` | Where is your LinearLayout t1, inside activity\_search\_result.xml or fragment\_search\_result? That could be mistake... |
53,672,523 | I'm a student, new to LINQ and we've been given an assignment to deal with LINQ queries.
My problem is I've been struggling the past days to figure out the correct way to perform this step: print the customers name that has "Milk" inside their orders.
```
Write a LINQ query to select all customers buying milk.
Print the Name of each customer in the query.
```
For the sake of time, here is the structure of the data so that you can understand it:
```
Product milk = new Product { Name = "Milk", Price = 13.02m };
Product butter = new Product { Name = "Butter", Price = 8.23m };
Product bread = new Product { Name = "Bread", Price = 17.91m };
Product cacao = new Product { Name = "Cacao", Price = 25.07m };
Product juice = new Product { Name = "Juice", Price = 17.03m };
Customer c1 = new Customer { Name = "x", City = "g", Orders = new Order[] {
new Order { Quantity = 2, Product = milk },
new Order { Quantity = 1, Product = butter },
new Order { Quantity = 1, Product = bread }
}
};
Customer c2 = new Customer { Name = "y", City = "g", Orders = new Order[] {
new Order { Quantity = 1, Product = cacao },
new Order { Quantity = 1, Product = bread },
new Order { Quantity = 2, Product = milk },
new Order { Quantity = 2, Product = butter },
}
};
Customer c3 = new Customer { Name = "z", City = "g", Orders = new Order[] {
new Order { Quantity = 3, Product = juice }
}
};
Customer[] customers = new Customer[] { c1, c2, c3 };
```
As an example of the syntax I'm using with LINQ here is a reference of working code:
```
var QueryCustomerByCity = from cus in customers.AsEnumerable()
where cus.City == "g"
select cus;
foreach (Customer c in QueryCustomerByCity)
Console.WriteLine("Customer {0} lives in {1}", c.Name, c.City);
```
I'm really trying hard to understand what's happening, so if you can help me please explain me how you reached such conclusion :)
Thank you a lot for your time! | 2018/12/07 | [
"https://Stackoverflow.com/questions/53672523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6327327/"
] | In your example, the call to `TryUpdateModelAsync` ends up setting properties on your `adminUpdate` instance based on values found in `ModelState`. If you want to set another value for `Password`, you can just do so after the call to `TryUpdateModelAsync`, like this:
```
if (await TryUpdateModelAsync(
adminUpdate,
"",
a => a.FirstName,
a => a.LastName,
a => a.Email,
a => a.Status,
a => a.CompanyId
))
{
adminUpdate.Password = password;
await _context.SaveChangesAsync();
return Redirect("/admin");
}
```
In the example above, I've also removed `a => a.Password` from the `TryUpdateModelAsync` as it is now redundant - whatever value gets set there is overridden in the explicit assignment before the call to `SaveChangesAsync`. | Can you try to add new line (right above TryUpdateModelAsync )
```
adminUpdate.Password = password;
if (await TryUpdateModelAsync(
adminUpdate,
``` |
4,945,956 | It's been while for release of MIDP 3.0 spec. But is there any device which supports this specifications ? | 2011/02/09 | [
"https://Stackoverflow.com/questions/4945956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/255507/"
] | I don't believe there are any commercially-available MIDP 3.0 phones available yet. The [Java ME benchmark list](http://www.club-java.com/TastePhone/J2ME/MIDP_Benchmark.jsp) only shows MIDP 2.1 as the highest supported version. Even Motorola, the spec lead, does not [list any MIDP 3.0 phones](http://developer.motorola.com/platforms/java/), nor does [Nokia](http://www.forum.nokia.com/Devices/Device_specifications/?filter=all). | Samsung galaxy pro b7510 support MIDP 3.0.Refer the link
[Midp3.0 supported device](http://www.newcellphoneprices.com/filter_view.php?filter_type=java&filter=3&txt=MIDP%203.0)
Some of **android** phones support **MIDP 3.0** |
37,601,346 | How do I create an Options Menu like in the following Screenshot:
[](https://i.stack.imgur.com/wxPNk.png)
The Options Menu should be opened afther clicking on the "More"-Icon of a RecyclerView Item!
My try was this:
```
@Override
public void onBindViewHolder(Holder holder, int position) {
holder.txvSongTitle.setText(sSongs[position].getTitle());
holder.txvSongInfo.setText(sSongs[position].getAlbum() + " - " + sSongs[position].getArtist());
holder.btnMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext, "More...", Toast.LENGTH_SHORT).show();
}
});
}
```
But this causes problems because the full item is clicked if I touch on the RecyclerView Item More-Button...
Here's my RecyclerViewOnTouchListener:
```
public class RecyclerViewOnTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector mGestureDetector;
private OnTouchCallback mOnTouchCallback;
public RecyclerViewOnTouchListener(Context context, final RecyclerView recyclerView, final OnTouchCallback onTouchCallback) {
mOnTouchCallback = onTouchCallback;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && onTouchCallback != null) {
onTouchCallback.onLongClick(child, recyclerView.getChildLayoutPosition(child));
}
super.onLongPress(e);
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && mOnTouchCallback != null && mGestureDetector.onTouchEvent(e)) {
mOnTouchCallback.onClick(child, rv.getChildLayoutPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface OnTouchCallback {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
```
I wasn't able to find any similar problem so I hope you can help me! | 2016/06/02 | [
"https://Stackoverflow.com/questions/37601346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5994190/"
] | step.1 add Recyclerview view layout.
step.2 Recyclerview rows layout recycler\_item.xml
```
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
card_view:cardCornerRadius="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/itemTextView"
style="@style/Base.TextAppearance.AppCompat.Body2"
android:layout_width="wrap_content"
android:layout_height="?attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:layout_centerVertical="true"
android:padding="8dp" />
<ImageView
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="@mipmap/more"
android:layout_alignParentRight="true"
android:text="Button"
android:padding="10dp"
android:layout_marginRight="10dp"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
```
Step 3. RecyclerAdapter
```
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<String> mItemList;
public RecyclerAdapter(List<String> itemList) {
mItemList = itemList;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.recycler_item, parent, false);
return RecyclerItemViewHolder.newInstance(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
RecyclerItemViewHolder holder = (RecyclerItemViewHolder) viewHolder;
String itemText = mItemList.get(position);
holder.setItemText(itemText);
}
@Override
public int getItemCount() {
return mItemList == null ? 0 : mItemList.size();
}
}
```
step.4 menu layout navigation\_drawer\_menu\_items.xml
```
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<item
android:id="@+id/navigation_drawer_item1"
android:icon="@android:drawable/ic_dialog_map"
android:title="Item 1" />
<item
android:id="@+id/navigation_drawer_item2"
android:icon="@android:drawable/ic_dialog_info"
android:title="Item 2" />
<item
android:id="@+id/navigation_drawer_item3"
android:icon="@android:drawable/ic_menu_share"
android:title="Item 3"/>
</menu>
```
step.5 add class RecyclerItemClickListener.java
```
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
@Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
@Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
// do nothing
}
}
```
step.6 add ItemTouchListener on Recyclerview.
```
private void initRecyclerView() {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(createItemList());
recyclerView.setAdapter(recyclerAdapter);
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, final int position) {
ImageView moreImage = (ImageView) view.findViewById(R.id.button);
moreImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openOptionMenu(v,position);
}
});
}
})
);
}
```
step.4 create popup menu.
```
public void openOptionMenu(View v,final int position){
PopupMenu popup = new PopupMenu(v.getContext(), v);
popup.getMenuInflater().inflate(R.menu.navigation_drawer_menu_items, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getBaseContext(), "You selected the action : " + item.getTitle()+" position "+position, Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();
}
``` | I guess it is better to handle click event in Activity as
TaskAdapter
```
public void onBindViewHolder(final TaskViewHolder holder, final int position) {
holder.name.setText(obj.get(position).getName());
Date date =obj.get(position).getUpdate_date();
String pattern = "dd-MM-YYYY";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String dateString = simpleDateFormat.format(new Date());
holder.date.setText(dateString);
}
public class TaskViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
final TextView name;
final ImageView image;
TextView date;
public TaskViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.txt_view);
image =(ImageView)itemView.findViewById(R.id.image_View);
date=(TextView)itemView.findViewById(R.id.txt_date);
name.setOnClickListener(this);
date.setOnClickListener(this);
image.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
TaskEntity task_item = obj.get(adapterPosition);
if(v.getId() == R.id.txt_view||v.getId()==R.id.txt_date) {
mClickHandler.onListItemClicked(task_item, v);
}
else if(v.getId() == R.id.image_View)
mClickHandler.onImageItemClicked(task_item,v);
}
}
public void setTaskList(List<TaskEntity> taskList)
{
this.obj = taskList;
notifyDataSetChanged();
}
public List<TaskEntity> getTaskList(){ return this.obj;}
public interface TaskclickListner
{
void onImageItemClicked(TaskEntity grid_item,View v);
void onListItemClicked(TaskEntity grid_item,View v);
}
```
}
Activity should implement the interface 'TaskclickListner' and should define the methods as
```
@Override
public void onListItemClicked(TaskEntity grid_item, View v) {
Intent intent = new Intent(getActivity(),ListItemsActivity.class);
intent.putExtra("taskId",grid_item.getTaskId());
startActivity(intent);
}
@Override
public void onImageItemClicked( final TaskEntity grid_item, View view) {
PopupMenu popupMenu = new PopupMenu(getActivity(), view);
popupMenu.inflate(R.menu.item_menu);
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(final MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
//right your action here
return true;
case R.id.edit:
//your code here
return true;
});
}
``` |
37,601,346 | How do I create an Options Menu like in the following Screenshot:
[](https://i.stack.imgur.com/wxPNk.png)
The Options Menu should be opened afther clicking on the "More"-Icon of a RecyclerView Item!
My try was this:
```
@Override
public void onBindViewHolder(Holder holder, int position) {
holder.txvSongTitle.setText(sSongs[position].getTitle());
holder.txvSongInfo.setText(sSongs[position].getAlbum() + " - " + sSongs[position].getArtist());
holder.btnMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext, "More...", Toast.LENGTH_SHORT).show();
}
});
}
```
But this causes problems because the full item is clicked if I touch on the RecyclerView Item More-Button...
Here's my RecyclerViewOnTouchListener:
```
public class RecyclerViewOnTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector mGestureDetector;
private OnTouchCallback mOnTouchCallback;
public RecyclerViewOnTouchListener(Context context, final RecyclerView recyclerView, final OnTouchCallback onTouchCallback) {
mOnTouchCallback = onTouchCallback;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && onTouchCallback != null) {
onTouchCallback.onLongClick(child, recyclerView.getChildLayoutPosition(child));
}
super.onLongPress(e);
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && mOnTouchCallback != null && mGestureDetector.onTouchEvent(e)) {
mOnTouchCallback.onClick(child, rv.getChildLayoutPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface OnTouchCallback {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
```
I wasn't able to find any similar problem so I hope you can help me! | 2016/06/02 | [
"https://Stackoverflow.com/questions/37601346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5994190/"
] | It is very easy to create an option menu like this. Just add a button in your list item design. You can use the following string to display 3 vertical dots.
```
<TextView
android:id="@+id/textViewOptions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:text="⋮"
android:textAppearance="?android:textAppearanceLarge" />
```
Now in your adapter inside onBindViewHolder() use the following code.
```
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//creating a popup menu
PopupMenu popup = new PopupMenu(mCtx, holder.buttonViewOption);
//inflating menu from xml resource
popup.inflate(R.menu.options_menu);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu1:
//handle menu1 click
return true;
case R.id.menu2:
//handle menu2 click
return true;
case R.id.menu3:
//handle menu3 click
return true;
default:
return false;
}
}
});
//displaying the popup
popup.show();
}
});
```
Thats it.
Source: [Options Menu For RecyclerView Item](https://www.simplifiedcoding.net/create-options-menu-recyclerview-item-tutorial/) | All the answers above are great. I just wanna add a small tip. making the 'more' button with *textView* is also a good solution but there is a more convenient way to do that. you can get the vector asset from *vector asset* menu in the android studio and use this asset to any button or view wherever you want.
```
//for instance
//ic_more_vert_black_24dp.xml
<vector android:height="24dp" android:tint="#cccccc"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M12,8c1.1,0 2,-0.9 2,-2s-
0.9,-2 -2,-2 -2,0.9 -2,2 0.9,2 2,2zM12,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2
-0.9,-2 -2,-2zM12,16c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2z"/>
</vector>
``` |
37,601,346 | How do I create an Options Menu like in the following Screenshot:
[](https://i.stack.imgur.com/wxPNk.png)
The Options Menu should be opened afther clicking on the "More"-Icon of a RecyclerView Item!
My try was this:
```
@Override
public void onBindViewHolder(Holder holder, int position) {
holder.txvSongTitle.setText(sSongs[position].getTitle());
holder.txvSongInfo.setText(sSongs[position].getAlbum() + " - " + sSongs[position].getArtist());
holder.btnMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext, "More...", Toast.LENGTH_SHORT).show();
}
});
}
```
But this causes problems because the full item is clicked if I touch on the RecyclerView Item More-Button...
Here's my RecyclerViewOnTouchListener:
```
public class RecyclerViewOnTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector mGestureDetector;
private OnTouchCallback mOnTouchCallback;
public RecyclerViewOnTouchListener(Context context, final RecyclerView recyclerView, final OnTouchCallback onTouchCallback) {
mOnTouchCallback = onTouchCallback;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && onTouchCallback != null) {
onTouchCallback.onLongClick(child, recyclerView.getChildLayoutPosition(child));
}
super.onLongPress(e);
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && mOnTouchCallback != null && mGestureDetector.onTouchEvent(e)) {
mOnTouchCallback.onClick(child, rv.getChildLayoutPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface OnTouchCallback {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
```
I wasn't able to find any similar problem so I hope you can help me! | 2016/06/02 | [
"https://Stackoverflow.com/questions/37601346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5994190/"
] | I found out that the only Menu, that looks like the Menu above is the `PopupMenu`.
So in `onClick`:
```
@Override
public void onClick(View view, int position, MotionEvent e) {
ImageButton btnMore = (ImageButton) view.findViewById(R.id.item_song_btnMore);
if (RecyclerViewOnTouchListener.isViewClicked(btnMore, e)) {
PopupMenu popupMenu = new PopupMenu(view.getContext(), btnMore);
getActivity().getMenuInflater().inflate(R.menu.menu_song, popupMenu.getMenu());
popupMenu.show();
//The following is only needed if you want to force a horizontal offset like margin_right to the PopupMenu
try {
Field fMenuHelper = PopupMenu.class.getDeclaredField("mPopup");
fMenuHelper.setAccessible(true);
Object oMenuHelper = fMenuHelper.get(popupMenu);
Class[] argTypes = new Class[] {int.class};
Field fListPopup = oMenuHelper.getClass().getDeclaredField("mPopup");
fListPopup.setAccessible(true);
Object oListPopup = fListPopup.get(oMenuHelper);
Class clListPopup = oListPopup.getClass();
int iWidth = (int) clListPopup.getDeclaredMethod("getWidth").invoke(oListPopup);
clListPopup.getDeclaredMethod("setHorizontalOffset", argTypes).invoke(oListPopup, -iWidth);
clListPopup.getDeclaredMethod("show").invoke(oListPopup);
}
catch (NoSuchFieldException nsfe) {
nsfe.printStackTrace();
}
catch (NoSuchMethodException nsme) {
nsme.printStackTrace();
}
catch (InvocationTargetException ite) {
ite.printStackTrace();
}
catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
else {
MusicPlayer.playSong(position);
}
}
```
You have to make your onClick-Method pass the MotionEvent and finally implement the Method `isViewClicked` in your RecyclerViewOnTouchListener:
```
public static boolean isViewClicked(View view, MotionEvent e) {
Rect rect = new Rect();
view.getGlobalVisibleRect(rect);
return rect.contains((int) e.getRawX(), (int) e.getRawY());
}
``` | **Simple Code In Kotlin : -**
```
holder!!.t_description!!.setOnClickListener {
val popup = PopupMenu(context, holder.t_description)
popup.inflate(R.menu.navigation)
popup.setOnMenuItemClickListener(object : PopupMenu.OnMenuItemClickListener{
override fun onMenuItemClick(p0: MenuItem?): Boolean {
Log.e(">>",p0.toString())
return true
}
})
popup.show();
}
```
**Only You Just Add Menu List and Use This CODE in Adapter with any view.**
thanks. |
37,601,346 | How do I create an Options Menu like in the following Screenshot:
[](https://i.stack.imgur.com/wxPNk.png)
The Options Menu should be opened afther clicking on the "More"-Icon of a RecyclerView Item!
My try was this:
```
@Override
public void onBindViewHolder(Holder holder, int position) {
holder.txvSongTitle.setText(sSongs[position].getTitle());
holder.txvSongInfo.setText(sSongs[position].getAlbum() + " - " + sSongs[position].getArtist());
holder.btnMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext, "More...", Toast.LENGTH_SHORT).show();
}
});
}
```
But this causes problems because the full item is clicked if I touch on the RecyclerView Item More-Button...
Here's my RecyclerViewOnTouchListener:
```
public class RecyclerViewOnTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector mGestureDetector;
private OnTouchCallback mOnTouchCallback;
public RecyclerViewOnTouchListener(Context context, final RecyclerView recyclerView, final OnTouchCallback onTouchCallback) {
mOnTouchCallback = onTouchCallback;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && onTouchCallback != null) {
onTouchCallback.onLongClick(child, recyclerView.getChildLayoutPosition(child));
}
super.onLongPress(e);
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && mOnTouchCallback != null && mGestureDetector.onTouchEvent(e)) {
mOnTouchCallback.onClick(child, rv.getChildLayoutPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface OnTouchCallback {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
```
I wasn't able to find any similar problem so I hope you can help me! | 2016/06/02 | [
"https://Stackoverflow.com/questions/37601346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5994190/"
] | step.1 add Recyclerview view layout.
step.2 Recyclerview rows layout recycler\_item.xml
```
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
card_view:cardCornerRadius="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/itemTextView"
style="@style/Base.TextAppearance.AppCompat.Body2"
android:layout_width="wrap_content"
android:layout_height="?attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:layout_centerVertical="true"
android:padding="8dp" />
<ImageView
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="@mipmap/more"
android:layout_alignParentRight="true"
android:text="Button"
android:padding="10dp"
android:layout_marginRight="10dp"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
```
Step 3. RecyclerAdapter
```
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<String> mItemList;
public RecyclerAdapter(List<String> itemList) {
mItemList = itemList;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.recycler_item, parent, false);
return RecyclerItemViewHolder.newInstance(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
RecyclerItemViewHolder holder = (RecyclerItemViewHolder) viewHolder;
String itemText = mItemList.get(position);
holder.setItemText(itemText);
}
@Override
public int getItemCount() {
return mItemList == null ? 0 : mItemList.size();
}
}
```
step.4 menu layout navigation\_drawer\_menu\_items.xml
```
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<item
android:id="@+id/navigation_drawer_item1"
android:icon="@android:drawable/ic_dialog_map"
android:title="Item 1" />
<item
android:id="@+id/navigation_drawer_item2"
android:icon="@android:drawable/ic_dialog_info"
android:title="Item 2" />
<item
android:id="@+id/navigation_drawer_item3"
android:icon="@android:drawable/ic_menu_share"
android:title="Item 3"/>
</menu>
```
step.5 add class RecyclerItemClickListener.java
```
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
@Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
@Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
// do nothing
}
}
```
step.6 add ItemTouchListener on Recyclerview.
```
private void initRecyclerView() {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(createItemList());
recyclerView.setAdapter(recyclerAdapter);
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, final int position) {
ImageView moreImage = (ImageView) view.findViewById(R.id.button);
moreImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openOptionMenu(v,position);
}
});
}
})
);
}
```
step.4 create popup menu.
```
public void openOptionMenu(View v,final int position){
PopupMenu popup = new PopupMenu(v.getContext(), v);
popup.getMenuInflater().inflate(R.menu.navigation_drawer_menu_items, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getBaseContext(), "You selected the action : " + item.getTitle()+" position "+position, Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();
}
``` | All the answers above are great. I just wanna add a small tip. making the 'more' button with *textView* is also a good solution but there is a more convenient way to do that. you can get the vector asset from *vector asset* menu in the android studio and use this asset to any button or view wherever you want.
```
//for instance
//ic_more_vert_black_24dp.xml
<vector android:height="24dp" android:tint="#cccccc"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M12,8c1.1,0 2,-0.9 2,-2s-
0.9,-2 -2,-2 -2,0.9 -2,2 0.9,2 2,2zM12,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2
-0.9,-2 -2,-2zM12,16c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2z"/>
</vector>
``` |
37,601,346 | How do I create an Options Menu like in the following Screenshot:
[](https://i.stack.imgur.com/wxPNk.png)
The Options Menu should be opened afther clicking on the "More"-Icon of a RecyclerView Item!
My try was this:
```
@Override
public void onBindViewHolder(Holder holder, int position) {
holder.txvSongTitle.setText(sSongs[position].getTitle());
holder.txvSongInfo.setText(sSongs[position].getAlbum() + " - " + sSongs[position].getArtist());
holder.btnMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext, "More...", Toast.LENGTH_SHORT).show();
}
});
}
```
But this causes problems because the full item is clicked if I touch on the RecyclerView Item More-Button...
Here's my RecyclerViewOnTouchListener:
```
public class RecyclerViewOnTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector mGestureDetector;
private OnTouchCallback mOnTouchCallback;
public RecyclerViewOnTouchListener(Context context, final RecyclerView recyclerView, final OnTouchCallback onTouchCallback) {
mOnTouchCallback = onTouchCallback;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && onTouchCallback != null) {
onTouchCallback.onLongClick(child, recyclerView.getChildLayoutPosition(child));
}
super.onLongPress(e);
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && mOnTouchCallback != null && mGestureDetector.onTouchEvent(e)) {
mOnTouchCallback.onClick(child, rv.getChildLayoutPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface OnTouchCallback {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
```
I wasn't able to find any similar problem so I hope you can help me! | 2016/06/02 | [
"https://Stackoverflow.com/questions/37601346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5994190/"
] | I found out that the only Menu, that looks like the Menu above is the `PopupMenu`.
So in `onClick`:
```
@Override
public void onClick(View view, int position, MotionEvent e) {
ImageButton btnMore = (ImageButton) view.findViewById(R.id.item_song_btnMore);
if (RecyclerViewOnTouchListener.isViewClicked(btnMore, e)) {
PopupMenu popupMenu = new PopupMenu(view.getContext(), btnMore);
getActivity().getMenuInflater().inflate(R.menu.menu_song, popupMenu.getMenu());
popupMenu.show();
//The following is only needed if you want to force a horizontal offset like margin_right to the PopupMenu
try {
Field fMenuHelper = PopupMenu.class.getDeclaredField("mPopup");
fMenuHelper.setAccessible(true);
Object oMenuHelper = fMenuHelper.get(popupMenu);
Class[] argTypes = new Class[] {int.class};
Field fListPopup = oMenuHelper.getClass().getDeclaredField("mPopup");
fListPopup.setAccessible(true);
Object oListPopup = fListPopup.get(oMenuHelper);
Class clListPopup = oListPopup.getClass();
int iWidth = (int) clListPopup.getDeclaredMethod("getWidth").invoke(oListPopup);
clListPopup.getDeclaredMethod("setHorizontalOffset", argTypes).invoke(oListPopup, -iWidth);
clListPopup.getDeclaredMethod("show").invoke(oListPopup);
}
catch (NoSuchFieldException nsfe) {
nsfe.printStackTrace();
}
catch (NoSuchMethodException nsme) {
nsme.printStackTrace();
}
catch (InvocationTargetException ite) {
ite.printStackTrace();
}
catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
else {
MusicPlayer.playSong(position);
}
}
```
You have to make your onClick-Method pass the MotionEvent and finally implement the Method `isViewClicked` in your RecyclerViewOnTouchListener:
```
public static boolean isViewClicked(View view, MotionEvent e) {
Rect rect = new Rect();
view.getGlobalVisibleRect(rect);
return rect.contains((int) e.getRawX(), (int) e.getRawY());
}
``` | step.1 add Recyclerview view layout.
step.2 Recyclerview rows layout recycler\_item.xml
```
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
card_view:cardCornerRadius="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/itemTextView"
style="@style/Base.TextAppearance.AppCompat.Body2"
android:layout_width="wrap_content"
android:layout_height="?attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:layout_centerVertical="true"
android:padding="8dp" />
<ImageView
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="@mipmap/more"
android:layout_alignParentRight="true"
android:text="Button"
android:padding="10dp"
android:layout_marginRight="10dp"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
```
Step 3. RecyclerAdapter
```
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<String> mItemList;
public RecyclerAdapter(List<String> itemList) {
mItemList = itemList;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.recycler_item, parent, false);
return RecyclerItemViewHolder.newInstance(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
RecyclerItemViewHolder holder = (RecyclerItemViewHolder) viewHolder;
String itemText = mItemList.get(position);
holder.setItemText(itemText);
}
@Override
public int getItemCount() {
return mItemList == null ? 0 : mItemList.size();
}
}
```
step.4 menu layout navigation\_drawer\_menu\_items.xml
```
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<item
android:id="@+id/navigation_drawer_item1"
android:icon="@android:drawable/ic_dialog_map"
android:title="Item 1" />
<item
android:id="@+id/navigation_drawer_item2"
android:icon="@android:drawable/ic_dialog_info"
android:title="Item 2" />
<item
android:id="@+id/navigation_drawer_item3"
android:icon="@android:drawable/ic_menu_share"
android:title="Item 3"/>
</menu>
```
step.5 add class RecyclerItemClickListener.java
```
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
@Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
@Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
// do nothing
}
}
```
step.6 add ItemTouchListener on Recyclerview.
```
private void initRecyclerView() {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(createItemList());
recyclerView.setAdapter(recyclerAdapter);
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, final int position) {
ImageView moreImage = (ImageView) view.findViewById(R.id.button);
moreImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openOptionMenu(v,position);
}
});
}
})
);
}
```
step.4 create popup menu.
```
public void openOptionMenu(View v,final int position){
PopupMenu popup = new PopupMenu(v.getContext(), v);
popup.getMenuInflater().inflate(R.menu.navigation_drawer_menu_items, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getBaseContext(), "You selected the action : " + item.getTitle()+" position "+position, Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();
}
``` |
37,601,346 | How do I create an Options Menu like in the following Screenshot:
[](https://i.stack.imgur.com/wxPNk.png)
The Options Menu should be opened afther clicking on the "More"-Icon of a RecyclerView Item!
My try was this:
```
@Override
public void onBindViewHolder(Holder holder, int position) {
holder.txvSongTitle.setText(sSongs[position].getTitle());
holder.txvSongInfo.setText(sSongs[position].getAlbum() + " - " + sSongs[position].getArtist());
holder.btnMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext, "More...", Toast.LENGTH_SHORT).show();
}
});
}
```
But this causes problems because the full item is clicked if I touch on the RecyclerView Item More-Button...
Here's my RecyclerViewOnTouchListener:
```
public class RecyclerViewOnTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector mGestureDetector;
private OnTouchCallback mOnTouchCallback;
public RecyclerViewOnTouchListener(Context context, final RecyclerView recyclerView, final OnTouchCallback onTouchCallback) {
mOnTouchCallback = onTouchCallback;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && onTouchCallback != null) {
onTouchCallback.onLongClick(child, recyclerView.getChildLayoutPosition(child));
}
super.onLongPress(e);
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && mOnTouchCallback != null && mGestureDetector.onTouchEvent(e)) {
mOnTouchCallback.onClick(child, rv.getChildLayoutPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface OnTouchCallback {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
```
I wasn't able to find any similar problem so I hope you can help me! | 2016/06/02 | [
"https://Stackoverflow.com/questions/37601346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5994190/"
] | **Simple Code In Kotlin : -**
```
holder!!.t_description!!.setOnClickListener {
val popup = PopupMenu(context, holder.t_description)
popup.inflate(R.menu.navigation)
popup.setOnMenuItemClickListener(object : PopupMenu.OnMenuItemClickListener{
override fun onMenuItemClick(p0: MenuItem?): Boolean {
Log.e(">>",p0.toString())
return true
}
})
popup.show();
}
```
**Only You Just Add Menu List and Use This CODE in Adapter with any view.**
thanks. | I guess it is better to handle click event in Activity as
TaskAdapter
```
public void onBindViewHolder(final TaskViewHolder holder, final int position) {
holder.name.setText(obj.get(position).getName());
Date date =obj.get(position).getUpdate_date();
String pattern = "dd-MM-YYYY";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String dateString = simpleDateFormat.format(new Date());
holder.date.setText(dateString);
}
public class TaskViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
final TextView name;
final ImageView image;
TextView date;
public TaskViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.txt_view);
image =(ImageView)itemView.findViewById(R.id.image_View);
date=(TextView)itemView.findViewById(R.id.txt_date);
name.setOnClickListener(this);
date.setOnClickListener(this);
image.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
TaskEntity task_item = obj.get(adapterPosition);
if(v.getId() == R.id.txt_view||v.getId()==R.id.txt_date) {
mClickHandler.onListItemClicked(task_item, v);
}
else if(v.getId() == R.id.image_View)
mClickHandler.onImageItemClicked(task_item,v);
}
}
public void setTaskList(List<TaskEntity> taskList)
{
this.obj = taskList;
notifyDataSetChanged();
}
public List<TaskEntity> getTaskList(){ return this.obj;}
public interface TaskclickListner
{
void onImageItemClicked(TaskEntity grid_item,View v);
void onListItemClicked(TaskEntity grid_item,View v);
}
```
}
Activity should implement the interface 'TaskclickListner' and should define the methods as
```
@Override
public void onListItemClicked(TaskEntity grid_item, View v) {
Intent intent = new Intent(getActivity(),ListItemsActivity.class);
intent.putExtra("taskId",grid_item.getTaskId());
startActivity(intent);
}
@Override
public void onImageItemClicked( final TaskEntity grid_item, View view) {
PopupMenu popupMenu = new PopupMenu(getActivity(), view);
popupMenu.inflate(R.menu.item_menu);
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(final MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
//right your action here
return true;
case R.id.edit:
//your code here
return true;
});
}
``` |
37,601,346 | How do I create an Options Menu like in the following Screenshot:
[](https://i.stack.imgur.com/wxPNk.png)
The Options Menu should be opened afther clicking on the "More"-Icon of a RecyclerView Item!
My try was this:
```
@Override
public void onBindViewHolder(Holder holder, int position) {
holder.txvSongTitle.setText(sSongs[position].getTitle());
holder.txvSongInfo.setText(sSongs[position].getAlbum() + " - " + sSongs[position].getArtist());
holder.btnMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext, "More...", Toast.LENGTH_SHORT).show();
}
});
}
```
But this causes problems because the full item is clicked if I touch on the RecyclerView Item More-Button...
Here's my RecyclerViewOnTouchListener:
```
public class RecyclerViewOnTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector mGestureDetector;
private OnTouchCallback mOnTouchCallback;
public RecyclerViewOnTouchListener(Context context, final RecyclerView recyclerView, final OnTouchCallback onTouchCallback) {
mOnTouchCallback = onTouchCallback;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && onTouchCallback != null) {
onTouchCallback.onLongClick(child, recyclerView.getChildLayoutPosition(child));
}
super.onLongPress(e);
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && mOnTouchCallback != null && mGestureDetector.onTouchEvent(e)) {
mOnTouchCallback.onClick(child, rv.getChildLayoutPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface OnTouchCallback {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
```
I wasn't able to find any similar problem so I hope you can help me! | 2016/06/02 | [
"https://Stackoverflow.com/questions/37601346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5994190/"
] | It is very easy to create an option menu like this. Just add a button in your list item design. You can use the following string to display 3 vertical dots.
```
<TextView
android:id="@+id/textViewOptions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:text="⋮"
android:textAppearance="?android:textAppearanceLarge" />
```
Now in your adapter inside onBindViewHolder() use the following code.
```
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//creating a popup menu
PopupMenu popup = new PopupMenu(mCtx, holder.buttonViewOption);
//inflating menu from xml resource
popup.inflate(R.menu.options_menu);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu1:
//handle menu1 click
return true;
case R.id.menu2:
//handle menu2 click
return true;
case R.id.menu3:
//handle menu3 click
return true;
default:
return false;
}
}
});
//displaying the popup
popup.show();
}
});
```
Thats it.
Source: [Options Menu For RecyclerView Item](https://www.simplifiedcoding.net/create-options-menu-recyclerview-item-tutorial/) | step.1 add Recyclerview view layout.
step.2 Recyclerview rows layout recycler\_item.xml
```
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
card_view:cardCornerRadius="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/itemTextView"
style="@style/Base.TextAppearance.AppCompat.Body2"
android:layout_width="wrap_content"
android:layout_height="?attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:layout_centerVertical="true"
android:padding="8dp" />
<ImageView
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="@mipmap/more"
android:layout_alignParentRight="true"
android:text="Button"
android:padding="10dp"
android:layout_marginRight="10dp"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
```
Step 3. RecyclerAdapter
```
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<String> mItemList;
public RecyclerAdapter(List<String> itemList) {
mItemList = itemList;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.recycler_item, parent, false);
return RecyclerItemViewHolder.newInstance(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
RecyclerItemViewHolder holder = (RecyclerItemViewHolder) viewHolder;
String itemText = mItemList.get(position);
holder.setItemText(itemText);
}
@Override
public int getItemCount() {
return mItemList == null ? 0 : mItemList.size();
}
}
```
step.4 menu layout navigation\_drawer\_menu\_items.xml
```
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<item
android:id="@+id/navigation_drawer_item1"
android:icon="@android:drawable/ic_dialog_map"
android:title="Item 1" />
<item
android:id="@+id/navigation_drawer_item2"
android:icon="@android:drawable/ic_dialog_info"
android:title="Item 2" />
<item
android:id="@+id/navigation_drawer_item3"
android:icon="@android:drawable/ic_menu_share"
android:title="Item 3"/>
</menu>
```
step.5 add class RecyclerItemClickListener.java
```
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
@Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
@Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
// do nothing
}
}
```
step.6 add ItemTouchListener on Recyclerview.
```
private void initRecyclerView() {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(createItemList());
recyclerView.setAdapter(recyclerAdapter);
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, final int position) {
ImageView moreImage = (ImageView) view.findViewById(R.id.button);
moreImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openOptionMenu(v,position);
}
});
}
})
);
}
```
step.4 create popup menu.
```
public void openOptionMenu(View v,final int position){
PopupMenu popup = new PopupMenu(v.getContext(), v);
popup.getMenuInflater().inflate(R.menu.navigation_drawer_menu_items, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getBaseContext(), "You selected the action : " + item.getTitle()+" position "+position, Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();
}
``` |
37,601,346 | How do I create an Options Menu like in the following Screenshot:
[](https://i.stack.imgur.com/wxPNk.png)
The Options Menu should be opened afther clicking on the "More"-Icon of a RecyclerView Item!
My try was this:
```
@Override
public void onBindViewHolder(Holder holder, int position) {
holder.txvSongTitle.setText(sSongs[position].getTitle());
holder.txvSongInfo.setText(sSongs[position].getAlbum() + " - " + sSongs[position].getArtist());
holder.btnMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext, "More...", Toast.LENGTH_SHORT).show();
}
});
}
```
But this causes problems because the full item is clicked if I touch on the RecyclerView Item More-Button...
Here's my RecyclerViewOnTouchListener:
```
public class RecyclerViewOnTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector mGestureDetector;
private OnTouchCallback mOnTouchCallback;
public RecyclerViewOnTouchListener(Context context, final RecyclerView recyclerView, final OnTouchCallback onTouchCallback) {
mOnTouchCallback = onTouchCallback;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && onTouchCallback != null) {
onTouchCallback.onLongClick(child, recyclerView.getChildLayoutPosition(child));
}
super.onLongPress(e);
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && mOnTouchCallback != null && mGestureDetector.onTouchEvent(e)) {
mOnTouchCallback.onClick(child, rv.getChildLayoutPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface OnTouchCallback {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
```
I wasn't able to find any similar problem so I hope you can help me! | 2016/06/02 | [
"https://Stackoverflow.com/questions/37601346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5994190/"
] | It is very easy to create an option menu like this. Just add a button in your list item design. You can use the following string to display 3 vertical dots.
```
<TextView
android:id="@+id/textViewOptions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:text="⋮"
android:textAppearance="?android:textAppearanceLarge" />
```
Now in your adapter inside onBindViewHolder() use the following code.
```
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//creating a popup menu
PopupMenu popup = new PopupMenu(mCtx, holder.buttonViewOption);
//inflating menu from xml resource
popup.inflate(R.menu.options_menu);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu1:
//handle menu1 click
return true;
case R.id.menu2:
//handle menu2 click
return true;
case R.id.menu3:
//handle menu3 click
return true;
default:
return false;
}
}
});
//displaying the popup
popup.show();
}
});
```
Thats it.
Source: [Options Menu For RecyclerView Item](https://www.simplifiedcoding.net/create-options-menu-recyclerview-item-tutorial/) | 1. There is a simple way to show menu like this:
ViewHolder:
define fields
```
private ImageView menuBtn;
private PopupMenu popupMenu;
```
Create method `bind` with logic of creating menu on button click and closing it on reusing view:
```
if (popupMenu != null) {
popupMenu.dismiss();
}
menuBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupMenu = new PopupMenu(v.getContext(), v);
createMenu(popupMenu.getMenu());
popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
@Override
public void onDismiss(PopupMenu menu) {
popupMenu = null;
}
});
popupMenu.show();
}
});
```
Method `createMenu(Menu menu)` is up to you, here is simple example:
```
menu.add("Menu title")
.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
// do whatever you want
}
});
```
2. For handling click on other part of list item you do not need set `OnItemTouchListener` on recycler view, but simple in method `onBindViewHolder` do:
```
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//handle click here
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
//handle long click here
}
});
``` |
37,601,346 | How do I create an Options Menu like in the following Screenshot:
[](https://i.stack.imgur.com/wxPNk.png)
The Options Menu should be opened afther clicking on the "More"-Icon of a RecyclerView Item!
My try was this:
```
@Override
public void onBindViewHolder(Holder holder, int position) {
holder.txvSongTitle.setText(sSongs[position].getTitle());
holder.txvSongInfo.setText(sSongs[position].getAlbum() + " - " + sSongs[position].getArtist());
holder.btnMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext, "More...", Toast.LENGTH_SHORT).show();
}
});
}
```
But this causes problems because the full item is clicked if I touch on the RecyclerView Item More-Button...
Here's my RecyclerViewOnTouchListener:
```
public class RecyclerViewOnTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector mGestureDetector;
private OnTouchCallback mOnTouchCallback;
public RecyclerViewOnTouchListener(Context context, final RecyclerView recyclerView, final OnTouchCallback onTouchCallback) {
mOnTouchCallback = onTouchCallback;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && onTouchCallback != null) {
onTouchCallback.onLongClick(child, recyclerView.getChildLayoutPosition(child));
}
super.onLongPress(e);
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && mOnTouchCallback != null && mGestureDetector.onTouchEvent(e)) {
mOnTouchCallback.onClick(child, rv.getChildLayoutPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface OnTouchCallback {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
```
I wasn't able to find any similar problem so I hope you can help me! | 2016/06/02 | [
"https://Stackoverflow.com/questions/37601346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5994190/"
] | It is very easy to create an option menu like this. Just add a button in your list item design. You can use the following string to display 3 vertical dots.
```
<TextView
android:id="@+id/textViewOptions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:text="⋮"
android:textAppearance="?android:textAppearanceLarge" />
```
Now in your adapter inside onBindViewHolder() use the following code.
```
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//creating a popup menu
PopupMenu popup = new PopupMenu(mCtx, holder.buttonViewOption);
//inflating menu from xml resource
popup.inflate(R.menu.options_menu);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu1:
//handle menu1 click
return true;
case R.id.menu2:
//handle menu2 click
return true;
case R.id.menu3:
//handle menu3 click
return true;
default:
return false;
}
}
});
//displaying the popup
popup.show();
}
});
```
Thats it.
Source: [Options Menu For RecyclerView Item](https://www.simplifiedcoding.net/create-options-menu-recyclerview-item-tutorial/) | **Simple Code In Kotlin : -**
```
holder!!.t_description!!.setOnClickListener {
val popup = PopupMenu(context, holder.t_description)
popup.inflate(R.menu.navigation)
popup.setOnMenuItemClickListener(object : PopupMenu.OnMenuItemClickListener{
override fun onMenuItemClick(p0: MenuItem?): Boolean {
Log.e(">>",p0.toString())
return true
}
})
popup.show();
}
```
**Only You Just Add Menu List and Use This CODE in Adapter with any view.**
thanks. |
37,601,346 | How do I create an Options Menu like in the following Screenshot:
[](https://i.stack.imgur.com/wxPNk.png)
The Options Menu should be opened afther clicking on the "More"-Icon of a RecyclerView Item!
My try was this:
```
@Override
public void onBindViewHolder(Holder holder, int position) {
holder.txvSongTitle.setText(sSongs[position].getTitle());
holder.txvSongInfo.setText(sSongs[position].getAlbum() + " - " + sSongs[position].getArtist());
holder.btnMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext, "More...", Toast.LENGTH_SHORT).show();
}
});
}
```
But this causes problems because the full item is clicked if I touch on the RecyclerView Item More-Button...
Here's my RecyclerViewOnTouchListener:
```
public class RecyclerViewOnTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector mGestureDetector;
private OnTouchCallback mOnTouchCallback;
public RecyclerViewOnTouchListener(Context context, final RecyclerView recyclerView, final OnTouchCallback onTouchCallback) {
mOnTouchCallback = onTouchCallback;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && onTouchCallback != null) {
onTouchCallback.onLongClick(child, recyclerView.getChildLayoutPosition(child));
}
super.onLongPress(e);
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && mOnTouchCallback != null && mGestureDetector.onTouchEvent(e)) {
mOnTouchCallback.onClick(child, rv.getChildLayoutPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface OnTouchCallback {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
```
I wasn't able to find any similar problem so I hope you can help me! | 2016/06/02 | [
"https://Stackoverflow.com/questions/37601346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5994190/"
] | It is very easy to create an option menu like this. Just add a button in your list item design. You can use the following string to display 3 vertical dots.
```
<TextView
android:id="@+id/textViewOptions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:text="⋮"
android:textAppearance="?android:textAppearanceLarge" />
```
Now in your adapter inside onBindViewHolder() use the following code.
```
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//creating a popup menu
PopupMenu popup = new PopupMenu(mCtx, holder.buttonViewOption);
//inflating menu from xml resource
popup.inflate(R.menu.options_menu);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu1:
//handle menu1 click
return true;
case R.id.menu2:
//handle menu2 click
return true;
case R.id.menu3:
//handle menu3 click
return true;
default:
return false;
}
}
});
//displaying the popup
popup.show();
}
});
```
Thats it.
Source: [Options Menu For RecyclerView Item](https://www.simplifiedcoding.net/create-options-menu-recyclerview-item-tutorial/) | Change the `RecyclerViewOnTouchListener` class to pass the `MotionEvent` to the `OnTouchCallback` implementation.
In the class implementing `onItemClick`, add the following:
```
@Override
public void onClick(final View view, int position, MotionEvent e) {
View menuButton = view.findViewById(R.id.menu);
if (isViewClicked(e, menuButton)) {
menuButton.setOnCreateContextMenuListener(this);
menuButton.showContextMenu();
return;
}
...
}
```
Where `isViewClicked` is the following:
```
private boolean isViewClicked(MotionEvent e, View view) {
Rect rect = new Rect();
view.getGlobalVisibleRect(rect);
return rect.contains((int) e.getRawX(), (int) e.getRawY());
}
```
To show a list of items anchored to a view (the menu button) use [ListPopupWindow](https://developer.android.com/reference/android/widget/ListPopupWindow.html) |
14,224,863 | I need to sort a NSMutableArray containing NSURLs with localizedStandardCompare:
```
[array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSString *f1 = [(NSURL *)obj1 absoluteString];
NSString *f2 = [(NSURL *)obj2 absoluteString];
return [f1 localizedStandardCompare:f2];
}];
```
This works fine, but I worry a bit about the performance: the block will be evaluated n log n times during the sort, so I'd like it to be fast (the array might have up to 100,000 elements). Since localizedStandardCompare is only available on NSString, I need to convert the URLs to strings. Above, I use `absoluteString`, but there are other methods that return a NSString, for example relativeString. Reading the NSURL class reference, I get the impression that relativeString might be faster, since the URL does not need to be resolved, but this is my first time with Cocoa and OS-X, and thus just a wild guess.
Additional constraint: in this case, all URLs come from a NSDirectoryEnumerator on local storage, so all are file URLs. It would be a bonus if the method would work for all kinds of URL, though.
My question: which method should I use to convert NSURL to NSString for best performance?
Profiling all possible methods might be possible, but I have only one (rather fast) OS-X machine, and who knows - one day the code might end up on iOS.
I'm using Xcode 4.5.2 on OS-X 10.8.2, but the program should work on older version, too (within reasonable bounds). | 2013/01/08 | [
"https://Stackoverflow.com/questions/14224863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1096710/"
] | So here is how I typically solve this problem. My notes are purely my opinion (religous?) about naming classes in an MVC project to keep clear their purpose.
Couple of interfaces to keep it extensible:
```
// be specific about what type of results, both in the name of the
// interface and the property needed, you don't want to have overlapping
// properies on your classes, I like suffixing interfaces that are specific
// to a View or Partial View with View
public interface IPersonSearchResultsView
{
IEnumerable<EFPerson> PersonSearchResults { get; }
}
public interface IPersonSearchCriteriaView
{
PersonSearchCriteriaModel PersonSearchModel { get; }
}
```
Couple of classes
```
// I like suffixing classes that I only use for MVC with Model
public PersonSearchCriteriaModel
{
public string Name {get; set;}
public string Company {get; set;}
public string DateStart {get; set;}
public string DateEnd {get; set;}
}
// I like suffixing classes that I used passed to a View/Partial View
// with ViewModel
public class PersonSearchViewModel : IPersonSearchResultsView,
IPersonSearchCriteriaView
{
public IEnumerable<EFPerson> PersonSearchResults { get; set; }
public PersonSearchCriteriaModel PersonSearchModel { get; set; }
}
```
Now for your controllers, I'll set them up in a way that would also allow you to do Ajax in the future.
```
public PersonController : Controller
{
public ActionResult Search()
{
var model = new PersonSearchViewModel();
// make sure we don't get a null reference exceptions
model.PersonSearchModel = new PersonSearchCriteriaModel ();
model.PersonSearchResults = new List<EFPerson>();
return this.View(model);
}
[HttpPost]
public ActionResult Search(PersonSearchViewModel model)
{
model.PersonSearchResults = this.GetPersonResults(model.PersonSearchModel);
return this.View(model)
}
// You could use this for Ajax
public ActionResult Results(PersonSearchViewModel model)
{
model.PersonSearchResults = this.GetPersonResults(model.PersonSearchModel);
return this.Partial("Partial-SearchResults", model)
}
private GetPersonResults(PersonSearchCriteriaModel criteria)
{
return DbContext.GetPersonResults(criteria)
}
}
```
Create a couple of partial-views your Views.
**/Views/Person/Partial-SearchCriteria.cshtml**
```
@model IPersonSearchCriteriaView
// the new part is for htmlAttributes, used by Ajax later
@using (Html.BeginForm(..., new { id="searchCriteria" }))
{
// Here is were the magic is, if you use the @Html.*For(m=>)
// Methods, they will create names that match the model
// and you can back back to the same model on Get/Post
<label>Name:</label>
@Html.TextBoxFor(m => Model.PersonSearchModel.Name)
// or let mvc create a working label automagically
@Html.EditorFor(m => Model.PersonSearchModel.Name)
// or let mvc create the entire form..
@Html.EditorFor(m => Model.PersonSearchModel)
}
```
**/Views/Person/Partial-SearchResults.cshtml**
```
@model IPersonSearchResultsView
@foreach (var person in Model.PersonSearchResults )
{
<tr>
<td class="list-field">
@Html.DisplayFor(modelItem => person.Name)
</td>
// etc
</tr>
}
```
And Finally the view:
**/Views/Person/Search.cshtml**
```
@model PersonSearchViewModel
@Html.Partial("Partial-SearchCriteria", Model)
// easily change the order of these
<div id="searchResults">
@Html.Partial("Partial-SearchResults", Model);
</div>
```
Now enabling Ajax is pretty crazy easy (simplified and my not be exactly right):
```
$.Ajax({
url: '/Person/Results',
data: $('#searchCriteria').serialize(),
success: function(jsonResult)
{
$('#searchResults').innerHtml(jsonResult);
});
``` | What I typically do is pass the posted Model back into the view. This way the values are not cleared out.
Your code would look something like this:
```
<div style="float:left;">
<div style="float:left;">
<label>Name:</label>
@Html.TextBox("name", Model.Name)
</div>
<div style="float:left; margin-left:15px">
<label>Company:</label>
@Html.TextBox("company", Model.Company)
</div>
<div style="float:left; margin-left:65px">
<label>Date Range:</label>
@Html.TextBox("dateStart", Model.DateStart, new { @class = "datefield", type = "date" })
to
@Html.TextBox("dateEnd", Model.DateEnd, new { @class = "datefield", type = "date" })
</div>
```
When initially getting the form, you'll have to create a new `Model`, otherwise the `Model` will be null and throw an exception when properties are called on it.
**Sample Model**
```
public class SearchModel
{
public SearchModel()
{
Results = new List<Result>();
}
public string Name {get; set;}
public string Company {get; set;}
public string DateStart {get; set;}
public string DateEnd {get; set;}
public List<Result> Results {get; set;}
}
@foreach (var item in Model.Results)
{
<tr>
<td class="list-field">
@Html.DisplayFor(modelItem => item.Name)
</td>
<td class="list-field">
@Html.DisplayFor(modelItem => item.CompanyName)
</td>
<td class="list-field">
@Html.DisplayFor(modelItem => item.City)
</td>
<td>
@Html.DisplayFor(modelItem => item.State)
</td>
<td class="list-field">
@Html.DisplayFor(modelItem => item.DateCreated)
</td>
<td class="list-field">
@Html.ActionLink("Edit", "Edit", new { id = item.ProfileID }) |
@Html.ActionLink("View", "View", new { id = item.ProfileID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ProfileID }, new { onclick = " return DeleteConfirm()" })
</td>
</tr>
}
```
Here is a [link](http://www.dotnetfunda.com/articles/article1317-how-to-create-a-simple-model-in-aspnet-mvc-and-display-the-same-tutorial.aspx) on creating models for a view in MVC. |
14,224,863 | I need to sort a NSMutableArray containing NSURLs with localizedStandardCompare:
```
[array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSString *f1 = [(NSURL *)obj1 absoluteString];
NSString *f2 = [(NSURL *)obj2 absoluteString];
return [f1 localizedStandardCompare:f2];
}];
```
This works fine, but I worry a bit about the performance: the block will be evaluated n log n times during the sort, so I'd like it to be fast (the array might have up to 100,000 elements). Since localizedStandardCompare is only available on NSString, I need to convert the URLs to strings. Above, I use `absoluteString`, but there are other methods that return a NSString, for example relativeString. Reading the NSURL class reference, I get the impression that relativeString might be faster, since the URL does not need to be resolved, but this is my first time with Cocoa and OS-X, and thus just a wild guess.
Additional constraint: in this case, all URLs come from a NSDirectoryEnumerator on local storage, so all are file URLs. It would be a bonus if the method would work for all kinds of URL, though.
My question: which method should I use to convert NSURL to NSString for best performance?
Profiling all possible methods might be possible, but I have only one (rather fast) OS-X machine, and who knows - one day the code might end up on iOS.
I'm using Xcode 4.5.2 on OS-X 10.8.2, but the program should work on older version, too (within reasonable bounds). | 2013/01/08 | [
"https://Stackoverflow.com/questions/14224863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1096710/"
] | if you are using html in mvc then check solution 2 from [here](http://www.codeproject.com/Questions/774540/how-to-retain-text-box-values-after-postback-in-as), `value="@Request["txtNumber1"]"` worked fine for me,
```
<input type="text" id="txtNumber1" name="txtNumber1" value="@Request["txtNumber1"]"/>
```
hope helps someone. | What I typically do is pass the posted Model back into the view. This way the values are not cleared out.
Your code would look something like this:
```
<div style="float:left;">
<div style="float:left;">
<label>Name:</label>
@Html.TextBox("name", Model.Name)
</div>
<div style="float:left; margin-left:15px">
<label>Company:</label>
@Html.TextBox("company", Model.Company)
</div>
<div style="float:left; margin-left:65px">
<label>Date Range:</label>
@Html.TextBox("dateStart", Model.DateStart, new { @class = "datefield", type = "date" })
to
@Html.TextBox("dateEnd", Model.DateEnd, new { @class = "datefield", type = "date" })
</div>
```
When initially getting the form, you'll have to create a new `Model`, otherwise the `Model` will be null and throw an exception when properties are called on it.
**Sample Model**
```
public class SearchModel
{
public SearchModel()
{
Results = new List<Result>();
}
public string Name {get; set;}
public string Company {get; set;}
public string DateStart {get; set;}
public string DateEnd {get; set;}
public List<Result> Results {get; set;}
}
@foreach (var item in Model.Results)
{
<tr>
<td class="list-field">
@Html.DisplayFor(modelItem => item.Name)
</td>
<td class="list-field">
@Html.DisplayFor(modelItem => item.CompanyName)
</td>
<td class="list-field">
@Html.DisplayFor(modelItem => item.City)
</td>
<td>
@Html.DisplayFor(modelItem => item.State)
</td>
<td class="list-field">
@Html.DisplayFor(modelItem => item.DateCreated)
</td>
<td class="list-field">
@Html.ActionLink("Edit", "Edit", new { id = item.ProfileID }) |
@Html.ActionLink("View", "View", new { id = item.ProfileID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ProfileID }, new { onclick = " return DeleteConfirm()" })
</td>
</tr>
}
```
Here is a [link](http://www.dotnetfunda.com/articles/article1317-how-to-create-a-simple-model-in-aspnet-mvc-and-display-the-same-tutorial.aspx) on creating models for a view in MVC. |
60,914,918 | ```js
import React from 'react';
import Slick from 'react-slick';
import style from './Slider.module.css';
import {Link} from 'react-router-dom';
const SliderTemplates = (props) => {
let template = null;
const settings= {
dots:true,
infinite: true,
arrows: false,
speed: 500,
slidesToShow:1,
slidesToScroll:1
}
switch(props.type){
case('featured'):
template= props.data.map((item, i)=>{
return(
<div key={i}>
<div className={style.featured_item}>
<div
className={style.featured_image}
style={{ background: `url(../../Assets/images/articles/${item.image})` }}>
<Link to={`/articles/${item.id}`}>
<div className={style.featured_caption}>
{item.title}s
</div>
</Link>
</div>
</div>
</div>
)
})
break;
default:
template=null;
}
return (
<Slick {...settings}>
{template}
</Slick>
);
};
export default SliderTemplates;
```
```css
.featured_item{
position: relative;
}
.feature_item a{
position: absolute;
width: 100%;
bottom: 0px;
text-decoration: none;
right: 0px;
}
.featured_image {
height: 330px;
background-size: cover !important;
background-repeat: no-repeat !important;
}
.featured_caption{
color: #fff;
top: 0px;
width: 100%;
padding: 20px;
font-weight: 300;
font-size: 28px;
box-sizing: border-box;
}
```
I am trying to map images from a folder (Address given in the picture attached) with in-line styling in ReactJs.
All the data is imported from db.json and I want to display the images(position: relative) with text (position: absolute) but the picture is not available for display and I can't find where I went wrong.
The picture is not displayed.[Screenshot](https://i.stack.imgur.com/VCqC7.jpg) | 2020/03/29 | [
"https://Stackoverflow.com/questions/60914918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7702048/"
] | Use [`MultiLabelBinarizer`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MultiLabelBinarizer.html) with `d.keys()` and `d.values()` of dictionary:
```
from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()
df = pd.DataFrame(mlb.fit_transform(d.values()), index=d.keys(),columns=mlb.classes_)
print (df)
col_1 col_2 col_3 col_4
GP 1 1 1 1
MIN 1 1 1 1
PTS 1 1 1 1
FGM 1 1 0 1
FGA 0 1 0 0
FG% 0 1 1 1
3P Made 0 1 1 0
AST 0 1 1 0
STL 0 1 0 0
BLK 0 1 1 0
TOV 0 0 1 0
```
Pandas only solution, but slowier with `Series`, [`Series.str.join`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.join.html) and [`Series.str.get_dummies`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.get_dummies.html):
```
df = pd.Series(d).str.join('|').str.get_dummies()
``` | You can create a series, `explode` it, and then use `get_dummies` with `sum`:
```
pd.get_dummies(pd.Series(d).explode()).sum(level=0)
```
Or you can play with the exploded series and `unstack`:
```
(pd.Series(d).explode()
.to_frame(name='cols')
.assign(values=1)
.set_index('cols', append=True)['values']
.unstack('cols', fill_value=0)
)
```
Output:
```
col_1 col_2 col_3 col_4
GP 1 1 1 1
MIN 1 1 1 1
PTS 1 1 1 1
FGM 1 1 0 1
FGA 0 1 0 0
FG% 0 1 1 1
3P Made 0 1 1 0
AST 0 1 1 0
STL 0 1 0 0
BLK 0 1 1 0
TOV 0 0 1 0
``` |
53,056,028 | I'm using for a GetAppRolesForUser function (and have tried variations of based on answers here):
```
private AuthContext db = new AuthContext();
...
var userRoles = Mapper.Map<List<RoleApi>>(
db.Users.SingleOrDefault(u => u.InternetId == username)
.Groups.SelectMany(g => g.Roles.Where(r => r.Asset.AssetName == application)));
```
I end up with this in SQL Profiler for every single RolesId each time:
```
exec sp_executesql N'SELECT
[Extent2].[GroupId] AS [GroupId],
[Extent2].[GroupName] AS [GroupName]
FROM [Auth].[Permissions] AS [Extent1]
INNER JOIN [Auth].[Groups] AS [Extent2] ON [Extent1].[GroupId] = [Extent2].[GroupId]
WHERE [Extent1].[RolesId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=6786
```
How do I refactor so EF produces a single query for userRoles and doesn't take 18 seconds to run? | 2018/10/30 | [
"https://Stackoverflow.com/questions/53056028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2762742/"
] | I think the problem is you're lazy loading the groups and roles.
One solution is eager load them before you call `SingleOrDefault`
```
var user = db.Users.Include(x => x.Groups.Select(y => y.Roles))
.SingleOrDefault(u => u.InternetId == username);
var groups = user.Groups.SelectMany(
g => g.Roles.Where(r => r.Asset.AssetName == application));
var userRoles = Mapper.Map<List<RoleApi>>(groups);
```
***Also note*** : there is no sanity checking for null here. | Here is another way of avoiding lazy loading. You can also look at projection and have only those fields which you need rather than loading the entire columns.
```
var userRoles = Mapper.Map<List<RoleApi>>(
db.Users.Where(u => u.InternetId == username).Select(../* projection */ )
.Groups.SelectMany(g => g.Roles.Where(r => r.Asset.AssetName == application)));
```
EF also comes with Include:
```
var userRoles = Mapper.Map<List<RoleApi>>(
db.Users.Where(u => u.InternetId == username).Select(../* projection */ )
.Include(g => g.Roles.Where(r => r.Asset.AssetName == application)));
```
Then can iterate the collection using multiple for loops. |
53,056,028 | I'm using for a GetAppRolesForUser function (and have tried variations of based on answers here):
```
private AuthContext db = new AuthContext();
...
var userRoles = Mapper.Map<List<RoleApi>>(
db.Users.SingleOrDefault(u => u.InternetId == username)
.Groups.SelectMany(g => g.Roles.Where(r => r.Asset.AssetName == application)));
```
I end up with this in SQL Profiler for every single RolesId each time:
```
exec sp_executesql N'SELECT
[Extent2].[GroupId] AS [GroupId],
[Extent2].[GroupName] AS [GroupName]
FROM [Auth].[Permissions] AS [Extent1]
INNER JOIN [Auth].[Groups] AS [Extent2] ON [Extent1].[GroupId] = [Extent2].[GroupId]
WHERE [Extent1].[RolesId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=6786
```
How do I refactor so EF produces a single query for userRoles and doesn't take 18 seconds to run? | 2018/10/30 | [
"https://Stackoverflow.com/questions/53056028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2762742/"
] | I think the problem is you're lazy loading the groups and roles.
One solution is eager load them before you call `SingleOrDefault`
```
var user = db.Users.Include(x => x.Groups.Select(y => y.Roles))
.SingleOrDefault(u => u.InternetId == username);
var groups = user.Groups.SelectMany(
g => g.Roles.Where(r => r.Asset.AssetName == application));
var userRoles = Mapper.Map<List<RoleApi>>(groups);
```
***Also note*** : there is no sanity checking for null here. | You have to be aware of two differences:
* The difference between IEnumerable and IQueryable
* The difference between functions that return `IQueryable<TResult>` (lazy) and functions that return `TResult` (executing)
Difference between `Enumerable` and `Queryable`
-----------------------------------------------
. A LINQ statement that is `AsEnumerable` is meant to be processed in your local process. It contains all code and all calls to execute the statement. This statement is executed as soon as `GetEnumerator` and `MoveNext` are called, either explicitly, or implicitly using `foreach` or LINQ statements that don't return `IEnumerable<...>`, like `ToList`, `FirstOrDefault`, and `Any`.
In contrast, an `IQueryable` is not meant to be processed in your process (however it can be done if you want). It is usually meant to be processed by a different process, usually a database management system.
For this an `IQueryable` holds an `Expression` and a `Provider`. The `Expression` represents the query that must be executed. The `Provider` knows who must execute the query (the DBMS), and which language this executor uses (usually SQL). When `GetEnumerator` and `MoveNext` are called, the `Provider` takes the `Expression` and translates it into the language of the `Executor`. The query is sen't to the executor. The returned data is presented `AsEnumerable`, where `GetEnumerator` and `MoveNext` are called.
Because of this translation into SQL, an IQueryable can't do all the things that an IEnumerable can do. The main thing is that it can't call your local functions. It can't even execute all LINQ functions. The better the quality of the `Provider` the more it can do. See [supported and unsupported LINQ methods](https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/supported-and-unsupported-linq-methods-linq-to-entities)
Lazy LINQ methods and executing LINQ methods
--------------------------------------------
There are two groups of LINQ methods. Those that return `IQueryable<...>/IEnumerable<...> and those that do not.
The first group use lazy loading. This means that at the end of the LINQ statement the query has been created, but it is not executed yet. Only 'GetEnumerator`and`MoveNext`will make that the`Provider`will translate the`Expression` and order the DBMS to execute the query.
Concatenating `IQueryables` will only change the `Expression`. This is a fairly fast procedure. Hence there is no performance gain if you make one big LINQ expression instead of concatenate them before you execute the query.
Usually the DBMS is smarter and better prepared to do selections than your process. The transfer of selected data to your local process is one of the slower parts of your query.
>
> Advice: Try to create your LINQ statements such, that the executing
> statement is the last one that can be executed by the DBMS. Make sure
> that you only select the properties that you actually plan to use.
>
>
>
So for example, don't transfer foreign keys if you don't use them.
Back to your question
---------------------
Leaving the mapper out of the question you start with:
```
db.Users.SingleOrDefault(...)
```
SingleOrDefault is a non-lazy function. It doesn't return `IQueryable<...>`. It will execute the query. It will transport one complete `User` to your local process, including its `Roles`.
Advice postpone the SingleOrDefault to the last statement:
```
var result = myDbcontext.Users
.Where(user => user.InternetId == username)
.SelectMany(user => user.Groups.Roles.Where(role => role.Asset.AssetName == application))
// until here, the query is not executed yet, execute it now:
.SingleOrDefault();
```
In words: From the sequence of `Users`, keep only those `Users` with an `InternetId` that equals `userName`. From all remaining `Users` (which you hope to be only one), select the sequence of `Roles` of the `Groups` of each `User`. However, we don't want to select all `Roles`, we only keep the `Roles` with an `AssetName` equal to `application`. Now put all remaining `Roles` into one collection (the `many` part in `SelectMany`), and select the zero or one remaining `Role` that you expect. |
53,056,028 | I'm using for a GetAppRolesForUser function (and have tried variations of based on answers here):
```
private AuthContext db = new AuthContext();
...
var userRoles = Mapper.Map<List<RoleApi>>(
db.Users.SingleOrDefault(u => u.InternetId == username)
.Groups.SelectMany(g => g.Roles.Where(r => r.Asset.AssetName == application)));
```
I end up with this in SQL Profiler for every single RolesId each time:
```
exec sp_executesql N'SELECT
[Extent2].[GroupId] AS [GroupId],
[Extent2].[GroupName] AS [GroupName]
FROM [Auth].[Permissions] AS [Extent1]
INNER JOIN [Auth].[Groups] AS [Extent2] ON [Extent1].[GroupId] = [Extent2].[GroupId]
WHERE [Extent1].[RolesId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=6786
```
How do I refactor so EF produces a single query for userRoles and doesn't take 18 seconds to run? | 2018/10/30 | [
"https://Stackoverflow.com/questions/53056028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2762742/"
] | TheGeneral's answer covers why you are getting caught out with lazy loading. You may also need to include Asset to get AssetName.
With AutoMapper you can avoid the need to Eager Load the entities by employing `.ProjectTo<T>()` to the `IQueryable`, provided there is a User accessible in Group.
For instance:
```
var roles = db.Groups.Where(g => g.User.Internetid == username)
.SelectMany(g => g.Roles.Where(r => r.Asset.AssetName == application))
.ProjectTo<RoleApi>()
.ToList();
```
This should leverage the deferred execution where AutoMapper will effectively project in the `.Select()` needed to populate the RoleApi instance based on your mapping/inspection. | Here is another way of avoiding lazy loading. You can also look at projection and have only those fields which you need rather than loading the entire columns.
```
var userRoles = Mapper.Map<List<RoleApi>>(
db.Users.Where(u => u.InternetId == username).Select(../* projection */ )
.Groups.SelectMany(g => g.Roles.Where(r => r.Asset.AssetName == application)));
```
EF also comes with Include:
```
var userRoles = Mapper.Map<List<RoleApi>>(
db.Users.Where(u => u.InternetId == username).Select(../* projection */ )
.Include(g => g.Roles.Where(r => r.Asset.AssetName == application)));
```
Then can iterate the collection using multiple for loops. |
53,056,028 | I'm using for a GetAppRolesForUser function (and have tried variations of based on answers here):
```
private AuthContext db = new AuthContext();
...
var userRoles = Mapper.Map<List<RoleApi>>(
db.Users.SingleOrDefault(u => u.InternetId == username)
.Groups.SelectMany(g => g.Roles.Where(r => r.Asset.AssetName == application)));
```
I end up with this in SQL Profiler for every single RolesId each time:
```
exec sp_executesql N'SELECT
[Extent2].[GroupId] AS [GroupId],
[Extent2].[GroupName] AS [GroupName]
FROM [Auth].[Permissions] AS [Extent1]
INNER JOIN [Auth].[Groups] AS [Extent2] ON [Extent1].[GroupId] = [Extent2].[GroupId]
WHERE [Extent1].[RolesId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=6786
```
How do I refactor so EF produces a single query for userRoles and doesn't take 18 seconds to run? | 2018/10/30 | [
"https://Stackoverflow.com/questions/53056028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2762742/"
] | TheGeneral's answer covers why you are getting caught out with lazy loading. You may also need to include Asset to get AssetName.
With AutoMapper you can avoid the need to Eager Load the entities by employing `.ProjectTo<T>()` to the `IQueryable`, provided there is a User accessible in Group.
For instance:
```
var roles = db.Groups.Where(g => g.User.Internetid == username)
.SelectMany(g => g.Roles.Where(r => r.Asset.AssetName == application))
.ProjectTo<RoleApi>()
.ToList();
```
This should leverage the deferred execution where AutoMapper will effectively project in the `.Select()` needed to populate the RoleApi instance based on your mapping/inspection. | You have to be aware of two differences:
* The difference between IEnumerable and IQueryable
* The difference between functions that return `IQueryable<TResult>` (lazy) and functions that return `TResult` (executing)
Difference between `Enumerable` and `Queryable`
-----------------------------------------------
. A LINQ statement that is `AsEnumerable` is meant to be processed in your local process. It contains all code and all calls to execute the statement. This statement is executed as soon as `GetEnumerator` and `MoveNext` are called, either explicitly, or implicitly using `foreach` or LINQ statements that don't return `IEnumerable<...>`, like `ToList`, `FirstOrDefault`, and `Any`.
In contrast, an `IQueryable` is not meant to be processed in your process (however it can be done if you want). It is usually meant to be processed by a different process, usually a database management system.
For this an `IQueryable` holds an `Expression` and a `Provider`. The `Expression` represents the query that must be executed. The `Provider` knows who must execute the query (the DBMS), and which language this executor uses (usually SQL). When `GetEnumerator` and `MoveNext` are called, the `Provider` takes the `Expression` and translates it into the language of the `Executor`. The query is sen't to the executor. The returned data is presented `AsEnumerable`, where `GetEnumerator` and `MoveNext` are called.
Because of this translation into SQL, an IQueryable can't do all the things that an IEnumerable can do. The main thing is that it can't call your local functions. It can't even execute all LINQ functions. The better the quality of the `Provider` the more it can do. See [supported and unsupported LINQ methods](https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/supported-and-unsupported-linq-methods-linq-to-entities)
Lazy LINQ methods and executing LINQ methods
--------------------------------------------
There are two groups of LINQ methods. Those that return `IQueryable<...>/IEnumerable<...> and those that do not.
The first group use lazy loading. This means that at the end of the LINQ statement the query has been created, but it is not executed yet. Only 'GetEnumerator`and`MoveNext`will make that the`Provider`will translate the`Expression` and order the DBMS to execute the query.
Concatenating `IQueryables` will only change the `Expression`. This is a fairly fast procedure. Hence there is no performance gain if you make one big LINQ expression instead of concatenate them before you execute the query.
Usually the DBMS is smarter and better prepared to do selections than your process. The transfer of selected data to your local process is one of the slower parts of your query.
>
> Advice: Try to create your LINQ statements such, that the executing
> statement is the last one that can be executed by the DBMS. Make sure
> that you only select the properties that you actually plan to use.
>
>
>
So for example, don't transfer foreign keys if you don't use them.
Back to your question
---------------------
Leaving the mapper out of the question you start with:
```
db.Users.SingleOrDefault(...)
```
SingleOrDefault is a non-lazy function. It doesn't return `IQueryable<...>`. It will execute the query. It will transport one complete `User` to your local process, including its `Roles`.
Advice postpone the SingleOrDefault to the last statement:
```
var result = myDbcontext.Users
.Where(user => user.InternetId == username)
.SelectMany(user => user.Groups.Roles.Where(role => role.Asset.AssetName == application))
// until here, the query is not executed yet, execute it now:
.SingleOrDefault();
```
In words: From the sequence of `Users`, keep only those `Users` with an `InternetId` that equals `userName`. From all remaining `Users` (which you hope to be only one), select the sequence of `Roles` of the `Groups` of each `User`. However, we don't want to select all `Roles`, we only keep the `Roles` with an `AssetName` equal to `application`. Now put all remaining `Roles` into one collection (the `many` part in `SelectMany`), and select the zero or one remaining `Role` that you expect. |
65,086,069 | To demonstrate this, I have few IPs in text file called `blocked.txt` with the following content:
```
1.1.1.1
1.1.1.2
1.1.1.3
2.1.1.1
2.1.1.2
```
So given an input of CIDR of `1.1.1.0/24`
I want to remove the IP that belongs this CIDR range which are `1.1.1.1`, `1.1.1.2` and `1.1.1.3`
The only thing that makes me stuck is how to list out all the IP if CIDR form is given. Example:
```
#!/bin/bash
cidr_ip="1.1.1.0/24"
ip_exist=$(echo "${cidr_ip}" | grep_all_the_ip_in_that_CIDR in blocked.txt)
echo ${ip_exist} # This will list out all the iP and then I can use this to remove the IP
```
The expected output, `blocked.txt` will only have this content:
```
2.1.1.1
2.1.1.2
```
=================================
I'm testing with this data:
```
161.35.169.25
104.228.72.171
177.5.53.176
103.56.43.225
20.58.48.57
27.115.124.6
1.1.1.1
111.229.188.72
27.115.124.70
51.15.179.65
77.245.149.46
180.163.220.68
71.68.239.90
45.142.120.87
42.236.10.125
42.236.10.114
212.70.149.53
1.1.1.0/24
1.1.1.9
1.1.1.10
1.1.1.2
1.1.1.3
2.1.1.0/24
2.1.1.1
3.1.1.0/24
212.70.149.84
103.249.77.2
5.178.86.76
``` | 2020/12/01 | [
"https://Stackoverflow.com/questions/65086069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13288989/"
] | ***EDIT:*** Since OP added few more samples to handle lines with `/` present one could try following.
```
awk -F'/' -v val="1.1.1.0/24" '
BEGIN{
match(val,/.*\./)
matched=substr(val,RSTART,RLENGTH-1)
split(substr(val,RSTART+RLENGTH),arr,"/")
for(i=arr[1];i<=arr[2];i++){
skip[matched"."i]
}
}
!($1 in skip)
' Input_file
```
---
---
Could you please try following, written and tested with shown samples in GNU `awk`. Where variable `val` is your range of IPs.
```
awk -v val="1.1.1.0/24" '
BEGIN{
match(val,/.*\./)
matched=substr(val,RSTART,RLENGTH-1)
split(substr(val,RSTART+RLENGTH),arr,"/")
for(i=arr[1];i<=arr[2];i++){
skip[matched"."i]
}
}
!($0 in skip)
' Input_file
```
***Explanation:*** Adding detailed explanation for above.
```
awk -v val="1.1.1.0/24" ' ##Starting awk program from here and creating variable val which has that range here.
BEGIN{ ##Starting BEGIN section of this program from here.
match(val,/.*\./) ##using match function to match everything till . in variable val here.
matched=substr(val,RSTART,RLENGTH-1) ##Creating matched which has sub string of matched regex value in var variable.
split(substr(val,RSTART+RLENGTH),arr,"/") ##Splitting rest of value of var which is actual range into array arr here.
for(i=arr[1];i<=arr[2];i++){ ##Running for loop from 1st item value to 2nd item value of array here.
skip[matched"."i] ##Creating skip array which has index as matched(variable) dot and i here, it contains which ips to be negleted basically.
}
}
!($0 in skip) ##In main block of program checking condition if current line is NOT present in skip then print that line.
' Input_file ##Mentioning Input_file name here.
``` | Another way of doing this is by using nmap which support CIDR notation:
```
nmap -sn -v 1.1.1.0/24 | awk '/^Nmap scan/ { print $5 }' > ipadds.txt
```
Run nmap on the CIDR range doing a simple ping scan with -v to display hosts that may be down also. Use awk to strip everything but the IP addresses, outputting them to a file ipadds.txt
```
grep -v -f ipadds.txt blocked.txt
```
Do an inverse search of blocked.txt using the entries in ipadds.txt.
NOTE - The solution may not be for everyone and will be dependant on network governance and your ability to use network scanning tools. You will also need sudo permissions to run nmap to ensure that the most optimal, accurate results are attained. |
306,907 | Does anyone know what these RCA-to-USB cables are/do? There doesn’t seem to be any electronics in the cable like an [EasyCap](http://images.google.com/images?safe=off&sout=1&q=easycap), so I can only assume that the RCA connectors are directly connected to the USB pins. I suppose that it *could* be used for A/V capture, assuming of course that there were some kind of driver/software, but then again, I doubt that the computer would pick it up as a device of any kind when you connect it since it would be directly connected to a TV/VCR/etc. Looking around, I see mentions of connecting it to “RCA cameras”, but that does not clear things up at all.
What are they?

 | 2011/07/06 | [
"https://superuser.com/questions/306907",
"https://superuser.com",
"https://superuser.com/users/3279/"
] | According to the [product description](http://rads.stackoverflow.com/amzn/click/B003QA5LA0) at Amazon, they are RCA-to-USB cables...
They plug into a camcorder via RCA, to display images/sound on certain "USB-enabled TVs and PCs." | hook a rca camera to the usb cable and you are now able to use any camera as a video conference room camera.
No driver needed. Most conference calls are able to be recorded thru the website you are using for the call.
You are correct! It will not work for recording, unless you are using some other program that allows you to delicate this camera for use inside the program you are using.
But there are many other usb cables that do cam with drivers to install for surveillance. |
306,907 | Does anyone know what these RCA-to-USB cables are/do? There doesn’t seem to be any electronics in the cable like an [EasyCap](http://images.google.com/images?safe=off&sout=1&q=easycap), so I can only assume that the RCA connectors are directly connected to the USB pins. I suppose that it *could* be used for A/V capture, assuming of course that there were some kind of driver/software, but then again, I doubt that the computer would pick it up as a device of any kind when you connect it since it would be directly connected to a TV/VCR/etc. Looking around, I see mentions of connecting it to “RCA cameras”, but that does not clear things up at all.
What are they?

 | 2011/07/06 | [
"https://superuser.com/questions/306907",
"https://superuser.com",
"https://superuser.com/users/3279/"
] | I did some digging and found some useful information in [a review on Amazon](http://www.amazon.com/review/R3EXGOXUSBCQ8T/ref=cm_cr_rdp_perm?ie=UTF8&ASIN=B003QA5LA0 "GSI - 3 RCA To USB Cable"). As you suspected, there is no analog/digital conversion hardware in the cable, the RCA lines are tied directly to the USB pins. The reviewer says that he disassembled a cable and found this pinout:
* USB `Ground` and USB `Data-` -> Ground of all three RCA connectors
* USB `Data+` -> Left audio and video composite pins
* USB `Vcc` -> Right audio pin
From that pinout, it is *impossible* for this cable to carry either a valid composite A/V signal (because the left audio and video composite pins are tied together), or a valid USB signal (because `Data-` and `Ground` are tied together). This cable is an elaborate—and [surprisingly](http://www.ebay.com/sch/i.html?_nkw=usb+rca+av+tv) [widespread](http://www.alibaba.com/products/F0/USB_Male_A_to_RCA_AV_TV/1.html)—scam. | According to the [product description](http://rads.stackoverflow.com/amzn/click/B003QA5LA0) at Amazon, they are RCA-to-USB cables...
They plug into a camcorder via RCA, to display images/sound on certain "USB-enabled TVs and PCs." |
306,907 | Does anyone know what these RCA-to-USB cables are/do? There doesn’t seem to be any electronics in the cable like an [EasyCap](http://images.google.com/images?safe=off&sout=1&q=easycap), so I can only assume that the RCA connectors are directly connected to the USB pins. I suppose that it *could* be used for A/V capture, assuming of course that there were some kind of driver/software, but then again, I doubt that the computer would pick it up as a device of any kind when you connect it since it would be directly connected to a TV/VCR/etc. Looking around, I see mentions of connecting it to “RCA cameras”, but that does not clear things up at all.
What are they?

 | 2011/07/06 | [
"https://superuser.com/questions/306907",
"https://superuser.com",
"https://superuser.com/users/3279/"
] | I did some digging and found some useful information in [a review on Amazon](http://www.amazon.com/review/R3EXGOXUSBCQ8T/ref=cm_cr_rdp_perm?ie=UTF8&ASIN=B003QA5LA0 "GSI - 3 RCA To USB Cable"). As you suspected, there is no analog/digital conversion hardware in the cable, the RCA lines are tied directly to the USB pins. The reviewer says that he disassembled a cable and found this pinout:
* USB `Ground` and USB `Data-` -> Ground of all three RCA connectors
* USB `Data+` -> Left audio and video composite pins
* USB `Vcc` -> Right audio pin
From that pinout, it is *impossible* for this cable to carry either a valid composite A/V signal (because the left audio and video composite pins are tied together), or a valid USB signal (because `Data-` and `Ground` are tied together). This cable is an elaborate—and [surprisingly](http://www.ebay.com/sch/i.html?_nkw=usb+rca+av+tv) [widespread](http://www.alibaba.com/products/F0/USB_Male_A_to_RCA_AV_TV/1.html)—scam. | hook a rca camera to the usb cable and you are now able to use any camera as a video conference room camera.
No driver needed. Most conference calls are able to be recorded thru the website you are using for the call.
You are correct! It will not work for recording, unless you are using some other program that allows you to delicate this camera for use inside the program you are using.
But there are many other usb cables that do cam with drivers to install for surveillance. |
23,482,982 | We have this line in my code base:
```
var uncurryThis = Function.bind.bind(Function.call);
```
That I'm trying to work through. Presumably, it uncurries. How do I work this out?
I guess it's a version of `Function.bind` whose own `this` is bound to `Function.call`. Doesn't help me enough. And I haven't found any uses, so I'm not even sure if you call it standalone or need to call it "as a method", only, you know, bind it first. | 2014/05/05 | [
"https://Stackoverflow.com/questions/23482982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339987/"
] | It passes the `call` function to the `bind` function, with the `bind` function itself being the value of `this`. Thus you get in return a wrapper around the `bind` function that arranges for `this` to be the `call` function when you call it. *That*, in turn, is a function that lets you create a wrapper around the `call` function bound to some argument you pass it.
In case you haven't been drinking coffee nonstop since you woke up this morning, step by step:
* `Function.bind.bind` is a reference to the `bind` function. The reference is generated from a property of — confusion point 1 — the `bind` function itself. Remember, the `bind` function, when called with some function as the object, is used to create a wrapper around that function with `this` bound to the first argument passed in.
* Thus that function call gives you a function back. That function works as if you called `Function.call.bind(something)`.
* If you pass some random function as an argument to *that* function, then, you get back a wrapper around the random function that, when called, will act like `randomFunction.call(whatever)`.
So:
```
function random() {
alert(this.foo);
}
var bb = Function.bind.bind(Function.call);
var randomcall = bb(random);
randomcall({ foo: "hello world" }); // alerts "hello world"
```
The ultimate point is this: you've got a function, and inside the function there's code that expects `this` to have some properties, and it uses `this` in one way or another. You'd really like to be able to use that function with some object here, some object there. You can obviously do that with
```
random.call(someObject);
```
But this magic "bind-bind-call" trick gives you a cheap way to create a variation on your function that lets you avoid the explicitly-coded invocation of `.call()`. It also allows you to hang onto your senior front-end developer position for a little bit longer.
*edit* — I'm going to spoil the punch line above because I just thought of a good reason to use the bind+call trick to obtain a function that arranges to make a call to some desired function that expects to operate via `this` on some "owner" object. Let's say you've got an array of strings, and you'd like to get a version of those strings in lower-case. You could write this:
```
var uc = ["Hello", "World"];
var lc = uc.map(function(s) { return s.toLowerCase(); });
```
But with the magic "bb" function we could also write:
```
var uc = ["Hello", "World"];
var tlc = bb(String.prototype.toLowerCase);
var lc = uc.map(tlc);
```
Not much of an improvement written that way, but if one were to make a set of `bb()`-ified wrappers of all the handy String prototype methods, it might make more sense. Of course, everything has a price, and it's probably the case that such wrappers will have some performance impact. (If practices like this were common then runtimes could probably be improved.) | OK. You know what [`bind`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) does? It's a method of Functions to fix their `this` argument, and returns a new function. It could be simplified to:
```
function bind(context) {
var fn = this;
return function() {
return fn.apply(context, arguments);
};
}
```
I will abbreviate function calls with contexts in a more functional style with lots of partial application: bindfn(context) -> fncontext. With arguments: (bindfn(context))(…) is equal to fncontext(…).
Similarly, [`call`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) does take a `this` value but instead of returning a function, it applies it right now: callfn(context, …) -> fncontext(…).
So now let's get at your code: `bind.call(bind, call)`. Here, you're applying `bind` on `bind` with `call` as the this value: bindbind(call). Let's expand this (with above rule) to bindcall. What if we now supplied some arguments to it?
>
> bindbind(call) *(fn)(context, …)*
>
>
> bindcall *(fn)(context, …)*
>
>
> call *fn(context, …)*
>
>
> *fncontext(…)*
>
>
>
Step by step, we could do
>
> uncurryThis = bindbind(call) `//` bindcall
>
>
> func = uncurryThis(method) `//` callmethod
>
>
> result = func(context, …) `//` methodcontext(…)
>
>
>
A practical use case for this are any "class" methods that are supposed to be converted to a static function, taking the object (on which the method would be called upon) as the first argument:
```
var uncurryThis = Function.bind.bind(Function.call);
var uc = uncurryThis(String.prototype.toUpperCase);
uc("hello") // in contrast to "hello".toUpperCase()
```
This can be helpful if you cannot place a method call, but need a static function; e.g. as in
```
["hello", "world"].map(uc) // imagine the necessary function expression
```
Also, the method you want to invoke might not be a method of the object itself, as in
```
var slice = uncurryThis(Array.prototype.slice);
slice(arguments) // instead of `Array.prototype.slice.call(arguments)` everywhere
```
---
If it helps, here is also an explicit implementation, without any binds:
```
function uncurryThis(method) {
return function(context/*, ...*/)
return method.apply(context, Array.prototype.slice.call(arguments, 1));
};
}
``` |
23,482,982 | We have this line in my code base:
```
var uncurryThis = Function.bind.bind(Function.call);
```
That I'm trying to work through. Presumably, it uncurries. How do I work this out?
I guess it's a version of `Function.bind` whose own `this` is bound to `Function.call`. Doesn't help me enough. And I haven't found any uses, so I'm not even sure if you call it standalone or need to call it "as a method", only, you know, bind it first. | 2014/05/05 | [
"https://Stackoverflow.com/questions/23482982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339987/"
] | It passes the `call` function to the `bind` function, with the `bind` function itself being the value of `this`. Thus you get in return a wrapper around the `bind` function that arranges for `this` to be the `call` function when you call it. *That*, in turn, is a function that lets you create a wrapper around the `call` function bound to some argument you pass it.
In case you haven't been drinking coffee nonstop since you woke up this morning, step by step:
* `Function.bind.bind` is a reference to the `bind` function. The reference is generated from a property of — confusion point 1 — the `bind` function itself. Remember, the `bind` function, when called with some function as the object, is used to create a wrapper around that function with `this` bound to the first argument passed in.
* Thus that function call gives you a function back. That function works as if you called `Function.call.bind(something)`.
* If you pass some random function as an argument to *that* function, then, you get back a wrapper around the random function that, when called, will act like `randomFunction.call(whatever)`.
So:
```
function random() {
alert(this.foo);
}
var bb = Function.bind.bind(Function.call);
var randomcall = bb(random);
randomcall({ foo: "hello world" }); // alerts "hello world"
```
The ultimate point is this: you've got a function, and inside the function there's code that expects `this` to have some properties, and it uses `this` in one way or another. You'd really like to be able to use that function with some object here, some object there. You can obviously do that with
```
random.call(someObject);
```
But this magic "bind-bind-call" trick gives you a cheap way to create a variation on your function that lets you avoid the explicitly-coded invocation of `.call()`. It also allows you to hang onto your senior front-end developer position for a little bit longer.
*edit* — I'm going to spoil the punch line above because I just thought of a good reason to use the bind+call trick to obtain a function that arranges to make a call to some desired function that expects to operate via `this` on some "owner" object. Let's say you've got an array of strings, and you'd like to get a version of those strings in lower-case. You could write this:
```
var uc = ["Hello", "World"];
var lc = uc.map(function(s) { return s.toLowerCase(); });
```
But with the magic "bb" function we could also write:
```
var uc = ["Hello", "World"];
var tlc = bb(String.prototype.toLowerCase);
var lc = uc.map(tlc);
```
Not much of an improvement written that way, but if one were to make a set of `bb()`-ified wrappers of all the handy String prototype methods, it might make more sense. Of course, everything has a price, and it's probably the case that such wrappers will have some performance impact. (If practices like this were common then runtimes could probably be improved.) | when we call bind on a function, it returns new function with this is replaced by context:
```
function random() {
alert(this.foo);
}
var newRandom = random.bind({foo:"hello world"}) //return new function same as //`random` with `this` is replaced by object {foo:"hello world"}
```
the same we have:
```
Function.bind.bind(Function.call)
// return new Function.bind with its `this` is replaced by `Function.call`
```
It has following source(used simplified version of `bind` function given by @Bergi):
```
var bb = function bind(context){
var fn = Function.call;
return function() {
return Function.call.apply(context, arguments); //also replace fn here for easier reading
};
}
```
Notice that context here will be function, for example `random`, so wen call bb(random) we has `newRandom` function as:
```
newRandom = function(){
return Function.call.apply(random, arguments); //also replace
}
//`apply` function replace `this` of Function.call to `random`, and apply Function(now become `random`) with arguments in `arguments` array.
``` |
23,482,982 | We have this line in my code base:
```
var uncurryThis = Function.bind.bind(Function.call);
```
That I'm trying to work through. Presumably, it uncurries. How do I work this out?
I guess it's a version of `Function.bind` whose own `this` is bound to `Function.call`. Doesn't help me enough. And I haven't found any uses, so I'm not even sure if you call it standalone or need to call it "as a method", only, you know, bind it first. | 2014/05/05 | [
"https://Stackoverflow.com/questions/23482982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339987/"
] | It passes the `call` function to the `bind` function, with the `bind` function itself being the value of `this`. Thus you get in return a wrapper around the `bind` function that arranges for `this` to be the `call` function when you call it. *That*, in turn, is a function that lets you create a wrapper around the `call` function bound to some argument you pass it.
In case you haven't been drinking coffee nonstop since you woke up this morning, step by step:
* `Function.bind.bind` is a reference to the `bind` function. The reference is generated from a property of — confusion point 1 — the `bind` function itself. Remember, the `bind` function, when called with some function as the object, is used to create a wrapper around that function with `this` bound to the first argument passed in.
* Thus that function call gives you a function back. That function works as if you called `Function.call.bind(something)`.
* If you pass some random function as an argument to *that* function, then, you get back a wrapper around the random function that, when called, will act like `randomFunction.call(whatever)`.
So:
```
function random() {
alert(this.foo);
}
var bb = Function.bind.bind(Function.call);
var randomcall = bb(random);
randomcall({ foo: "hello world" }); // alerts "hello world"
```
The ultimate point is this: you've got a function, and inside the function there's code that expects `this` to have some properties, and it uses `this` in one way or another. You'd really like to be able to use that function with some object here, some object there. You can obviously do that with
```
random.call(someObject);
```
But this magic "bind-bind-call" trick gives you a cheap way to create a variation on your function that lets you avoid the explicitly-coded invocation of `.call()`. It also allows you to hang onto your senior front-end developer position for a little bit longer.
*edit* — I'm going to spoil the punch line above because I just thought of a good reason to use the bind+call trick to obtain a function that arranges to make a call to some desired function that expects to operate via `this` on some "owner" object. Let's say you've got an array of strings, and you'd like to get a version of those strings in lower-case. You could write this:
```
var uc = ["Hello", "World"];
var lc = uc.map(function(s) { return s.toLowerCase(); });
```
But with the magic "bb" function we could also write:
```
var uc = ["Hello", "World"];
var tlc = bb(String.prototype.toLowerCase);
var lc = uc.map(tlc);
```
Not much of an improvement written that way, but if one were to make a set of `bb()`-ified wrappers of all the handy String prototype methods, it might make more sense. Of course, everything has a price, and it's probably the case that such wrappers will have some performance impact. (If practices like this were common then runtimes could probably be improved.) | I think this can be explained more clearly if you work backward.
**Context:**
Suppose we want to lowercase an array of strings. This can be done like so:
```
[‘A’, ‘B’].map(s => s.toLowerCase())
```
Let's say, for whatever reason, I want to make this call more generic. I don't like how `s` is bound to `this` and the fat arrow is tied to `toLowerCase()`.
How about this?
```
[‘A’, ‘B’].map(String.prototype.toLowerCase)
```
Well, this doesn't work because `map` passes the element as the first argument but `String.prototype.toLowerCase` takes no arguments. It expects the input string to be passed as `this`.
So a question is can we create a `wrapper` function that makes this work?
```
[‘A’, ‘B’].map(wrapper(String.prototype.toLowerCase))
```
`wrapper` returns a function that turns the first argument passed into `this` for `String.prototype.toLowerCase` to use.
I claim that your `uncurryThis === wrapper`.
---
**Proof:**
So let's not try to understand `unCurryThis` all at once. Instead, let's use some formulas to transform `unCurryThis` into something more understandable.
Some formulas first:
```
instance.function(...args)
=== (instance.constructor.prototype).function.call(instance, ...args)
=== (Class.prototype).function.call(instance, ...args) [1]
=== (Class.prototype).function.bind(instance)(...args) [2]
```
For example,
```
Class === String
instance === 'STRING'
function === toLowerCase
args === []
---
'string'.toLowerCase()
=== ('STRING'.constructor.prototype).toLowerCase.call('STRING')
=== (String.prototype).toLowerCase.call('STRING')
=== (String.prototype).toLowerCase.bind('STRING')()
```
So let's just blindly apply these formulas without worrying about what the confusing `uncurryThis` looks like:
```
'string'
=== (wrapper)(String.prototype.toLowerCase)('STRING')
=== (uncurryThis)(String.prototype.toLowerCase)('STRING')
=== (Function.bind.bind(Function.call))(String.prototype.toLowerCase)('STRING')
// Function.bind is not really the generic form because it's not using the prototype
// Here Function is an instance of a Function and not the constructor.prototype
// It is similar to calling Array.bind or someFunction.bind
// a more correct version would be
// someFunction.constructor.prototype.bind === Function.prototype.bind, so
=== (Function.prototype.bind.bind(Function.prototype.call))(String.prototype.toLowerCase)('STRING')
// Apply formula 2
// instance.function(...args) === (Class.prototype).function.bind(instance)(...args) [2]
// Class === Function
// function === bind
// instance === Function.prototype.call
// ...args === String.prototype.toLowerCase
=== instance.function(...args)('STRING')
=== (Function.prototype.call).bind(String.prototype.toLowerCase)('STRING')
// Apply formula 2 again
// Class == Function
// function == call
// instance === String.prototype.toLowerCase
// ...args === 'STRING'
=== instance.function(...args)
=== (String.prototype.toLowerCase).call('STRING')
// Apply formula 1
instance.function(...args) === (Class.prototype).function.call(instance, ...args) [1]
// Class === String
// function === toLowerCase
// instance === 'STRING'
// args === []
=== instance.function(...args)
=== 'STRING'.toLowerCase(...[])
=== 'STRING'.toLowerCase()
// So we have
(wrapper)(String.prototype.toLowerCase)('STRING')
=== (uncurryThis)(String.prototype.toLowerCase)('STRING')
=== 'STRING'.toLowerCase()
=== 'string'
```
---
**Reverse Proof:**
So you might wonder "how did the guy even derive the `uncurryThis` function"?
You can reverse the proof to derive it. I am just copying the equations from above but reversed:
```
'STRING'.toLowerCase()
=== (String.prototype.toLowerCase).call('STRING') // apply formula [1]
=== (Function.prototype.call).bind(String.prototype.toLowerCase)('STRING') // apply formula [2]
// At this point, you might wonder why `uncurryThis !== (Function.prototype.call).bind)
// since it also takes (String.prototype.toLowerCase)('STRING')
// This is because passing in (Function.prototype.call).bind) as an argument
// is the same as passing in Function.prototype.bind
// `this` binding isn't done unless you call
// (Function.prototype.call).bind)(String.prototype.toLowerCase)
// at that exact moment.
// If you want to be able to pass unCurryThis as a function, you need to bind the
// Function.prototype.call to the Function.prototype.bind.
=== (Function.prototype.bind.bind(Function.prototype.call))(String.prototype.toLowerCase)('STRING') // apply formula 2
=== (Function.bind.bind(Function.call))(String.prototype.toLowerCase)('STRING') // un-generic-ize
=== (uncurryThis)(String.prototype.toLowerCase)('STRING')
=== (wrapper)(String.prototype.toLowerCase)('STRING')
=>
unCurryThis === wrapper === Function.bind.bind(Function.call)
```
Still pretty confusing to follow but try to write out what `Class`, `function`, `instance`, and `args` are each time I am applying formulas [1] and [2], and it should make sense. |
23,482,982 | We have this line in my code base:
```
var uncurryThis = Function.bind.bind(Function.call);
```
That I'm trying to work through. Presumably, it uncurries. How do I work this out?
I guess it's a version of `Function.bind` whose own `this` is bound to `Function.call`. Doesn't help me enough. And I haven't found any uses, so I'm not even sure if you call it standalone or need to call it "as a method", only, you know, bind it first. | 2014/05/05 | [
"https://Stackoverflow.com/questions/23482982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339987/"
] | OK. You know what [`bind`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) does? It's a method of Functions to fix their `this` argument, and returns a new function. It could be simplified to:
```
function bind(context) {
var fn = this;
return function() {
return fn.apply(context, arguments);
};
}
```
I will abbreviate function calls with contexts in a more functional style with lots of partial application: bindfn(context) -> fncontext. With arguments: (bindfn(context))(…) is equal to fncontext(…).
Similarly, [`call`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) does take a `this` value but instead of returning a function, it applies it right now: callfn(context, …) -> fncontext(…).
So now let's get at your code: `bind.call(bind, call)`. Here, you're applying `bind` on `bind` with `call` as the this value: bindbind(call). Let's expand this (with above rule) to bindcall. What if we now supplied some arguments to it?
>
> bindbind(call) *(fn)(context, …)*
>
>
> bindcall *(fn)(context, …)*
>
>
> call *fn(context, …)*
>
>
> *fncontext(…)*
>
>
>
Step by step, we could do
>
> uncurryThis = bindbind(call) `//` bindcall
>
>
> func = uncurryThis(method) `//` callmethod
>
>
> result = func(context, …) `//` methodcontext(…)
>
>
>
A practical use case for this are any "class" methods that are supposed to be converted to a static function, taking the object (on which the method would be called upon) as the first argument:
```
var uncurryThis = Function.bind.bind(Function.call);
var uc = uncurryThis(String.prototype.toUpperCase);
uc("hello") // in contrast to "hello".toUpperCase()
```
This can be helpful if you cannot place a method call, but need a static function; e.g. as in
```
["hello", "world"].map(uc) // imagine the necessary function expression
```
Also, the method you want to invoke might not be a method of the object itself, as in
```
var slice = uncurryThis(Array.prototype.slice);
slice(arguments) // instead of `Array.prototype.slice.call(arguments)` everywhere
```
---
If it helps, here is also an explicit implementation, without any binds:
```
function uncurryThis(method) {
return function(context/*, ...*/)
return method.apply(context, Array.prototype.slice.call(arguments, 1));
};
}
``` | when we call bind on a function, it returns new function with this is replaced by context:
```
function random() {
alert(this.foo);
}
var newRandom = random.bind({foo:"hello world"}) //return new function same as //`random` with `this` is replaced by object {foo:"hello world"}
```
the same we have:
```
Function.bind.bind(Function.call)
// return new Function.bind with its `this` is replaced by `Function.call`
```
It has following source(used simplified version of `bind` function given by @Bergi):
```
var bb = function bind(context){
var fn = Function.call;
return function() {
return Function.call.apply(context, arguments); //also replace fn here for easier reading
};
}
```
Notice that context here will be function, for example `random`, so wen call bb(random) we has `newRandom` function as:
```
newRandom = function(){
return Function.call.apply(random, arguments); //also replace
}
//`apply` function replace `this` of Function.call to `random`, and apply Function(now become `random`) with arguments in `arguments` array.
``` |
23,482,982 | We have this line in my code base:
```
var uncurryThis = Function.bind.bind(Function.call);
```
That I'm trying to work through. Presumably, it uncurries. How do I work this out?
I guess it's a version of `Function.bind` whose own `this` is bound to `Function.call`. Doesn't help me enough. And I haven't found any uses, so I'm not even sure if you call it standalone or need to call it "as a method", only, you know, bind it first. | 2014/05/05 | [
"https://Stackoverflow.com/questions/23482982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339987/"
] | OK. You know what [`bind`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) does? It's a method of Functions to fix their `this` argument, and returns a new function. It could be simplified to:
```
function bind(context) {
var fn = this;
return function() {
return fn.apply(context, arguments);
};
}
```
I will abbreviate function calls with contexts in a more functional style with lots of partial application: bindfn(context) -> fncontext. With arguments: (bindfn(context))(…) is equal to fncontext(…).
Similarly, [`call`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) does take a `this` value but instead of returning a function, it applies it right now: callfn(context, …) -> fncontext(…).
So now let's get at your code: `bind.call(bind, call)`. Here, you're applying `bind` on `bind` with `call` as the this value: bindbind(call). Let's expand this (with above rule) to bindcall. What if we now supplied some arguments to it?
>
> bindbind(call) *(fn)(context, …)*
>
>
> bindcall *(fn)(context, …)*
>
>
> call *fn(context, …)*
>
>
> *fncontext(…)*
>
>
>
Step by step, we could do
>
> uncurryThis = bindbind(call) `//` bindcall
>
>
> func = uncurryThis(method) `//` callmethod
>
>
> result = func(context, …) `//` methodcontext(…)
>
>
>
A practical use case for this are any "class" methods that are supposed to be converted to a static function, taking the object (on which the method would be called upon) as the first argument:
```
var uncurryThis = Function.bind.bind(Function.call);
var uc = uncurryThis(String.prototype.toUpperCase);
uc("hello") // in contrast to "hello".toUpperCase()
```
This can be helpful if you cannot place a method call, but need a static function; e.g. as in
```
["hello", "world"].map(uc) // imagine the necessary function expression
```
Also, the method you want to invoke might not be a method of the object itself, as in
```
var slice = uncurryThis(Array.prototype.slice);
slice(arguments) // instead of `Array.prototype.slice.call(arguments)` everywhere
```
---
If it helps, here is also an explicit implementation, without any binds:
```
function uncurryThis(method) {
return function(context/*, ...*/)
return method.apply(context, Array.prototype.slice.call(arguments, 1));
};
}
``` | I think this can be explained more clearly if you work backward.
**Context:**
Suppose we want to lowercase an array of strings. This can be done like so:
```
[‘A’, ‘B’].map(s => s.toLowerCase())
```
Let's say, for whatever reason, I want to make this call more generic. I don't like how `s` is bound to `this` and the fat arrow is tied to `toLowerCase()`.
How about this?
```
[‘A’, ‘B’].map(String.prototype.toLowerCase)
```
Well, this doesn't work because `map` passes the element as the first argument but `String.prototype.toLowerCase` takes no arguments. It expects the input string to be passed as `this`.
So a question is can we create a `wrapper` function that makes this work?
```
[‘A’, ‘B’].map(wrapper(String.prototype.toLowerCase))
```
`wrapper` returns a function that turns the first argument passed into `this` for `String.prototype.toLowerCase` to use.
I claim that your `uncurryThis === wrapper`.
---
**Proof:**
So let's not try to understand `unCurryThis` all at once. Instead, let's use some formulas to transform `unCurryThis` into something more understandable.
Some formulas first:
```
instance.function(...args)
=== (instance.constructor.prototype).function.call(instance, ...args)
=== (Class.prototype).function.call(instance, ...args) [1]
=== (Class.prototype).function.bind(instance)(...args) [2]
```
For example,
```
Class === String
instance === 'STRING'
function === toLowerCase
args === []
---
'string'.toLowerCase()
=== ('STRING'.constructor.prototype).toLowerCase.call('STRING')
=== (String.prototype).toLowerCase.call('STRING')
=== (String.prototype).toLowerCase.bind('STRING')()
```
So let's just blindly apply these formulas without worrying about what the confusing `uncurryThis` looks like:
```
'string'
=== (wrapper)(String.prototype.toLowerCase)('STRING')
=== (uncurryThis)(String.prototype.toLowerCase)('STRING')
=== (Function.bind.bind(Function.call))(String.prototype.toLowerCase)('STRING')
// Function.bind is not really the generic form because it's not using the prototype
// Here Function is an instance of a Function and not the constructor.prototype
// It is similar to calling Array.bind or someFunction.bind
// a more correct version would be
// someFunction.constructor.prototype.bind === Function.prototype.bind, so
=== (Function.prototype.bind.bind(Function.prototype.call))(String.prototype.toLowerCase)('STRING')
// Apply formula 2
// instance.function(...args) === (Class.prototype).function.bind(instance)(...args) [2]
// Class === Function
// function === bind
// instance === Function.prototype.call
// ...args === String.prototype.toLowerCase
=== instance.function(...args)('STRING')
=== (Function.prototype.call).bind(String.prototype.toLowerCase)('STRING')
// Apply formula 2 again
// Class == Function
// function == call
// instance === String.prototype.toLowerCase
// ...args === 'STRING'
=== instance.function(...args)
=== (String.prototype.toLowerCase).call('STRING')
// Apply formula 1
instance.function(...args) === (Class.prototype).function.call(instance, ...args) [1]
// Class === String
// function === toLowerCase
// instance === 'STRING'
// args === []
=== instance.function(...args)
=== 'STRING'.toLowerCase(...[])
=== 'STRING'.toLowerCase()
// So we have
(wrapper)(String.prototype.toLowerCase)('STRING')
=== (uncurryThis)(String.prototype.toLowerCase)('STRING')
=== 'STRING'.toLowerCase()
=== 'string'
```
---
**Reverse Proof:**
So you might wonder "how did the guy even derive the `uncurryThis` function"?
You can reverse the proof to derive it. I am just copying the equations from above but reversed:
```
'STRING'.toLowerCase()
=== (String.prototype.toLowerCase).call('STRING') // apply formula [1]
=== (Function.prototype.call).bind(String.prototype.toLowerCase)('STRING') // apply formula [2]
// At this point, you might wonder why `uncurryThis !== (Function.prototype.call).bind)
// since it also takes (String.prototype.toLowerCase)('STRING')
// This is because passing in (Function.prototype.call).bind) as an argument
// is the same as passing in Function.prototype.bind
// `this` binding isn't done unless you call
// (Function.prototype.call).bind)(String.prototype.toLowerCase)
// at that exact moment.
// If you want to be able to pass unCurryThis as a function, you need to bind the
// Function.prototype.call to the Function.prototype.bind.
=== (Function.prototype.bind.bind(Function.prototype.call))(String.prototype.toLowerCase)('STRING') // apply formula 2
=== (Function.bind.bind(Function.call))(String.prototype.toLowerCase)('STRING') // un-generic-ize
=== (uncurryThis)(String.prototype.toLowerCase)('STRING')
=== (wrapper)(String.prototype.toLowerCase)('STRING')
=>
unCurryThis === wrapper === Function.bind.bind(Function.call)
```
Still pretty confusing to follow but try to write out what `Class`, `function`, `instance`, and `args` are each time I am applying formulas [1] and [2], and it should make sense. |
3,393,829 | I want to open the dialog box when the user clicks on a browse button in the nib. This would search for a picture he wants from his pc and upload it. How do I do this programmatically in iphone. | 2010/08/03 | [
"https://Stackoverflow.com/questions/3393829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/397734/"
] | What you need is:
```
//declaration:
MyConstuctor(int inDenominator, int inNumerator, int inWholeNumber = 0);
//definition:
MyConstuctor::MyConstuctor(int inDenominator,int inNumerator,int inWholeNumber)
{
mNum = inNumerator;
mDen = inDenominator;
mWhole = inWholeNumber;
}
```
This way you will be able to provide a non-default value for `inWholeNumber`; and you will be able not to provide it so 0 will be used as the default.
---
As an additional tip, better use [initialization list](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6) in the definition:
```
//definition:
MyConstuctor::MyConstuctor(int inDenominator,int inNumerator,int inWholeNumber) :
mNum(inNumerator), mDen(inDenominator), mWhole (inWholeNumber)
{
}
``` | No, you need to provide the default value in the declaration of the method only. The definition of the method should have all 3 parameters without the default value. If the user of the class chooses to pass the 3rd parameter it will be used, otherwise default value specified in the declaration will be used. |
3,393,829 | I want to open the dialog box when the user clicks on a browse button in the nib. This would search for a picture he wants from his pc and upload it. How do I do this programmatically in iphone. | 2010/08/03 | [
"https://Stackoverflow.com/questions/3393829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/397734/"
] | No, you need to provide the default value in the declaration of the method only. The definition of the method should have all 3 parameters without the default value. If the user of the class chooses to pass the 3rd parameter it will be used, otherwise default value specified in the declaration will be used. | You should add the default parameter to the declaration as well and the default value in the implementation is not necessary. |
3,393,829 | I want to open the dialog box when the user clicks on a browse button in the nib. This would search for a picture he wants from his pc and upload it. How do I do this programmatically in iphone. | 2010/08/03 | [
"https://Stackoverflow.com/questions/3393829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/397734/"
] | What you need is:
```
//declaration:
MyConstuctor(int inDenominator, int inNumerator, int inWholeNumber = 0);
//definition:
MyConstuctor::MyConstuctor(int inDenominator,int inNumerator,int inWholeNumber)
{
mNum = inNumerator;
mDen = inDenominator;
mWhole = inWholeNumber;
}
```
This way you will be able to provide a non-default value for `inWholeNumber`; and you will be able not to provide it so 0 will be used as the default.
---
As an additional tip, better use [initialization list](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6) in the definition:
```
//definition:
MyConstuctor::MyConstuctor(int inDenominator,int inNumerator,int inWholeNumber) :
mNum(inNumerator), mDen(inDenominator), mWhole (inWholeNumber)
{
}
``` | You should add the default parameter to the declaration as well and the default value in the implementation is not necessary. |
26,613,419 | I'm gonna build a website with 2 layouts: boxed and full width by Bootstrap 3. As bootstrap document, I can create full width layout by using `.container-fluid`, is it right? In addition, I want to know the way create boxed width layout too. | 2014/10/28 | [
"https://Stackoverflow.com/questions/26613419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494232/"
] | Use .container for a responsive fixed width container.
```
<div class="container">
...
</div>
```
Use .container-fluid for a full width container, spanning the entire width of your viewport.
```
<div class="container-fluid">
...
</div>
```
<http://getbootstrap.com/css/> | It sounds like the solution you are referring to is going to take you specifying the container widths using media queries.
Something like this should work for what you are after:
```
/* Customize container */
@media (min-width: 960px) {
.container {
max-width: 780px;
}
}
```
The above apply to whether you want the page to be responsive (fluid). If you add the above and add the default template from their page, you should see the differences. Hope this helps.
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<h1>Hello, world!</h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
``` |
23,679,968 | I've got a browser game and I have recently started adding audio to the game.
Chrome does not load the whole page and gets stuck at `"91 requests | 8.1 MB transferred"` and does not load any more content; and it even breaks the website in all other tabs, saying `Waiting for available socket`.
After 5 mins (exactly) the data are loaded.


This does not happen on any other browser.
Removing one MP3 file (the latest added one) fixed the problem, so is it perhaps a data limit problem? | 2014/05/15 | [
"https://Stackoverflow.com/questions/23679968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1989999/"
] | **Explanation:**
This problem occurs because Chrome allows up to 6 open connections by default. So if you're streaming multiple media files simultaneously from 6 `<video>` or `<audio>` tags, the 7th connection (for example, an image) will just hang, until one of the sockets opens up. Usually, an open connection will close after 5 minutes of inactivity, and that's why you're seeing your .pngs finally loading at that point.
**Solution 1:**
You can avoid this by minimizing the number of media tags that keep an open connection. And if you need to have more than 6, make sure that you load them last, or that they don't have attributes like `preload="auto"`.
**Solution 2:**
If you're trying to use multiple sound effects for a web game, you could use the [Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API). Or to simplify things, just use a library like [SoundJS](http://www.createjs.com/soundjs), which is a great tool for playing a large amount of sound effects / music tracks simultaneously.
**Solution 3: Force-open Sockets** (Not recommended)
If you must, you can force-open the sockets in your browser (In Chrome only):
1. Go to the address bar and type `chrome://net-internals`.
2. Select `Sockets` from the menu.
3. Click on the `Flush socket pools` button.
This solution is not recommended because you shouldn't expect your visitors to follow these instructions to be able to view your site. | simple and correct solution is put off preload your audio and video file from setting and recheck your page your problem of waiting for available socket will resolved ...
if you use jplayer then replace **preload:"metadata"** to **preload:"none"** from jplayer JS file ...
**preload:"metadata"** is the default value which play your audio/video file on page load thats why google chrome showing "waiting for available socket" error |
23,679,968 | I've got a browser game and I have recently started adding audio to the game.
Chrome does not load the whole page and gets stuck at `"91 requests | 8.1 MB transferred"` and does not load any more content; and it even breaks the website in all other tabs, saying `Waiting for available socket`.
After 5 mins (exactly) the data are loaded.


This does not happen on any other browser.
Removing one MP3 file (the latest added one) fixed the problem, so is it perhaps a data limit problem? | 2014/05/15 | [
"https://Stackoverflow.com/questions/23679968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1989999/"
] | **Explanation:**
This problem occurs because Chrome allows up to 6 open connections by default. So if you're streaming multiple media files simultaneously from 6 `<video>` or `<audio>` tags, the 7th connection (for example, an image) will just hang, until one of the sockets opens up. Usually, an open connection will close after 5 minutes of inactivity, and that's why you're seeing your .pngs finally loading at that point.
**Solution 1:**
You can avoid this by minimizing the number of media tags that keep an open connection. And if you need to have more than 6, make sure that you load them last, or that they don't have attributes like `preload="auto"`.
**Solution 2:**
If you're trying to use multiple sound effects for a web game, you could use the [Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API). Or to simplify things, just use a library like [SoundJS](http://www.createjs.com/soundjs), which is a great tool for playing a large amount of sound effects / music tracks simultaneously.
**Solution 3: Force-open Sockets** (Not recommended)
If you must, you can force-open the sockets in your browser (In Chrome only):
1. Go to the address bar and type `chrome://net-internals`.
2. Select `Sockets` from the menu.
3. Click on the `Flush socket pools` button.
This solution is not recommended because you shouldn't expect your visitors to follow these instructions to be able to view your site. | Our first thought is that the site is down or the like, but the truth is that this is not the problem or disability. Nor is it a problem because a simple connection when tested under Firefox, Opera or services Explorer open as normal.
The error in Chrome displays a sign that says "This site is not available" and clarification with the legend "Error 15 (net :: ERR\_SOCKET\_NOT\_CONNECTED): Unknown error". The error is quite usual in Google Chrome, more precisely in its updates, and its workaround is to restart the computer.
As partial solutions are not much we offer a tutorial for you solve the fault in less than a minute.
To avoid this problem and ensure that services are normally open in Google Chrome should insert the following into the address bar: chrome: // net-internals (then give "Enter"). They then have to go to the "Socket" in the left menu and choose "Flush Socket Pools" (look at the following screenshots to guide <http://www.fixotip.com/how-to-fix-error-waiting-for-available-sockets-in-google-chrome/>)
This has the problem solved and no longer will experience problems accessing Gmail, Google or any of the services of the Mountain View giant. I hope you found it useful and share the tutorial with whom they need or social networks: Facebook, Twitter or Google+. |
23,679,968 | I've got a browser game and I have recently started adding audio to the game.
Chrome does not load the whole page and gets stuck at `"91 requests | 8.1 MB transferred"` and does not load any more content; and it even breaks the website in all other tabs, saying `Waiting for available socket`.
After 5 mins (exactly) the data are loaded.


This does not happen on any other browser.
Removing one MP3 file (the latest added one) fixed the problem, so is it perhaps a data limit problem? | 2014/05/15 | [
"https://Stackoverflow.com/questions/23679968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1989999/"
] | Looks like you are hitting the limit on connections per server. I see you are loading a lot of static files and my advice is to separate them on subdomains and serve them directly with Nginx for example.
* Create a subdomain called *img.yoursite.com* and load all your images
from there.
* Create a subdomain called *scripts.yourdomain.com* and load all your JS and CSS files from there.
* Create a subdomain called *sounds.yoursite.com* and load all your MP3s from there... etc..
Nginx has great options for directly serving static files and managing the static files caching. | The message:
>
> Waiting for available socket...
>
>
>
is shown, because you've reached a limit on the ssl\_socket\_pool either per Host, Proxy or Group.
Here are the maximum number of HTTP connections which you can make with a Chrome browser:
* The maximum number of connections per proxy is 32 connections. This can be changed in [Policy List](http://www.chromium.org/administrators/policy-list-3#MaxConnectionsPerProxy).
* Maximum per Host: 6 connections.
This is likely hardcoded in the source code of the web browser, so you can't change it.
* Total 256 HTTP connections pooled per browser.
Source: [Enterprise networking for Chrome devices](https://support.google.com/chrome/a/answer/3339263?hl=en)
The above limits can be checked or flushed at `chrome://net-internals/#sockets` (or in real-time at `chrome://net-internals/#events&q=type:SOCKET%20is:active`).
---
Your issue with audio can be related to [Chrome bug 162627](https://bugs.chromium.org/p/chromium/issues/detail?id=162627) where HTML5 audio fails to load and it hits max simultaneous connections per server:proxy. This is still active issue at the time of writing (2016).
Much older issue related to [HTML5 video request stay pending](https://stackoverflow.com/q/16137381/55075), then it's probably related to [Issue #234779](https://bugs.chromium.org/p/chromium/issues/detail?id=234779) which has been fixed 2014. And related to SPDY which can be found in [Issue 324653: SPDY issue: waiting for available sockets](https://bugs.chromium.org/p/chromium/issues/detail?id=324653), but this was already fixed in 2014, so probably it's not related.
Other related issue now marked as duplicate can be found in [Issue 401845: Failure to preload audio metadata. Loaded only 6 of 10+](https://bugs.chromium.org/p/chromium/issues/detail?id=401845) which was related to the problem with the media player code leaving a bunch of paused requests hanging around.
---
This also may be related to some Chrome adware or antivirus extensions using your sockets in the backgrounds (like *Sophos* or [*Kaspersky*](https://superuser.com/q/770293/87805)), so check for *Network* activity in *DevTools*. |
23,679,968 | I've got a browser game and I have recently started adding audio to the game.
Chrome does not load the whole page and gets stuck at `"91 requests | 8.1 MB transferred"` and does not load any more content; and it even breaks the website in all other tabs, saying `Waiting for available socket`.
After 5 mins (exactly) the data are loaded.


This does not happen on any other browser.
Removing one MP3 file (the latest added one) fixed the problem, so is it perhaps a data limit problem? | 2014/05/15 | [
"https://Stackoverflow.com/questions/23679968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1989999/"
] | **Explanation:**
This problem occurs because Chrome allows up to 6 open connections by default. So if you're streaming multiple media files simultaneously from 6 `<video>` or `<audio>` tags, the 7th connection (for example, an image) will just hang, until one of the sockets opens up. Usually, an open connection will close after 5 minutes of inactivity, and that's why you're seeing your .pngs finally loading at that point.
**Solution 1:**
You can avoid this by minimizing the number of media tags that keep an open connection. And if you need to have more than 6, make sure that you load them last, or that they don't have attributes like `preload="auto"`.
**Solution 2:**
If you're trying to use multiple sound effects for a web game, you could use the [Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API). Or to simplify things, just use a library like [SoundJS](http://www.createjs.com/soundjs), which is a great tool for playing a large amount of sound effects / music tracks simultaneously.
**Solution 3: Force-open Sockets** (Not recommended)
If you must, you can force-open the sockets in your browser (In Chrome only):
1. Go to the address bar and type `chrome://net-internals`.
2. Select `Sockets` from the menu.
3. Click on the `Flush socket pools` button.
This solution is not recommended because you shouldn't expect your visitors to follow these instructions to be able to view your site. | Chrome is a Chromium-based browser and Chromium-based browsers only allow maximum 6 open socket connections at a time, when the 7th connection starts up it will just sit idle and wait for one of the 6 which are running to stop and then it will start running.
Hence the error code **‘waiting for available sockets’**, the 7th one will wait for one of those 6 sockets to become available and then it will start running.
You can either
* 1. Clear browser cache & cookies (<https://geekdroids.com/waiting-for-available-socket/#1_Clear_browser_cache_cookies>)
* 2. Flush socket pools (<https://geekdroids.com/waiting-for-available-socket/#2_Flush_socket_pools>)
* 3. Flush DNS (<https://geekdroids.com/waiting-for-available-socket/#3_Flush_DNS>) |
23,679,968 | I've got a browser game and I have recently started adding audio to the game.
Chrome does not load the whole page and gets stuck at `"91 requests | 8.1 MB transferred"` and does not load any more content; and it even breaks the website in all other tabs, saying `Waiting for available socket`.
After 5 mins (exactly) the data are loaded.


This does not happen on any other browser.
Removing one MP3 file (the latest added one) fixed the problem, so is it perhaps a data limit problem? | 2014/05/15 | [
"https://Stackoverflow.com/questions/23679968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1989999/"
] | Looks like you are hitting the limit on connections per server. I see you are loading a lot of static files and my advice is to separate them on subdomains and serve them directly with Nginx for example.
* Create a subdomain called *img.yoursite.com* and load all your images
from there.
* Create a subdomain called *scripts.yourdomain.com* and load all your JS and CSS files from there.
* Create a subdomain called *sounds.yoursite.com* and load all your MP3s from there... etc..
Nginx has great options for directly serving static files and managing the static files caching. | Chrome is a Chromium-based browser and Chromium-based browsers only allow maximum 6 open socket connections at a time, when the 7th connection starts up it will just sit idle and wait for one of the 6 which are running to stop and then it will start running.
Hence the error code **‘waiting for available sockets’**, the 7th one will wait for one of those 6 sockets to become available and then it will start running.
You can either
* 1. Clear browser cache & cookies (<https://geekdroids.com/waiting-for-available-socket/#1_Clear_browser_cache_cookies>)
* 2. Flush socket pools (<https://geekdroids.com/waiting-for-available-socket/#2_Flush_socket_pools>)
* 3. Flush DNS (<https://geekdroids.com/waiting-for-available-socket/#3_Flush_DNS>) |
23,679,968 | I've got a browser game and I have recently started adding audio to the game.
Chrome does not load the whole page and gets stuck at `"91 requests | 8.1 MB transferred"` and does not load any more content; and it even breaks the website in all other tabs, saying `Waiting for available socket`.
After 5 mins (exactly) the data are loaded.


This does not happen on any other browser.
Removing one MP3 file (the latest added one) fixed the problem, so is it perhaps a data limit problem? | 2014/05/15 | [
"https://Stackoverflow.com/questions/23679968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1989999/"
] | The message:
>
> Waiting for available socket...
>
>
>
is shown, because you've reached a limit on the ssl\_socket\_pool either per Host, Proxy or Group.
Here are the maximum number of HTTP connections which you can make with a Chrome browser:
* The maximum number of connections per proxy is 32 connections. This can be changed in [Policy List](http://www.chromium.org/administrators/policy-list-3#MaxConnectionsPerProxy).
* Maximum per Host: 6 connections.
This is likely hardcoded in the source code of the web browser, so you can't change it.
* Total 256 HTTP connections pooled per browser.
Source: [Enterprise networking for Chrome devices](https://support.google.com/chrome/a/answer/3339263?hl=en)
The above limits can be checked or flushed at `chrome://net-internals/#sockets` (or in real-time at `chrome://net-internals/#events&q=type:SOCKET%20is:active`).
---
Your issue with audio can be related to [Chrome bug 162627](https://bugs.chromium.org/p/chromium/issues/detail?id=162627) where HTML5 audio fails to load and it hits max simultaneous connections per server:proxy. This is still active issue at the time of writing (2016).
Much older issue related to [HTML5 video request stay pending](https://stackoverflow.com/q/16137381/55075), then it's probably related to [Issue #234779](https://bugs.chromium.org/p/chromium/issues/detail?id=234779) which has been fixed 2014. And related to SPDY which can be found in [Issue 324653: SPDY issue: waiting for available sockets](https://bugs.chromium.org/p/chromium/issues/detail?id=324653), but this was already fixed in 2014, so probably it's not related.
Other related issue now marked as duplicate can be found in [Issue 401845: Failure to preload audio metadata. Loaded only 6 of 10+](https://bugs.chromium.org/p/chromium/issues/detail?id=401845) which was related to the problem with the media player code leaving a bunch of paused requests hanging around.
---
This also may be related to some Chrome adware or antivirus extensions using your sockets in the backgrounds (like *Sophos* or [*Kaspersky*](https://superuser.com/q/770293/87805)), so check for *Network* activity in *DevTools*. | Our first thought is that the site is down or the like, but the truth is that this is not the problem or disability. Nor is it a problem because a simple connection when tested under Firefox, Opera or services Explorer open as normal.
The error in Chrome displays a sign that says "This site is not available" and clarification with the legend "Error 15 (net :: ERR\_SOCKET\_NOT\_CONNECTED): Unknown error". The error is quite usual in Google Chrome, more precisely in its updates, and its workaround is to restart the computer.
As partial solutions are not much we offer a tutorial for you solve the fault in less than a minute.
To avoid this problem and ensure that services are normally open in Google Chrome should insert the following into the address bar: chrome: // net-internals (then give "Enter"). They then have to go to the "Socket" in the left menu and choose "Flush Socket Pools" (look at the following screenshots to guide <http://www.fixotip.com/how-to-fix-error-waiting-for-available-sockets-in-google-chrome/>)
This has the problem solved and no longer will experience problems accessing Gmail, Google or any of the services of the Mountain View giant. I hope you found it useful and share the tutorial with whom they need or social networks: Facebook, Twitter or Google+. |
23,679,968 | I've got a browser game and I have recently started adding audio to the game.
Chrome does not load the whole page and gets stuck at `"91 requests | 8.1 MB transferred"` and does not load any more content; and it even breaks the website in all other tabs, saying `Waiting for available socket`.
After 5 mins (exactly) the data are loaded.


This does not happen on any other browser.
Removing one MP3 file (the latest added one) fixed the problem, so is it perhaps a data limit problem? | 2014/05/15 | [
"https://Stackoverflow.com/questions/23679968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1989999/"
] | simple and correct solution is put off preload your audio and video file from setting and recheck your page your problem of waiting for available socket will resolved ...
if you use jplayer then replace **preload:"metadata"** to **preload:"none"** from jplayer JS file ...
**preload:"metadata"** is the default value which play your audio/video file on page load thats why google chrome showing "waiting for available socket" error | Chrome is a Chromium-based browser and Chromium-based browsers only allow maximum 6 open socket connections at a time, when the 7th connection starts up it will just sit idle and wait for one of the 6 which are running to stop and then it will start running.
Hence the error code **‘waiting for available sockets’**, the 7th one will wait for one of those 6 sockets to become available and then it will start running.
You can either
* 1. Clear browser cache & cookies (<https://geekdroids.com/waiting-for-available-socket/#1_Clear_browser_cache_cookies>)
* 2. Flush socket pools (<https://geekdroids.com/waiting-for-available-socket/#2_Flush_socket_pools>)
* 3. Flush DNS (<https://geekdroids.com/waiting-for-available-socket/#3_Flush_DNS>) |
23,679,968 | I've got a browser game and I have recently started adding audio to the game.
Chrome does not load the whole page and gets stuck at `"91 requests | 8.1 MB transferred"` and does not load any more content; and it even breaks the website in all other tabs, saying `Waiting for available socket`.
After 5 mins (exactly) the data are loaded.


This does not happen on any other browser.
Removing one MP3 file (the latest added one) fixed the problem, so is it perhaps a data limit problem? | 2014/05/15 | [
"https://Stackoverflow.com/questions/23679968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1989999/"
] | The message:
>
> Waiting for available socket...
>
>
>
is shown, because you've reached a limit on the ssl\_socket\_pool either per Host, Proxy or Group.
Here are the maximum number of HTTP connections which you can make with a Chrome browser:
* The maximum number of connections per proxy is 32 connections. This can be changed in [Policy List](http://www.chromium.org/administrators/policy-list-3#MaxConnectionsPerProxy).
* Maximum per Host: 6 connections.
This is likely hardcoded in the source code of the web browser, so you can't change it.
* Total 256 HTTP connections pooled per browser.
Source: [Enterprise networking for Chrome devices](https://support.google.com/chrome/a/answer/3339263?hl=en)
The above limits can be checked or flushed at `chrome://net-internals/#sockets` (or in real-time at `chrome://net-internals/#events&q=type:SOCKET%20is:active`).
---
Your issue with audio can be related to [Chrome bug 162627](https://bugs.chromium.org/p/chromium/issues/detail?id=162627) where HTML5 audio fails to load and it hits max simultaneous connections per server:proxy. This is still active issue at the time of writing (2016).
Much older issue related to [HTML5 video request stay pending](https://stackoverflow.com/q/16137381/55075), then it's probably related to [Issue #234779](https://bugs.chromium.org/p/chromium/issues/detail?id=234779) which has been fixed 2014. And related to SPDY which can be found in [Issue 324653: SPDY issue: waiting for available sockets](https://bugs.chromium.org/p/chromium/issues/detail?id=324653), but this was already fixed in 2014, so probably it's not related.
Other related issue now marked as duplicate can be found in [Issue 401845: Failure to preload audio metadata. Loaded only 6 of 10+](https://bugs.chromium.org/p/chromium/issues/detail?id=401845) which was related to the problem with the media player code leaving a bunch of paused requests hanging around.
---
This also may be related to some Chrome adware or antivirus extensions using your sockets in the backgrounds (like *Sophos* or [*Kaspersky*](https://superuser.com/q/770293/87805)), so check for *Network* activity in *DevTools*. | simple and correct solution is put off preload your audio and video file from setting and recheck your page your problem of waiting for available socket will resolved ...
if you use jplayer then replace **preload:"metadata"** to **preload:"none"** from jplayer JS file ...
**preload:"metadata"** is the default value which play your audio/video file on page load thats why google chrome showing "waiting for available socket" error |
23,679,968 | I've got a browser game and I have recently started adding audio to the game.
Chrome does not load the whole page and gets stuck at `"91 requests | 8.1 MB transferred"` and does not load any more content; and it even breaks the website in all other tabs, saying `Waiting for available socket`.
After 5 mins (exactly) the data are loaded.


This does not happen on any other browser.
Removing one MP3 file (the latest added one) fixed the problem, so is it perhaps a data limit problem? | 2014/05/15 | [
"https://Stackoverflow.com/questions/23679968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1989999/"
] | The message:
>
> Waiting for available socket...
>
>
>
is shown, because you've reached a limit on the ssl\_socket\_pool either per Host, Proxy or Group.
Here are the maximum number of HTTP connections which you can make with a Chrome browser:
* The maximum number of connections per proxy is 32 connections. This can be changed in [Policy List](http://www.chromium.org/administrators/policy-list-3#MaxConnectionsPerProxy).
* Maximum per Host: 6 connections.
This is likely hardcoded in the source code of the web browser, so you can't change it.
* Total 256 HTTP connections pooled per browser.
Source: [Enterprise networking for Chrome devices](https://support.google.com/chrome/a/answer/3339263?hl=en)
The above limits can be checked or flushed at `chrome://net-internals/#sockets` (or in real-time at `chrome://net-internals/#events&q=type:SOCKET%20is:active`).
---
Your issue with audio can be related to [Chrome bug 162627](https://bugs.chromium.org/p/chromium/issues/detail?id=162627) where HTML5 audio fails to load and it hits max simultaneous connections per server:proxy. This is still active issue at the time of writing (2016).
Much older issue related to [HTML5 video request stay pending](https://stackoverflow.com/q/16137381/55075), then it's probably related to [Issue #234779](https://bugs.chromium.org/p/chromium/issues/detail?id=234779) which has been fixed 2014. And related to SPDY which can be found in [Issue 324653: SPDY issue: waiting for available sockets](https://bugs.chromium.org/p/chromium/issues/detail?id=324653), but this was already fixed in 2014, so probably it's not related.
Other related issue now marked as duplicate can be found in [Issue 401845: Failure to preload audio metadata. Loaded only 6 of 10+](https://bugs.chromium.org/p/chromium/issues/detail?id=401845) which was related to the problem with the media player code leaving a bunch of paused requests hanging around.
---
This also may be related to some Chrome adware or antivirus extensions using your sockets in the backgrounds (like *Sophos* or [*Kaspersky*](https://superuser.com/q/770293/87805)), so check for *Network* activity in *DevTools*. | Chrome is a Chromium-based browser and Chromium-based browsers only allow maximum 6 open socket connections at a time, when the 7th connection starts up it will just sit idle and wait for one of the 6 which are running to stop and then it will start running.
Hence the error code **‘waiting for available sockets’**, the 7th one will wait for one of those 6 sockets to become available and then it will start running.
You can either
* 1. Clear browser cache & cookies (<https://geekdroids.com/waiting-for-available-socket/#1_Clear_browser_cache_cookies>)
* 2. Flush socket pools (<https://geekdroids.com/waiting-for-available-socket/#2_Flush_socket_pools>)
* 3. Flush DNS (<https://geekdroids.com/waiting-for-available-socket/#3_Flush_DNS>) |
23,679,968 | I've got a browser game and I have recently started adding audio to the game.
Chrome does not load the whole page and gets stuck at `"91 requests | 8.1 MB transferred"` and does not load any more content; and it even breaks the website in all other tabs, saying `Waiting for available socket`.
After 5 mins (exactly) the data are loaded.


This does not happen on any other browser.
Removing one MP3 file (the latest added one) fixed the problem, so is it perhaps a data limit problem? | 2014/05/15 | [
"https://Stackoverflow.com/questions/23679968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1989999/"
] | Looks like you are hitting the limit on connections per server. I see you are loading a lot of static files and my advice is to separate them on subdomains and serve them directly with Nginx for example.
* Create a subdomain called *img.yoursite.com* and load all your images
from there.
* Create a subdomain called *scripts.yourdomain.com* and load all your JS and CSS files from there.
* Create a subdomain called *sounds.yoursite.com* and load all your MP3s from there... etc..
Nginx has great options for directly serving static files and managing the static files caching. | Our first thought is that the site is down or the like, but the truth is that this is not the problem or disability. Nor is it a problem because a simple connection when tested under Firefox, Opera or services Explorer open as normal.
The error in Chrome displays a sign that says "This site is not available" and clarification with the legend "Error 15 (net :: ERR\_SOCKET\_NOT\_CONNECTED): Unknown error". The error is quite usual in Google Chrome, more precisely in its updates, and its workaround is to restart the computer.
As partial solutions are not much we offer a tutorial for you solve the fault in less than a minute.
To avoid this problem and ensure that services are normally open in Google Chrome should insert the following into the address bar: chrome: // net-internals (then give "Enter"). They then have to go to the "Socket" in the left menu and choose "Flush Socket Pools" (look at the following screenshots to guide <http://www.fixotip.com/how-to-fix-error-waiting-for-available-sockets-in-google-chrome/>)
This has the problem solved and no longer will experience problems accessing Gmail, Google or any of the services of the Mountain View giant. I hope you found it useful and share the tutorial with whom they need or social networks: Facebook, Twitter or Google+. |
11,450,481 | I am working with CodeIgniter and have created a custom form preferences custom config. In that I have an array that is as follows:
```none
Array
(
[1] => Category 1
[2] => Category 2
[3] => Category 3
[4] => Category 4
[5] => Category 5
)
```
I am passing that to the view as the var `$service_categories` what I'd then like to do is match it to the "value" that is in the database. I.E 5. If it matches then show `Category 5` in the view. At the moment I am just showing `5` - This is no good to the user.
The variable `$service->service_category` is a number.
The var `service` produces:
```none
Array
(
[0] => stdClass Object
(
[service_id] => 3
[organisation_id] => 2
[service_name] => Edited Service 3
[service_description] => This is service 3 provided by
[service_category] => 5
[service_metadata] => Metadata for service 3 - Edited
[service_cost] => 22.00
[service_active] => active
)
)
```
My current PHP for this is as follows:
```php
if (in_array($service->service_category, $service_categories))
{
echo "Exists";
}
```
However, the `Exists` is not showing in the view. It is showing nothing at all.
Am I doing something wrong with the `in_array` method? | 2012/07/12 | [
"https://Stackoverflow.com/questions/11450481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265431/"
] | `in_array()` checks if a *value* exists in the array. So in\_array('Category 1', $service\_categories) would work.
However, to check if a key is present in an array, you can use:
```
if(array_key_exists($service->service_category, $service_categories)) {
echo "Exists";
}
```
I think, this is what you're looking for. | >
> The variable : $service->service\_category is a number.
>
>
>
And that precisely is the problem: your testing to see if "5" is equal to "Category 5", which it is obviously not. Simplest solution would be to prepend the "5" with "Category ":
```
<?php
$category = 'Category ' . $service->service_category;
if (in_array($category, $service_categories)) {
echo "Exists";
}
```
**EDIT**: If you want to check if the array *key* exists (because '5' => 'Category 5'), this could be achieved with isset( ) or array\_key\_exists.
```
<?php
if (array_key_exists ($service->service_category, $service_categories )) {
echo "Exists";
}
// does the same:
if (isset ($service_categories[service->service_category] )) {
echo "Exists";
}
``` |
11,450,481 | I am working with CodeIgniter and have created a custom form preferences custom config. In that I have an array that is as follows:
```none
Array
(
[1] => Category 1
[2] => Category 2
[3] => Category 3
[4] => Category 4
[5] => Category 5
)
```
I am passing that to the view as the var `$service_categories` what I'd then like to do is match it to the "value" that is in the database. I.E 5. If it matches then show `Category 5` in the view. At the moment I am just showing `5` - This is no good to the user.
The variable `$service->service_category` is a number.
The var `service` produces:
```none
Array
(
[0] => stdClass Object
(
[service_id] => 3
[organisation_id] => 2
[service_name] => Edited Service 3
[service_description] => This is service 3 provided by
[service_category] => 5
[service_metadata] => Metadata for service 3 - Edited
[service_cost] => 22.00
[service_active] => active
)
)
```
My current PHP for this is as follows:
```php
if (in_array($service->service_category, $service_categories))
{
echo "Exists";
}
```
However, the `Exists` is not showing in the view. It is showing nothing at all.
Am I doing something wrong with the `in_array` method? | 2012/07/12 | [
"https://Stackoverflow.com/questions/11450481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265431/"
] | `in_array()` checks if a *value* exists in the array. So in\_array('Category 1', $service\_categories) would work.
However, to check if a key is present in an array, you can use:
```
if(array_key_exists($service->service_category, $service_categories)) {
echo "Exists";
}
```
I think, this is what you're looking for. | I think [array\_key\_exists](http://php.net/manual/en/function.array-key-exists.php) is the function you might search. |
11,450,481 | I am working with CodeIgniter and have created a custom form preferences custom config. In that I have an array that is as follows:
```none
Array
(
[1] => Category 1
[2] => Category 2
[3] => Category 3
[4] => Category 4
[5] => Category 5
)
```
I am passing that to the view as the var `$service_categories` what I'd then like to do is match it to the "value" that is in the database. I.E 5. If it matches then show `Category 5` in the view. At the moment I am just showing `5` - This is no good to the user.
The variable `$service->service_category` is a number.
The var `service` produces:
```none
Array
(
[0] => stdClass Object
(
[service_id] => 3
[organisation_id] => 2
[service_name] => Edited Service 3
[service_description] => This is service 3 provided by
[service_category] => 5
[service_metadata] => Metadata for service 3 - Edited
[service_cost] => 22.00
[service_active] => active
)
)
```
My current PHP for this is as follows:
```php
if (in_array($service->service_category, $service_categories))
{
echo "Exists";
}
```
However, the `Exists` is not showing in the view. It is showing nothing at all.
Am I doing something wrong with the `in_array` method? | 2012/07/12 | [
"https://Stackoverflow.com/questions/11450481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265431/"
] | `in_array()` checks if a *value* exists in the array. So in\_array('Category 1', $service\_categories) would work.
However, to check if a key is present in an array, you can use:
```
if(array_key_exists($service->service_category, $service_categories)) {
echo "Exists";
}
```
I think, this is what you're looking for. | ```
if (isset($service_categories[$service->service_category])) {
echo "Exists";
}
``` |
36,061 | I just started working with ASP.NET MVC a few weeks ago, and I'm finding that it can be very easy to write spaghetti code in the controllers. For my first project, I created a very simple view with a few controls. At first, all of my code was in the `Index()` action result. That worked okay for a while, but as more features get added to the page, the more the code grows. I would like my code to be split up into multiple action results. I made an attempt at refactoring.
Here is my View:
```
@model TpgInternalSite.Models.RepairInvoice
@{
ViewBag.Title = "Repair Invoicing";
Layout = "~/Views/Shared/_Layout100.cshtml";
}
<h2>Repair Invoice</h2>
<script type="text/javascript">
$(document).ready(function () {
$('@(ViewBag.SetFocusTo)').focus();
$('#RmaNumber, #SerialNumber').keydown(function (event) {
if (event.keyCode == 13 || event.keyCode == 9) {
var RmaNumber = $('#RmaNumber').val();
var SerialNumber = $('#SerialNumber').val();
event.preventDefault(); //Stops enter key from triggering the Process button.
if (event.target.id == 'RmaNumber'){
var link = '/Invoice/RmaNumberScan?rmaNumber=' + RmaNumber;
location.href = link;
}
else {
var link = '/Invoice/SerialNumberScan?rmaNumber=' + RmaNumber + '&serialNumber=' + SerialNumber;
location.href = link;
}
}
});
});
</script>
<br />
<br />
<div class="form-horizontal">
@using (Html.BeginForm("Index", "Invoice", FormMethod.Post))
{
<div class="control-group">
<div class="control-label">
RMA#
</div>
<div class="controls">
@Html.TextBoxFor(x => x.RmaNumber)
</div>
</div>
<div class="control-group">
<div class="control-label">
SERIAL#
</div>
<div class="controls">
@Html.TextBoxFor(x => x.SerialNumber)
</div>
</div>
<div class="control-group">
<div class="control-label">
Terminal Type:
</div>
<div class="controls">
@Html.LabelForModel(Model.TerminalType)
</div>
</div>
<div class="control-group">
<div class="control-label">
Warranty:
</div>
<div class="controls">
@Html.CheckBox("warranty", Model.UnderWarranty, new { disabled = "disabled" })
</div>
</div>
<div class="control-group">
<div class="control-label">
Repair Level:
</div>
<div class="controls">
@Html.DropDownListFor(x => x.RepairLevels, new SelectList(Model.RepairLevels))
</div>
</div>
<div class="form-actions">
<input name="process" class="btn primary" type="submit" id="process" value="Process" />
</div>
}
</div>
</>
```
And my controller looks like this:
```
public ActionResult Index()
{
ViewBag.SetFocusTo = "#RmaNumber";
Session["RmaDetail"] = null;
return View(repairInvoice);
}
[HttpPost]
public ActionResult Index(RepairInvoice ri)
{
if (Session["RmaDetail"] != null)
{
var rmaDetail = Session["RmaDetail"] as SVC05200;
RepairInvoiceDataLayer.UpdateRmaRepairLevel(rmaDetail, ri.RepairLevels[0].Trim());
ViewBag.SuccessMessage = "Repair level updated successfully.";
ViewBag.SetFocusTo = "#RmaNumber";
ModelState.Clear();
ri.SerialNumber = string.Empty;
Session["RmaDetail"] = null;
}
return View(ri);
}
public ActionResult RmaNumberScan(string rmaNumber)
{
repairInvoice.RmaNumber = rmaNumber;
if (!string.IsNullOrEmpty(rmaNumber))
{
try
{
bool IsValidRma = RepairInvoiceDataLayer.IsValidRmaNumber(rmaNumber);
if (IsValidRma)
{
ViewBag.SetFocusTo = "#SerialNumber";
}
else
{
ViewBag.AlertMessage = "RMA Number not found.";
}
}
catch (Exception ex)
{
ViewBag.ErrorMessage = "An error occured searching for RMA Number. Please try again.";
log.Fatal(ex.ExceptionToString());
}
}
return View("Index", repairInvoice);
}
public ActionResult SerialNumberScan(string rmaNumber, string serialNumber)
{
if (!string.IsNullOrEmpty(rmaNumber) && !string.IsNullOrEmpty(serialNumber))
{
try
{
if (serialNumber.Length > 20)
{
serialNumber = serialNumber.Remove(20);
}
ModelState["SerialNumber"].Value = new ValueProviderResult(serialNumber, serialNumber, CultureInfo.CurrentCulture);
var result = RepairInvoiceDataLayer.SelectRmaDetail(rmaNumber, serialNumber);
if (result != null)
{
if (result.Received == 1)
{
Nullable<bool> workOrderClosed = RepairInvoiceDataLayer.WorkOrderClosed(result.RETDOCID, result.LNSEQNBR, serialNumber);
if (workOrderClosed.HasValue)
{
if (workOrderClosed.Value)
{
Session["RmaDetail"] = result;
repairInvoice.TerminalType = result.ITEMNMBR.Trim();
repairInvoice.UnderWarranty = RepairInvoiceDataLayer.UnderWarranty(result.RETDOCID, result.LNSEQNBR, serialNumber, result.CUSTNMBR);
ViewBag.SetFocusTo = "#RepairLevels";
}
else
{
ViewBag.AlertMessage = "Work order not closed.";
}
}
else
{
ViewBag.AlertMessage = "Work order not found.";
}
}
else
{
ViewBag.AlertMessage = "Line item has not been received.";
}
}
else
{
ViewBag.AlertMessage = "Serial Number not found.";
}
}
catch (Exception ex)
{
ViewBag.ErrorMessage = "An error occured searching for Serial Number. Please try again.";
log.Fatal(string.Format("An error occured searching for Serial Number. RMA Number: {0} Serial Number: {1}", rmaNumber, serialNumber, ex));
}
}
return View("Index", repairInvoice);
}
```
Basically my page is setup to handle this current process flow:
1. User types a number into the RMA number textbox and hits `enter` or `tab`. JavaScript detects `enter` or `tab` key and navigates to /Invoice/RmaNumberScan and passes a query string with the number entered. Logic is performed in the `RmaNumberScan` action result.
2. Next, the user types a number into the serial scan textbox and hits `tab` or `enter`. The /Invoice/SerialNumberScan is called and passes query strings to the `SerialNumberScan` method.
3. User clicks the process button and then the `Index()` with the `HTTPPOST` method fires.
Am I on the right track, or am I doing MVC incorrectly? I come from a webforms background, and I want to split up my code. My attempt just feels so dirty and I don't like the fact that my action result name appears in the URL. I just want my code to be easily maintained and readable.
Since all of my database logic is done in my `RepairInvoiceDataLayer`, I still don't understand how the service layer comes into play here. What code from this controller would go into the service layer? | 2013/11/25 | [
"https://codereview.stackexchange.com/questions/36061",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/32574/"
] | It sounds like you need to add a service layer where you can include all your business logic. This way your controller classes do not become bloated with business logic and they are only dealing with the handling of requests and the population of view-models.
Using thin controllers like this you can separate your logic out to different services and make it easier to practice the [Single Responsibility Principle](http://en.wikipedia.org/wiki/Single_responsibility_principle).
Please see this question and accepted answer but I've included an example below: [Creating a service layer for my MVC application](https://stackoverflow.com/questions/14887871/creating-a-service-layer-for-my-mvc-application)
Your controller:
```
[Dependency]
public IInvoiceService InvoiceService;
public ActionResult Index()
{
//code
return View(repairInvoice);
}
[HttpPost]
public ActionResult Index(RepairInvoice ri)
{
this.InvoiceService.ProcessInvoice(ri.RmaNumber, ri.SerialNumber); // add on other params as appropriate
return View(ri);
}
```
Service layer would consist of multiple classes, each with their own responsibility such as:
```
public class InvoiceService : IInvoiceService
{
public void ProcessInvoice(string rmaNumber, string serialNumber)
{
// Do any processing here
}
}
```
I would recommend creating an interface for each separate service and then you can use [Dependency Injection](http://msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx) to instantiate the concrete classes using [Unity](https://unity.codeplex.com/) or similar. | Although @SilverlightFox is right in that you need to separate your business logic from contoller; this in itself will not improve readability of your code; as the biggest problem, namely **Arrow Code** will still remain.
**Arrow Code** results from to many nesting levels in code.
Also in an `if/else` statement handling the exceptional case later separates the condition from its consequence. By handling the exceptional case next to the condition and returning early solves both problems.
Your business logic method would look like this after said transformation.
```
public RmaDetail SerialNumberScan(int rmaNumber, int serialNumber, RepairInvoice repairInvoice) {
var result = SelectRmaDetail(rmaNumber, serialNumber);
if (result != null) throw new BusinessException("Serial Number not found.");
if (result.Received != 1) throw new BusinessException("Line item has not been received.");
bool? workOrderClosed = WorkOrderClosed(result.LNSEQNBR, result.LNSEQNBR, serialNumber);
if (!workOrderClosed.HasValue) throw new BusinessException("Work order not found.");
if (workOrderClosed.Value == false) throw new BusinessException("Work order not closed.");
repairInvoice.TerminalType = result.ITEMNMBR.Trim();
repairInvoice.UnderWarranty = RepairInvoiceDataLayer.UnderWarranty(result.RETDOCID, result.LNSEQNBR, serialNumber, result.CUSTNMBR);
return result;
}
```
The rest of the spaghetti comes from user input validation. Although it, too, can be remedied by short-cut returns; the better way would be doing as much validation declaratively as possible. General error handling should also be done declaratively. After making those changes your `SerialNumberScan` action read like the following:
```
public ActionResult SerialNumberScan(string rmaNumber, string serialNumber)
{
if (ModelState.IsValid)
{
ModelState["SerialNumber"].Value = new ValueProviderResult(serialNumber, serialNumber, CultureInfo.CurrentCulture);
try
{
var rmaDetail = BusinessLayer.SerialNumberScan(rmaNumber, serialNumber, repairInvoice);
Session["RmaDetail"] = rmaDetail;
ViewBag.SetFocusTo = "#RepairLevels";
}
catch (BusinessException ex)
{
ViewBag.AlertMessage = ex.Message;
}
}
return View("Index", repairInvoice);
}
```
EDIT how not to have to pass repairInvoice to business layer
------------------------------------------------------------
```
// put this class in your business layer namespace
public class SerialNumberScanResult
{
public RmaDetail RmaDetail { get; private set; }
public bool UnderWarranty { get; private set; }
public SerialNuberScanResult(RmaDetail rmaDetail, bool underWarranty)
{
RmaDetail = rmaDetail;
UnderWarranty = underWarranty;
}
}
public SerialNuberScanResult SerialNumberScan(int rmaNumber, int serialNumber) {
var rmaDetail = SelectRmaDetail(rmaNumber, serialNumber);
if (rmaDetail != null) throw new BusinessException("Serial Number not found.");
if (rmaDetail.Received != 1) throw new BusinessException("Line item has not been received.");
bool? workOrderClosed = WorkOrderClosed(rmaDetail.LNSEQNBR, rmaDetail.LNSEQNBR, serialNumber);
if (!workOrderClosed.HasValue) throw new BusinessException("Work order not found.");
if (workOrderClosed.Value == false) throw new BusinessException("Work order not closed.");
bool underWarranty = RepairInvoiceDataLayer.UnderWarranty(rmaDetail.RETDOCID, rmaDetail.LNSEQNBR, serialNumber, rmaDetail.CUSTNMBR);
return new SerialNuberScanResult(rmaDetail, underWarranty);
}
public ActionResult SerialNumberScan(string rmaNumber, string serialNumber)
{
if (ModelState.IsValid)
{
ModelState["SerialNumber"].Value = new ValueProviderResult(serialNumber, serialNumber, CultureInfo.CurrentCulture);
try
{
var result = BusinessLayer.SerialNumberScan(rmaNumber, serialNumber);
repairInvoice.TerminalType = result.RmaDetail.ITEMNMBR.Trim();
repairInvoice.UnderWarranty = result.UnderWarranty;
Session["RmaDetail"] = result.RmaDetail;
ViewBag.SetFocusTo = "#RepairLevels";
}
catch (BusinessException ex)
{
ViewBag.AlertMessage = ex.Message;
}
}
return View("Index", repairInvoice);
}
``` |
45,982,383 | This is the code to create a database copy in Azure using service management api's
```
SqlManagementClient sqlClient = new SqlManagementClient sqlClient ();
DatabaseCopyCreateParameters newDatabaseParameters = new DatabaseCopyCreateParameters()
{
IsContinuous = true,
PartnerDatabase = srcDB
PartnerServer = srcserver
};
sqlClient.DatabaseCopies.Create(dbservername, dbname, newDatabaseParameters);
```
It got created in the location say "east asia".
As you can see I am not providing any location details, then how it is created in this location? | 2017/08/31 | [
"https://Stackoverflow.com/questions/45982383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4328901/"
] | Location is decided based on the server location. Since my server is in East Asia, Obviously db will be in East Asia | You can avoid this by copying the database using T-SQL as explained below:
```
-- Execute on the master database of the target server (server2)
-- Start copying from Server1 to Server2
CREATE DATABASE Database1_copy AS COPY OF server1.Database1;
```
For more information, click [here](https://learn.microsoft.com/en-us/azure/sql-database/sql-database-copy).
Hope this helps. |
8,310 | Is there a quantum algorithm allowing to determine the state with the highest probability of occurring (i.e. highest square amplitude), more efficiently than repeatedly measuring and estimating a histogram? | 2019/09/25 | [
"https://quantumcomputing.stackexchange.com/questions/8310",
"https://quantumcomputing.stackexchange.com",
"https://quantumcomputing.stackexchange.com/users/8598/"
] | Yes. It is, for instance, part of Grover's algorithm and to be precise it is the 'Amplitude Amplification' part. $2| \psi \rangle \langle \psi | - I$, which will increase the amplitudes by
their difference from the average | It looks like you want an algorithm that, given a state of the form $|\psi\rangle=\alpha|0\rangle+\beta|1\rangle$ with $|\alpha|\ge|\beta|$, gives back $|0\rangle$ with probability greater than $|\alpha|^2$.
I don't think this is possible.
Indeed, say such a mapping $\mathcal E$ existed. This $\mathcal E$ must be such that the probability of finding $\mathcal E(\psi)$ in $|0\rangle$, that is, $\mathrm{Tr}[\mathbb P\_0\mathcal E(\psi)]$, is greater than $|\alpha|^2$ if $|\alpha|\ge|\beta|$, while at the same time
$\mathrm{Tr}[\mathbb P\_1\mathcal E(\psi)]\ge |\beta|^2$ when $|\beta|\ge|\alpha|$.
In other words, this map would have to satisfy
\begin{aligned}
\mathrm{Tr}[\mathbb P\_0\mathcal E(\psi)]&\ge |\alpha|^2,\quad\text{if }|\alpha|\ge1/2\\
\mathrm{Tr}[\mathbb P\_0\mathcal E(\psi)]&\le |\alpha|^2,\quad\text{if }|\alpha|\le1/2.
\end{aligned}
Note that I'm using the shorthand notation $\mathbb P\_\psi\equiv|\psi\rangle\!\langle\psi|$ here.
Consider how such a $\mathcal E$ would have to act on the input $|\psi\rangle=|0\rangle$. The only way to satisfy the above relations is to have $\mathcal E(\psi)=\mathcal E(\mathbb P\_0)=\mathbb P\_0$, and similarly $\mathcal E(\mathbb P\_1)=\mathbb P\_1$. But this, by linearity, fully characterises $\mathcal E$, forcing it to equal the identity operation.
In other words, no, you cannot have an algorithm which magically amplifies the amplitude of the state with the largest probability.
Note that this argument relies on the fact that $\mathcal E$ *cannot* contain knowledge about the state to be amplified. If you instead ask for an algorithm which amplifies the amplitude of a target state, then this is possible, and it's called amplitude amplification, as has already been mentioned in the other answers. |
16,908,635 | Just started c++ and I'm working on making blackjack. I've set it up so a player's hand is a string of cards, ex: hand[1] = ❤2 hand[2] = ❤J
I've made a function to add up the values of all of the cards in the cards array but i'm running into a problem:
```
int handValue(string hand[]){
int handSum;
//returns value of total amount of cards in hand+1
int numCards = nextCard(hand);
string value;
for (int i = 0; i < numCards ; i++){
//Checks the second character of a card to find a value (1,2,3...T,J,Q,K)
string value = hand[i][1];
if (value == "T" || value == "J"|| value == "Q" || value == "K") {
handSum += 10;
}
}
return handSum;
}
```
This line is where I'm having the problem:
```
string card = hand[i][1];
```
Yielding the error:
>
> Invalid conversion from 'char' to 'const char\*'.
>
>
>
Why exactly am I getting this error and how do I fix it? Thanks! | 2013/06/04 | [
"https://Stackoverflow.com/questions/16908635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2441938/"
] | Your `GetHashCode` implementation does not return the same value for (A, B) and (B, A). The `HashSet` checks if it already contains a given hash at the moment of insertion. If it doesn't, then the object will be considered new.
If you correct your `GetHashCode`, then at the moment of inserting the second `Pair` the `HashSet` will see that the hash code already exists and verify equality with the other objects sharing the same hash code. | Just remove this: \*397
If they are considered duplicates, they must **return the same int from GetHashCode()**. (However, if they are not considered duplicates they are still allowed to return the same int, that will only affect performance). |
98,488 | So I'm still relatively a newbie when it comes to rulings on using weapons and such, but I was wondering is it feasible for a level 1 bard (human or half elf most likely) starting out to be able to wield a two-handed great sword?
That being said the idea is the bard will mostly be a healer of sort, but for role playing purposes it's that he's from a clan/family of swordsman and warriors so he aspires to be one and refuses to give up on wielding a mighty greatsword.
Are there any requirements etc? | 2017/04/20 | [
"https://rpg.stackexchange.com/questions/98488",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/35430/"
] | Well technically you could wield anything as a weapon, you just wouldn't have much success with it (you do not add your proficiency bonus to attacks, which is a +2 at 1st level). To be competent with a weapon, you need proficiency with it. Bards do not get proficiency with two-handed swords, so you have two options:
1. If the variant human is allowed by your GM, you can take the Weapon Master feat at 1st level, and choose greatsword as one of the four weapons you gain proficiency with.
2. If you are willing to wait until 3rd level, you can pick the College of Valor and gain proficiency with all martial weapons (including the greatsword). | In 5e D&D, the Bard does not start with proficiency with Greatswords. However, if you choose the College of Valor archetype then you can get proficiency with Greatswords at level 3.
If you don't want to wait that long / go with different college, there are other options:
* The easiest is to use the variant Human and choose the feat *Weapon Master* which allows you to gain proficiency with 4 weapons of your choice.
* You can choose the *Weapon Master* feat instead of using a Ability Score Increase you'd get when leveling up.
* Finally, you could also choose to [multi-class](https://roll20.net/compendium/dnd5e/Character%20Advancement#toc_7) into a different class which is granted proficiency in Greatswords.
NOTE: You are still able to use Greatswords even without being proficient (or any other weapon, for that matter). The only difference is that you won't be able to add your proficiency bonus to attack rolls when using that weapon. |
98,488 | So I'm still relatively a newbie when it comes to rulings on using weapons and such, but I was wondering is it feasible for a level 1 bard (human or half elf most likely) starting out to be able to wield a two-handed great sword?
That being said the idea is the bard will mostly be a healer of sort, but for role playing purposes it's that he's from a clan/family of swordsman and warriors so he aspires to be one and refuses to give up on wielding a mighty greatsword.
Are there any requirements etc? | 2017/04/20 | [
"https://rpg.stackexchange.com/questions/98488",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/35430/"
] | As others have noted, taking the College of Valor as a 3rd level bard is an 0ption. Multiclassing is an option. The Weapons Master feat is an option. All of those are significant constraints or character development expenses to get one weapon proficiency. They each come with other benefits, of course, but they may not represent what you are trying to do with your character.
Another option would be to work with your gamemaster on a custom background. Your background generally gives you at least two skills and a feature; perhaps your gamemaster would let you substitute greatsword proficiency for one of those, based on your family history. | In 5e D&D, the Bard does not start with proficiency with Greatswords. However, if you choose the College of Valor archetype then you can get proficiency with Greatswords at level 3.
If you don't want to wait that long / go with different college, there are other options:
* The easiest is to use the variant Human and choose the feat *Weapon Master* which allows you to gain proficiency with 4 weapons of your choice.
* You can choose the *Weapon Master* feat instead of using a Ability Score Increase you'd get when leveling up.
* Finally, you could also choose to [multi-class](https://roll20.net/compendium/dnd5e/Character%20Advancement#toc_7) into a different class which is granted proficiency in Greatswords.
NOTE: You are still able to use Greatswords even without being proficient (or any other weapon, for that matter). The only difference is that you won't be able to add your proficiency bonus to attack rolls when using that weapon. |
98,488 | So I'm still relatively a newbie when it comes to rulings on using weapons and such, but I was wondering is it feasible for a level 1 bard (human or half elf most likely) starting out to be able to wield a two-handed great sword?
That being said the idea is the bard will mostly be a healer of sort, but for role playing purposes it's that he's from a clan/family of swordsman and warriors so he aspires to be one and refuses to give up on wielding a mighty greatsword.
Are there any requirements etc? | 2017/04/20 | [
"https://rpg.stackexchange.com/questions/98488",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/35430/"
] | In 5e D&D, the Bard does not start with proficiency with Greatswords. However, if you choose the College of Valor archetype then you can get proficiency with Greatswords at level 3.
If you don't want to wait that long / go with different college, there are other options:
* The easiest is to use the variant Human and choose the feat *Weapon Master* which allows you to gain proficiency with 4 weapons of your choice.
* You can choose the *Weapon Master* feat instead of using a Ability Score Increase you'd get when leveling up.
* Finally, you could also choose to [multi-class](https://roll20.net/compendium/dnd5e/Character%20Advancement#toc_7) into a different class which is granted proficiency in Greatswords.
NOTE: You are still able to use Greatswords even without being proficient (or any other weapon, for that matter). The only difference is that you won't be able to add your proficiency bonus to attack rolls when using that weapon. | Worthy to note, at 2nd level Jack-of-All-Trades is one of the most pft overlooked and OP early boosts in the game. You are at least half proficient with anything with which you are not fully proficient. This would include greatswords, as well as initiative, per RAW, confirmed and legit bard power plays. Be sure to always inspire, always jackofalltrades, and always song of rest (did I mention vicious mockery?) As a low level bard you will be a hero at all times to your adventuring party.
Also variant human+ritual casting wizard familiar amongst other gems = nice healing touch delivery if your party needs some healing support. I love being the most versatile character on the map at all times and still being a potent purecasting arcana beethoven sorcerer/maestro. I may give greatsword a go though, I had been considering a greatsword ranger but I just dont love them like I love bard... Still not sure I could go valor vs lore though.... Access to every spell in the game cross class cherry picking could make for a very nasty great weapon fighter. Warcaster would be nice to flavor in a singing greatsword mmmmm |
98,488 | So I'm still relatively a newbie when it comes to rulings on using weapons and such, but I was wondering is it feasible for a level 1 bard (human or half elf most likely) starting out to be able to wield a two-handed great sword?
That being said the idea is the bard will mostly be a healer of sort, but for role playing purposes it's that he's from a clan/family of swordsman and warriors so he aspires to be one and refuses to give up on wielding a mighty greatsword.
Are there any requirements etc? | 2017/04/20 | [
"https://rpg.stackexchange.com/questions/98488",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/35430/"
] | Well technically you could wield anything as a weapon, you just wouldn't have much success with it (you do not add your proficiency bonus to attacks, which is a +2 at 1st level). To be competent with a weapon, you need proficiency with it. Bards do not get proficiency with two-handed swords, so you have two options:
1. If the variant human is allowed by your GM, you can take the Weapon Master feat at 1st level, and choose greatsword as one of the four weapons you gain proficiency with.
2. If you are willing to wait until 3rd level, you can pick the College of Valor and gain proficiency with all martial weapons (including the greatsword). | As others have noted, taking the College of Valor as a 3rd level bard is an 0ption. Multiclassing is an option. The Weapons Master feat is an option. All of those are significant constraints or character development expenses to get one weapon proficiency. They each come with other benefits, of course, but they may not represent what you are trying to do with your character.
Another option would be to work with your gamemaster on a custom background. Your background generally gives you at least two skills and a feature; perhaps your gamemaster would let you substitute greatsword proficiency for one of those, based on your family history. |
98,488 | So I'm still relatively a newbie when it comes to rulings on using weapons and such, but I was wondering is it feasible for a level 1 bard (human or half elf most likely) starting out to be able to wield a two-handed great sword?
That being said the idea is the bard will mostly be a healer of sort, but for role playing purposes it's that he's from a clan/family of swordsman and warriors so he aspires to be one and refuses to give up on wielding a mighty greatsword.
Are there any requirements etc? | 2017/04/20 | [
"https://rpg.stackexchange.com/questions/98488",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/35430/"
] | Well technically you could wield anything as a weapon, you just wouldn't have much success with it (you do not add your proficiency bonus to attacks, which is a +2 at 1st level). To be competent with a weapon, you need proficiency with it. Bards do not get proficiency with two-handed swords, so you have two options:
1. If the variant human is allowed by your GM, you can take the Weapon Master feat at 1st level, and choose greatsword as one of the four weapons you gain proficiency with.
2. If you are willing to wait until 3rd level, you can pick the College of Valor and gain proficiency with all martial weapons (including the greatsword). | As others have said, there are a few easy ways to do this:
1. variant human - weapon master feat (1st level)
2. valor bard archetype (3rd level)
3. multiclass into barbarian, fighter, paladin, or ranger
4. wield a longsword with 2 hands (1d10 damage), and re-flavor it as a slightly undersized greatsword. Maybe your character never completed their training (or is fairly small), and is using a slightly smaller greatsword because of that.
5. Wield the greatsword. Anyone can pick up any weapon and use it. You just won't get to add your proficiency bonus (+2 at level 1) to attack rolls. |
98,488 | So I'm still relatively a newbie when it comes to rulings on using weapons and such, but I was wondering is it feasible for a level 1 bard (human or half elf most likely) starting out to be able to wield a two-handed great sword?
That being said the idea is the bard will mostly be a healer of sort, but for role playing purposes it's that he's from a clan/family of swordsman and warriors so he aspires to be one and refuses to give up on wielding a mighty greatsword.
Are there any requirements etc? | 2017/04/20 | [
"https://rpg.stackexchange.com/questions/98488",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/35430/"
] | Well technically you could wield anything as a weapon, you just wouldn't have much success with it (you do not add your proficiency bonus to attacks, which is a +2 at 1st level). To be competent with a weapon, you need proficiency with it. Bards do not get proficiency with two-handed swords, so you have two options:
1. If the variant human is allowed by your GM, you can take the Weapon Master feat at 1st level, and choose greatsword as one of the four weapons you gain proficiency with.
2. If you are willing to wait until 3rd level, you can pick the College of Valor and gain proficiency with all martial weapons (including the greatsword). | Worthy to note, at 2nd level Jack-of-All-Trades is one of the most pft overlooked and OP early boosts in the game. You are at least half proficient with anything with which you are not fully proficient. This would include greatswords, as well as initiative, per RAW, confirmed and legit bard power plays. Be sure to always inspire, always jackofalltrades, and always song of rest (did I mention vicious mockery?) As a low level bard you will be a hero at all times to your adventuring party.
Also variant human+ritual casting wizard familiar amongst other gems = nice healing touch delivery if your party needs some healing support. I love being the most versatile character on the map at all times and still being a potent purecasting arcana beethoven sorcerer/maestro. I may give greatsword a go though, I had been considering a greatsword ranger but I just dont love them like I love bard... Still not sure I could go valor vs lore though.... Access to every spell in the game cross class cherry picking could make for a very nasty great weapon fighter. Warcaster would be nice to flavor in a singing greatsword mmmmm |
98,488 | So I'm still relatively a newbie when it comes to rulings on using weapons and such, but I was wondering is it feasible for a level 1 bard (human or half elf most likely) starting out to be able to wield a two-handed great sword?
That being said the idea is the bard will mostly be a healer of sort, but for role playing purposes it's that he's from a clan/family of swordsman and warriors so he aspires to be one and refuses to give up on wielding a mighty greatsword.
Are there any requirements etc? | 2017/04/20 | [
"https://rpg.stackexchange.com/questions/98488",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/35430/"
] | As others have noted, taking the College of Valor as a 3rd level bard is an 0ption. Multiclassing is an option. The Weapons Master feat is an option. All of those are significant constraints or character development expenses to get one weapon proficiency. They each come with other benefits, of course, but they may not represent what you are trying to do with your character.
Another option would be to work with your gamemaster on a custom background. Your background generally gives you at least two skills and a feature; perhaps your gamemaster would let you substitute greatsword proficiency for one of those, based on your family history. | As others have said, there are a few easy ways to do this:
1. variant human - weapon master feat (1st level)
2. valor bard archetype (3rd level)
3. multiclass into barbarian, fighter, paladin, or ranger
4. wield a longsword with 2 hands (1d10 damage), and re-flavor it as a slightly undersized greatsword. Maybe your character never completed their training (or is fairly small), and is using a slightly smaller greatsword because of that.
5. Wield the greatsword. Anyone can pick up any weapon and use it. You just won't get to add your proficiency bonus (+2 at level 1) to attack rolls. |
98,488 | So I'm still relatively a newbie when it comes to rulings on using weapons and such, but I was wondering is it feasible for a level 1 bard (human or half elf most likely) starting out to be able to wield a two-handed great sword?
That being said the idea is the bard will mostly be a healer of sort, but for role playing purposes it's that he's from a clan/family of swordsman and warriors so he aspires to be one and refuses to give up on wielding a mighty greatsword.
Are there any requirements etc? | 2017/04/20 | [
"https://rpg.stackexchange.com/questions/98488",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/35430/"
] | As others have noted, taking the College of Valor as a 3rd level bard is an 0ption. Multiclassing is an option. The Weapons Master feat is an option. All of those are significant constraints or character development expenses to get one weapon proficiency. They each come with other benefits, of course, but they may not represent what you are trying to do with your character.
Another option would be to work with your gamemaster on a custom background. Your background generally gives you at least two skills and a feature; perhaps your gamemaster would let you substitute greatsword proficiency for one of those, based on your family history. | Worthy to note, at 2nd level Jack-of-All-Trades is one of the most pft overlooked and OP early boosts in the game. You are at least half proficient with anything with which you are not fully proficient. This would include greatswords, as well as initiative, per RAW, confirmed and legit bard power plays. Be sure to always inspire, always jackofalltrades, and always song of rest (did I mention vicious mockery?) As a low level bard you will be a hero at all times to your adventuring party.
Also variant human+ritual casting wizard familiar amongst other gems = nice healing touch delivery if your party needs some healing support. I love being the most versatile character on the map at all times and still being a potent purecasting arcana beethoven sorcerer/maestro. I may give greatsword a go though, I had been considering a greatsword ranger but I just dont love them like I love bard... Still not sure I could go valor vs lore though.... Access to every spell in the game cross class cherry picking could make for a very nasty great weapon fighter. Warcaster would be nice to flavor in a singing greatsword mmmmm |
98,488 | So I'm still relatively a newbie when it comes to rulings on using weapons and such, but I was wondering is it feasible for a level 1 bard (human or half elf most likely) starting out to be able to wield a two-handed great sword?
That being said the idea is the bard will mostly be a healer of sort, but for role playing purposes it's that he's from a clan/family of swordsman and warriors so he aspires to be one and refuses to give up on wielding a mighty greatsword.
Are there any requirements etc? | 2017/04/20 | [
"https://rpg.stackexchange.com/questions/98488",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/35430/"
] | As others have said, there are a few easy ways to do this:
1. variant human - weapon master feat (1st level)
2. valor bard archetype (3rd level)
3. multiclass into barbarian, fighter, paladin, or ranger
4. wield a longsword with 2 hands (1d10 damage), and re-flavor it as a slightly undersized greatsword. Maybe your character never completed their training (or is fairly small), and is using a slightly smaller greatsword because of that.
5. Wield the greatsword. Anyone can pick up any weapon and use it. You just won't get to add your proficiency bonus (+2 at level 1) to attack rolls. | Worthy to note, at 2nd level Jack-of-All-Trades is one of the most pft overlooked and OP early boosts in the game. You are at least half proficient with anything with which you are not fully proficient. This would include greatswords, as well as initiative, per RAW, confirmed and legit bard power plays. Be sure to always inspire, always jackofalltrades, and always song of rest (did I mention vicious mockery?) As a low level bard you will be a hero at all times to your adventuring party.
Also variant human+ritual casting wizard familiar amongst other gems = nice healing touch delivery if your party needs some healing support. I love being the most versatile character on the map at all times and still being a potent purecasting arcana beethoven sorcerer/maestro. I may give greatsword a go though, I had been considering a greatsword ranger but I just dont love them like I love bard... Still not sure I could go valor vs lore though.... Access to every spell in the game cross class cherry picking could make for a very nasty great weapon fighter. Warcaster would be nice to flavor in a singing greatsword mmmmm |
46,919,402 | I have been using Oracle cloud PAAS linux server for my DB machine (Oracle 11g) and having linux application server where i can run all my Java applications.
Assume i have spring based web application which can connect cloud DB machine. I have tried to access the schema in Toad for oracle, it is working as expected but when i try to hit the DB for retrieving the data from application it gives below error.
```
java.sql.SQLException: Io exception: Oracle Error ORA-12650
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:255)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:387)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:420)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:154)
at GetConnection.main(GetConnection.java:35)
```
I have also tried to extend the service access from SID to service name in DB machine. Still give same error. Same code works fine in another cloud machine, which was set by us. But this cloud machine was done by oracle team and most of the things are by default.
Please share your suggestion to fix this issue. | 2017/10/24 | [
"https://Stackoverflow.com/questions/46919402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3003757/"
] | This issue is because of Oracle DB machine encryption **ENCRYPTION\_SERVER** settings. As i understood which is default and set it to enabled, when we set it to ***disabled*** or comment the line then application will work as expected. Below is the file name for reference,
```
Filename : sqlnet.ora (We have to disable ENCRYPTION_SERVER settings)
File Location : ../oracle/product/11.2.0/dbhome_1/network/admin
```
Hope this helps some one.! | It did not help me at all. Actually I followed your solution and I ended up having another error more critical and serious than the one trying to solve.
Let me explain. First of all the value "disabled" that you mentioned is not even an accepted value for this parameter. According to Oracle ([Oracle Docs](https://docs.oracle.com/cd/E11882_01/network.112/e10835/sqlnet.htm#NETRF206)) these are the accepted values that anyone can use:
SQLNET.ENCRYPTION\_SERVER
Purpose
To turn encryption on for the database server.
Default
accepted
Values
* `accepted`: to enable the security service if required or requested by the other side.
* `rejected`: to disable the security service, even if the required by the other side.
* `requested`: to enable the security service if the other side allows it.
* `required`: to enable the security service and disallow the connection if the other side is not enabled for the security service.
Example
```
SQLNET.ENCRYPTION_SERVER=accepted
```
In my case being a 12c Oracle Cloud database the default was set to "required" giving me the error "Io exception: Oracle Error ORA-12650" when trying to start my application.
Setting the parameter to "accepted" solved the issue and managed to start my application.
In case you still get the error you can also set the following parameter to accepted:
SQLNET.CRYPTO\_CHECKSUM\_SERVER = accepted
if you see that in your sqlnet.ora the value is set to "required".
Please have in mind that my application as well as my OCI setup are for testing purposes only and they are not intended to be used in production environment. Setting the value of `SQLNET.ENCRYPTION_SERVER` and `SQLNET.CRYPTO_CHECKSUM_SERVER` to "accepted" will significantly lower your Database's security making it vulnerable to any attacks from any application that has access to it. The best case scenario is to modify your application to use the ENCRYPTION as "required". |
46,919,402 | I have been using Oracle cloud PAAS linux server for my DB machine (Oracle 11g) and having linux application server where i can run all my Java applications.
Assume i have spring based web application which can connect cloud DB machine. I have tried to access the schema in Toad for oracle, it is working as expected but when i try to hit the DB for retrieving the data from application it gives below error.
```
java.sql.SQLException: Io exception: Oracle Error ORA-12650
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:255)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:387)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:420)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:154)
at GetConnection.main(GetConnection.java:35)
```
I have also tried to extend the service access from SID to service name in DB machine. Still give same error. Same code works fine in another cloud machine, which was set by us. But this cloud machine was done by oracle team and most of the things are by default.
Please share your suggestion to fix this issue. | 2017/10/24 | [
"https://Stackoverflow.com/questions/46919402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3003757/"
] | This issue is because of Oracle DB machine encryption **ENCRYPTION\_SERVER** settings. As i understood which is default and set it to enabled, when we set it to ***disabled*** or comment the line then application will work as expected. Below is the file name for reference,
```
Filename : sqlnet.ora (We have to disable ENCRYPTION_SERVER settings)
File Location : ../oracle/product/11.2.0/dbhome_1/network/admin
```
Hope this helps some one.! | Downgrading the OJDBC jar to version7 also works - Replace higher version(ojdbc14.jar was the culprit in my case) with ojdbc7.jar in your dependency files |
46,919,402 | I have been using Oracle cloud PAAS linux server for my DB machine (Oracle 11g) and having linux application server where i can run all my Java applications.
Assume i have spring based web application which can connect cloud DB machine. I have tried to access the schema in Toad for oracle, it is working as expected but when i try to hit the DB for retrieving the data from application it gives below error.
```
java.sql.SQLException: Io exception: Oracle Error ORA-12650
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:255)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:387)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:420)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:154)
at GetConnection.main(GetConnection.java:35)
```
I have also tried to extend the service access from SID to service name in DB machine. Still give same error. Same code works fine in another cloud machine, which was set by us. But this cloud machine was done by oracle team and most of the things are by default.
Please share your suggestion to fix this issue. | 2017/10/24 | [
"https://Stackoverflow.com/questions/46919402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3003757/"
] | It did not help me at all. Actually I followed your solution and I ended up having another error more critical and serious than the one trying to solve.
Let me explain. First of all the value "disabled" that you mentioned is not even an accepted value for this parameter. According to Oracle ([Oracle Docs](https://docs.oracle.com/cd/E11882_01/network.112/e10835/sqlnet.htm#NETRF206)) these are the accepted values that anyone can use:
SQLNET.ENCRYPTION\_SERVER
Purpose
To turn encryption on for the database server.
Default
accepted
Values
* `accepted`: to enable the security service if required or requested by the other side.
* `rejected`: to disable the security service, even if the required by the other side.
* `requested`: to enable the security service if the other side allows it.
* `required`: to enable the security service and disallow the connection if the other side is not enabled for the security service.
Example
```
SQLNET.ENCRYPTION_SERVER=accepted
```
In my case being a 12c Oracle Cloud database the default was set to "required" giving me the error "Io exception: Oracle Error ORA-12650" when trying to start my application.
Setting the parameter to "accepted" solved the issue and managed to start my application.
In case you still get the error you can also set the following parameter to accepted:
SQLNET.CRYPTO\_CHECKSUM\_SERVER = accepted
if you see that in your sqlnet.ora the value is set to "required".
Please have in mind that my application as well as my OCI setup are for testing purposes only and they are not intended to be used in production environment. Setting the value of `SQLNET.ENCRYPTION_SERVER` and `SQLNET.CRYPTO_CHECKSUM_SERVER` to "accepted" will significantly lower your Database's security making it vulnerable to any attacks from any application that has access to it. The best case scenario is to modify your application to use the ENCRYPTION as "required". | Downgrading the OJDBC jar to version7 also works - Replace higher version(ojdbc14.jar was the culprit in my case) with ojdbc7.jar in your dependency files |
63,057,420 | I get the following errors, when I try to deploy the following Firebase Javascript Function via the command "firebase deploy --only functions" from Firebase-Tools CLI in Version 8.6.0.
```
exports.notifyNewMessage = functions.firestore.document("posts/{postId}").onCreate((docSnapshot, context) => {
firestore.collection('accounts').get().then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
return doc.data().name;
});
});
});
```
I found this example code on the official firebase documentation: <https://firebase.google.com/docs/firestore/query-data/get-data#get_all_documents_in_a_collection>
When I try to deploy the code there is running an esLint Check and I get the following errors:
```
2:5 error Expected catch() or return promise/catch-or-return
2:49 warning Unexpected function expression prefer-arrow-callback
2:49 error Each then() should return a value or throw promise/always-return
3:31 warning Unexpected function expression prefer-arrow-callback
```
How I have to fix these errors?
Can someone give me an example, how the Promise with Catch have to look like?
My goal is to get the users accounts data logged in the console to do further operations later. But I don't know how to get these user data logged in the console yet. | 2020/07/23 | [
"https://Stackoverflow.com/questions/63057420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11924602/"
] | Sending a body with a GET request is not supported by HTTP. See [this Q&A](https://stackoverflow.com/questions/978061/http-get-with-request-body) for full details. But if you really want to do this, even though you know it's wrong, you can do it this way:
```golang
iKnowThisBodyShouldBeIgnored := strings.NewReader("text that won't mean anything")
req, err := http.NewRequest(http.MethodGet, "http://example.com/foo", iKnowThisBodyShouldBeIgnored)
if err != nil {
panic(err)
}
res, err := http.DefaultClient.Do(req)
``` | 1. Do not send body in a GET request: [an explanation](https://stackoverflow.com/questions/978061).
RFC 7231 [says](https://www.rfc-editor.org/rfc/rfc7231#section-4.3.1) the following:
>
> A payload within a GET request message has no defined semantics;
> sending a payload body on a GET request might cause some existing
> implementations to reject the request.
>
>
>
2. If you must, do not use `net/http.Get` as it's just a convenience function.
Instead, go one level deeper and construct a proper [`http.Request`](https://golang.org/pkg/net/http/#Request) which then perform by calling the [`Do`](https://golang.org/pkg/net/http/#Client.Do) method on an instance of [`http.Client`](https://golang.org/pkg/net/http/#Client) (the [`http.DefaultClient`](https://golang.org/pkg/net/http/#DefaultClient) should be just fine). |
11,061,929 | I am working on a web application where users can upload different files MS Word (.doc and .docx), Excel (.xls and .xlsx), Power point, PDF, text files and Rich Text Files (.rtf).
As part of the application flow I would like to display a preview of the contents of the files in an IFrame, HTML best but I can go with text, using a PHP class
The approach I am using is:
1. Identify the extension of each file
2. Process each file differently
3. Display the text or HMTL
Is there any library that does this? | 2012/06/16 | [
"https://Stackoverflow.com/questions/11061929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200120/"
] | There is no single library that solves the problem so I solved it using the following libraries for each file type:
a) MS Word documents - Live Docx (http://www.phplivedocx.org/2009/08/13/convert-docx-doc-rtf-to-html-in-php/)
b) MS Excel - PHP Excel (http://phpexcel.codeplex.com/)
c) Text from PDF - class from this Pastebin <http://pastebin.com/hRviHKp1>
d) Powerpoint - still work in progress
I have provided more details on my blog <http://ssmusoke.wordpress.com/2012/06/16/display-contents-of-different-file-formats-wordexcelpowerpointpdfrtf-as-html/> | I had a similar task a few years ago and we ended up using OpenOffice in server mode with ImageMagick to retrieve Thumbnails images of PowerPoint documents. For some kind of presentations library.
Basically the idea is to run OpenOffice and convert your documents to PDF and then use ImageMagick to create a thumbnail image of the first page of that PDF.
This guy here uses OpenOffice with another tool to convert documents: <https://stackoverflow.com/a/1046159/626621> (could help you)
Advantage of this is, I think, that an image as a preview of the document will be more telling to your users than just the text. |
49,316,374 | I had this working without jquery, but the problem was that the tooltip was appearing on the whole div rather than just the PNG.
The mouseover function worked well with jquery so I decided to switch to that, however I do not know how to trigger the CSS animation when the mouseover function runs.
```js
$('#cookie').mouseover(function() {
//$('#tooltip').removeClass('.cookieToolTip');
$('#tooltip').addClass('.cookieToolTipHovered');
});
// I also have some code to move the tooltip wherever the cursor is:
var tooltip = document.querySelectorAll('.cookieToolTip');
document.addEventListener('mousemove', fn, false);
function fn(e) {
for (var i = tooltip.length; i--;) {
tooltip[i].style.left = e.pageX + 'px';
tooltip[i].style.top = e.pageY + 'px';
}
}
```
```css
.cookieToolTipHovered {
visibility: visible;
opacity: 1;
}
.cookieToolTip {
background: #C8C8C8;
margin-left: 28px;
padding: 10px;
position: absolute;
z-index: 1000;
width: 200px;
height: 50px;
opacity: 0;
visibility: hidden;
transition: opacity 1s;
border: 1px solid black;
border-radius: 5px;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="zoomin">
<img id="cookie" oncontextmenu="return false" ondragstart="return false" src="http://www.pngall.com/wp-content/uploads/2016/07/Cookie-Download-PNG.png" />
<span class="cookieToolTip" id="tooltip">This is a picture of a cookie.</span>
</div>
``` | 2018/03/16 | [
"https://Stackoverflow.com/questions/49316374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9488393/"
] | You can change the CSS - you may want to hide (display:none) instead of using visibility since moving the mouse to the edge of the screen will add scrollbars now
```js
$('#cookie').mouseover(function() {
$('#tooltip').css({"opacity":1, "visibility": "visible"})
});
$('#cookie').mouseout(function() {
$('#tooltip').css({ opacity: 0, visibility: "hidden"})
});
// I also have some code to move the tooltip wherever the cursor is:
var $tooltip = $('#tooltip');
$(document).on("mousemove",function(e) {
$tooltip.css({"left": e.pageX + 'px', "top" : e.pageY + 'px'});
})
```
```css
.cookieToolTip {
background: #C8C8C8;
margin-left: 28px;
padding: 10px;
position: absolute;
z-index: 1000;
width: 200px;
height: 50px;
opacity: 0;
visibility: hidden;
transition: opacity 1s;
border: 1px solid black;
border-radius: 5px;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="zoomin">
<img id="cookie" oncontextmenu="return false" ondragstart="return false" src="http://www.pngall.com/wp-content/uploads/2016/07/Cookie-Download-PNG.png" />
<span class="cookieToolTip" id="tooltip">This is a picture of a cookie.</span>
</div>
``` | When adding and removing class do not use the `.` before the classname...as it will add a class with the name `.class` instead of `class`.
You can make your code a little bit cleaner and use ES6 variable declaration ( as a bonus :) ). If your html markup is like in your example ( tooltip exactly after the image ), you can use css selector and get rid of the mouseover/mousein/mouseout methods. See example below, when you hover out of the image the tooltip dissapears
```js
const cookie = $("#cookie"),
tooltip = $('.cookieToolTip')
cookie.on("mousemove", function(e) {
for (let i = tooltip.length; i--;) {
tooltip[i].style.left = e.pageX + 'px';
tooltip[i].style.top = e.pageY + 'px';
}
})
```
```css
.cookieToolTip {
background: #C8C8C8;
margin-left: 28px;
padding: 10px;
position: absolute;
z-index: 1000;
width: 200px;
height: 50px;
opacity: 0;
transition: opacity 1s;
border: 1px solid black;
border-radius: 5px;
}
#cookie:hover + .cookieToolTip{
opacity:1
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="zoomin">
<img id="cookie" oncontextmenu="return false" ondragstart="return false" src="http://via.placeholder.com/350x150" />
<span class="cookieToolTip" id="tooltip">This is a picture of a cookie.</span>
</div>
``` |
49,316,374 | I had this working without jquery, but the problem was that the tooltip was appearing on the whole div rather than just the PNG.
The mouseover function worked well with jquery so I decided to switch to that, however I do not know how to trigger the CSS animation when the mouseover function runs.
```js
$('#cookie').mouseover(function() {
//$('#tooltip').removeClass('.cookieToolTip');
$('#tooltip').addClass('.cookieToolTipHovered');
});
// I also have some code to move the tooltip wherever the cursor is:
var tooltip = document.querySelectorAll('.cookieToolTip');
document.addEventListener('mousemove', fn, false);
function fn(e) {
for (var i = tooltip.length; i--;) {
tooltip[i].style.left = e.pageX + 'px';
tooltip[i].style.top = e.pageY + 'px';
}
}
```
```css
.cookieToolTipHovered {
visibility: visible;
opacity: 1;
}
.cookieToolTip {
background: #C8C8C8;
margin-left: 28px;
padding: 10px;
position: absolute;
z-index: 1000;
width: 200px;
height: 50px;
opacity: 0;
visibility: hidden;
transition: opacity 1s;
border: 1px solid black;
border-radius: 5px;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="zoomin">
<img id="cookie" oncontextmenu="return false" ondragstart="return false" src="http://www.pngall.com/wp-content/uploads/2016/07/Cookie-Download-PNG.png" />
<span class="cookieToolTip" id="tooltip">This is a picture of a cookie.</span>
</div>
``` | 2018/03/16 | [
"https://Stackoverflow.com/questions/49316374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9488393/"
] | When adding and removing class do not use the `.` before the classname...as it will add a class with the name `.class` instead of `class`.
You can make your code a little bit cleaner and use ES6 variable declaration ( as a bonus :) ). If your html markup is like in your example ( tooltip exactly after the image ), you can use css selector and get rid of the mouseover/mousein/mouseout methods. See example below, when you hover out of the image the tooltip dissapears
```js
const cookie = $("#cookie"),
tooltip = $('.cookieToolTip')
cookie.on("mousemove", function(e) {
for (let i = tooltip.length; i--;) {
tooltip[i].style.left = e.pageX + 'px';
tooltip[i].style.top = e.pageY + 'px';
}
})
```
```css
.cookieToolTip {
background: #C8C8C8;
margin-left: 28px;
padding: 10px;
position: absolute;
z-index: 1000;
width: 200px;
height: 50px;
opacity: 0;
transition: opacity 1s;
border: 1px solid black;
border-radius: 5px;
}
#cookie:hover + .cookieToolTip{
opacity:1
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="zoomin">
<img id="cookie" oncontextmenu="return false" ondragstart="return false" src="http://via.placeholder.com/350x150" />
<span class="cookieToolTip" id="tooltip">This is a picture of a cookie.</span>
</div>
``` | when you add a class you don't need the dot before the class name because it's a declaration, not a selector
```
Wrong: $('#cookie').addClass('.cookieToolTipHovered');
Correct: $('#cookie').addClass('cookieToolTipHovered');
```
Then, you need to remove the class when you're out, if you don't the class will keep applied, by the other part, select the proper item to apply (hover / mouseover...) condition (see the example below).
```js
$('.zoomin').mouseover(function() {
$('#cookie').addClass('cookieToolTipHovered');
});
$('#cookie').mouseout(function() {
$('#cookie').removeClass('cookieToolTipHovered');
});
```
```css
.cookieToolTipHovered {
opacity: 0.35;
transition: 1s;
}
.cookieToolTip {
background: #C8C8C8;
margin-left: 28px;
padding: 10px;
position: absolute;
z-index: 1000;
width: 200px;
height: 50px;
opacity: 0;
visibility: hidden;
transition: opacity 1s;
border: 1px solid black;
border-radius: 5px;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="zoomin">
<img id="cookie" oncontextmenu="return false" ondragstart="return false" src="http://www.pngall.com/wp-content/uploads/2016/07/Cookie-Download-PNG.png" />
<span class="cookieToolTip" id="tooltip">This is a picture of a cookie.</span>
</div>
``` |
Subsets and Splits