qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
22,202,887
I got the following XML: ``` <Node attr1="value1" attr2="value2"> <SubNode SubAttr1="subValue1" subAttr2="subValue2" /> </Node> ``` I would like to know if there is a way to do a XQuery expression to return only the `<Node>` element. `<Node attr1="value1" attr2="value2"> <Node>`
2014/03/05
[ "https://Stackoverflow.com/questions/22202887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1571185/" ]
I'm sorry you're out of luck here for a general solution – if you're bound to use Microsoft SQL Server, which does not offer computed element constructors with names that are computed on the fly (like @dirkk is using). When you know that this element is always called "Node", you can do following (using a fixed node name): ``` element Node { /Node/@* } ``` If you also want to include (direct) text children: ``` element Node { /Node/@*, /Node/text() } ``` If you need to support arbitrary element names: you cannot do this with XQuery in SQL Server.
You can write a function to do this: ``` declare function local:strip-children($e as element()*) as element()* { element {node-name($e)} {$e/@*} }; local:strip-children(/Node) ``` Of course you can also do this without a function like so: ``` element {node-name(/node)} {/Node/@*} ``` So you simply inline the code from the function. However, in my opinion the function approach is much more reusable.
10,376,380
I'm using jQuery to open a popup window which works great but I've also have it that the #content div detaches from "parent" page ... ``` $('.newWindow').click(function(ev){ window.open('popout.html','pop out','width=400,height=345'); ev.preventDefault(); $('#content').detach(); return false; }); ``` link used: ``` <a href="popout.html" rel="0" class="newWindow">Pop Out Window</a> ``` How can I "re-attach" that div when pop up window is closed? I've tried many of the answers I found here on SO but none seem to work. **Update:** It seems my browser cached the popup window as when I viewed the source (via right click view source) I noticed any changes I made IE the new JS code was not there so closed browser and reopened and hey presto code edits where there... have temporarily gone for: ``` window.onunload = function(){ window.opener.location.reload(); }; ``` which refreshes the parent page on child close but would still prefer a reattach approach.
2012/04/29
[ "https://Stackoverflow.com/questions/10376380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1359310/" ]
``` $(document).keydown(function(event) { if(event.keyCode === 70) { $.("#myTextarea").css('display','block'); $.('textarea').focus(); return false; } ``` Basically you need to prevent the default event behavior by return false from the function or calling event.preventDefault(). <http://api.jquery.com/event.preventDefault/>
try this: ``` $(document).keydown(function(event) { if(event.keyCode === 70) { $.("#myTextarea").val(" "); $.("#myTextarea").css('display','block'); $.('textarea').focus(); } ```
2,920,424
In elasticity, the kinetic energy $T$ and the potential energy $V$ are $$ T(u\_t) = \frac{1}{2}\rho{u\_t}^2 \qquad\text{and}\qquad V(u\_x) = \frac{1}{2} E {u\_x}^2 , $$ where $u$ is the displacement, $u\_t$ the velocity, and $u\_x$ the strain. The symbols $\rho>0$ and $E>0$ denote respectively the mass density and Young's modulus. The corresponding Lagrangian is $\mathcal{L} = T-V$. Using the principle of least action, how do we show that the 1D wave equation $$\rho u\_{tt} = E u\_{xx}$$ is the corresponding Euler-Lagrange equation? If this wave equation comes from $\frac{\text d}{\text d t} \frac{\partial \mathcal{L}}{\partial \dot q} = \frac{\partial \mathcal{L}}{\partial q}$, what is $q$? On the left-hand side, one would like $\dot{q} = u\_t$, while on the right-hand side, ${q} = u$ gives zero. How to resolve this inconsistency? I am aware of [this exercise](https://math.stackexchange.com/q/270110/418542) from Evans, but would like to tackle the particular case of the wave equation in elasticity.
2018/09/17
[ "https://math.stackexchange.com/questions/2920424", "https://math.stackexchange.com", "https://math.stackexchange.com/users/418542/" ]
In this case you have $q=u$ is a single function of two variables $(x\_1,x\_2)=(t,x)$, so Euler-Lagrange takes the form $$ \dfrac{\partial\mathcal{L}}{\partial q}=\sum\_{j=1}^{2}\frac{\partial}{\partial x\_j}\left(\frac{\partial\mathcal{L}}{\partial q\_{,j}}\right) $$ where $q\_{,j}=\dfrac{\partial q}{\partial x\_j}$. In other words, it is $$ \dfrac{\partial\mathcal{L}}{\partial q}=\frac{\partial}{\partial t}\left(\frac{\partial\mathcal{L}}{\partial u\_t}\right)+\frac{\partial}{\partial x}\left(\frac{\partial\mathcal{L}}{\partial u\_x}\right). $$
After I read some books dedicated to variational calculus, I came up with the following answer, which is perfectly consistent with the accepted answer by @user10354138. From the Lagrangian density $$\mathcal L(u,u\_t,u\_x) = T(u\_t)-V(u\_x)$$ defined in OP, we formulate the principle of stationary action $\delta \mathcal A = 0$, where $\mathcal A = \iint \mathcal L \,\text{d}x\text d t$ is the action, and $\delta \mathcal A$ denotes its first variation w.r.t. $u$, $u\_t$, $u\_x$. Using integration by parts and the commutativity of variation and differentiation, we find \begin{aligned} \delta A &= \iint\_{\Bbb R^2} \left(\frac{\partial \mathcal L}{\partial u}\delta u + \frac{\partial \mathcal L}{\partial u\_t}\delta u\_t + \frac{\partial \mathcal L}{\partial u\_x}\delta u\_x\right) \text{d}x\text d t \\ &= \iint\_{\Bbb R^2} \left(\frac{\partial \mathcal L}{\partial u} - \frac{\partial}{\partial t}\frac{\partial \mathcal L}{\partial u\_t} - \frac{\partial}{\partial x}\frac{\partial \mathcal L}{\partial u\_x}\right) \delta u\, \text{d}x\text d t \, , \end{aligned} where natural boundary conditions have been assumed. This gives us the Euler-Lagrange equation $$ \frac{\partial \mathcal L}{\partial u} - \frac{\partial}{\partial t}\frac{\partial \mathcal L}{\partial u\_t} - \frac{\partial}{\partial x}\frac{\partial \mathcal L}{\partial u\_x} = 0 $$ and therefore the wave equation $\rho u\_{tt} - E u\_{xx} = 0$.
31,707,358
I have a question about §7.3.4/6 in the c++ standard: > > If name lookup finds a declaration for a name in two different > namespaces, and the declarations do not declare the same entity and do > not declare functions, the use of the name is ill-formed. > > > Is seems to suggest that there are cases where the same entity is declared in two different namespaces. Else the wording "and the declarations do not declare the same entity" would not have been needed. Any examples of such situations? Remember that using-declarations are not declaring any entity. They are just referring to a declaration of an entity done elsewhere (possibly indirectly via other using-declarations). Using-declarations are introducing their name into a declarative region however, but that is another thing. Remember also that using-directives are not declaring any entities either. An finally observe that out of line definitions (definitions using qualified names) for namespace members are not declaring anything in the namespace where they occur, but only in the target namespace.
2015/07/29
[ "https://Stackoverflow.com/questions/31707358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1272610/" ]
Yes, with `extern`. From [dcl.link]: > > Two declarations for a function > with C language linkage with the same function name (ignoring the namespace names that qualify it) that > appear in different namespace scopes refer to the same function. **Two declarations for a variable with C > language linkage with the same name (ignoring the namespace names that qualify it) that appear in different > namespace scopes refer to the same variable.** > > > For example: ``` namespace A { extern "C" int x; } namespace B { extern "C" int x; } extern "C" { int x; } namespace D { using namespace A; using namespace B; } ``` `A::x` and `B::x` (and `::x`) are all the same entity. As a result, `D::x` is not ill-formed. --- Upon further reflection, with a combo of *using-declaration*s and *using-directive*s, we can come up with an easier example that doesn't rely on `extern`: ``` namespace A { int i; } namespace B { using A::i; } namespace C { using A::i; } namespace D { using namespace B; using namespace C; } int main() { D::i = 4; // name lookup finds `i` declared in two different namespaces, // B and C. However, both of those declarations refer to the // same entity, A::i } ```
But using declarations do declare names for entities. From the C++11 standard, §7.3.3[namespace.udecl]/1: > > A using-declaration introduces a name into the declarative region in which the using-declaration appears. > > > > > > > *using-declaration*: > > > > > > > > > > > > > > `using typename`*opt* *nested-name-specifier unqualified-id* `;` > > > > > > `using ::` *unqualified-id* `;` > > > > > > > > > > > > > > > > > > > > > **The member name specified in a using-declaration is declared in the declarative region in which the using-declaration appears.** > > >
31,707,358
I have a question about §7.3.4/6 in the c++ standard: > > If name lookup finds a declaration for a name in two different > namespaces, and the declarations do not declare the same entity and do > not declare functions, the use of the name is ill-formed. > > > Is seems to suggest that there are cases where the same entity is declared in two different namespaces. Else the wording "and the declarations do not declare the same entity" would not have been needed. Any examples of such situations? Remember that using-declarations are not declaring any entity. They are just referring to a declaration of an entity done elsewhere (possibly indirectly via other using-declarations). Using-declarations are introducing their name into a declarative region however, but that is another thing. Remember also that using-directives are not declaring any entities either. An finally observe that out of line definitions (definitions using qualified names) for namespace members are not declaring anything in the namespace where they occur, but only in the target namespace.
2015/07/29
[ "https://Stackoverflow.com/questions/31707358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1272610/" ]
Yes, with `extern`. From [dcl.link]: > > Two declarations for a function > with C language linkage with the same function name (ignoring the namespace names that qualify it) that > appear in different namespace scopes refer to the same function. **Two declarations for a variable with C > language linkage with the same name (ignoring the namespace names that qualify it) that appear in different > namespace scopes refer to the same variable.** > > > For example: ``` namespace A { extern "C" int x; } namespace B { extern "C" int x; } extern "C" { int x; } namespace D { using namespace A; using namespace B; } ``` `A::x` and `B::x` (and `::x`) are all the same entity. As a result, `D::x` is not ill-formed. --- Upon further reflection, with a combo of *using-declaration*s and *using-directive*s, we can come up with an easier example that doesn't rely on `extern`: ``` namespace A { int i; } namespace B { using A::i; } namespace C { using A::i; } namespace D { using namespace B; using namespace C; } int main() { D::i = 4; // name lookup finds `i` declared in two different namespaces, // B and C. However, both of those declarations refer to the // same entity, A::i } ```
``` namespace A{ void fun(){} } namespace B{ void fun(){} } int main() { using namespace A; using namespace B; fun()//ambiguous call here because this entity is present in both the namespaces } ``` In above code call to fun is ambiguous as look up will not able to find the correct fun to call . Second example is below : ``` namespace N { namespace A {int i;} } struct A {static int i;}; using namespace N; int i = A::i; ``` In later case ,call is ambiguous as entity 'A' is present in both the namespaces (N and global namespace) . Hope this will help
31,707,358
I have a question about §7.3.4/6 in the c++ standard: > > If name lookup finds a declaration for a name in two different > namespaces, and the declarations do not declare the same entity and do > not declare functions, the use of the name is ill-formed. > > > Is seems to suggest that there are cases where the same entity is declared in two different namespaces. Else the wording "and the declarations do not declare the same entity" would not have been needed. Any examples of such situations? Remember that using-declarations are not declaring any entity. They are just referring to a declaration of an entity done elsewhere (possibly indirectly via other using-declarations). Using-declarations are introducing their name into a declarative region however, but that is another thing. Remember also that using-directives are not declaring any entities either. An finally observe that out of line definitions (definitions using qualified names) for namespace members are not declaring anything in the namespace where they occur, but only in the target namespace.
2015/07/29
[ "https://Stackoverflow.com/questions/31707358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1272610/" ]
But using declarations do declare names for entities. From the C++11 standard, §7.3.3[namespace.udecl]/1: > > A using-declaration introduces a name into the declarative region in which the using-declaration appears. > > > > > > > *using-declaration*: > > > > > > > > > > > > > > `using typename`*opt* *nested-name-specifier unqualified-id* `;` > > > > > > `using ::` *unqualified-id* `;` > > > > > > > > > > > > > > > > > > > > > **The member name specified in a using-declaration is declared in the declarative region in which the using-declaration appears.** > > >
``` namespace A{ void fun(){} } namespace B{ void fun(){} } int main() { using namespace A; using namespace B; fun()//ambiguous call here because this entity is present in both the namespaces } ``` In above code call to fun is ambiguous as look up will not able to find the correct fun to call . Second example is below : ``` namespace N { namespace A {int i;} } struct A {static int i;}; using namespace N; int i = A::i; ``` In later case ,call is ambiguous as entity 'A' is present in both the namespaces (N and global namespace) . Hope this will help
37,793,738
I´m writing because it´s been really difficult to understand the Jira Development Environment, given that there are many differences between 6.x and 7.x versions and the documentations not always is accurate, as far as I could see as a starter in this platform. **I´d like to know if someone can help me to create an agile project in Jira (v.7.1.7) under a development environment, and there, I´ll start to test the code I´m writting as scripts for Script Runner.** I installed everything to develop as explained [here](https://developer.atlassian.com/docs/getting-started/set-up-the-atlassian-plugin-sdk-and-build-a-project/set-up-the-sdk-prerequisites-on-a-windows-system). The server I´m running is started with: **atlas-run-standalone --product jira** or **atlas-run** when I start to write something in the plugin development. I use this the most. Jira is opened through: <http://localhost:2990/jira/> The version of jira says: v7.1.7 When I try to create a project, jira offers only the business kind of projects (project management, task management, process management), but I need the software kind of projects, or at least the scrum projects, because I´m developing a small piece of code that requires epics, stories and scrum oriented concepts, which are not present in the projects I can create right now. Any ideas about this problem? Does someone know why I can´t create agile projects in my server if the plugin of jira agile must be installed by default in the 7.x version of jira? Thanks in advance for any help or orientation.
2016/06/13
[ "https://Stackoverflow.com/questions/37793738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6441394/" ]
I received an answer from the Jira Team. "... when JIRA is up and running, please go to Admin > Applications section and install JIRA Software (Agile) part of JIRA. It brings all development extensions..." I didn´t know that had to be activated in the version 7 of Jira. There, I could find the Agile package.
JIRA has a lot of history and it shows in its documentation. I'll try to give some pointers. [This page](https://developer.atlassian.com/jiradev/latest-updates/preparing-for-jira-7-0/jira-7-0-api-changes) lists the API changes between JIRA 6 and 7. Because JIRA 7 introduced different applications (core, software, service desk) this also means that the API to create projects changed: * You now have to [specify a project type when you create a project](https://developer.atlassian.com/jiradev/latest-updates/preparing-for-jira-7-0/jira-7-0-api-changes#JIRA7.0-APIchanges-projecttypes). * The [validation/creation of projects](https://developer.atlassian.com/jiradev/latest-updates/preparing-for-jira-7-0/jira-7-0-api-changes#JIRA7.0-APIchanges-projectcreationapi) has changed. Also, if you want to get access to the jira-software api sources in your IDE, then you need to add the appropriate dependencies to your pom. This is described [here](https://developer.atlassian.com/docs/advanced-topics/configure-amps-to-run-jira-core-with-additional-applications-installed). [This page](https://developer.atlassian.com/jiradev/jira-apis) lists all the available api documentation (both REST and java) for the different applications. The JIRA Software API documentation is available [here](https://docs.atlassian.com/jira-software/6.7.12/). At the time of writing, 6.7.12 is the latest JIRA Software version. That API also contains an additional service to create projects. Look at [ProjectService](https://docs.atlassian.com/jira-software/6.7.12/com/atlassian/greenhopper/service/project/ProjectService.html). Hope this helps.
8,727,326
I'm working on a tracking system which will save a web user's activity to a **database**, it will be a simple system which I want to only intiate a save "when" a user click's on a specific link. I have found so many applications which have a lot of features such as chart, history and etc. My problem with them is I don't want anything that complex and I want to develop it myself. Could you please help me figure out which JavaScript functions should be used for this task. (how can I gather information from browser and send it to database when specific links are clicked)
2012/01/04
[ "https://Stackoverflow.com/questions/8727326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813625/" ]
The regexpr for a 6 digit number is ``` \d{6} ``` Edit: The code will look like ``` public static String extractDigits(final String in) { final Pattern p = Pattern.compile( "(\\d{6})" ); final Matcher m = p.matcher( in ); if ( m.find() ) { return m.group( 0 ); } return ""; } ```
Not sure if Java's Regex supports lookarounds. If it does: ``` (?<!\d)\d{6}(?!\d) ``` Edit: it does. (Thanks Bohemian)
8,727,326
I'm working on a tracking system which will save a web user's activity to a **database**, it will be a simple system which I want to only intiate a save "when" a user click's on a specific link. I have found so many applications which have a lot of features such as chart, history and etc. My problem with them is I don't want anything that complex and I want to develop it myself. Could you please help me figure out which JavaScript functions should be used for this task. (how can I gather information from browser and send it to database when specific links are clicked)
2012/01/04
[ "https://Stackoverflow.com/questions/8727326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813625/" ]
Not sure if Java's Regex supports lookarounds. If it does: ``` (?<!\d)\d{6}(?!\d) ``` Edit: it does. (Thanks Bohemian)
Why not simply use `substring()`? ``` String s = "Your code: 123456. Your reference number is 012. The total amount is E 1250,00.."; String s2 = s.substring(11); String code = s2.substring(0, s2.indexOf(".")); ``` or just: ``` String code = s.substring(11, 17); ``` since it's always 6 digits.
8,727,326
I'm working on a tracking system which will save a web user's activity to a **database**, it will be a simple system which I want to only intiate a save "when" a user click's on a specific link. I have found so many applications which have a lot of features such as chart, history and etc. My problem with them is I don't want anything that complex and I want to develop it myself. Could you please help me figure out which JavaScript functions should be used for this task. (how can I gather information from browser and send it to database when specific links are clicked)
2012/01/04
[ "https://Stackoverflow.com/questions/8727326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813625/" ]
Not sure if Java's Regex supports lookarounds. If it does: ``` (?<!\d)\d{6}(?!\d) ``` Edit: it does. (Thanks Bohemian)
``` String text = "125432"; String regex = "\\D*\\d{6}\\D*"; Matcher m = Pattern.compile(regex).matcher(text); if(m.find()) System.out.println(m.group(0).trim().substring(0,6)); ```
8,727,326
I'm working on a tracking system which will save a web user's activity to a **database**, it will be a simple system which I want to only intiate a save "when" a user click's on a specific link. I have found so many applications which have a lot of features such as chart, history and etc. My problem with them is I don't want anything that complex and I want to develop it myself. Could you please help me figure out which JavaScript functions should be used for this task. (how can I gather information from browser and send it to database when specific links are clicked)
2012/01/04
[ "https://Stackoverflow.com/questions/8727326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813625/" ]
The regexpr for a 6 digit number is ``` \d{6} ``` Edit: The code will look like ``` public static String extractDigits(final String in) { final Pattern p = Pattern.compile( "(\\d{6})" ); final Matcher m = p.matcher( in ); if ( m.find() ) { return m.group( 0 ); } return ""; } ```
Why not simply use `substring()`? ``` String s = "Your code: 123456. Your reference number is 012. The total amount is E 1250,00.."; String s2 = s.substring(11); String code = s2.substring(0, s2.indexOf(".")); ``` or just: ``` String code = s.substring(11, 17); ``` since it's always 6 digits.
8,727,326
I'm working on a tracking system which will save a web user's activity to a **database**, it will be a simple system which I want to only intiate a save "when" a user click's on a specific link. I have found so many applications which have a lot of features such as chart, history and etc. My problem with them is I don't want anything that complex and I want to develop it myself. Could you please help me figure out which JavaScript functions should be used for this task. (how can I gather information from browser and send it to database when specific links are clicked)
2012/01/04
[ "https://Stackoverflow.com/questions/8727326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813625/" ]
The regexpr for a 6 digit number is ``` \d{6} ``` Edit: The code will look like ``` public static String extractDigits(final String in) { final Pattern p = Pattern.compile( "(\\d{6})" ); final Matcher m = p.matcher( in ); if ( m.find() ) { return m.group( 0 ); } return ""; } ```
``` String text = "125432"; String regex = "\\D*\\d{6}\\D*"; Matcher m = Pattern.compile(regex).matcher(text); if(m.find()) System.out.println(m.group(0).trim().substring(0,6)); ```
8,727,326
I'm working on a tracking system which will save a web user's activity to a **database**, it will be a simple system which I want to only intiate a save "when" a user click's on a specific link. I have found so many applications which have a lot of features such as chart, history and etc. My problem with them is I don't want anything that complex and I want to develop it myself. Could you please help me figure out which JavaScript functions should be used for this task. (how can I gather information from browser and send it to database when specific links are clicked)
2012/01/04
[ "https://Stackoverflow.com/questions/8727326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813625/" ]
Why not simply use `substring()`? ``` String s = "Your code: 123456. Your reference number is 012. The total amount is E 1250,00.."; String s2 = s.substring(11); String code = s2.substring(0, s2.indexOf(".")); ``` or just: ``` String code = s.substring(11, 17); ``` since it's always 6 digits.
``` String text = "125432"; String regex = "\\D*\\d{6}\\D*"; Matcher m = Pattern.compile(regex).matcher(text); if(m.find()) System.out.println(m.group(0).trim().substring(0,6)); ```
14,364,556
I am upgrading a project from Rails 2.3.2 to 2.3.15. It appears that `exists?` may now be considered a finder, which means functions such as `after_find` are now callbacks from `exists?`. In 2.3.2 `exists?` did not trigger a callback to `after_find`. I am having trouble finding a readable changelog other than commits on github which explicitly names this change in policy. Can someone confirm that `exists?` did not call `after_find` (should it be present) in 2.3.2 and it does in 2.3.15? If this is the case, is there a clean Rails way to segregate the `after_find` call? I need some code executed after a true find, not after an `exists?`. As a temporary work-around, I am experimenting with making this the first line in my model's `after_find`: ```rb return unless self.has_attribute?(:some_attrib_your_model_uses_in_after_find) ```
2013/01/16
[ "https://Stackoverflow.com/questions/14364556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/300041/" ]
For your second question, use the `nonzero()` method. I had to dig through [the source](https://github.com/scipy/scipy/blob/v0.11.0/scipy/sparse/base.py#L415) to find it, since I couldn't find it in any of the reference documentation. ``` def nonzero(self): """nonzero indices Returns a tuple of arrays (row,col) containing the indices of the non-zero elements of the matrix. Examples -------- >>> from scipy.sparse import csr_matrix >>> A = csr_matrix([[1,2,0],[0,0,3],[4,0,5]]) >>> A.nonzero() (array([0, 0, 1, 2, 2]), array([0, 1, 2, 0, 2])) """ ```
> > what does `[0,1:3]` mean? > > > That means: row 0, elements `1` to `3` (exclusive). Since Numpy and Scipy use zero-based indices, row 0 is the first row and `1:3` denotes the first and second column. `Asp[0, 1:2,3]` is invalid because you've got three indices, `0`, `1:2` and `3`. Matrices only have two axes. This is all standard Numpy stuff; read any good tutorial on that package.
41,655,797
App open on first fragment and there is 2 tabs i want to refresh second fragment when i move to it but i don't want to refresh first fragment MainActivity ------------ ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new Main_Button(), "Main"); adapter.addFragment(new TwoFragment(), "Main2"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } ``` please explain your answer because i'm new in android and i don't know how i can do that
2017/01/14
[ "https://Stackoverflow.com/questions/41655797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6811388/" ]
When a `Fragment` is made visible (i.e., the selected page in your `ViewPager`), its [setUserVisibleHint()](https://developer.android.com/reference/android/support/v4/app/Fragment.html#setUserVisibleHint(boolean)) method is called. You can override that method in your `TwoFragment` and use it to trigger a refresh. ``` public class TwoFragment extends Fragment { @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { // Refresh your fragment here } } ```
Try This ``` ViewPager mViewPager = (ViewPager)findViewById(R.id.pager); mViewPager.setOffscreenPageLimit(2); ```
41,655,797
App open on first fragment and there is 2 tabs i want to refresh second fragment when i move to it but i don't want to refresh first fragment MainActivity ------------ ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new Main_Button(), "Main"); adapter.addFragment(new TwoFragment(), "Main2"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } ``` please explain your answer because i'm new in android and i don't know how i can do that
2017/01/14
[ "https://Stackoverflow.com/questions/41655797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6811388/" ]
When a `Fragment` is made visible (i.e., the selected page in your `ViewPager`), its [setUserVisibleHint()](https://developer.android.com/reference/android/support/v4/app/Fragment.html#setUserVisibleHint(boolean)) method is called. You can override that method in your `TwoFragment` and use it to trigger a refresh. ``` public class TwoFragment extends Fragment { @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { // Refresh your fragment here } } ```
As of 2020 it is advisable to use architecture components(MVVM) such as LiveData and viewModel This way all Fragments can share the same state see docs here <https://developer.android.com/jetpack/guide>
41,655,797
App open on first fragment and there is 2 tabs i want to refresh second fragment when i move to it but i don't want to refresh first fragment MainActivity ------------ ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new Main_Button(), "Main"); adapter.addFragment(new TwoFragment(), "Main2"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } ``` please explain your answer because i'm new in android and i don't know how i can do that
2017/01/14
[ "https://Stackoverflow.com/questions/41655797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6811388/" ]
Try this - it works for me This code reloads current fragment, when it visible to user. Works when swiping and when back button pressed on next fragment. ```js @Override public void setUserVisibleHint(boolean isVisible) { super.setUserVisibleHint(isVisible); if (isVisible) { FragmentTransaction ftr = getFragmentManager().beginTransaction(); ftr.detach(this).attach(this).commit(); } } ```
If you wouldn't mind refreshing every fragment every time a tab changes, you could simply override the `getItemPosition()` method of your FragmentPagerAdapter and make it return always the value `POSITION_NONE`. Example: ``` @Override public int getItemPosition(Object object) { return POSITION_NONE; } ``` By doing that, you tell android to refresh the fragment each time the view pager tries to get it. Performance wise, it isn't the best practice. So there is a second approach: First, create an interface to be called when your need refresh: ``` public interface Updatable { public void update(); } ``` Then, make your fragments implement this interface: ``` public class MyFragment extends Fragment implements Updateable { ... @Override public void update() { // refresh your fragment, if needed } } ``` If your really wish to *not* update your first fragment, do nothing in its `update()` method. Third, override the `getItemPosition` method and call `update()`. This will be called every time a fragment gets selected: ``` @Override public int getItemPosition(Object object) { Updatable f = (Updatable) object; if (f != null) { f.update(); } return super.getItemPosition(object); } ``` Most of this code came from [this answer](https://stackoverflow.com/questions/18088076/update-fragment-from-viewpager).
41,655,797
App open on first fragment and there is 2 tabs i want to refresh second fragment when i move to it but i don't want to refresh first fragment MainActivity ------------ ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new Main_Button(), "Main"); adapter.addFragment(new TwoFragment(), "Main2"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } ``` please explain your answer because i'm new in android and i don't know how i can do that
2017/01/14
[ "https://Stackoverflow.com/questions/41655797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6811388/" ]
Try This ``` ViewPager mViewPager = (ViewPager)findViewById(R.id.pager); mViewPager.setOffscreenPageLimit(2); ```
As of 2020 it is advisable to use architecture components(MVVM) such as LiveData and viewModel This way all Fragments can share the same state see docs here <https://developer.android.com/jetpack/guide>
41,655,797
App open on first fragment and there is 2 tabs i want to refresh second fragment when i move to it but i don't want to refresh first fragment MainActivity ------------ ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new Main_Button(), "Main"); adapter.addFragment(new TwoFragment(), "Main2"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } ``` please explain your answer because i'm new in android and i don't know how i can do that
2017/01/14
[ "https://Stackoverflow.com/questions/41655797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6811388/" ]
Try This ``` ViewPager mViewPager = (ViewPager)findViewById(R.id.pager); mViewPager.setOffscreenPageLimit(2); ```
you could use ViewPager.addOnPageChangeListener to listen to when the fragments are swiped and incorporate some type of action there.
41,655,797
App open on first fragment and there is 2 tabs i want to refresh second fragment when i move to it but i don't want to refresh first fragment MainActivity ------------ ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new Main_Button(), "Main"); adapter.addFragment(new TwoFragment(), "Main2"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } ``` please explain your answer because i'm new in android and i don't know how i can do that
2017/01/14
[ "https://Stackoverflow.com/questions/41655797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6811388/" ]
When a `Fragment` is made visible (i.e., the selected page in your `ViewPager`), its [setUserVisibleHint()](https://developer.android.com/reference/android/support/v4/app/Fragment.html#setUserVisibleHint(boolean)) method is called. You can override that method in your `TwoFragment` and use it to trigger a refresh. ``` public class TwoFragment extends Fragment { @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { // Refresh your fragment here } } ```
Inside Your fragment class use the below code: ``` @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { getFragmentManager().beginTransaction().detach(this).attach(this).commit(); } } ```
41,655,797
App open on first fragment and there is 2 tabs i want to refresh second fragment when i move to it but i don't want to refresh first fragment MainActivity ------------ ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new Main_Button(), "Main"); adapter.addFragment(new TwoFragment(), "Main2"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } ``` please explain your answer because i'm new in android and i don't know how i can do that
2017/01/14
[ "https://Stackoverflow.com/questions/41655797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6811388/" ]
Try This ``` ViewPager mViewPager = (ViewPager)findViewById(R.id.pager); mViewPager.setOffscreenPageLimit(2); ```
If you wouldn't mind refreshing every fragment every time a tab changes, you could simply override the `getItemPosition()` method of your FragmentPagerAdapter and make it return always the value `POSITION_NONE`. Example: ``` @Override public int getItemPosition(Object object) { return POSITION_NONE; } ``` By doing that, you tell android to refresh the fragment each time the view pager tries to get it. Performance wise, it isn't the best practice. So there is a second approach: First, create an interface to be called when your need refresh: ``` public interface Updatable { public void update(); } ``` Then, make your fragments implement this interface: ``` public class MyFragment extends Fragment implements Updateable { ... @Override public void update() { // refresh your fragment, if needed } } ``` If your really wish to *not* update your first fragment, do nothing in its `update()` method. Third, override the `getItemPosition` method and call `update()`. This will be called every time a fragment gets selected: ``` @Override public int getItemPosition(Object object) { Updatable f = (Updatable) object; if (f != null) { f.update(); } return super.getItemPosition(object); } ``` Most of this code came from [this answer](https://stackoverflow.com/questions/18088076/update-fragment-from-viewpager).
41,655,797
App open on first fragment and there is 2 tabs i want to refresh second fragment when i move to it but i don't want to refresh first fragment MainActivity ------------ ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new Main_Button(), "Main"); adapter.addFragment(new TwoFragment(), "Main2"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } ``` please explain your answer because i'm new in android and i don't know how i can do that
2017/01/14
[ "https://Stackoverflow.com/questions/41655797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6811388/" ]
As of 2020 it is advisable to use architecture components(MVVM) such as LiveData and viewModel This way all Fragments can share the same state see docs here <https://developer.android.com/jetpack/guide>
If you wouldn't mind refreshing every fragment every time a tab changes, you could simply override the `getItemPosition()` method of your FragmentPagerAdapter and make it return always the value `POSITION_NONE`. Example: ``` @Override public int getItemPosition(Object object) { return POSITION_NONE; } ``` By doing that, you tell android to refresh the fragment each time the view pager tries to get it. Performance wise, it isn't the best practice. So there is a second approach: First, create an interface to be called when your need refresh: ``` public interface Updatable { public void update(); } ``` Then, make your fragments implement this interface: ``` public class MyFragment extends Fragment implements Updateable { ... @Override public void update() { // refresh your fragment, if needed } } ``` If your really wish to *not* update your first fragment, do nothing in its `update()` method. Third, override the `getItemPosition` method and call `update()`. This will be called every time a fragment gets selected: ``` @Override public int getItemPosition(Object object) { Updatable f = (Updatable) object; if (f != null) { f.update(); } return super.getItemPosition(object); } ``` Most of this code came from [this answer](https://stackoverflow.com/questions/18088076/update-fragment-from-viewpager).
41,655,797
App open on first fragment and there is 2 tabs i want to refresh second fragment when i move to it but i don't want to refresh first fragment MainActivity ------------ ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new Main_Button(), "Main"); adapter.addFragment(new TwoFragment(), "Main2"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } ``` please explain your answer because i'm new in android and i don't know how i can do that
2017/01/14
[ "https://Stackoverflow.com/questions/41655797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6811388/" ]
When a `Fragment` is made visible (i.e., the selected page in your `ViewPager`), its [setUserVisibleHint()](https://developer.android.com/reference/android/support/v4/app/Fragment.html#setUserVisibleHint(boolean)) method is called. You can override that method in your `TwoFragment` and use it to trigger a refresh. ``` public class TwoFragment extends Fragment { @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { // Refresh your fragment here } } ```
Try this - it works for me This code reloads current fragment, when it visible to user. Works when swiping and when back button pressed on next fragment. ```js @Override public void setUserVisibleHint(boolean isVisible) { super.setUserVisibleHint(isVisible); if (isVisible) { FragmentTransaction ftr = getFragmentManager().beginTransaction(); ftr.detach(this).attach(this).commit(); } } ```
41,655,797
App open on first fragment and there is 2 tabs i want to refresh second fragment when i move to it but i don't want to refresh first fragment MainActivity ------------ ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new Main_Button(), "Main"); adapter.addFragment(new TwoFragment(), "Main2"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } ``` please explain your answer because i'm new in android and i don't know how i can do that
2017/01/14
[ "https://Stackoverflow.com/questions/41655797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6811388/" ]
Inside Your fragment class use the below code: ``` @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { getFragmentManager().beginTransaction().detach(this).attach(this).commit(); } } ```
If you wouldn't mind refreshing every fragment every time a tab changes, you could simply override the `getItemPosition()` method of your FragmentPagerAdapter and make it return always the value `POSITION_NONE`. Example: ``` @Override public int getItemPosition(Object object) { return POSITION_NONE; } ``` By doing that, you tell android to refresh the fragment each time the view pager tries to get it. Performance wise, it isn't the best practice. So there is a second approach: First, create an interface to be called when your need refresh: ``` public interface Updatable { public void update(); } ``` Then, make your fragments implement this interface: ``` public class MyFragment extends Fragment implements Updateable { ... @Override public void update() { // refresh your fragment, if needed } } ``` If your really wish to *not* update your first fragment, do nothing in its `update()` method. Third, override the `getItemPosition` method and call `update()`. This will be called every time a fragment gets selected: ``` @Override public int getItemPosition(Object object) { Updatable f = (Updatable) object; if (f != null) { f.update(); } return super.getItemPosition(object); } ``` Most of this code came from [this answer](https://stackoverflow.com/questions/18088076/update-fragment-from-viewpager).
17,854,351
``` DECLARE @A VARCHAR(MAX), @StartPosistion int, @StringLen int Select -- Setting up the strings to split (details) @StartPosistion = charindex('Eye Colour:', details), @StringLen = patindex('%'+CHAR(10)+'%',substring(details,@StartPosistion ,len(details))) FROM XXX.XXX --Table/Database SELECT substring(XXX.XXX ,@StartPosistion ,@StringLen-1 ) AS EyeColour, ``` Essentially I have a column in a table called 'details', which is usually filled with all sorts of information such as: ``` Name: Person Person Age: 40 Hair Colour: Blue Eye Colour: Red ``` I know ideally this information should be stored as seperate columns, but lets assume there is no choice for whatever reason. To get back just the eye colour of a certain person, I could run the above code which looks for a starting position, in this case the words 'Eye Colour:' and then shows me everything in that one line while removing all the unndeeded information around it. Essentially, running the bottom select statement will give me the output 'Eye Colour: Red', but what if I wanted to remove the word 'Eye Colour:' so that the only thing that outputs is the word 'Red'. Is there a way of going about with this without overcomplicating the code? Thanks for any help.
2013/07/25
[ "https://Stackoverflow.com/questions/17854351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1058168/" ]
When You use charindex('Eye Colour:', details) the charindex will return starting postion of Eye Colour, but ideally you need location after Eye coluor so you can just hard code 11+1, 11 being the length of 'Eye Colour:' and Plus 1 for actual starting postion of RED. can you please give the details of on value so that i can help better. Regards Ashutosh Arya
Replace the search string in the results you already have with "substring(XXX.XXX ,@StartPosistion ,@StringLen-1 ) AS EyeColour" you're getting "Eye Colour: Red" so around that... ``` Replace (substring(XXX.XXX ,@StartPosistion ,@StringLen-1 ), 'Eye Colour: ', '') AS EyeColourValueOnly ```
19,687,959
I have an object of type `Product` and type `Variant`. `Variant` and `Product` have the same structure, but are two different types, and so I can't make just one method to encompass both. Is it possible to make an extension method that would accept both of these types?
2013/10/30
[ "https://Stackoverflow.com/questions/19687959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2316642/" ]
You cannot do that unless `Product` and `Variant` have common base class or interface. If they have common base class or interface then you can try to write extension method for it e.g. ``` public static void MyMethod(this ICommonInterface obj) {} ``` Otherwise you'll have to create two separate extensions methods. You can try to extract common code to a separate method which will be called from your extension methods.
You could take advantage of the `dynamic` type: ``` using System.Linq; class Program { static void Main(string[] args) { var myList = new object[] { new Product(){Id=1}, new Variant(){Id=1} }; Process(myList); } static void Process(object[] myList) { foreach (dynamic item in myList) { item.Id += 1; } } } class Product { public int Id { get; set; } public string Name { get; set; } public string Foo { get; set; } } class Variant { public int Id { get; set; } public string Name { get; set; } public string Bar { get; set; } } pub ``` Using an extension method: ``` public static class X { public static void Process(this object[] myList) { foreach (dynamic item in myList) { item.Id += 1; } } } ``` And the sample usage: ``` myList.Process(); ``` **Another alternative** ... is to use an object-object mapper such as [AutoMapper](http://www.nuget.org/packages/AutoMapper/). For the sample `Product` and `Variant` sample types above, you would have to define the members mapping with the following type which shares the common members of the 2 classes: ``` public class MyMapper { public int Id { get; set; } public string Name { get; set; } } ``` The members mapping looks like this: ``` Mapper.CreateMap<Product, MyMapper>() .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id)) .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name)); Mapper.CreateMap<Variant, MyMapper>() .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id)) .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name)); ``` And you might get a working `List<MyMapper>` like this: ``` var myMapperList = myList.Select(item => item.Map()).ToList(); ``` The `Map<T>` extension method: ``` public static MyMapper Map<T>(this T obj) { return (MyMapper)Mapper.Map(obj, obj.GetType(), typeof(MyMapper)); } ``` From this point further, you would define your extension methods for the `MyMapper` type.
19,687,959
I have an object of type `Product` and type `Variant`. `Variant` and `Product` have the same structure, but are two different types, and so I can't make just one method to encompass both. Is it possible to make an extension method that would accept both of these types?
2013/10/30
[ "https://Stackoverflow.com/questions/19687959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2316642/" ]
You cannot do that unless `Product` and `Variant` have common base class or interface. If they have common base class or interface then you can try to write extension method for it e.g. ``` public static void MyMethod(this ICommonInterface obj) {} ``` Otherwise you'll have to create two separate extensions methods. You can try to extract common code to a separate method which will be called from your extension methods.
Steve, Two possible answers to this question from a Commerce Server perspective. Depends on whether you are talking about the Core Systems API or the Commerce Foundation API. I'll address both below: **OPTION 1 : Commerce Server Core Systems API** Unfortunately, the two classes Product and Variant DO NOT share a common base class (unless you count System.Object ;-). Although Microsoft.CommerceServer.Catalog.Product inherits from Microsoft.CommerceServer.Catalog.CatalogItem, Variant does not inherit from CatalogItem or any other common base class. Variant inherits directly from System.Object. Therefore, you cannot write an extension method that can be leveraged by both classes. The class definition documentation for all Catalog System objects (for the Core Systems API) can be found here <http://msdn.microsoft.com/en-us/library/microsoft.commerceserver.catalog(v=cs.70).aspx> ![enter image description here](https://i.stack.imgur.com/dwTHy.png) **OPTION 2 : Commerce Foundation API** If you are referring to Product and Variant in terms of objects being returned from calls to the Commerce Foundation, then ALL objects returned by requests using the Commerce Server Operation Service are returned as type ICommerceEntity. If you are using concrete data types to wrap CommerceEntity, then you can still use the .ToCommerceEntity() method and you could write your extension from ICommerceEntity. The only problem with that approach is ALL classes inheriting from ICommerceEntity would be able to use the extension methods. ![enter image description here](https://i.stack.imgur.com/eBxh1.gif) View <http://msdn.microsoft.com/en-us/library/dd451701.aspx> for more on concrete data types in Commerce Foundation.
19,687,959
I have an object of type `Product` and type `Variant`. `Variant` and `Product` have the same structure, but are two different types, and so I can't make just one method to encompass both. Is it possible to make an extension method that would accept both of these types?
2013/10/30
[ "https://Stackoverflow.com/questions/19687959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2316642/" ]
You cannot do that unless `Product` and `Variant` have common base class or interface. If they have common base class or interface then you can try to write extension method for it e.g. ``` public static void MyMethod(this ICommonInterface obj) {} ``` Otherwise you'll have to create two separate extensions methods. You can try to extract common code to a separate method which will be called from your extension methods.
You can not change the Product and Variant classes, but you can subclass them and apply a interface to the subclass. This interface can be used for the extension method: ``` using System; public class Program { public static void Main() { var p = new MyProduct(); p.Name = "test"; Console.WriteLine(p.GetName()); } } public class Product { public int Id { get; set; } public string Name { get; set; } public string Foo { get; set; } } public class Variant { public int Id { get; set; } public string Name { get; set; } public string Bar { get; set; } } public class MyProduct: Product, IType { } public class MyVariant: Variant, IType { } public static class Extensions { public static string GetName(this IType type){ return type.Name; } } public interface IType { string Name {get; set; } } ``` See: <https://dotnetfiddle.net/u1JJmJ>
19,687,959
I have an object of type `Product` and type `Variant`. `Variant` and `Product` have the same structure, but are two different types, and so I can't make just one method to encompass both. Is it possible to make an extension method that would accept both of these types?
2013/10/30
[ "https://Stackoverflow.com/questions/19687959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2316642/" ]
Steve, Two possible answers to this question from a Commerce Server perspective. Depends on whether you are talking about the Core Systems API or the Commerce Foundation API. I'll address both below: **OPTION 1 : Commerce Server Core Systems API** Unfortunately, the two classes Product and Variant DO NOT share a common base class (unless you count System.Object ;-). Although Microsoft.CommerceServer.Catalog.Product inherits from Microsoft.CommerceServer.Catalog.CatalogItem, Variant does not inherit from CatalogItem or any other common base class. Variant inherits directly from System.Object. Therefore, you cannot write an extension method that can be leveraged by both classes. The class definition documentation for all Catalog System objects (for the Core Systems API) can be found here <http://msdn.microsoft.com/en-us/library/microsoft.commerceserver.catalog(v=cs.70).aspx> ![enter image description here](https://i.stack.imgur.com/dwTHy.png) **OPTION 2 : Commerce Foundation API** If you are referring to Product and Variant in terms of objects being returned from calls to the Commerce Foundation, then ALL objects returned by requests using the Commerce Server Operation Service are returned as type ICommerceEntity. If you are using concrete data types to wrap CommerceEntity, then you can still use the .ToCommerceEntity() method and you could write your extension from ICommerceEntity. The only problem with that approach is ALL classes inheriting from ICommerceEntity would be able to use the extension methods. ![enter image description here](https://i.stack.imgur.com/eBxh1.gif) View <http://msdn.microsoft.com/en-us/library/dd451701.aspx> for more on concrete data types in Commerce Foundation.
You could take advantage of the `dynamic` type: ``` using System.Linq; class Program { static void Main(string[] args) { var myList = new object[] { new Product(){Id=1}, new Variant(){Id=1} }; Process(myList); } static void Process(object[] myList) { foreach (dynamic item in myList) { item.Id += 1; } } } class Product { public int Id { get; set; } public string Name { get; set; } public string Foo { get; set; } } class Variant { public int Id { get; set; } public string Name { get; set; } public string Bar { get; set; } } pub ``` Using an extension method: ``` public static class X { public static void Process(this object[] myList) { foreach (dynamic item in myList) { item.Id += 1; } } } ``` And the sample usage: ``` myList.Process(); ``` **Another alternative** ... is to use an object-object mapper such as [AutoMapper](http://www.nuget.org/packages/AutoMapper/). For the sample `Product` and `Variant` sample types above, you would have to define the members mapping with the following type which shares the common members of the 2 classes: ``` public class MyMapper { public int Id { get; set; } public string Name { get; set; } } ``` The members mapping looks like this: ``` Mapper.CreateMap<Product, MyMapper>() .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id)) .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name)); Mapper.CreateMap<Variant, MyMapper>() .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id)) .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name)); ``` And you might get a working `List<MyMapper>` like this: ``` var myMapperList = myList.Select(item => item.Map()).ToList(); ``` The `Map<T>` extension method: ``` public static MyMapper Map<T>(this T obj) { return (MyMapper)Mapper.Map(obj, obj.GetType(), typeof(MyMapper)); } ``` From this point further, you would define your extension methods for the `MyMapper` type.
19,687,959
I have an object of type `Product` and type `Variant`. `Variant` and `Product` have the same structure, but are two different types, and so I can't make just one method to encompass both. Is it possible to make an extension method that would accept both of these types?
2013/10/30
[ "https://Stackoverflow.com/questions/19687959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2316642/" ]
Steve, Two possible answers to this question from a Commerce Server perspective. Depends on whether you are talking about the Core Systems API or the Commerce Foundation API. I'll address both below: **OPTION 1 : Commerce Server Core Systems API** Unfortunately, the two classes Product and Variant DO NOT share a common base class (unless you count System.Object ;-). Although Microsoft.CommerceServer.Catalog.Product inherits from Microsoft.CommerceServer.Catalog.CatalogItem, Variant does not inherit from CatalogItem or any other common base class. Variant inherits directly from System.Object. Therefore, you cannot write an extension method that can be leveraged by both classes. The class definition documentation for all Catalog System objects (for the Core Systems API) can be found here <http://msdn.microsoft.com/en-us/library/microsoft.commerceserver.catalog(v=cs.70).aspx> ![enter image description here](https://i.stack.imgur.com/dwTHy.png) **OPTION 2 : Commerce Foundation API** If you are referring to Product and Variant in terms of objects being returned from calls to the Commerce Foundation, then ALL objects returned by requests using the Commerce Server Operation Service are returned as type ICommerceEntity. If you are using concrete data types to wrap CommerceEntity, then you can still use the .ToCommerceEntity() method and you could write your extension from ICommerceEntity. The only problem with that approach is ALL classes inheriting from ICommerceEntity would be able to use the extension methods. ![enter image description here](https://i.stack.imgur.com/eBxh1.gif) View <http://msdn.microsoft.com/en-us/library/dd451701.aspx> for more on concrete data types in Commerce Foundation.
You can not change the Product and Variant classes, but you can subclass them and apply a interface to the subclass. This interface can be used for the extension method: ``` using System; public class Program { public static void Main() { var p = new MyProduct(); p.Name = "test"; Console.WriteLine(p.GetName()); } } public class Product { public int Id { get; set; } public string Name { get; set; } public string Foo { get; set; } } public class Variant { public int Id { get; set; } public string Name { get; set; } public string Bar { get; set; } } public class MyProduct: Product, IType { } public class MyVariant: Variant, IType { } public static class Extensions { public static string GetName(this IType type){ return type.Name; } } public interface IType { string Name {get; set; } } ``` See: <https://dotnetfiddle.net/u1JJmJ>
22,728,427
i have android application that display a listview that extends Base Adapter to get image and text. now i want to add a header section for this list view how to do it ? can anyone help me ??? this is how the list view is shown ![enter image description here](https://i.stack.imgur.com/UXls0.png) **what i wnat is that before the first item display a header and before the last item to display a header.** activity\_group\_list.xml ========================= ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".GroupList" > <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" > </ListView> </RelativeLayout> ``` row\_list\_group.xml ==================== ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="5dip" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:src="@drawable/algeria_flag" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@+id/imageView1" android:ems="10" android:text="text" /> </RelativeLayout> ``` ItemDetails.java ================ ``` package com.devleb.expandablelistdemo3; public class ItemDetails { String Name; int image; public String getName() { return Name; } public void setName(String name) { Name = name; } public int getImage() { return image; } public void setImage(int image) { this.image = image; } } ``` CustomAdapter.java ================== ``` package com.devleb.expandablelistdemo3; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView.FindListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class CustomAdapter extends BaseAdapter { private static ArrayList<ItemDetails> itemDetailsarrayList; LayoutInflater layoutInflater; String[] teamName; int[] teamFlag; Context context; public CustomAdapter(ArrayList<ItemDetails> result, Context c) { itemDetailsarrayList = result; context = c; } @Override public int getCount() { // TODO Auto-generated method stub return itemDetailsarrayList.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return itemDetailsarrayList.get(arg0); } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return arg0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View row = layoutInflater.inflate(R.layout.row_list_group, parent, false); TextView txt = (TextView) row.findViewById(R.id.textView1); ImageView imgv = (ImageView) row.findViewById(R.id.imageView1); txt.setText(itemDetailsarrayList.get(position).getName()); imgv.setImageResource(itemDetailsarrayList.get(position).getImage()); return row; } } ``` GroupList.java ============== ``` package com.devleb.expandablelistdemo3; import java.lang.reflect.Array; import java.util.ArrayList; import android.os.Bundle; import android.app.Activity; import android.content.ClipData.Item; import android.view.Menu; import android.widget.ListView; public class GroupList extends Activity { int[] img = { R.drawable.brazil_flag, R.drawable.croatian_flag, R.drawable.mexico_flag, R.drawable.cameroon_flag, R.drawable.spain, R.drawable.netherlands_flag, R.drawable.czech_republic_flag, R.drawable.australia, R.drawable.colombia_flag, R.drawable.gress, R.drawable.cote_divoire_flag, R.drawable.japan, R.drawable.uruguay_flag, R.drawable.costa_rica_flag, R.drawable.england_flag, R.drawable.italy_flag, R.drawable.switzerland, R.drawable.ecuador_flag, R.drawable.france_flag, R.drawable.honduras_flag, R.drawable.argentina_flag, R.drawable.bousna, R.drawable.iran_flag, R.drawable.nigeria_flag, R.drawable.germany_flag, R.drawable.portugal, R.drawable.ghana_flag, R.drawable.united_states_flag, R.drawable.belgium_flag, R.drawable.algeria_flag, R.drawable.russia_flag, R.drawable.korea_flag }; String[] name = { "BRA", "CRO", "MEX", "CMR", "ESP", "NED", "CHI", "AUS", "COL", "GRE", "CIV", "JPN", "URU", "CRC", "ENG", "ITA", "SUI", "ECU", "FRA", "HON", "ARG", "BIH", "IRN", "NGA", "GER", "POR", "GHA", "USA", "BEL", "ALG", "RUS", "KOR" }; ItemDetails item_details; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group_list); ArrayList<ItemDetails> result = getList(); ListView lv = (ListView) findViewById(R.id.list); lv.setAdapter(new CustomAdapter(result, getApplicationContext())); } private ArrayList<ItemDetails> getList() { ArrayList<ItemDetails> results = new ArrayList<ItemDetails>(); for (int i = 0; i <32; i++) { item_details = new ItemDetails(); item_details.setName(name[i]); item_details.setImage(img[i]); results.add(item_details); } return results; } ``` added section ============= ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group_list); TextView txtSection = (TextView)findViewById(R.id.textSeparator); ArrayList<ItemDetails> result = getList(); lv = (ListView) findViewById(R.id.list); lv.addHeaderView(txtSection); lv.setAdapter(new CustomAdapter(result, getApplicationContext())); } private ArrayList<ItemDetails> getList() { ArrayList<ItemDetails> results = new ArrayList<ItemDetails>(); for (int i = 0; i <4; i++) { item_details = new ItemDetails(); View layout_section = getLayoutInflater().inflate(R.layout.activity_group_section_list, null); lv.addHeaderView(layout_section ); item_details.setName(name[i]); item_details.setImage(img[i]); results.add(item_details); } return results; } } ``` log cat ======= ``` 03-29 08:30:34.271: E/AndroidRuntime(2900): Caused by: java.lang.NullPointerException 03-29 08:30:34.271: E/AndroidRuntime(2900): at com.devleb.expandablelistdemo3.GroupList.getList(GroupList.java:59) ```
2014/03/29
[ "https://Stackoverflow.com/questions/22728427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3006788/" ]
Simply use the current system time to "undo" the seed by introducing a new unique random seed: ``` set.seed(Sys.time()) ``` If you need more precision, consider fetching the [system timestamp by millisecond](https://stackoverflow.com/questions/16548528/linux-command-to-get-time-in-milliseconds) (use R's `system(..., intern = TRUE)` function).
set.seed() just works for the first line containing randomly sample, and will not influence the next following command. If you want it to work for the other lines, you must call the set.seed function with the same "seed"-the parameter.
22,728,427
i have android application that display a listview that extends Base Adapter to get image and text. now i want to add a header section for this list view how to do it ? can anyone help me ??? this is how the list view is shown ![enter image description here](https://i.stack.imgur.com/UXls0.png) **what i wnat is that before the first item display a header and before the last item to display a header.** activity\_group\_list.xml ========================= ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".GroupList" > <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" > </ListView> </RelativeLayout> ``` row\_list\_group.xml ==================== ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="5dip" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:src="@drawable/algeria_flag" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@+id/imageView1" android:ems="10" android:text="text" /> </RelativeLayout> ``` ItemDetails.java ================ ``` package com.devleb.expandablelistdemo3; public class ItemDetails { String Name; int image; public String getName() { return Name; } public void setName(String name) { Name = name; } public int getImage() { return image; } public void setImage(int image) { this.image = image; } } ``` CustomAdapter.java ================== ``` package com.devleb.expandablelistdemo3; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView.FindListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class CustomAdapter extends BaseAdapter { private static ArrayList<ItemDetails> itemDetailsarrayList; LayoutInflater layoutInflater; String[] teamName; int[] teamFlag; Context context; public CustomAdapter(ArrayList<ItemDetails> result, Context c) { itemDetailsarrayList = result; context = c; } @Override public int getCount() { // TODO Auto-generated method stub return itemDetailsarrayList.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return itemDetailsarrayList.get(arg0); } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return arg0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View row = layoutInflater.inflate(R.layout.row_list_group, parent, false); TextView txt = (TextView) row.findViewById(R.id.textView1); ImageView imgv = (ImageView) row.findViewById(R.id.imageView1); txt.setText(itemDetailsarrayList.get(position).getName()); imgv.setImageResource(itemDetailsarrayList.get(position).getImage()); return row; } } ``` GroupList.java ============== ``` package com.devleb.expandablelistdemo3; import java.lang.reflect.Array; import java.util.ArrayList; import android.os.Bundle; import android.app.Activity; import android.content.ClipData.Item; import android.view.Menu; import android.widget.ListView; public class GroupList extends Activity { int[] img = { R.drawable.brazil_flag, R.drawable.croatian_flag, R.drawable.mexico_flag, R.drawable.cameroon_flag, R.drawable.spain, R.drawable.netherlands_flag, R.drawable.czech_republic_flag, R.drawable.australia, R.drawable.colombia_flag, R.drawable.gress, R.drawable.cote_divoire_flag, R.drawable.japan, R.drawable.uruguay_flag, R.drawable.costa_rica_flag, R.drawable.england_flag, R.drawable.italy_flag, R.drawable.switzerland, R.drawable.ecuador_flag, R.drawable.france_flag, R.drawable.honduras_flag, R.drawable.argentina_flag, R.drawable.bousna, R.drawable.iran_flag, R.drawable.nigeria_flag, R.drawable.germany_flag, R.drawable.portugal, R.drawable.ghana_flag, R.drawable.united_states_flag, R.drawable.belgium_flag, R.drawable.algeria_flag, R.drawable.russia_flag, R.drawable.korea_flag }; String[] name = { "BRA", "CRO", "MEX", "CMR", "ESP", "NED", "CHI", "AUS", "COL", "GRE", "CIV", "JPN", "URU", "CRC", "ENG", "ITA", "SUI", "ECU", "FRA", "HON", "ARG", "BIH", "IRN", "NGA", "GER", "POR", "GHA", "USA", "BEL", "ALG", "RUS", "KOR" }; ItemDetails item_details; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group_list); ArrayList<ItemDetails> result = getList(); ListView lv = (ListView) findViewById(R.id.list); lv.setAdapter(new CustomAdapter(result, getApplicationContext())); } private ArrayList<ItemDetails> getList() { ArrayList<ItemDetails> results = new ArrayList<ItemDetails>(); for (int i = 0; i <32; i++) { item_details = new ItemDetails(); item_details.setName(name[i]); item_details.setImage(img[i]); results.add(item_details); } return results; } ``` added section ============= ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group_list); TextView txtSection = (TextView)findViewById(R.id.textSeparator); ArrayList<ItemDetails> result = getList(); lv = (ListView) findViewById(R.id.list); lv.addHeaderView(txtSection); lv.setAdapter(new CustomAdapter(result, getApplicationContext())); } private ArrayList<ItemDetails> getList() { ArrayList<ItemDetails> results = new ArrayList<ItemDetails>(); for (int i = 0; i <4; i++) { item_details = new ItemDetails(); View layout_section = getLayoutInflater().inflate(R.layout.activity_group_section_list, null); lv.addHeaderView(layout_section ); item_details.setName(name[i]); item_details.setImage(img[i]); results.add(item_details); } return results; } } ``` log cat ======= ``` 03-29 08:30:34.271: E/AndroidRuntime(2900): Caused by: java.lang.NullPointerException 03-29 08:30:34.271: E/AndroidRuntime(2900): at com.devleb.expandablelistdemo3.GroupList.getList(GroupList.java:59) ```
2014/03/29
[ "https://Stackoverflow.com/questions/22728427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3006788/" ]
Simply use the current system time to "undo" the seed by introducing a new unique random seed: ``` set.seed(Sys.time()) ``` If you need more precision, consider fetching the [system timestamp by millisecond](https://stackoverflow.com/questions/16548528/linux-command-to-get-time-in-milliseconds) (use R's `system(..., intern = TRUE)` function).
set.seed() only works for the next execution. so what you want is already happening. see this example ``` set.seed(12) sample(1:15, 5) ``` [1] 2 12 13 4 15 ``` sample(1:15, 5) # run the same code again you will see different results ``` [1] 1 3 9 15 12 ``` set.seed(12)#set seed again to see first set of results sample(1:15, 5) ``` [1] 2 12 13 4 15
22,728,427
i have android application that display a listview that extends Base Adapter to get image and text. now i want to add a header section for this list view how to do it ? can anyone help me ??? this is how the list view is shown ![enter image description here](https://i.stack.imgur.com/UXls0.png) **what i wnat is that before the first item display a header and before the last item to display a header.** activity\_group\_list.xml ========================= ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".GroupList" > <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" > </ListView> </RelativeLayout> ``` row\_list\_group.xml ==================== ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="5dip" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:src="@drawable/algeria_flag" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@+id/imageView1" android:ems="10" android:text="text" /> </RelativeLayout> ``` ItemDetails.java ================ ``` package com.devleb.expandablelistdemo3; public class ItemDetails { String Name; int image; public String getName() { return Name; } public void setName(String name) { Name = name; } public int getImage() { return image; } public void setImage(int image) { this.image = image; } } ``` CustomAdapter.java ================== ``` package com.devleb.expandablelistdemo3; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView.FindListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class CustomAdapter extends BaseAdapter { private static ArrayList<ItemDetails> itemDetailsarrayList; LayoutInflater layoutInflater; String[] teamName; int[] teamFlag; Context context; public CustomAdapter(ArrayList<ItemDetails> result, Context c) { itemDetailsarrayList = result; context = c; } @Override public int getCount() { // TODO Auto-generated method stub return itemDetailsarrayList.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return itemDetailsarrayList.get(arg0); } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return arg0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View row = layoutInflater.inflate(R.layout.row_list_group, parent, false); TextView txt = (TextView) row.findViewById(R.id.textView1); ImageView imgv = (ImageView) row.findViewById(R.id.imageView1); txt.setText(itemDetailsarrayList.get(position).getName()); imgv.setImageResource(itemDetailsarrayList.get(position).getImage()); return row; } } ``` GroupList.java ============== ``` package com.devleb.expandablelistdemo3; import java.lang.reflect.Array; import java.util.ArrayList; import android.os.Bundle; import android.app.Activity; import android.content.ClipData.Item; import android.view.Menu; import android.widget.ListView; public class GroupList extends Activity { int[] img = { R.drawable.brazil_flag, R.drawable.croatian_flag, R.drawable.mexico_flag, R.drawable.cameroon_flag, R.drawable.spain, R.drawable.netherlands_flag, R.drawable.czech_republic_flag, R.drawable.australia, R.drawable.colombia_flag, R.drawable.gress, R.drawable.cote_divoire_flag, R.drawable.japan, R.drawable.uruguay_flag, R.drawable.costa_rica_flag, R.drawable.england_flag, R.drawable.italy_flag, R.drawable.switzerland, R.drawable.ecuador_flag, R.drawable.france_flag, R.drawable.honduras_flag, R.drawable.argentina_flag, R.drawable.bousna, R.drawable.iran_flag, R.drawable.nigeria_flag, R.drawable.germany_flag, R.drawable.portugal, R.drawable.ghana_flag, R.drawable.united_states_flag, R.drawable.belgium_flag, R.drawable.algeria_flag, R.drawable.russia_flag, R.drawable.korea_flag }; String[] name = { "BRA", "CRO", "MEX", "CMR", "ESP", "NED", "CHI", "AUS", "COL", "GRE", "CIV", "JPN", "URU", "CRC", "ENG", "ITA", "SUI", "ECU", "FRA", "HON", "ARG", "BIH", "IRN", "NGA", "GER", "POR", "GHA", "USA", "BEL", "ALG", "RUS", "KOR" }; ItemDetails item_details; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group_list); ArrayList<ItemDetails> result = getList(); ListView lv = (ListView) findViewById(R.id.list); lv.setAdapter(new CustomAdapter(result, getApplicationContext())); } private ArrayList<ItemDetails> getList() { ArrayList<ItemDetails> results = new ArrayList<ItemDetails>(); for (int i = 0; i <32; i++) { item_details = new ItemDetails(); item_details.setName(name[i]); item_details.setImage(img[i]); results.add(item_details); } return results; } ``` added section ============= ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group_list); TextView txtSection = (TextView)findViewById(R.id.textSeparator); ArrayList<ItemDetails> result = getList(); lv = (ListView) findViewById(R.id.list); lv.addHeaderView(txtSection); lv.setAdapter(new CustomAdapter(result, getApplicationContext())); } private ArrayList<ItemDetails> getList() { ArrayList<ItemDetails> results = new ArrayList<ItemDetails>(); for (int i = 0; i <4; i++) { item_details = new ItemDetails(); View layout_section = getLayoutInflater().inflate(R.layout.activity_group_section_list, null); lv.addHeaderView(layout_section ); item_details.setName(name[i]); item_details.setImage(img[i]); results.add(item_details); } return results; } } ``` log cat ======= ``` 03-29 08:30:34.271: E/AndroidRuntime(2900): Caused by: java.lang.NullPointerException 03-29 08:30:34.271: E/AndroidRuntime(2900): at com.devleb.expandablelistdemo3.GroupList.getList(GroupList.java:59) ```
2014/03/29
[ "https://Stackoverflow.com/questions/22728427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3006788/" ]
Simply use the current system time to "undo" the seed by introducing a new unique random seed: ``` set.seed(Sys.time()) ``` If you need more precision, consider fetching the [system timestamp by millisecond](https://stackoverflow.com/questions/16548528/linux-command-to-get-time-in-milliseconds) (use R's `system(..., intern = TRUE)` function).
``` set.seed(NULL) ``` See help documents - `?set.seed`: > > "If called with seed = NULL it re-initializes (see ‘Note’) as if no seed had yet been set." > > >
22,728,427
i have android application that display a listview that extends Base Adapter to get image and text. now i want to add a header section for this list view how to do it ? can anyone help me ??? this is how the list view is shown ![enter image description here](https://i.stack.imgur.com/UXls0.png) **what i wnat is that before the first item display a header and before the last item to display a header.** activity\_group\_list.xml ========================= ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".GroupList" > <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" > </ListView> </RelativeLayout> ``` row\_list\_group.xml ==================== ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="5dip" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:src="@drawable/algeria_flag" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@+id/imageView1" android:ems="10" android:text="text" /> </RelativeLayout> ``` ItemDetails.java ================ ``` package com.devleb.expandablelistdemo3; public class ItemDetails { String Name; int image; public String getName() { return Name; } public void setName(String name) { Name = name; } public int getImage() { return image; } public void setImage(int image) { this.image = image; } } ``` CustomAdapter.java ================== ``` package com.devleb.expandablelistdemo3; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView.FindListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class CustomAdapter extends BaseAdapter { private static ArrayList<ItemDetails> itemDetailsarrayList; LayoutInflater layoutInflater; String[] teamName; int[] teamFlag; Context context; public CustomAdapter(ArrayList<ItemDetails> result, Context c) { itemDetailsarrayList = result; context = c; } @Override public int getCount() { // TODO Auto-generated method stub return itemDetailsarrayList.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return itemDetailsarrayList.get(arg0); } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return arg0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View row = layoutInflater.inflate(R.layout.row_list_group, parent, false); TextView txt = (TextView) row.findViewById(R.id.textView1); ImageView imgv = (ImageView) row.findViewById(R.id.imageView1); txt.setText(itemDetailsarrayList.get(position).getName()); imgv.setImageResource(itemDetailsarrayList.get(position).getImage()); return row; } } ``` GroupList.java ============== ``` package com.devleb.expandablelistdemo3; import java.lang.reflect.Array; import java.util.ArrayList; import android.os.Bundle; import android.app.Activity; import android.content.ClipData.Item; import android.view.Menu; import android.widget.ListView; public class GroupList extends Activity { int[] img = { R.drawable.brazil_flag, R.drawable.croatian_flag, R.drawable.mexico_flag, R.drawable.cameroon_flag, R.drawable.spain, R.drawable.netherlands_flag, R.drawable.czech_republic_flag, R.drawable.australia, R.drawable.colombia_flag, R.drawable.gress, R.drawable.cote_divoire_flag, R.drawable.japan, R.drawable.uruguay_flag, R.drawable.costa_rica_flag, R.drawable.england_flag, R.drawable.italy_flag, R.drawable.switzerland, R.drawable.ecuador_flag, R.drawable.france_flag, R.drawable.honduras_flag, R.drawable.argentina_flag, R.drawable.bousna, R.drawable.iran_flag, R.drawable.nigeria_flag, R.drawable.germany_flag, R.drawable.portugal, R.drawable.ghana_flag, R.drawable.united_states_flag, R.drawable.belgium_flag, R.drawable.algeria_flag, R.drawable.russia_flag, R.drawable.korea_flag }; String[] name = { "BRA", "CRO", "MEX", "CMR", "ESP", "NED", "CHI", "AUS", "COL", "GRE", "CIV", "JPN", "URU", "CRC", "ENG", "ITA", "SUI", "ECU", "FRA", "HON", "ARG", "BIH", "IRN", "NGA", "GER", "POR", "GHA", "USA", "BEL", "ALG", "RUS", "KOR" }; ItemDetails item_details; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group_list); ArrayList<ItemDetails> result = getList(); ListView lv = (ListView) findViewById(R.id.list); lv.setAdapter(new CustomAdapter(result, getApplicationContext())); } private ArrayList<ItemDetails> getList() { ArrayList<ItemDetails> results = new ArrayList<ItemDetails>(); for (int i = 0; i <32; i++) { item_details = new ItemDetails(); item_details.setName(name[i]); item_details.setImage(img[i]); results.add(item_details); } return results; } ``` added section ============= ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group_list); TextView txtSection = (TextView)findViewById(R.id.textSeparator); ArrayList<ItemDetails> result = getList(); lv = (ListView) findViewById(R.id.list); lv.addHeaderView(txtSection); lv.setAdapter(new CustomAdapter(result, getApplicationContext())); } private ArrayList<ItemDetails> getList() { ArrayList<ItemDetails> results = new ArrayList<ItemDetails>(); for (int i = 0; i <4; i++) { item_details = new ItemDetails(); View layout_section = getLayoutInflater().inflate(R.layout.activity_group_section_list, null); lv.addHeaderView(layout_section ); item_details.setName(name[i]); item_details.setImage(img[i]); results.add(item_details); } return results; } } ``` log cat ======= ``` 03-29 08:30:34.271: E/AndroidRuntime(2900): Caused by: java.lang.NullPointerException 03-29 08:30:34.271: E/AndroidRuntime(2900): at com.devleb.expandablelistdemo3.GroupList.getList(GroupList.java:59) ```
2014/03/29
[ "https://Stackoverflow.com/questions/22728427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3006788/" ]
set.seed() only works for the next execution. so what you want is already happening. see this example ``` set.seed(12) sample(1:15, 5) ``` [1] 2 12 13 4 15 ``` sample(1:15, 5) # run the same code again you will see different results ``` [1] 1 3 9 15 12 ``` set.seed(12)#set seed again to see first set of results sample(1:15, 5) ``` [1] 2 12 13 4 15
set.seed() just works for the first line containing randomly sample, and will not influence the next following command. If you want it to work for the other lines, you must call the set.seed function with the same "seed"-the parameter.
22,728,427
i have android application that display a listview that extends Base Adapter to get image and text. now i want to add a header section for this list view how to do it ? can anyone help me ??? this is how the list view is shown ![enter image description here](https://i.stack.imgur.com/UXls0.png) **what i wnat is that before the first item display a header and before the last item to display a header.** activity\_group\_list.xml ========================= ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".GroupList" > <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" > </ListView> </RelativeLayout> ``` row\_list\_group.xml ==================== ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="5dip" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:src="@drawable/algeria_flag" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@+id/imageView1" android:ems="10" android:text="text" /> </RelativeLayout> ``` ItemDetails.java ================ ``` package com.devleb.expandablelistdemo3; public class ItemDetails { String Name; int image; public String getName() { return Name; } public void setName(String name) { Name = name; } public int getImage() { return image; } public void setImage(int image) { this.image = image; } } ``` CustomAdapter.java ================== ``` package com.devleb.expandablelistdemo3; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView.FindListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class CustomAdapter extends BaseAdapter { private static ArrayList<ItemDetails> itemDetailsarrayList; LayoutInflater layoutInflater; String[] teamName; int[] teamFlag; Context context; public CustomAdapter(ArrayList<ItemDetails> result, Context c) { itemDetailsarrayList = result; context = c; } @Override public int getCount() { // TODO Auto-generated method stub return itemDetailsarrayList.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return itemDetailsarrayList.get(arg0); } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return arg0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View row = layoutInflater.inflate(R.layout.row_list_group, parent, false); TextView txt = (TextView) row.findViewById(R.id.textView1); ImageView imgv = (ImageView) row.findViewById(R.id.imageView1); txt.setText(itemDetailsarrayList.get(position).getName()); imgv.setImageResource(itemDetailsarrayList.get(position).getImage()); return row; } } ``` GroupList.java ============== ``` package com.devleb.expandablelistdemo3; import java.lang.reflect.Array; import java.util.ArrayList; import android.os.Bundle; import android.app.Activity; import android.content.ClipData.Item; import android.view.Menu; import android.widget.ListView; public class GroupList extends Activity { int[] img = { R.drawable.brazil_flag, R.drawable.croatian_flag, R.drawable.mexico_flag, R.drawable.cameroon_flag, R.drawable.spain, R.drawable.netherlands_flag, R.drawable.czech_republic_flag, R.drawable.australia, R.drawable.colombia_flag, R.drawable.gress, R.drawable.cote_divoire_flag, R.drawable.japan, R.drawable.uruguay_flag, R.drawable.costa_rica_flag, R.drawable.england_flag, R.drawable.italy_flag, R.drawable.switzerland, R.drawable.ecuador_flag, R.drawable.france_flag, R.drawable.honduras_flag, R.drawable.argentina_flag, R.drawable.bousna, R.drawable.iran_flag, R.drawable.nigeria_flag, R.drawable.germany_flag, R.drawable.portugal, R.drawable.ghana_flag, R.drawable.united_states_flag, R.drawable.belgium_flag, R.drawable.algeria_flag, R.drawable.russia_flag, R.drawable.korea_flag }; String[] name = { "BRA", "CRO", "MEX", "CMR", "ESP", "NED", "CHI", "AUS", "COL", "GRE", "CIV", "JPN", "URU", "CRC", "ENG", "ITA", "SUI", "ECU", "FRA", "HON", "ARG", "BIH", "IRN", "NGA", "GER", "POR", "GHA", "USA", "BEL", "ALG", "RUS", "KOR" }; ItemDetails item_details; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group_list); ArrayList<ItemDetails> result = getList(); ListView lv = (ListView) findViewById(R.id.list); lv.setAdapter(new CustomAdapter(result, getApplicationContext())); } private ArrayList<ItemDetails> getList() { ArrayList<ItemDetails> results = new ArrayList<ItemDetails>(); for (int i = 0; i <32; i++) { item_details = new ItemDetails(); item_details.setName(name[i]); item_details.setImage(img[i]); results.add(item_details); } return results; } ``` added section ============= ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group_list); TextView txtSection = (TextView)findViewById(R.id.textSeparator); ArrayList<ItemDetails> result = getList(); lv = (ListView) findViewById(R.id.list); lv.addHeaderView(txtSection); lv.setAdapter(new CustomAdapter(result, getApplicationContext())); } private ArrayList<ItemDetails> getList() { ArrayList<ItemDetails> results = new ArrayList<ItemDetails>(); for (int i = 0; i <4; i++) { item_details = new ItemDetails(); View layout_section = getLayoutInflater().inflate(R.layout.activity_group_section_list, null); lv.addHeaderView(layout_section ); item_details.setName(name[i]); item_details.setImage(img[i]); results.add(item_details); } return results; } } ``` log cat ======= ``` 03-29 08:30:34.271: E/AndroidRuntime(2900): Caused by: java.lang.NullPointerException 03-29 08:30:34.271: E/AndroidRuntime(2900): at com.devleb.expandablelistdemo3.GroupList.getList(GroupList.java:59) ```
2014/03/29
[ "https://Stackoverflow.com/questions/22728427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3006788/" ]
``` set.seed(NULL) ``` See help documents - `?set.seed`: > > "If called with seed = NULL it re-initializes (see ‘Note’) as if no seed had yet been set." > > >
set.seed() just works for the first line containing randomly sample, and will not influence the next following command. If you want it to work for the other lines, you must call the set.seed function with the same "seed"-the parameter.
22,728,427
i have android application that display a listview that extends Base Adapter to get image and text. now i want to add a header section for this list view how to do it ? can anyone help me ??? this is how the list view is shown ![enter image description here](https://i.stack.imgur.com/UXls0.png) **what i wnat is that before the first item display a header and before the last item to display a header.** activity\_group\_list.xml ========================= ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".GroupList" > <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" > </ListView> </RelativeLayout> ``` row\_list\_group.xml ==================== ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="5dip" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:src="@drawable/algeria_flag" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@+id/imageView1" android:ems="10" android:text="text" /> </RelativeLayout> ``` ItemDetails.java ================ ``` package com.devleb.expandablelistdemo3; public class ItemDetails { String Name; int image; public String getName() { return Name; } public void setName(String name) { Name = name; } public int getImage() { return image; } public void setImage(int image) { this.image = image; } } ``` CustomAdapter.java ================== ``` package com.devleb.expandablelistdemo3; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView.FindListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class CustomAdapter extends BaseAdapter { private static ArrayList<ItemDetails> itemDetailsarrayList; LayoutInflater layoutInflater; String[] teamName; int[] teamFlag; Context context; public CustomAdapter(ArrayList<ItemDetails> result, Context c) { itemDetailsarrayList = result; context = c; } @Override public int getCount() { // TODO Auto-generated method stub return itemDetailsarrayList.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return itemDetailsarrayList.get(arg0); } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return arg0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View row = layoutInflater.inflate(R.layout.row_list_group, parent, false); TextView txt = (TextView) row.findViewById(R.id.textView1); ImageView imgv = (ImageView) row.findViewById(R.id.imageView1); txt.setText(itemDetailsarrayList.get(position).getName()); imgv.setImageResource(itemDetailsarrayList.get(position).getImage()); return row; } } ``` GroupList.java ============== ``` package com.devleb.expandablelistdemo3; import java.lang.reflect.Array; import java.util.ArrayList; import android.os.Bundle; import android.app.Activity; import android.content.ClipData.Item; import android.view.Menu; import android.widget.ListView; public class GroupList extends Activity { int[] img = { R.drawable.brazil_flag, R.drawable.croatian_flag, R.drawable.mexico_flag, R.drawable.cameroon_flag, R.drawable.spain, R.drawable.netherlands_flag, R.drawable.czech_republic_flag, R.drawable.australia, R.drawable.colombia_flag, R.drawable.gress, R.drawable.cote_divoire_flag, R.drawable.japan, R.drawable.uruguay_flag, R.drawable.costa_rica_flag, R.drawable.england_flag, R.drawable.italy_flag, R.drawable.switzerland, R.drawable.ecuador_flag, R.drawable.france_flag, R.drawable.honduras_flag, R.drawable.argentina_flag, R.drawable.bousna, R.drawable.iran_flag, R.drawable.nigeria_flag, R.drawable.germany_flag, R.drawable.portugal, R.drawable.ghana_flag, R.drawable.united_states_flag, R.drawable.belgium_flag, R.drawable.algeria_flag, R.drawable.russia_flag, R.drawable.korea_flag }; String[] name = { "BRA", "CRO", "MEX", "CMR", "ESP", "NED", "CHI", "AUS", "COL", "GRE", "CIV", "JPN", "URU", "CRC", "ENG", "ITA", "SUI", "ECU", "FRA", "HON", "ARG", "BIH", "IRN", "NGA", "GER", "POR", "GHA", "USA", "BEL", "ALG", "RUS", "KOR" }; ItemDetails item_details; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group_list); ArrayList<ItemDetails> result = getList(); ListView lv = (ListView) findViewById(R.id.list); lv.setAdapter(new CustomAdapter(result, getApplicationContext())); } private ArrayList<ItemDetails> getList() { ArrayList<ItemDetails> results = new ArrayList<ItemDetails>(); for (int i = 0; i <32; i++) { item_details = new ItemDetails(); item_details.setName(name[i]); item_details.setImage(img[i]); results.add(item_details); } return results; } ``` added section ============= ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group_list); TextView txtSection = (TextView)findViewById(R.id.textSeparator); ArrayList<ItemDetails> result = getList(); lv = (ListView) findViewById(R.id.list); lv.addHeaderView(txtSection); lv.setAdapter(new CustomAdapter(result, getApplicationContext())); } private ArrayList<ItemDetails> getList() { ArrayList<ItemDetails> results = new ArrayList<ItemDetails>(); for (int i = 0; i <4; i++) { item_details = new ItemDetails(); View layout_section = getLayoutInflater().inflate(R.layout.activity_group_section_list, null); lv.addHeaderView(layout_section ); item_details.setName(name[i]); item_details.setImage(img[i]); results.add(item_details); } return results; } } ``` log cat ======= ``` 03-29 08:30:34.271: E/AndroidRuntime(2900): Caused by: java.lang.NullPointerException 03-29 08:30:34.271: E/AndroidRuntime(2900): at com.devleb.expandablelistdemo3.GroupList.getList(GroupList.java:59) ```
2014/03/29
[ "https://Stackoverflow.com/questions/22728427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3006788/" ]
``` set.seed(NULL) ``` See help documents - `?set.seed`: > > "If called with seed = NULL it re-initializes (see ‘Note’) as if no seed had yet been set." > > >
set.seed() only works for the next execution. so what you want is already happening. see this example ``` set.seed(12) sample(1:15, 5) ``` [1] 2 12 13 4 15 ``` sample(1:15, 5) # run the same code again you will see different results ``` [1] 1 3 9 15 12 ``` set.seed(12)#set seed again to see first set of results sample(1:15, 5) ``` [1] 2 12 13 4 15
5,889,160
I am currently trying to check my db table to see if a user's level is equal to or less than 10, if so then show an entire html list, if not and is equal or less than 5 show only the remaining part of the list. Here's where I started: ``` <?php $levels = mysql_query("SELECT level FROM users"); if ($levels <= 10) { ?> html list <?php if ($levels <= 5) ?> html list <?php } ?> ``` I am trying to wrap my head around it, I just can't seem to get it.
2011/05/04
[ "https://Stackoverflow.com/questions/5889160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/726082/" ]
Try this: ``` <?php if ($levels <= 5): ?> html list <?php elseif ($levels <= 10): ?> html list <?php endif; ?> ``` As [David Fells said](https://stackoverflow.com/questions/5889160/php-if-statment-for-showing-certain-blocks-of-html/5889185#5889185), make sure you are getting a result first :) **EDIT**: I misread your question I think. Try this instead: ``` <?php if ($levels <= 10): /* If equal to or less than 10 */ ?> <?php if ($levels > 5): /* if greater than 5 */ ?> first part of html list <?php endif; ?> second part of html list <?php endif; ?> ``` I was confused by this: > > if a user's level is equal to or less than 10, if so then show an entire html list, ***if not*** and is equal or less than 5 show only the remaining part of the list > > > ..as 0-5 will be less or equal to ten. Please excuse the mixup, GL!
You need to ask for the levels <= 5 before levels <= 10, because levels <= 10 will always find levels <= 5.
5,889,160
I am currently trying to check my db table to see if a user's level is equal to or less than 10, if so then show an entire html list, if not and is equal or less than 5 show only the remaining part of the list. Here's where I started: ``` <?php $levels = mysql_query("SELECT level FROM users"); if ($levels <= 10) { ?> html list <?php if ($levels <= 5) ?> html list <?php } ?> ``` I am trying to wrap my head around it, I just can't seem to get it.
2011/05/04
[ "https://Stackoverflow.com/questions/5889160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/726082/" ]
Try this: ``` <?php if ($levels <= 5): ?> html list <?php elseif ($levels <= 10): ?> html list <?php endif; ?> ``` As [David Fells said](https://stackoverflow.com/questions/5889160/php-if-statment-for-showing-certain-blocks-of-html/5889185#5889185), make sure you are getting a result first :) **EDIT**: I misread your question I think. Try this instead: ``` <?php if ($levels <= 10): /* If equal to or less than 10 */ ?> <?php if ($levels > 5): /* if greater than 5 */ ?> first part of html list <?php endif; ?> second part of html list <?php endif; ?> ``` I was confused by this: > > if a user's level is equal to or less than 10, if so then show an entire html list, ***if not*** and is equal or less than 5 show only the remaining part of the list > > > ..as 0-5 will be less or equal to ten. Please excuse the mixup, GL!
The code has lots of bugs- Firstly, ``` $levels = mysql_query("SELECT level FROM users"); ``` returns an array with levels of all the users. You want to query specific user's level using WHERE clause. Next , when you want to differentiate between <=5 and btween 5 &10, u need to use either of the methods ``` if($levels>5 && $levels <=10){ `enter code here` }elseif($levels<=5){ `enter code here` } ``` Or ``` if($levels<=5){ `enter code here` }elseif($levels<=10){ `enter code here` } ``` I prefer the second one in this case as it involves one less comparison. Next, you look like just beginning out in PHP. You did not close the braces and did not use else statements.
5,889,160
I am currently trying to check my db table to see if a user's level is equal to or less than 10, if so then show an entire html list, if not and is equal or less than 5 show only the remaining part of the list. Here's where I started: ``` <?php $levels = mysql_query("SELECT level FROM users"); if ($levels <= 10) { ?> html list <?php if ($levels <= 5) ?> html list <?php } ?> ``` I am trying to wrap my head around it, I just can't seem to get it.
2011/05/04
[ "https://Stackoverflow.com/questions/5889160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/726082/" ]
``` $result = mysql_query(sprintf("SELECT level FROM users WHERE user_id = %d", $current_user_id)); if (list($level) = mysql_fetch_array($result)) { if ($level <= 5) { // whatever } elseif ($level <= 10) { // whatever } else { // whatever } } ``` Does that clear it up at all? You need to supply the ID of the current user, and then you need to actually retrieve the value from the $result. The $result is a variable of type resource, and you have to work on it with functions designed to do so.
You need to ask for the levels <= 5 before levels <= 10, because levels <= 10 will always find levels <= 5.
5,889,160
I am currently trying to check my db table to see if a user's level is equal to or less than 10, if so then show an entire html list, if not and is equal or less than 5 show only the remaining part of the list. Here's where I started: ``` <?php $levels = mysql_query("SELECT level FROM users"); if ($levels <= 10) { ?> html list <?php if ($levels <= 5) ?> html list <?php } ?> ``` I am trying to wrap my head around it, I just can't seem to get it.
2011/05/04
[ "https://Stackoverflow.com/questions/5889160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/726082/" ]
``` $result = mysql_query(sprintf("SELECT level FROM users WHERE user_id = %d", $current_user_id)); if (list($level) = mysql_fetch_array($result)) { if ($level <= 5) { // whatever } elseif ($level <= 10) { // whatever } else { // whatever } } ``` Does that clear it up at all? You need to supply the ID of the current user, and then you need to actually retrieve the value from the $result. The $result is a variable of type resource, and you have to work on it with functions designed to do so.
The code has lots of bugs- Firstly, ``` $levels = mysql_query("SELECT level FROM users"); ``` returns an array with levels of all the users. You want to query specific user's level using WHERE clause. Next , when you want to differentiate between <=5 and btween 5 &10, u need to use either of the methods ``` if($levels>5 && $levels <=10){ `enter code here` }elseif($levels<=5){ `enter code here` } ``` Or ``` if($levels<=5){ `enter code here` }elseif($levels<=10){ `enter code here` } ``` I prefer the second one in this case as it involves one less comparison. Next, you look like just beginning out in PHP. You did not close the braces and did not use else statements.
41,238,403
I am using Hazelast Map and trying to store Objects against key which is object of my custom class i.e. `HMapKey`. Here is snippet of `HMapKey` class. ``` public class HMapKey implements Serializable{ private String keyCode; private long time; public HMapKey(String keyCode, long time) { this.keyCode = keyCode; this.time = time; } public String getKeyCode() { return keyCode; } public void setKeyCode(String keyCode) { this.keyCode = keyCode; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((keyCode == null) ? 0 : keyCode.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HMapKey other = (HMapKey) obj; if (keyCode == null) { if (other.keyCode != null) return false; } else if (!keyCode.equals(other.keyCode)) return false; return true; } } ``` As you can see in above code, I have used only `keyCode` in equals() method to compare two objects. So no matter what value is there for `time` variable. But when I use this object as key in Hazelcast's Map, and try to retrieve it, I think Hazelcast checking each and every variable of key class, because of this, even if I have same `keyCode` variable value and different `time` variable, Hazelcast returning me as `NULL`. Is there any configuration to tell Hazelcast not to go for all variable checking and use existing `equals()` method only? Here is code how I am trying to retrieve data from map ``` HazelcastInstance instance = Hazelcast.newHazelcastInstance(); private static ConcurrentMap<HMapKey, String> testMap = instance.getMap("TEST_MAP"); testMap.put(new HMapKey("code1",123), "This is Code 1"); System.out.println(testMap.get(new HMapKey("code1",0))); ``` Means, while insertion, I have created key object like `new HMapKey("code1",123)` but while retrieving it, I am creating new object as `new HMapKey("code1",0)` and this is returning me as null value. Whereas if I try with `new HMapKey("code1",123)` it's working fine.
2016/12/20
[ "https://Stackoverflow.com/questions/41238403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2074626/" ]
First of all, I don't know what you're trying to do when you say "I try to retrieve it". If you use your key as in the get method everything works fine: ``` @Test public void test() { HazelcastInstance hz = createHazelcastInstance(); IMap<HMapKey, Integer> map = hz.getMap("aaa"); HMapKey key = new HMapKey(); key.keyCode = "code1"; key.time = 123; HMapKey key2 = new HMapKey(); key2.keyCode = "code2"; key2.time = 246; map.put(key, 1); map.put(key2, 2); int value = map.get(key); assertEquals(value, 1); } ``` If you want to retrieve a value basing on the whole key value the HMapKey needs to implement `Comparable`. Then you can query like this: `map.values(Predicates.equal("__key", yourHKMapKeyInstance));`
Hazelcast does not deserialize the keys / values and executes `equals` or `hashCode` methods but compares the serialized objects by their corresponding bytestream. If you're searching for one or more properties, please see the answer from Tom <https://stackoverflow.com/a/41238649/917336>
41,238,403
I am using Hazelast Map and trying to store Objects against key which is object of my custom class i.e. `HMapKey`. Here is snippet of `HMapKey` class. ``` public class HMapKey implements Serializable{ private String keyCode; private long time; public HMapKey(String keyCode, long time) { this.keyCode = keyCode; this.time = time; } public String getKeyCode() { return keyCode; } public void setKeyCode(String keyCode) { this.keyCode = keyCode; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((keyCode == null) ? 0 : keyCode.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HMapKey other = (HMapKey) obj; if (keyCode == null) { if (other.keyCode != null) return false; } else if (!keyCode.equals(other.keyCode)) return false; return true; } } ``` As you can see in above code, I have used only `keyCode` in equals() method to compare two objects. So no matter what value is there for `time` variable. But when I use this object as key in Hazelcast's Map, and try to retrieve it, I think Hazelcast checking each and every variable of key class, because of this, even if I have same `keyCode` variable value and different `time` variable, Hazelcast returning me as `NULL`. Is there any configuration to tell Hazelcast not to go for all variable checking and use existing `equals()` method only? Here is code how I am trying to retrieve data from map ``` HazelcastInstance instance = Hazelcast.newHazelcastInstance(); private static ConcurrentMap<HMapKey, String> testMap = instance.getMap("TEST_MAP"); testMap.put(new HMapKey("code1",123), "This is Code 1"); System.out.println(testMap.get(new HMapKey("code1",0))); ``` Means, while insertion, I have created key object like `new HMapKey("code1",123)` but while retrieving it, I am creating new object as `new HMapKey("code1",0)` and this is returning me as null value. Whereas if I try with `new HMapKey("code1",123)` it's working fine.
2016/12/20
[ "https://Stackoverflow.com/questions/41238403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2074626/" ]
You can achieve that by declaring variable `time` as `transient`. But note that it will lead to collisions and give random results. Your put operation would overwrite the previous value even though it's properties are different. ``` HazelcastInstance instance = Hazelcast.newHazelcastInstance(); IMap<HMapKey, String> testMap = instance.getMap("TEST_MAP"); testMap.put(new HMapKey("code1",123), "This is Code 1"); System.out.println("HMapKey with time=0: " + testMap.get(new HMapKey("code1",0))); System.out.println("HMapKey with time=123: " + testMap.get(new HMapKey("code1",123))); testMap.put(new HMapKey("code1",456), "This is Code 2"); System.out.println("HMapKey with time=123: " + testMap.get(new HMapKey("code1",123))); ``` Output would be: ``` HMapKey with time=0: This is Code 1 HMapKey with time=123: This is Code 1 HMapKey with time=123: This is Code 2 ```
Hazelcast does not deserialize the keys / values and executes `equals` or `hashCode` methods but compares the serialized objects by their corresponding bytestream. If you're searching for one or more properties, please see the answer from Tom <https://stackoverflow.com/a/41238649/917336>
9,456,111
As I read from [android sample](http://developer.android.com/resources/tutorials/notepad/index.html), if I use SimpleCursorAdapter, it automatically set the id of list view to primary key of the table, so if I call the following event : ``` protected void onListItemClick(ListView l, View v, int position, long id) { ...... } ``` I can easily determine which item (row) of database has been selected, by reading the id parameter. But I am populating my list view by implementing my own custom ArrayAdapter. As I explained in my former [question](https://stackoverflow.com/questions/9444101/android-widget-arrayadaptert-just-accept-row-template/). So I don't know how to get the selected ID of list view item. My table just has two column, the \_Id of long type and is primary key, and name of nvarchar type. Thanks.
2012/02/26
[ "https://Stackoverflow.com/questions/9456111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/178643/" ]
As your `List<T>` consists of custom data container objects, you just have to add a method such as `getPrimaryKey()` to that data container class. Now, in the method `onListItemClicked`, you can easily read that key by doing ``` DataContainer dataContainer = myDataList.get(position); int primaryKey = dataContainer.getPrimaryKey(); ``` or simply ``` int primaryKey = myDataList.get(position).getPrimaryKey(); ```
Extend CursorAdapter instead of ArrayAdapter. Then override bindView and newView to implement custom logic and behaviour.
24,067,201
I'm trying to use OpenAL for an IOS game I'm working on, but having an issue opening the audio device. Specifically, when I call the function alcOpenDevice(NULL), I get 'NULL' in return. This is causing issues, of course, but I can't tell what I'm doing wrong. I'm new to OpenAL, so I've been looking at a couple guides [here](http://ohno789.blogspot.com/2013/08/openal-on-ios.html) and [here](https://github.com/software-mariodiana/AudioBufferPlayer/wiki/Replacing-C-functions-deprecated-in-iOS-7) to see what I need to do. If I download their sample projects and test 'em, they both work fine. If I copy their files into my project, and ignore the files I made, they still work fine. I'm assuming something got lost in translation when I started rebuilding the code for use in my project. Asking around and searching online hasn't given me any leads though, so I'm hoping someone here could put me on the right track. Here's the actual setup code I'm using in my AudioPlayer.m ``` - (void)setup { audioSampleBuffers = [NSMutableDictionary new]; audioSampleSources = [NSMutableArray new]; [self setupAudioSession]; [self setupAudioDevice]; [self setupNotifications]; } - (BOOL)setupAudioSession { // // This has been depricated. // // /* Setup the Audio Session and monitor interruptions */ // AudioSessionInitialize(NULL, NULL, AudioInterruptionListenerCallback, NULL); // // /* Set the category for the Audio Session */ // UInt32 session_category = kAudioSessionCategory_MediaPlayback; // AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(session_category), &session_category); // // /* Make the Audio Session active */ // AudioSessionSetActive(true); BOOL success = NO; NSError *error = nil; AVAudioSession *session = [AVAudioSession sharedInstance]; success = [session setCategory:AVAudioSessionCategoryPlayback error:&error]; if (!success) { NSLog(@"%@ Error setting category: %@", NSStringFromSelector(_cmd), [error localizedDescription]); return success; } success = [session setActive:YES error:&error]; if (!success) { NSLog(@"Error activating session: %@", [error localizedDescription]); } return success; } - (BOOL)setupAudioDevice { // 'NULL' uses the default device. openALDevice = alcOpenDevice(NULL); // Returns 'NULL' ALenum error = alGetError(); // Returns '0' NSLog(@"%i", error); if (!openALDevice) { NSLog(@"Something went wrong setting up the audio device."); return NO; } // Create a context to use with the device, and make it the current context. openALContext = alcCreateContext(openALDevice, NULL); alcMakeContextCurrent(openALContext); [self createAudioSources]; // Setup was successful return YES; } - (void)createAudioSources { ALuint sourceID; for (int i = 0; i < kMaxConcurrentSources; i++) { // Create a single source. alGenSources(1, &sourceID); // Add it to the array. [audioSampleSources addObject:[NSNumber numberWithUnsignedInt:sourceID]]; } } ``` Note: I'm running IOS 7.1.1 on a new iPad air, and using Xcode 5.1.1. This issue has been confirmed on the iPad, my simulator, and an iPod touch.
2014/06/05
[ "https://Stackoverflow.com/questions/24067201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1320607/" ]
[This SO answer](https://stackoverflow.com/questions/4201220/openal-initialization-problem-ipod-only) seems to validate my comment about `AVAudioSession` conflicting with OpenAL. Try removing `AVAudioSession`, or initializing OpenAL first (tho I imagine this would cause the inverse problem).
Alright, so I ended up starting over in a fresh project with a copy-pasted version of AudioSamplePlayer from the first sample project I linked. -It worked. I then edited it step by step back to the format I had set up in my project. -It still works! I still don't know what I did wrong the first time, and I'm not sure it was even in my audio player anymore, but It's running now. I blame gremlins. ...maybe alien surveillance.
24,067,201
I'm trying to use OpenAL for an IOS game I'm working on, but having an issue opening the audio device. Specifically, when I call the function alcOpenDevice(NULL), I get 'NULL' in return. This is causing issues, of course, but I can't tell what I'm doing wrong. I'm new to OpenAL, so I've been looking at a couple guides [here](http://ohno789.blogspot.com/2013/08/openal-on-ios.html) and [here](https://github.com/software-mariodiana/AudioBufferPlayer/wiki/Replacing-C-functions-deprecated-in-iOS-7) to see what I need to do. If I download their sample projects and test 'em, they both work fine. If I copy their files into my project, and ignore the files I made, they still work fine. I'm assuming something got lost in translation when I started rebuilding the code for use in my project. Asking around and searching online hasn't given me any leads though, so I'm hoping someone here could put me on the right track. Here's the actual setup code I'm using in my AudioPlayer.m ``` - (void)setup { audioSampleBuffers = [NSMutableDictionary new]; audioSampleSources = [NSMutableArray new]; [self setupAudioSession]; [self setupAudioDevice]; [self setupNotifications]; } - (BOOL)setupAudioSession { // // This has been depricated. // // /* Setup the Audio Session and monitor interruptions */ // AudioSessionInitialize(NULL, NULL, AudioInterruptionListenerCallback, NULL); // // /* Set the category for the Audio Session */ // UInt32 session_category = kAudioSessionCategory_MediaPlayback; // AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(session_category), &session_category); // // /* Make the Audio Session active */ // AudioSessionSetActive(true); BOOL success = NO; NSError *error = nil; AVAudioSession *session = [AVAudioSession sharedInstance]; success = [session setCategory:AVAudioSessionCategoryPlayback error:&error]; if (!success) { NSLog(@"%@ Error setting category: %@", NSStringFromSelector(_cmd), [error localizedDescription]); return success; } success = [session setActive:YES error:&error]; if (!success) { NSLog(@"Error activating session: %@", [error localizedDescription]); } return success; } - (BOOL)setupAudioDevice { // 'NULL' uses the default device. openALDevice = alcOpenDevice(NULL); // Returns 'NULL' ALenum error = alGetError(); // Returns '0' NSLog(@"%i", error); if (!openALDevice) { NSLog(@"Something went wrong setting up the audio device."); return NO; } // Create a context to use with the device, and make it the current context. openALContext = alcCreateContext(openALDevice, NULL); alcMakeContextCurrent(openALContext); [self createAudioSources]; // Setup was successful return YES; } - (void)createAudioSources { ALuint sourceID; for (int i = 0; i < kMaxConcurrentSources; i++) { // Create a single source. alGenSources(1, &sourceID); // Add it to the array. [audioSampleSources addObject:[NSNumber numberWithUnsignedInt:sourceID]]; } } ``` Note: I'm running IOS 7.1.1 on a new iPad air, and using Xcode 5.1.1. This issue has been confirmed on the iPad, my simulator, and an iPod touch.
2014/06/05
[ "https://Stackoverflow.com/questions/24067201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1320607/" ]
**The Short Answer:** Apple's implementation of `alcOpenDevice()` only returns the device once. Every subsequent call returns NULL. This function can be called by a lot of Apple audio code, so take out EVERY TRACE of audio code before using OpenAL and manually calling that function yourself. **The Long Answer:** I spent half a day dealing with this problem while using ObjectAL, and ended up doing exactly what you did, re-making the entire project. It worked, until out of curiosity I copied the entire project over, then same problem again, `alcOpenDevice(NULL)` returned NULL. By chance I stumbled upon the answer. It was this bit of code in my swift game scene: ``` let jumpSound = SKAction.playSoundFileNamed("WhistleJump.mp3", waitForCompletion: false) ``` And then I remembered I had this problem before without SKAction involved. That time it turned out I was using ObjectAL in two different ways, I used OALSimpleAudio in one place, and OpenAL objects in another, and it was initializing my audio session twice. The common thread between these two incidents is both times `alcOpenDevice()` was called more than once during the life of the application. The first time it was ObjectAL calling it twice due to my misuse of the library. The second `SKAction.playSoundFileNamed()` must have called `alcOpenDevice()` before my ObjectAL code did. Upon further research I found this bit in the OpenAL 1.1 Specification: --- 6.1.1. Connecting to a Device ----------------------------- The alcOpenDevice function allows the application (i.e. the client program) to connect to a device (i.e. the server). ALCdevice \* alcOpenDevice (const ALCchar \*deviceSpecifier); If the function returns NULL, then no sound driver/device has been found. The argument is a null terminated string that requests a certain device or device configuration. If NULL is specified, the implementation will provide an implementation specific default. --- My hunch is that Apple's implementation of this function only returns the correct device **ONCE** for the life of the application. Every time alcOpenDevice is called after that, it returns NULL. So bottom line: Take out every trace of audio code before switching to OpenAL. Even code that seems safe, like `SKAction.playSoundFileNamed()` still might contain a call to `alcOpenDevice()` buried deep in its implementation. For those using ObjectAL, here is the console output of this problem to help them find their way here from google, as I couldn't find a good answer myself: ``` OAL Error: +[ALWrapper openDevice:]: Could not open device (null) OAL Error: -[ALDevice initWithDeviceSpecifier:]: <ALDevice: 0x17679b20>: Failed to create OpenAL device (null) OAL Error: +[ALWrapper closeDevice:]: Invalid Enum (error code 0x0000a003) OAL Warning: -[OALAudioSession onAudioError:]: Received audio error notification, but last reset was 0.012216 seconds ago. Doing nothing. fatal error: unexpectedly found nil while unwrapping an Optional value ```
[This SO answer](https://stackoverflow.com/questions/4201220/openal-initialization-problem-ipod-only) seems to validate my comment about `AVAudioSession` conflicting with OpenAL. Try removing `AVAudioSession`, or initializing OpenAL first (tho I imagine this would cause the inverse problem).
24,067,201
I'm trying to use OpenAL for an IOS game I'm working on, but having an issue opening the audio device. Specifically, when I call the function alcOpenDevice(NULL), I get 'NULL' in return. This is causing issues, of course, but I can't tell what I'm doing wrong. I'm new to OpenAL, so I've been looking at a couple guides [here](http://ohno789.blogspot.com/2013/08/openal-on-ios.html) and [here](https://github.com/software-mariodiana/AudioBufferPlayer/wiki/Replacing-C-functions-deprecated-in-iOS-7) to see what I need to do. If I download their sample projects and test 'em, they both work fine. If I copy their files into my project, and ignore the files I made, they still work fine. I'm assuming something got lost in translation when I started rebuilding the code for use in my project. Asking around and searching online hasn't given me any leads though, so I'm hoping someone here could put me on the right track. Here's the actual setup code I'm using in my AudioPlayer.m ``` - (void)setup { audioSampleBuffers = [NSMutableDictionary new]; audioSampleSources = [NSMutableArray new]; [self setupAudioSession]; [self setupAudioDevice]; [self setupNotifications]; } - (BOOL)setupAudioSession { // // This has been depricated. // // /* Setup the Audio Session and monitor interruptions */ // AudioSessionInitialize(NULL, NULL, AudioInterruptionListenerCallback, NULL); // // /* Set the category for the Audio Session */ // UInt32 session_category = kAudioSessionCategory_MediaPlayback; // AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(session_category), &session_category); // // /* Make the Audio Session active */ // AudioSessionSetActive(true); BOOL success = NO; NSError *error = nil; AVAudioSession *session = [AVAudioSession sharedInstance]; success = [session setCategory:AVAudioSessionCategoryPlayback error:&error]; if (!success) { NSLog(@"%@ Error setting category: %@", NSStringFromSelector(_cmd), [error localizedDescription]); return success; } success = [session setActive:YES error:&error]; if (!success) { NSLog(@"Error activating session: %@", [error localizedDescription]); } return success; } - (BOOL)setupAudioDevice { // 'NULL' uses the default device. openALDevice = alcOpenDevice(NULL); // Returns 'NULL' ALenum error = alGetError(); // Returns '0' NSLog(@"%i", error); if (!openALDevice) { NSLog(@"Something went wrong setting up the audio device."); return NO; } // Create a context to use with the device, and make it the current context. openALContext = alcCreateContext(openALDevice, NULL); alcMakeContextCurrent(openALContext); [self createAudioSources]; // Setup was successful return YES; } - (void)createAudioSources { ALuint sourceID; for (int i = 0; i < kMaxConcurrentSources; i++) { // Create a single source. alGenSources(1, &sourceID); // Add it to the array. [audioSampleSources addObject:[NSNumber numberWithUnsignedInt:sourceID]]; } } ``` Note: I'm running IOS 7.1.1 on a new iPad air, and using Xcode 5.1.1. This issue has been confirmed on the iPad, my simulator, and an iPod touch.
2014/06/05
[ "https://Stackoverflow.com/questions/24067201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1320607/" ]
**The Short Answer:** Apple's implementation of `alcOpenDevice()` only returns the device once. Every subsequent call returns NULL. This function can be called by a lot of Apple audio code, so take out EVERY TRACE of audio code before using OpenAL and manually calling that function yourself. **The Long Answer:** I spent half a day dealing with this problem while using ObjectAL, and ended up doing exactly what you did, re-making the entire project. It worked, until out of curiosity I copied the entire project over, then same problem again, `alcOpenDevice(NULL)` returned NULL. By chance I stumbled upon the answer. It was this bit of code in my swift game scene: ``` let jumpSound = SKAction.playSoundFileNamed("WhistleJump.mp3", waitForCompletion: false) ``` And then I remembered I had this problem before without SKAction involved. That time it turned out I was using ObjectAL in two different ways, I used OALSimpleAudio in one place, and OpenAL objects in another, and it was initializing my audio session twice. The common thread between these two incidents is both times `alcOpenDevice()` was called more than once during the life of the application. The first time it was ObjectAL calling it twice due to my misuse of the library. The second `SKAction.playSoundFileNamed()` must have called `alcOpenDevice()` before my ObjectAL code did. Upon further research I found this bit in the OpenAL 1.1 Specification: --- 6.1.1. Connecting to a Device ----------------------------- The alcOpenDevice function allows the application (i.e. the client program) to connect to a device (i.e. the server). ALCdevice \* alcOpenDevice (const ALCchar \*deviceSpecifier); If the function returns NULL, then no sound driver/device has been found. The argument is a null terminated string that requests a certain device or device configuration. If NULL is specified, the implementation will provide an implementation specific default. --- My hunch is that Apple's implementation of this function only returns the correct device **ONCE** for the life of the application. Every time alcOpenDevice is called after that, it returns NULL. So bottom line: Take out every trace of audio code before switching to OpenAL. Even code that seems safe, like `SKAction.playSoundFileNamed()` still might contain a call to `alcOpenDevice()` buried deep in its implementation. For those using ObjectAL, here is the console output of this problem to help them find their way here from google, as I couldn't find a good answer myself: ``` OAL Error: +[ALWrapper openDevice:]: Could not open device (null) OAL Error: -[ALDevice initWithDeviceSpecifier:]: <ALDevice: 0x17679b20>: Failed to create OpenAL device (null) OAL Error: +[ALWrapper closeDevice:]: Invalid Enum (error code 0x0000a003) OAL Warning: -[OALAudioSession onAudioError:]: Received audio error notification, but last reset was 0.012216 seconds ago. Doing nothing. fatal error: unexpectedly found nil while unwrapping an Optional value ```
Alright, so I ended up starting over in a fresh project with a copy-pasted version of AudioSamplePlayer from the first sample project I linked. -It worked. I then edited it step by step back to the format I had set up in my project. -It still works! I still don't know what I did wrong the first time, and I'm not sure it was even in my audio player anymore, but It's running now. I blame gremlins. ...maybe alien surveillance.
17,217,266
I am trying to group results that I am getting from store to be displayed inside ComboBox . I have a combobox that looks like this: ![enter image description here](https://i.stack.imgur.com/dMXO1.png) and I need it to look like this : ![enter image description here](https://i.stack.imgur.com/7mFAE.png) That means grouped by category (order / invoice ). My combobox defined like this : ``` Ext.define('NG.view.searchcombo.Combo', { requires: ['Ext.form.field.ComboBox'], extend: 'Ext.form.ComboBox', alias: 'widget.searchcombo', minChars:3, fieldLabel: 'Choose Search', store: 'Search', displayField: 'name', valueField: 'id', typeAhead: false, hideLabel: true, hideTrigger:false, anchor: '100%', listConfig: { loadingText: 'Searching...', emptyText: 'No matching posts found.', // Custom rendering template for each item getInnerTpl: function() { return '<h3>{name} / {category}</h3>' +'{excerpt}' ; } }, pageSize: 10, initComponent: function () { this.callParent(arguments); } }); ``` and my data is like this : ``` [{ "id": 1, "name": "one", "category": "invoice" }, { "id": 2, "name": "two", "category": "invoice" }, { "id": 3, "name": "one", "category": "order" }, { "id": 4, "name": "two", "category": "order" }, { "id": 5, "name": "three", "category": "invoice" }, { "id": 6, "name": "four", "category": "invoice" }, { "id": 7, "name": "three", "category": "order" }, { "id": 8, "name": "four", "category": "order" }, { "id": 9, "name": "five", "category": "invoice" }, { "id": 10, "name": "six", "category": "invoice" }, { "id": 11, "name": "five", "category": "order" }, { "id": 12, "name": "six", "category": "order" }, { "id": 13, "name": "seven", "category": "invoice" }, { "id": 14, "name": "eight", "category": "invoice" }, { "id": 15, "name": "seven", "category": "order" }, { "id": 16, "name": "eight", "category": "order" }] ``` I think that can be done by using `Ext.XTemplate` but I am not familiar with `Ext.XTemplate`.
2013/06/20
[ "https://Stackoverflow.com/questions/17217266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1035712/" ]
Please, you can get this done using a Grid to Render your combobox content. Refer to this post: <http://www.sencha.com/forum/showthread.php?132328-CLOSED-ComboBox-using-Grid-instead-of-BoundList> Following the article I was able to create this: ![enter image description here](https://i.stack.imgur.com/42vYI.png)
That is the code the worked for me: If you are using Sencha Architect, add the createPicker inside an Override and manually create the listConfig as an Object. ``` { xtype: 'combobox', createPicker: function() { var me = this, picker, menuCls = Ext.baseCSSPrefix + 'menu', opts = Ext.apply({ selModel: { mode: me.multiSelect ? 'SIMPLE' : 'SINGLE' }, floating: true, hidden: true, ownerCt: me.ownerCt, cls: me.el.up('.' + menuCls) ? menuCls : '', store: me.store, displayField: me.displayField, focusOnToFront: false, pageSize: me.pageSize }, me.listConfig, me.defaultListConfig); // NOTE: we simply use a grid panel //picker = me.picker = Ext.create('Ext.view.BoundList', opts); picker = me.picker = Ext.create('Ext.grid.Panel', opts); // hack: pass getNode() to the view picker.getNode = function() { picker.getView().getNode(arguments); }; me.mon(picker.getView(), { refresh: me.onListRefresh, scope: me }); me.mon(picker, { itemclick: me.onItemClick, // refresh: me.onListRefresh, scope: me }); me.mon(picker.getSelectionModel(), { selectionChange: me.onListSelectionChange, scope: me }); return picker; }, listConfig: { columns: [{ xtype: "gridcolumn", dataIndex: "id", text: "Id" }, { xtype: "gridcolumn", dataIndex: "name", text: "Name" }], features: [{ ftype: "grouping" }] }, fieldLabel: 'Label', queryMode: 'local', store: 'myTestStore' } ```
17,217,266
I am trying to group results that I am getting from store to be displayed inside ComboBox . I have a combobox that looks like this: ![enter image description here](https://i.stack.imgur.com/dMXO1.png) and I need it to look like this : ![enter image description here](https://i.stack.imgur.com/7mFAE.png) That means grouped by category (order / invoice ). My combobox defined like this : ``` Ext.define('NG.view.searchcombo.Combo', { requires: ['Ext.form.field.ComboBox'], extend: 'Ext.form.ComboBox', alias: 'widget.searchcombo', minChars:3, fieldLabel: 'Choose Search', store: 'Search', displayField: 'name', valueField: 'id', typeAhead: false, hideLabel: true, hideTrigger:false, anchor: '100%', listConfig: { loadingText: 'Searching...', emptyText: 'No matching posts found.', // Custom rendering template for each item getInnerTpl: function() { return '<h3>{name} / {category}</h3>' +'{excerpt}' ; } }, pageSize: 10, initComponent: function () { this.callParent(arguments); } }); ``` and my data is like this : ``` [{ "id": 1, "name": "one", "category": "invoice" }, { "id": 2, "name": "two", "category": "invoice" }, { "id": 3, "name": "one", "category": "order" }, { "id": 4, "name": "two", "category": "order" }, { "id": 5, "name": "three", "category": "invoice" }, { "id": 6, "name": "four", "category": "invoice" }, { "id": 7, "name": "three", "category": "order" }, { "id": 8, "name": "four", "category": "order" }, { "id": 9, "name": "five", "category": "invoice" }, { "id": 10, "name": "six", "category": "invoice" }, { "id": 11, "name": "five", "category": "order" }, { "id": 12, "name": "six", "category": "order" }, { "id": 13, "name": "seven", "category": "invoice" }, { "id": 14, "name": "eight", "category": "invoice" }, { "id": 15, "name": "seven", "category": "order" }, { "id": 16, "name": "eight", "category": "order" }] ``` I think that can be done by using `Ext.XTemplate` but I am not familiar with `Ext.XTemplate`.
2013/06/20
[ "https://Stackoverflow.com/questions/17217266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1035712/" ]
Please, you can get this done using a Grid to Render your combobox content. Refer to this post: <http://www.sencha.com/forum/showthread.php?132328-CLOSED-ComboBox-using-Grid-instead-of-BoundList> Following the article I was able to create this: ![enter image description here](https://i.stack.imgur.com/42vYI.png)
I've implemented my own version of the combo with a grid as its list component. You can get it on [GitHub](https://github.com/rixo/GridPicker), and I've put some [examples online](http://planysphere.fr/ext/GridPicker/examples/). The 3rd example closely matches what you're trying to achieve. Here's an example that would match even more closely. You'd only be left with the styling to do: ``` Ext.widget('gridpicker', { queryMode: 'local' ,displayField: 'name' ,store: { fields: ['name', 'group'] ,proxy: {type: 'memory', reader: 'array'} ,data: ... ,groupField: 'group' ,sorters: {property: 'name', order: 'ASC'} } ,gridConfig: { features: [{ ftype:'grouping' ,groupHeaderTpl: '{name}' ,collapsible: false }] ,columns: [{ width: 30 ,renderer: function(value, md, record, rowIndex) { return '<img src="..." />'; } },{ dataIndex: 'name' ,flex: 1 }] } }); ```
17,217,266
I am trying to group results that I am getting from store to be displayed inside ComboBox . I have a combobox that looks like this: ![enter image description here](https://i.stack.imgur.com/dMXO1.png) and I need it to look like this : ![enter image description here](https://i.stack.imgur.com/7mFAE.png) That means grouped by category (order / invoice ). My combobox defined like this : ``` Ext.define('NG.view.searchcombo.Combo', { requires: ['Ext.form.field.ComboBox'], extend: 'Ext.form.ComboBox', alias: 'widget.searchcombo', minChars:3, fieldLabel: 'Choose Search', store: 'Search', displayField: 'name', valueField: 'id', typeAhead: false, hideLabel: true, hideTrigger:false, anchor: '100%', listConfig: { loadingText: 'Searching...', emptyText: 'No matching posts found.', // Custom rendering template for each item getInnerTpl: function() { return '<h3>{name} / {category}</h3>' +'{excerpt}' ; } }, pageSize: 10, initComponent: function () { this.callParent(arguments); } }); ``` and my data is like this : ``` [{ "id": 1, "name": "one", "category": "invoice" }, { "id": 2, "name": "two", "category": "invoice" }, { "id": 3, "name": "one", "category": "order" }, { "id": 4, "name": "two", "category": "order" }, { "id": 5, "name": "three", "category": "invoice" }, { "id": 6, "name": "four", "category": "invoice" }, { "id": 7, "name": "three", "category": "order" }, { "id": 8, "name": "four", "category": "order" }, { "id": 9, "name": "five", "category": "invoice" }, { "id": 10, "name": "six", "category": "invoice" }, { "id": 11, "name": "five", "category": "order" }, { "id": 12, "name": "six", "category": "order" }, { "id": 13, "name": "seven", "category": "invoice" }, { "id": 14, "name": "eight", "category": "invoice" }, { "id": 15, "name": "seven", "category": "order" }, { "id": 16, "name": "eight", "category": "order" }] ``` I think that can be done by using `Ext.XTemplate` but I am not familiar with `Ext.XTemplate`.
2013/06/20
[ "https://Stackoverflow.com/questions/17217266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1035712/" ]
I wanted a much simpler solution, so I'll share what I came up with. For my purposes, I had a `key` that I wanted to group on, which is a single character. I knew the headers I wanted to show for each key, so I pre-sorted the list to make sure the types came together, and then I just render a group header each time I see a new key. ``` myStore.sort('key', 'DESC'); Ext.create('Ext.form.field.ComboBox', { store: myStore, queryMode: 'local', displayField: 'name', valueField: 'id', listConfig: { cls: 'grouped-list' }, tpl: Ext.create('Ext.XTemplate', '{[this.currentKey = null]}' + '<tpl for=".">', '<tpl if="this.shouldShowHeader(key)">' + '<div class="group-header">{[this.showHeader(values.key)]}</div>' + '</tpl>' + '<div class="x-boundlist-item">{name}</div>', '</tpl>', { shouldShowHeader: function(key){ return this.currentKey != key; }, showHeader: function(key){ this.currentKey = key; switch (key) { case 's': return 'Structures'; case 'f': return 'Filters'; ... } return 'Other'; } } ) }); ``` Using the following CSS: ``` .grouped-list .x-boundlist-item { padding: 1px 3px 0 10px } .grouped-list .group-header { padding: 4px; font-weight: bold; border-bottom: 1px solid #ddd; } ``` And this data: ``` [ { key: 's', name: '2014 Product Development' }, { key: 'f', name: 'Message Filter' }, { key: 's', name: '2014 Product Development (Little)' }, { key: 's', name: 'Global Structure' }, { key: 'f', name: 'My SW' } ] ``` I get a nice looking grouped list like this: ![](https://i.stack.imgur.com/GxK8U.png)
Please, you can get this done using a Grid to Render your combobox content. Refer to this post: <http://www.sencha.com/forum/showthread.php?132328-CLOSED-ComboBox-using-Grid-instead-of-BoundList> Following the article I was able to create this: ![enter image description here](https://i.stack.imgur.com/42vYI.png)
17,217,266
I am trying to group results that I am getting from store to be displayed inside ComboBox . I have a combobox that looks like this: ![enter image description here](https://i.stack.imgur.com/dMXO1.png) and I need it to look like this : ![enter image description here](https://i.stack.imgur.com/7mFAE.png) That means grouped by category (order / invoice ). My combobox defined like this : ``` Ext.define('NG.view.searchcombo.Combo', { requires: ['Ext.form.field.ComboBox'], extend: 'Ext.form.ComboBox', alias: 'widget.searchcombo', minChars:3, fieldLabel: 'Choose Search', store: 'Search', displayField: 'name', valueField: 'id', typeAhead: false, hideLabel: true, hideTrigger:false, anchor: '100%', listConfig: { loadingText: 'Searching...', emptyText: 'No matching posts found.', // Custom rendering template for each item getInnerTpl: function() { return '<h3>{name} / {category}</h3>' +'{excerpt}' ; } }, pageSize: 10, initComponent: function () { this.callParent(arguments); } }); ``` and my data is like this : ``` [{ "id": 1, "name": "one", "category": "invoice" }, { "id": 2, "name": "two", "category": "invoice" }, { "id": 3, "name": "one", "category": "order" }, { "id": 4, "name": "two", "category": "order" }, { "id": 5, "name": "three", "category": "invoice" }, { "id": 6, "name": "four", "category": "invoice" }, { "id": 7, "name": "three", "category": "order" }, { "id": 8, "name": "four", "category": "order" }, { "id": 9, "name": "five", "category": "invoice" }, { "id": 10, "name": "six", "category": "invoice" }, { "id": 11, "name": "five", "category": "order" }, { "id": 12, "name": "six", "category": "order" }, { "id": 13, "name": "seven", "category": "invoice" }, { "id": 14, "name": "eight", "category": "invoice" }, { "id": 15, "name": "seven", "category": "order" }, { "id": 16, "name": "eight", "category": "order" }] ``` I think that can be done by using `Ext.XTemplate` but I am not familiar with `Ext.XTemplate`.
2013/06/20
[ "https://Stackoverflow.com/questions/17217266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1035712/" ]
This is an extension that improves on Sean Adkinson answer above by making a reusable component from his code. I have had mixed results with replacing BoundList with a GridPanel with Ext 5.0.1 there for this is what I used. One caveat it does not support collapsing the groups but it works great for me. Tested in Extjs 4.2.3 and 5.0.1. You can see it in Sencha [fiddle](https://fiddle.sencha.com/fiddle/e5n) Hope it helps someone out there. ```js Ext.define('Ext.ux.GroupComboBox', { extend: 'Ext.form.field.ComboBox', alias: 'widget.groupcombobox', /* * @cfg groupField String value of field to groupBy, set this to any field in your model */ groupField: 'group', listConfig: { cls: 'grouped-list' }, initComponent: function() { var me = this; me.tpl = new Ext.XTemplate([ '{%this.currentGroup = null%}', '<tpl for=".">', ' <tpl if="this.shouldShowHeader(' + me.groupField + ')">', ' <div class="group-header">{[this.showHeader(values.' + me.groupField + ')]}</div>', ' </tpl>', ' <div class="x-boundlist-item">{' + me.displayField + '}</div>', '</tpl>', { shouldShowHeader: function(group) { return this.currentGroup != group; }, showHeader: function(group) { this.currentGroup = group; return group; } } ]); me.callParent(arguments); } }); //Example usage var Restaurants = Ext.create('Ext.data.Store', { storeId: 'restaraunts', fields: ['name', 'cuisine'], sorters: ['cuisine', 'name'], groupField: 'cuisine', data: [{ name: 'Cheesecake Factory', cuisine: 'American' }, { name: 'University Cafe', cuisine: 'American' }, { name: 'Creamery', cuisine: 'American' }, { name: 'Old Pro', cuisine: 'American' }, { name: 'Nola\'s', cuisine: 'Cajun' }, { name: 'House of Bagels', cuisine: 'Bagels' }, { name: 'The Prolific Oven', cuisine: 'Sandwiches' }, { name: 'La Strada', cuisine: 'Italian' }, { name: 'Buca di Beppo', cuisine: 'Italian' }, { name: 'Pasta?', cuisine: 'Italian' }, { name: 'Madame Tam', cuisine: 'Asian' }, { name: 'Sprout Cafe', cuisine: 'Salad' }, { name: 'Pluto\'s', cuisine: 'Salad' }, { name: 'Junoon', cuisine: 'Indian' }, { name: 'Bistro Maxine', cuisine: 'French' }, { name: 'Three Seasons', cuisine: 'Vietnamese' }, { name: 'Sancho\'s Taquira', cuisine: 'Mexican' }, { name: 'Reposado', cuisine: 'Mexican' }, { name: 'Siam Royal', cuisine: 'Thai' }, { name: 'Krung Siam', cuisine: 'Thai' }, { name: 'Thaiphoon', cuisine: 'Thai' }, { name: 'Tamarine', cuisine: 'Vietnamese' }, { name: 'Joya', cuisine: 'Tapas' }, { name: 'Jing Jing', cuisine: 'Chinese' }, { name: 'Patxi\'s Pizza', cuisine: 'Pizza' }, { name: 'Evvia Estiatorio', cuisine: 'Mediterranean' }, { name: 'Gyros-Gyros', cuisine: 'Mediterranean' }, { name: 'Mango Caribbean Cafe', cuisine: 'Caribbean' }, { name: 'Coconuts Caribbean Restaurant &amp; Bar', cuisine: 'Caribbean' }, { name: 'Rose &amp; Crown', cuisine: 'English' }, { name: 'Baklava', cuisine: 'Mediterranean' }, { name: 'Mandarin Gourmet', cuisine: 'Chinese' }, { name: 'Bangkok Cuisine', cuisine: 'Thai' }, { name: 'Darbar Indian Cuisine', cuisine: 'Indian' }, { name: 'Mantra', cuisine: 'Indian' }, { name: 'Janta', cuisine: 'Indian' }, { name: 'Starbucks', cuisine: 'Coffee' }, { name: 'Peet\'s Coffee', cuisine: 'Coffee' }, { name: 'Coupa Cafe', cuisine: 'Coffee' }, { name: 'Lytton Coffee Company', cuisine: 'Coffee' }, { name: 'Il Fornaio', cuisine: 'Italian' }, { name: 'Lavanda', cuisine: 'Mediterranean' }, { name: 'MacArthur Park', cuisine: 'American' }, { name: 'St Michael\'s Alley', cuisine: 'Californian' }, { name: 'Cafe Renzo', cuisine: 'Italian' }, { name: 'Miyake', cuisine: 'Sushi' }, { name: 'Sushi Tomo', cuisine: 'Sushi' }, { name: 'Kanpai', cuisine: 'Sushi' }, { name: 'Pizza My Heart', cuisine: 'Pizza' }, { name: 'New York Pizza', cuisine: 'Pizza' }, { name: 'Loving Hut', cuisine: 'Vegan' }, { name: 'Garden Fresh', cuisine: 'Vegan' }, { name: 'Cafe Epi', cuisine: 'French' }, { name: 'Tai Pan', cuisine: 'Chinese' }] }); Ext.create('Ext.container.Viewport', { items: Ext.create('Ext.ux.GroupComboBox', { fieldLabel: 'Restaurants', name: 'txtRestaurant', forceSelection: true, editable: false, queryMode: 'local', triggerAction: 'all', multiSelect: true, groupField: 'cuisine', displayField: 'name', valueField: 'name', store: Restaurants, width: 400 }) }).show(); ``` ```css .grouped-list .x-boundlist-item { padding: 1px 3px 0 10px; } .grouped-list .group-header { padding: 4px; font-weight: bold; border-bottom: 1px solid #ddd; } ```
Please, you can get this done using a Grid to Render your combobox content. Refer to this post: <http://www.sencha.com/forum/showthread.php?132328-CLOSED-ComboBox-using-Grid-instead-of-BoundList> Following the article I was able to create this: ![enter image description here](https://i.stack.imgur.com/42vYI.png)
17,217,266
I am trying to group results that I am getting from store to be displayed inside ComboBox . I have a combobox that looks like this: ![enter image description here](https://i.stack.imgur.com/dMXO1.png) and I need it to look like this : ![enter image description here](https://i.stack.imgur.com/7mFAE.png) That means grouped by category (order / invoice ). My combobox defined like this : ``` Ext.define('NG.view.searchcombo.Combo', { requires: ['Ext.form.field.ComboBox'], extend: 'Ext.form.ComboBox', alias: 'widget.searchcombo', minChars:3, fieldLabel: 'Choose Search', store: 'Search', displayField: 'name', valueField: 'id', typeAhead: false, hideLabel: true, hideTrigger:false, anchor: '100%', listConfig: { loadingText: 'Searching...', emptyText: 'No matching posts found.', // Custom rendering template for each item getInnerTpl: function() { return '<h3>{name} / {category}</h3>' +'{excerpt}' ; } }, pageSize: 10, initComponent: function () { this.callParent(arguments); } }); ``` and my data is like this : ``` [{ "id": 1, "name": "one", "category": "invoice" }, { "id": 2, "name": "two", "category": "invoice" }, { "id": 3, "name": "one", "category": "order" }, { "id": 4, "name": "two", "category": "order" }, { "id": 5, "name": "three", "category": "invoice" }, { "id": 6, "name": "four", "category": "invoice" }, { "id": 7, "name": "three", "category": "order" }, { "id": 8, "name": "four", "category": "order" }, { "id": 9, "name": "five", "category": "invoice" }, { "id": 10, "name": "six", "category": "invoice" }, { "id": 11, "name": "five", "category": "order" }, { "id": 12, "name": "six", "category": "order" }, { "id": 13, "name": "seven", "category": "invoice" }, { "id": 14, "name": "eight", "category": "invoice" }, { "id": 15, "name": "seven", "category": "order" }, { "id": 16, "name": "eight", "category": "order" }] ``` I think that can be done by using `Ext.XTemplate` but I am not familiar with `Ext.XTemplate`.
2013/06/20
[ "https://Stackoverflow.com/questions/17217266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1035712/" ]
I wanted a much simpler solution, so I'll share what I came up with. For my purposes, I had a `key` that I wanted to group on, which is a single character. I knew the headers I wanted to show for each key, so I pre-sorted the list to make sure the types came together, and then I just render a group header each time I see a new key. ``` myStore.sort('key', 'DESC'); Ext.create('Ext.form.field.ComboBox', { store: myStore, queryMode: 'local', displayField: 'name', valueField: 'id', listConfig: { cls: 'grouped-list' }, tpl: Ext.create('Ext.XTemplate', '{[this.currentKey = null]}' + '<tpl for=".">', '<tpl if="this.shouldShowHeader(key)">' + '<div class="group-header">{[this.showHeader(values.key)]}</div>' + '</tpl>' + '<div class="x-boundlist-item">{name}</div>', '</tpl>', { shouldShowHeader: function(key){ return this.currentKey != key; }, showHeader: function(key){ this.currentKey = key; switch (key) { case 's': return 'Structures'; case 'f': return 'Filters'; ... } return 'Other'; } } ) }); ``` Using the following CSS: ``` .grouped-list .x-boundlist-item { padding: 1px 3px 0 10px } .grouped-list .group-header { padding: 4px; font-weight: bold; border-bottom: 1px solid #ddd; } ``` And this data: ``` [ { key: 's', name: '2014 Product Development' }, { key: 'f', name: 'Message Filter' }, { key: 's', name: '2014 Product Development (Little)' }, { key: 's', name: 'Global Structure' }, { key: 'f', name: 'My SW' } ] ``` I get a nice looking grouped list like this: ![](https://i.stack.imgur.com/GxK8U.png)
That is the code the worked for me: If you are using Sencha Architect, add the createPicker inside an Override and manually create the listConfig as an Object. ``` { xtype: 'combobox', createPicker: function() { var me = this, picker, menuCls = Ext.baseCSSPrefix + 'menu', opts = Ext.apply({ selModel: { mode: me.multiSelect ? 'SIMPLE' : 'SINGLE' }, floating: true, hidden: true, ownerCt: me.ownerCt, cls: me.el.up('.' + menuCls) ? menuCls : '', store: me.store, displayField: me.displayField, focusOnToFront: false, pageSize: me.pageSize }, me.listConfig, me.defaultListConfig); // NOTE: we simply use a grid panel //picker = me.picker = Ext.create('Ext.view.BoundList', opts); picker = me.picker = Ext.create('Ext.grid.Panel', opts); // hack: pass getNode() to the view picker.getNode = function() { picker.getView().getNode(arguments); }; me.mon(picker.getView(), { refresh: me.onListRefresh, scope: me }); me.mon(picker, { itemclick: me.onItemClick, // refresh: me.onListRefresh, scope: me }); me.mon(picker.getSelectionModel(), { selectionChange: me.onListSelectionChange, scope: me }); return picker; }, listConfig: { columns: [{ xtype: "gridcolumn", dataIndex: "id", text: "Id" }, { xtype: "gridcolumn", dataIndex: "name", text: "Name" }], features: [{ ftype: "grouping" }] }, fieldLabel: 'Label', queryMode: 'local', store: 'myTestStore' } ```
17,217,266
I am trying to group results that I am getting from store to be displayed inside ComboBox . I have a combobox that looks like this: ![enter image description here](https://i.stack.imgur.com/dMXO1.png) and I need it to look like this : ![enter image description here](https://i.stack.imgur.com/7mFAE.png) That means grouped by category (order / invoice ). My combobox defined like this : ``` Ext.define('NG.view.searchcombo.Combo', { requires: ['Ext.form.field.ComboBox'], extend: 'Ext.form.ComboBox', alias: 'widget.searchcombo', minChars:3, fieldLabel: 'Choose Search', store: 'Search', displayField: 'name', valueField: 'id', typeAhead: false, hideLabel: true, hideTrigger:false, anchor: '100%', listConfig: { loadingText: 'Searching...', emptyText: 'No matching posts found.', // Custom rendering template for each item getInnerTpl: function() { return '<h3>{name} / {category}</h3>' +'{excerpt}' ; } }, pageSize: 10, initComponent: function () { this.callParent(arguments); } }); ``` and my data is like this : ``` [{ "id": 1, "name": "one", "category": "invoice" }, { "id": 2, "name": "two", "category": "invoice" }, { "id": 3, "name": "one", "category": "order" }, { "id": 4, "name": "two", "category": "order" }, { "id": 5, "name": "three", "category": "invoice" }, { "id": 6, "name": "four", "category": "invoice" }, { "id": 7, "name": "three", "category": "order" }, { "id": 8, "name": "four", "category": "order" }, { "id": 9, "name": "five", "category": "invoice" }, { "id": 10, "name": "six", "category": "invoice" }, { "id": 11, "name": "five", "category": "order" }, { "id": 12, "name": "six", "category": "order" }, { "id": 13, "name": "seven", "category": "invoice" }, { "id": 14, "name": "eight", "category": "invoice" }, { "id": 15, "name": "seven", "category": "order" }, { "id": 16, "name": "eight", "category": "order" }] ``` I think that can be done by using `Ext.XTemplate` but I am not familiar with `Ext.XTemplate`.
2013/06/20
[ "https://Stackoverflow.com/questions/17217266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1035712/" ]
This is an extension that improves on Sean Adkinson answer above by making a reusable component from his code. I have had mixed results with replacing BoundList with a GridPanel with Ext 5.0.1 there for this is what I used. One caveat it does not support collapsing the groups but it works great for me. Tested in Extjs 4.2.3 and 5.0.1. You can see it in Sencha [fiddle](https://fiddle.sencha.com/fiddle/e5n) Hope it helps someone out there. ```js Ext.define('Ext.ux.GroupComboBox', { extend: 'Ext.form.field.ComboBox', alias: 'widget.groupcombobox', /* * @cfg groupField String value of field to groupBy, set this to any field in your model */ groupField: 'group', listConfig: { cls: 'grouped-list' }, initComponent: function() { var me = this; me.tpl = new Ext.XTemplate([ '{%this.currentGroup = null%}', '<tpl for=".">', ' <tpl if="this.shouldShowHeader(' + me.groupField + ')">', ' <div class="group-header">{[this.showHeader(values.' + me.groupField + ')]}</div>', ' </tpl>', ' <div class="x-boundlist-item">{' + me.displayField + '}</div>', '</tpl>', { shouldShowHeader: function(group) { return this.currentGroup != group; }, showHeader: function(group) { this.currentGroup = group; return group; } } ]); me.callParent(arguments); } }); //Example usage var Restaurants = Ext.create('Ext.data.Store', { storeId: 'restaraunts', fields: ['name', 'cuisine'], sorters: ['cuisine', 'name'], groupField: 'cuisine', data: [{ name: 'Cheesecake Factory', cuisine: 'American' }, { name: 'University Cafe', cuisine: 'American' }, { name: 'Creamery', cuisine: 'American' }, { name: 'Old Pro', cuisine: 'American' }, { name: 'Nola\'s', cuisine: 'Cajun' }, { name: 'House of Bagels', cuisine: 'Bagels' }, { name: 'The Prolific Oven', cuisine: 'Sandwiches' }, { name: 'La Strada', cuisine: 'Italian' }, { name: 'Buca di Beppo', cuisine: 'Italian' }, { name: 'Pasta?', cuisine: 'Italian' }, { name: 'Madame Tam', cuisine: 'Asian' }, { name: 'Sprout Cafe', cuisine: 'Salad' }, { name: 'Pluto\'s', cuisine: 'Salad' }, { name: 'Junoon', cuisine: 'Indian' }, { name: 'Bistro Maxine', cuisine: 'French' }, { name: 'Three Seasons', cuisine: 'Vietnamese' }, { name: 'Sancho\'s Taquira', cuisine: 'Mexican' }, { name: 'Reposado', cuisine: 'Mexican' }, { name: 'Siam Royal', cuisine: 'Thai' }, { name: 'Krung Siam', cuisine: 'Thai' }, { name: 'Thaiphoon', cuisine: 'Thai' }, { name: 'Tamarine', cuisine: 'Vietnamese' }, { name: 'Joya', cuisine: 'Tapas' }, { name: 'Jing Jing', cuisine: 'Chinese' }, { name: 'Patxi\'s Pizza', cuisine: 'Pizza' }, { name: 'Evvia Estiatorio', cuisine: 'Mediterranean' }, { name: 'Gyros-Gyros', cuisine: 'Mediterranean' }, { name: 'Mango Caribbean Cafe', cuisine: 'Caribbean' }, { name: 'Coconuts Caribbean Restaurant &amp; Bar', cuisine: 'Caribbean' }, { name: 'Rose &amp; Crown', cuisine: 'English' }, { name: 'Baklava', cuisine: 'Mediterranean' }, { name: 'Mandarin Gourmet', cuisine: 'Chinese' }, { name: 'Bangkok Cuisine', cuisine: 'Thai' }, { name: 'Darbar Indian Cuisine', cuisine: 'Indian' }, { name: 'Mantra', cuisine: 'Indian' }, { name: 'Janta', cuisine: 'Indian' }, { name: 'Starbucks', cuisine: 'Coffee' }, { name: 'Peet\'s Coffee', cuisine: 'Coffee' }, { name: 'Coupa Cafe', cuisine: 'Coffee' }, { name: 'Lytton Coffee Company', cuisine: 'Coffee' }, { name: 'Il Fornaio', cuisine: 'Italian' }, { name: 'Lavanda', cuisine: 'Mediterranean' }, { name: 'MacArthur Park', cuisine: 'American' }, { name: 'St Michael\'s Alley', cuisine: 'Californian' }, { name: 'Cafe Renzo', cuisine: 'Italian' }, { name: 'Miyake', cuisine: 'Sushi' }, { name: 'Sushi Tomo', cuisine: 'Sushi' }, { name: 'Kanpai', cuisine: 'Sushi' }, { name: 'Pizza My Heart', cuisine: 'Pizza' }, { name: 'New York Pizza', cuisine: 'Pizza' }, { name: 'Loving Hut', cuisine: 'Vegan' }, { name: 'Garden Fresh', cuisine: 'Vegan' }, { name: 'Cafe Epi', cuisine: 'French' }, { name: 'Tai Pan', cuisine: 'Chinese' }] }); Ext.create('Ext.container.Viewport', { items: Ext.create('Ext.ux.GroupComboBox', { fieldLabel: 'Restaurants', name: 'txtRestaurant', forceSelection: true, editable: false, queryMode: 'local', triggerAction: 'all', multiSelect: true, groupField: 'cuisine', displayField: 'name', valueField: 'name', store: Restaurants, width: 400 }) }).show(); ``` ```css .grouped-list .x-boundlist-item { padding: 1px 3px 0 10px; } .grouped-list .group-header { padding: 4px; font-weight: bold; border-bottom: 1px solid #ddd; } ```
That is the code the worked for me: If you are using Sencha Architect, add the createPicker inside an Override and manually create the listConfig as an Object. ``` { xtype: 'combobox', createPicker: function() { var me = this, picker, menuCls = Ext.baseCSSPrefix + 'menu', opts = Ext.apply({ selModel: { mode: me.multiSelect ? 'SIMPLE' : 'SINGLE' }, floating: true, hidden: true, ownerCt: me.ownerCt, cls: me.el.up('.' + menuCls) ? menuCls : '', store: me.store, displayField: me.displayField, focusOnToFront: false, pageSize: me.pageSize }, me.listConfig, me.defaultListConfig); // NOTE: we simply use a grid panel //picker = me.picker = Ext.create('Ext.view.BoundList', opts); picker = me.picker = Ext.create('Ext.grid.Panel', opts); // hack: pass getNode() to the view picker.getNode = function() { picker.getView().getNode(arguments); }; me.mon(picker.getView(), { refresh: me.onListRefresh, scope: me }); me.mon(picker, { itemclick: me.onItemClick, // refresh: me.onListRefresh, scope: me }); me.mon(picker.getSelectionModel(), { selectionChange: me.onListSelectionChange, scope: me }); return picker; }, listConfig: { columns: [{ xtype: "gridcolumn", dataIndex: "id", text: "Id" }, { xtype: "gridcolumn", dataIndex: "name", text: "Name" }], features: [{ ftype: "grouping" }] }, fieldLabel: 'Label', queryMode: 'local', store: 'myTestStore' } ```
17,217,266
I am trying to group results that I am getting from store to be displayed inside ComboBox . I have a combobox that looks like this: ![enter image description here](https://i.stack.imgur.com/dMXO1.png) and I need it to look like this : ![enter image description here](https://i.stack.imgur.com/7mFAE.png) That means grouped by category (order / invoice ). My combobox defined like this : ``` Ext.define('NG.view.searchcombo.Combo', { requires: ['Ext.form.field.ComboBox'], extend: 'Ext.form.ComboBox', alias: 'widget.searchcombo', minChars:3, fieldLabel: 'Choose Search', store: 'Search', displayField: 'name', valueField: 'id', typeAhead: false, hideLabel: true, hideTrigger:false, anchor: '100%', listConfig: { loadingText: 'Searching...', emptyText: 'No matching posts found.', // Custom rendering template for each item getInnerTpl: function() { return '<h3>{name} / {category}</h3>' +'{excerpt}' ; } }, pageSize: 10, initComponent: function () { this.callParent(arguments); } }); ``` and my data is like this : ``` [{ "id": 1, "name": "one", "category": "invoice" }, { "id": 2, "name": "two", "category": "invoice" }, { "id": 3, "name": "one", "category": "order" }, { "id": 4, "name": "two", "category": "order" }, { "id": 5, "name": "three", "category": "invoice" }, { "id": 6, "name": "four", "category": "invoice" }, { "id": 7, "name": "three", "category": "order" }, { "id": 8, "name": "four", "category": "order" }, { "id": 9, "name": "five", "category": "invoice" }, { "id": 10, "name": "six", "category": "invoice" }, { "id": 11, "name": "five", "category": "order" }, { "id": 12, "name": "six", "category": "order" }, { "id": 13, "name": "seven", "category": "invoice" }, { "id": 14, "name": "eight", "category": "invoice" }, { "id": 15, "name": "seven", "category": "order" }, { "id": 16, "name": "eight", "category": "order" }] ``` I think that can be done by using `Ext.XTemplate` but I am not familiar with `Ext.XTemplate`.
2013/06/20
[ "https://Stackoverflow.com/questions/17217266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1035712/" ]
I wanted a much simpler solution, so I'll share what I came up with. For my purposes, I had a `key` that I wanted to group on, which is a single character. I knew the headers I wanted to show for each key, so I pre-sorted the list to make sure the types came together, and then I just render a group header each time I see a new key. ``` myStore.sort('key', 'DESC'); Ext.create('Ext.form.field.ComboBox', { store: myStore, queryMode: 'local', displayField: 'name', valueField: 'id', listConfig: { cls: 'grouped-list' }, tpl: Ext.create('Ext.XTemplate', '{[this.currentKey = null]}' + '<tpl for=".">', '<tpl if="this.shouldShowHeader(key)">' + '<div class="group-header">{[this.showHeader(values.key)]}</div>' + '</tpl>' + '<div class="x-boundlist-item">{name}</div>', '</tpl>', { shouldShowHeader: function(key){ return this.currentKey != key; }, showHeader: function(key){ this.currentKey = key; switch (key) { case 's': return 'Structures'; case 'f': return 'Filters'; ... } return 'Other'; } } ) }); ``` Using the following CSS: ``` .grouped-list .x-boundlist-item { padding: 1px 3px 0 10px } .grouped-list .group-header { padding: 4px; font-weight: bold; border-bottom: 1px solid #ddd; } ``` And this data: ``` [ { key: 's', name: '2014 Product Development' }, { key: 'f', name: 'Message Filter' }, { key: 's', name: '2014 Product Development (Little)' }, { key: 's', name: 'Global Structure' }, { key: 'f', name: 'My SW' } ] ``` I get a nice looking grouped list like this: ![](https://i.stack.imgur.com/GxK8U.png)
I've implemented my own version of the combo with a grid as its list component. You can get it on [GitHub](https://github.com/rixo/GridPicker), and I've put some [examples online](http://planysphere.fr/ext/GridPicker/examples/). The 3rd example closely matches what you're trying to achieve. Here's an example that would match even more closely. You'd only be left with the styling to do: ``` Ext.widget('gridpicker', { queryMode: 'local' ,displayField: 'name' ,store: { fields: ['name', 'group'] ,proxy: {type: 'memory', reader: 'array'} ,data: ... ,groupField: 'group' ,sorters: {property: 'name', order: 'ASC'} } ,gridConfig: { features: [{ ftype:'grouping' ,groupHeaderTpl: '{name}' ,collapsible: false }] ,columns: [{ width: 30 ,renderer: function(value, md, record, rowIndex) { return '<img src="..." />'; } },{ dataIndex: 'name' ,flex: 1 }] } }); ```
17,217,266
I am trying to group results that I am getting from store to be displayed inside ComboBox . I have a combobox that looks like this: ![enter image description here](https://i.stack.imgur.com/dMXO1.png) and I need it to look like this : ![enter image description here](https://i.stack.imgur.com/7mFAE.png) That means grouped by category (order / invoice ). My combobox defined like this : ``` Ext.define('NG.view.searchcombo.Combo', { requires: ['Ext.form.field.ComboBox'], extend: 'Ext.form.ComboBox', alias: 'widget.searchcombo', minChars:3, fieldLabel: 'Choose Search', store: 'Search', displayField: 'name', valueField: 'id', typeAhead: false, hideLabel: true, hideTrigger:false, anchor: '100%', listConfig: { loadingText: 'Searching...', emptyText: 'No matching posts found.', // Custom rendering template for each item getInnerTpl: function() { return '<h3>{name} / {category}</h3>' +'{excerpt}' ; } }, pageSize: 10, initComponent: function () { this.callParent(arguments); } }); ``` and my data is like this : ``` [{ "id": 1, "name": "one", "category": "invoice" }, { "id": 2, "name": "two", "category": "invoice" }, { "id": 3, "name": "one", "category": "order" }, { "id": 4, "name": "two", "category": "order" }, { "id": 5, "name": "three", "category": "invoice" }, { "id": 6, "name": "four", "category": "invoice" }, { "id": 7, "name": "three", "category": "order" }, { "id": 8, "name": "four", "category": "order" }, { "id": 9, "name": "five", "category": "invoice" }, { "id": 10, "name": "six", "category": "invoice" }, { "id": 11, "name": "five", "category": "order" }, { "id": 12, "name": "six", "category": "order" }, { "id": 13, "name": "seven", "category": "invoice" }, { "id": 14, "name": "eight", "category": "invoice" }, { "id": 15, "name": "seven", "category": "order" }, { "id": 16, "name": "eight", "category": "order" }] ``` I think that can be done by using `Ext.XTemplate` but I am not familiar with `Ext.XTemplate`.
2013/06/20
[ "https://Stackoverflow.com/questions/17217266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1035712/" ]
This is an extension that improves on Sean Adkinson answer above by making a reusable component from his code. I have had mixed results with replacing BoundList with a GridPanel with Ext 5.0.1 there for this is what I used. One caveat it does not support collapsing the groups but it works great for me. Tested in Extjs 4.2.3 and 5.0.1. You can see it in Sencha [fiddle](https://fiddle.sencha.com/fiddle/e5n) Hope it helps someone out there. ```js Ext.define('Ext.ux.GroupComboBox', { extend: 'Ext.form.field.ComboBox', alias: 'widget.groupcombobox', /* * @cfg groupField String value of field to groupBy, set this to any field in your model */ groupField: 'group', listConfig: { cls: 'grouped-list' }, initComponent: function() { var me = this; me.tpl = new Ext.XTemplate([ '{%this.currentGroup = null%}', '<tpl for=".">', ' <tpl if="this.shouldShowHeader(' + me.groupField + ')">', ' <div class="group-header">{[this.showHeader(values.' + me.groupField + ')]}</div>', ' </tpl>', ' <div class="x-boundlist-item">{' + me.displayField + '}</div>', '</tpl>', { shouldShowHeader: function(group) { return this.currentGroup != group; }, showHeader: function(group) { this.currentGroup = group; return group; } } ]); me.callParent(arguments); } }); //Example usage var Restaurants = Ext.create('Ext.data.Store', { storeId: 'restaraunts', fields: ['name', 'cuisine'], sorters: ['cuisine', 'name'], groupField: 'cuisine', data: [{ name: 'Cheesecake Factory', cuisine: 'American' }, { name: 'University Cafe', cuisine: 'American' }, { name: 'Creamery', cuisine: 'American' }, { name: 'Old Pro', cuisine: 'American' }, { name: 'Nola\'s', cuisine: 'Cajun' }, { name: 'House of Bagels', cuisine: 'Bagels' }, { name: 'The Prolific Oven', cuisine: 'Sandwiches' }, { name: 'La Strada', cuisine: 'Italian' }, { name: 'Buca di Beppo', cuisine: 'Italian' }, { name: 'Pasta?', cuisine: 'Italian' }, { name: 'Madame Tam', cuisine: 'Asian' }, { name: 'Sprout Cafe', cuisine: 'Salad' }, { name: 'Pluto\'s', cuisine: 'Salad' }, { name: 'Junoon', cuisine: 'Indian' }, { name: 'Bistro Maxine', cuisine: 'French' }, { name: 'Three Seasons', cuisine: 'Vietnamese' }, { name: 'Sancho\'s Taquira', cuisine: 'Mexican' }, { name: 'Reposado', cuisine: 'Mexican' }, { name: 'Siam Royal', cuisine: 'Thai' }, { name: 'Krung Siam', cuisine: 'Thai' }, { name: 'Thaiphoon', cuisine: 'Thai' }, { name: 'Tamarine', cuisine: 'Vietnamese' }, { name: 'Joya', cuisine: 'Tapas' }, { name: 'Jing Jing', cuisine: 'Chinese' }, { name: 'Patxi\'s Pizza', cuisine: 'Pizza' }, { name: 'Evvia Estiatorio', cuisine: 'Mediterranean' }, { name: 'Gyros-Gyros', cuisine: 'Mediterranean' }, { name: 'Mango Caribbean Cafe', cuisine: 'Caribbean' }, { name: 'Coconuts Caribbean Restaurant &amp; Bar', cuisine: 'Caribbean' }, { name: 'Rose &amp; Crown', cuisine: 'English' }, { name: 'Baklava', cuisine: 'Mediterranean' }, { name: 'Mandarin Gourmet', cuisine: 'Chinese' }, { name: 'Bangkok Cuisine', cuisine: 'Thai' }, { name: 'Darbar Indian Cuisine', cuisine: 'Indian' }, { name: 'Mantra', cuisine: 'Indian' }, { name: 'Janta', cuisine: 'Indian' }, { name: 'Starbucks', cuisine: 'Coffee' }, { name: 'Peet\'s Coffee', cuisine: 'Coffee' }, { name: 'Coupa Cafe', cuisine: 'Coffee' }, { name: 'Lytton Coffee Company', cuisine: 'Coffee' }, { name: 'Il Fornaio', cuisine: 'Italian' }, { name: 'Lavanda', cuisine: 'Mediterranean' }, { name: 'MacArthur Park', cuisine: 'American' }, { name: 'St Michael\'s Alley', cuisine: 'Californian' }, { name: 'Cafe Renzo', cuisine: 'Italian' }, { name: 'Miyake', cuisine: 'Sushi' }, { name: 'Sushi Tomo', cuisine: 'Sushi' }, { name: 'Kanpai', cuisine: 'Sushi' }, { name: 'Pizza My Heart', cuisine: 'Pizza' }, { name: 'New York Pizza', cuisine: 'Pizza' }, { name: 'Loving Hut', cuisine: 'Vegan' }, { name: 'Garden Fresh', cuisine: 'Vegan' }, { name: 'Cafe Epi', cuisine: 'French' }, { name: 'Tai Pan', cuisine: 'Chinese' }] }); Ext.create('Ext.container.Viewport', { items: Ext.create('Ext.ux.GroupComboBox', { fieldLabel: 'Restaurants', name: 'txtRestaurant', forceSelection: true, editable: false, queryMode: 'local', triggerAction: 'all', multiSelect: true, groupField: 'cuisine', displayField: 'name', valueField: 'name', store: Restaurants, width: 400 }) }).show(); ``` ```css .grouped-list .x-boundlist-item { padding: 1px 3px 0 10px; } .grouped-list .group-header { padding: 4px; font-weight: bold; border-bottom: 1px solid #ddd; } ```
I've implemented my own version of the combo with a grid as its list component. You can get it on [GitHub](https://github.com/rixo/GridPicker), and I've put some [examples online](http://planysphere.fr/ext/GridPicker/examples/). The 3rd example closely matches what you're trying to achieve. Here's an example that would match even more closely. You'd only be left with the styling to do: ``` Ext.widget('gridpicker', { queryMode: 'local' ,displayField: 'name' ,store: { fields: ['name', 'group'] ,proxy: {type: 'memory', reader: 'array'} ,data: ... ,groupField: 'group' ,sorters: {property: 'name', order: 'ASC'} } ,gridConfig: { features: [{ ftype:'grouping' ,groupHeaderTpl: '{name}' ,collapsible: false }] ,columns: [{ width: 30 ,renderer: function(value, md, record, rowIndex) { return '<img src="..." />'; } },{ dataIndex: 'name' ,flex: 1 }] } }); ```
17,217,266
I am trying to group results that I am getting from store to be displayed inside ComboBox . I have a combobox that looks like this: ![enter image description here](https://i.stack.imgur.com/dMXO1.png) and I need it to look like this : ![enter image description here](https://i.stack.imgur.com/7mFAE.png) That means grouped by category (order / invoice ). My combobox defined like this : ``` Ext.define('NG.view.searchcombo.Combo', { requires: ['Ext.form.field.ComboBox'], extend: 'Ext.form.ComboBox', alias: 'widget.searchcombo', minChars:3, fieldLabel: 'Choose Search', store: 'Search', displayField: 'name', valueField: 'id', typeAhead: false, hideLabel: true, hideTrigger:false, anchor: '100%', listConfig: { loadingText: 'Searching...', emptyText: 'No matching posts found.', // Custom rendering template for each item getInnerTpl: function() { return '<h3>{name} / {category}</h3>' +'{excerpt}' ; } }, pageSize: 10, initComponent: function () { this.callParent(arguments); } }); ``` and my data is like this : ``` [{ "id": 1, "name": "one", "category": "invoice" }, { "id": 2, "name": "two", "category": "invoice" }, { "id": 3, "name": "one", "category": "order" }, { "id": 4, "name": "two", "category": "order" }, { "id": 5, "name": "three", "category": "invoice" }, { "id": 6, "name": "four", "category": "invoice" }, { "id": 7, "name": "three", "category": "order" }, { "id": 8, "name": "four", "category": "order" }, { "id": 9, "name": "five", "category": "invoice" }, { "id": 10, "name": "six", "category": "invoice" }, { "id": 11, "name": "five", "category": "order" }, { "id": 12, "name": "six", "category": "order" }, { "id": 13, "name": "seven", "category": "invoice" }, { "id": 14, "name": "eight", "category": "invoice" }, { "id": 15, "name": "seven", "category": "order" }, { "id": 16, "name": "eight", "category": "order" }] ``` I think that can be done by using `Ext.XTemplate` but I am not familiar with `Ext.XTemplate`.
2013/06/20
[ "https://Stackoverflow.com/questions/17217266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1035712/" ]
I wanted a much simpler solution, so I'll share what I came up with. For my purposes, I had a `key` that I wanted to group on, which is a single character. I knew the headers I wanted to show for each key, so I pre-sorted the list to make sure the types came together, and then I just render a group header each time I see a new key. ``` myStore.sort('key', 'DESC'); Ext.create('Ext.form.field.ComboBox', { store: myStore, queryMode: 'local', displayField: 'name', valueField: 'id', listConfig: { cls: 'grouped-list' }, tpl: Ext.create('Ext.XTemplate', '{[this.currentKey = null]}' + '<tpl for=".">', '<tpl if="this.shouldShowHeader(key)">' + '<div class="group-header">{[this.showHeader(values.key)]}</div>' + '</tpl>' + '<div class="x-boundlist-item">{name}</div>', '</tpl>', { shouldShowHeader: function(key){ return this.currentKey != key; }, showHeader: function(key){ this.currentKey = key; switch (key) { case 's': return 'Structures'; case 'f': return 'Filters'; ... } return 'Other'; } } ) }); ``` Using the following CSS: ``` .grouped-list .x-boundlist-item { padding: 1px 3px 0 10px } .grouped-list .group-header { padding: 4px; font-weight: bold; border-bottom: 1px solid #ddd; } ``` And this data: ``` [ { key: 's', name: '2014 Product Development' }, { key: 'f', name: 'Message Filter' }, { key: 's', name: '2014 Product Development (Little)' }, { key: 's', name: 'Global Structure' }, { key: 'f', name: 'My SW' } ] ``` I get a nice looking grouped list like this: ![](https://i.stack.imgur.com/GxK8U.png)
This is an extension that improves on Sean Adkinson answer above by making a reusable component from his code. I have had mixed results with replacing BoundList with a GridPanel with Ext 5.0.1 there for this is what I used. One caveat it does not support collapsing the groups but it works great for me. Tested in Extjs 4.2.3 and 5.0.1. You can see it in Sencha [fiddle](https://fiddle.sencha.com/fiddle/e5n) Hope it helps someone out there. ```js Ext.define('Ext.ux.GroupComboBox', { extend: 'Ext.form.field.ComboBox', alias: 'widget.groupcombobox', /* * @cfg groupField String value of field to groupBy, set this to any field in your model */ groupField: 'group', listConfig: { cls: 'grouped-list' }, initComponent: function() { var me = this; me.tpl = new Ext.XTemplate([ '{%this.currentGroup = null%}', '<tpl for=".">', ' <tpl if="this.shouldShowHeader(' + me.groupField + ')">', ' <div class="group-header">{[this.showHeader(values.' + me.groupField + ')]}</div>', ' </tpl>', ' <div class="x-boundlist-item">{' + me.displayField + '}</div>', '</tpl>', { shouldShowHeader: function(group) { return this.currentGroup != group; }, showHeader: function(group) { this.currentGroup = group; return group; } } ]); me.callParent(arguments); } }); //Example usage var Restaurants = Ext.create('Ext.data.Store', { storeId: 'restaraunts', fields: ['name', 'cuisine'], sorters: ['cuisine', 'name'], groupField: 'cuisine', data: [{ name: 'Cheesecake Factory', cuisine: 'American' }, { name: 'University Cafe', cuisine: 'American' }, { name: 'Creamery', cuisine: 'American' }, { name: 'Old Pro', cuisine: 'American' }, { name: 'Nola\'s', cuisine: 'Cajun' }, { name: 'House of Bagels', cuisine: 'Bagels' }, { name: 'The Prolific Oven', cuisine: 'Sandwiches' }, { name: 'La Strada', cuisine: 'Italian' }, { name: 'Buca di Beppo', cuisine: 'Italian' }, { name: 'Pasta?', cuisine: 'Italian' }, { name: 'Madame Tam', cuisine: 'Asian' }, { name: 'Sprout Cafe', cuisine: 'Salad' }, { name: 'Pluto\'s', cuisine: 'Salad' }, { name: 'Junoon', cuisine: 'Indian' }, { name: 'Bistro Maxine', cuisine: 'French' }, { name: 'Three Seasons', cuisine: 'Vietnamese' }, { name: 'Sancho\'s Taquira', cuisine: 'Mexican' }, { name: 'Reposado', cuisine: 'Mexican' }, { name: 'Siam Royal', cuisine: 'Thai' }, { name: 'Krung Siam', cuisine: 'Thai' }, { name: 'Thaiphoon', cuisine: 'Thai' }, { name: 'Tamarine', cuisine: 'Vietnamese' }, { name: 'Joya', cuisine: 'Tapas' }, { name: 'Jing Jing', cuisine: 'Chinese' }, { name: 'Patxi\'s Pizza', cuisine: 'Pizza' }, { name: 'Evvia Estiatorio', cuisine: 'Mediterranean' }, { name: 'Gyros-Gyros', cuisine: 'Mediterranean' }, { name: 'Mango Caribbean Cafe', cuisine: 'Caribbean' }, { name: 'Coconuts Caribbean Restaurant &amp; Bar', cuisine: 'Caribbean' }, { name: 'Rose &amp; Crown', cuisine: 'English' }, { name: 'Baklava', cuisine: 'Mediterranean' }, { name: 'Mandarin Gourmet', cuisine: 'Chinese' }, { name: 'Bangkok Cuisine', cuisine: 'Thai' }, { name: 'Darbar Indian Cuisine', cuisine: 'Indian' }, { name: 'Mantra', cuisine: 'Indian' }, { name: 'Janta', cuisine: 'Indian' }, { name: 'Starbucks', cuisine: 'Coffee' }, { name: 'Peet\'s Coffee', cuisine: 'Coffee' }, { name: 'Coupa Cafe', cuisine: 'Coffee' }, { name: 'Lytton Coffee Company', cuisine: 'Coffee' }, { name: 'Il Fornaio', cuisine: 'Italian' }, { name: 'Lavanda', cuisine: 'Mediterranean' }, { name: 'MacArthur Park', cuisine: 'American' }, { name: 'St Michael\'s Alley', cuisine: 'Californian' }, { name: 'Cafe Renzo', cuisine: 'Italian' }, { name: 'Miyake', cuisine: 'Sushi' }, { name: 'Sushi Tomo', cuisine: 'Sushi' }, { name: 'Kanpai', cuisine: 'Sushi' }, { name: 'Pizza My Heart', cuisine: 'Pizza' }, { name: 'New York Pizza', cuisine: 'Pizza' }, { name: 'Loving Hut', cuisine: 'Vegan' }, { name: 'Garden Fresh', cuisine: 'Vegan' }, { name: 'Cafe Epi', cuisine: 'French' }, { name: 'Tai Pan', cuisine: 'Chinese' }] }); Ext.create('Ext.container.Viewport', { items: Ext.create('Ext.ux.GroupComboBox', { fieldLabel: 'Restaurants', name: 'txtRestaurant', forceSelection: true, editable: false, queryMode: 'local', triggerAction: 'all', multiSelect: true, groupField: 'cuisine', displayField: 'name', valueField: 'name', store: Restaurants, width: 400 }) }).show(); ``` ```css .grouped-list .x-boundlist-item { padding: 1px 3px 0 10px; } .grouped-list .group-header { padding: 4px; font-weight: bold; border-bottom: 1px solid #ddd; } ```
46,998,985
HTML: ``` <form> <div class="form-group"> <label for="vorname">Vorname</label> <input type="text" class="form-control" id="vorname" onkeyup="createLoginName();" placeholder=""> </div> <div class="form-group"> <label for="nachname">Nachname</label> <input type="text" class="form-control" id="nachname" onkeyup="createLoginName();" placeholder=""> </div> <div class="form-group"> <label for="loginname">Loginname</label> <input type="text" class="form-control" id="loginname" placeholder="" disabled> </div> <div class="form-group"> <label for="passwort">Passwort</label> <input type="password" class="form-control" id="passwort1" onkeyup="char_count();" placeholder=""> </div> <div class="form-group"> <label for="passwort">Passwort wiederholen</label> <input type="password" class="form-control" id="passwort2" onkeyup="char_count(); checkPassword();" placeholder=""> </div> <p><span id="feedback"></span></p> <button type="submit" id="registrieren" class="btn btn-primary">Registrieren</button> </form> ``` JavaScript: ``` checkPassword(); function checkPassword(){ var inputPasswort1 = document.getElementById("passwort1").value; var inputPasswort2 = document.getElementById("passwort2").value; if(inputPasswort1 != inputPasswort2){ document.getElementById("registrieren").setAttribute("disabled", "true"); } else { document.getElementById("registrieren").setAttribute("disabled", "false"); } } ``` I tried different things already but it doesn't seem to work. Any ideas or suggestions? With **console.log(inputPasswort1 + " " + inputPasswort2);** I checked both variables but they are okay, I get the correct values. <https://jsfiddle.net/t8hx3wk7/4/>
2017/10/29
[ "https://Stackoverflow.com/questions/46998985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8582176/" ]
I would phrase this as: ``` INSERT INTO temp_Log (?, ?) -- put the column names here SELECT dq1.RowID, (CASE WHEN MIN(dq1.Action) = MAX(d1.Action) THEN MIN(dq1.Action) WHEN SUM(dq1.Action = 'Allow') > 0 AND SUM(dq1.Action = 'Reject') > 0 THEN 'Reject' WHEN SUM(dq1.Action = 'Allow') > 0 AND SUM(dq1.Action = 'Fix') > 0 THEN 'Fix' ELSE ?? -- your rules don't specify END) as Action FROM DQLog dq1 WHERE NOT EXISTS (SELECT 1 FROM DQLog d12 WHERE dq1.RowID = dq2.RowID ) GROUP BY dq1.RowId; ``` Notes: * List the columns when doing an insert. This is a best practice and will prevent coding errors in the future. * This includes the two rules you specify. However, there are other cases you don't specify. Hence, the `ELSE ??`. * `NOT EXISTS` is better than `NOT IN` for two reasons. First, `NOT IN` will filter out all rows if even one row in the subquery is `NULL`. Second, `NOT EXISTS` should be faster than having an aggregation subquery.
If it's not possible that a Row\_ID has Allow as Action more than once, then following query should work: ``` INSERT INTO temp_Log (SELECT distinct RowID,Action FROM DQLog Where Action = 'Reject' UNION ALL SELECT distinct RowID,Action FROM DQLog Where Action = 'Fix' And RowID not in (Select distinct RowID from DQLog where Action='Reject') ) ; ``` **EDIT:** I've mentioned 2 options in my comment. Here it how it goes: **Option 1:** Convert Action columns to lower case values. ``` Update DQLog set Action = Lower(Action); ``` The above query will convert all the values of `Action` in Lower case. Now you can run following query and it's done: ``` INSERT INTO temp_Log (SELECT distinct RowID,Action FROM DQLog Where Action = 'reject' UNION ALL SELECT distinct RowID,Action FROM DQLog Where Action = 'fix' And RowID not in (Select distinct RowID from DQLog where Action='reject') ) ; ``` Hence your task is done and your redundant data is fixed too. ``` Option 2: ``` Just add the all possible variation of `Fix` and `Reject` in where clause of my main query as follows: ``` INSERT INTO temp_Log (SELECT distinct RowID,Action FROM DQLog Where Action = 'Reject' or Action='reject' UNION ALL SELECT distinct RowID,Action FROM DQLog Where Action = 'Fix' or Action = 'fix' And RowID not in (Select distinct RowID from DQLog where Action='Reject'or Action='reject') ) ; ``` I will advice you to go for `Option 1` ! Hope it helps!
41,487,598
I have a client with a Azure subscription sitting in a US GOV data center. This subscription is under an EA (not pay-as-you-go). Attempting to use the standard billing APIs (ratecard and usage) fails with a 'Subscription not found' error. I.e. running the following: ``` https://management.azure.com/subscriptions/[subscription id here]/providers/Microsoft.Commerce/RateCard?api-version=2015-06-01-preview&$filter=OfferDurableId eq 'MS-AZR-USGOV-0017P' and Currency eq 'USD' and Locale eq 'en-US' and RegionInfo eq 'US' ``` fails with: ``` { "error": { "code": "SubscriptionNotFound", "message": "The subscription '[subscription id here]' could not be found." } } ``` I've found very little information on the rate card and usage APIs with EA accounts and even less information on these APIs for accounts running in a US GOV Azure region. Does anyone know if this is supposed to work?
2017/01/05
[ "https://Stackoverflow.com/questions/41487598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7379668/" ]
I don't have any experience with the Gov environment, but otherwise my experience is that Resource Usage API also works for EA, whereas the RateCard does not. I would suggest you to start out with the powershell cmdlets for an easy start \* *Get-AzureRmUsage* <https://learn.microsoft.com/en-us/powershell/resourcemanager/azurerm.insights/v2.3.0/get-azurermusage> Be sure that you have powershell running correctly towards the Government environment first. If you want to roll your own client remember to use the correct endpoints as described in "Azure Government developer guide" <https://learn.microsoft.com/en-us/azure/azure-government-developer-guide> Brgds Brian
For EA offer IDs, you need to use the following API: > > <https://consumption.azure.com/v2/enrollments/(enrollment_id)/pricesheet> > > > You will need to provide EA API Key (different than bearer token from other APIs): > > curl -X GET <https://consumption.azure.com/v2/enrollments/(enrollment_id)/pricesheet> -H 'authorization: Bearer (api\_key)' > > > Note that the API bearer token needs to be created in the EA Portal under the User Account. More detail can be found here: <https://learn.microsoft.com/en-us/azure/billing/billing-enterprise-api> Also note that the user must have appropriate privileges otherwise the API will reject your request.
54,667,290
On the app that I develop I want to have english and greek in debug mode (because I don't speak greek and the app is for Greece) and only Greek when when in release( because I have a requirement to only support Greek and no english when the app is released). So, does anyone know how can I do this in iOS?
2019/02/13
[ "https://Stackoverflow.com/questions/54667290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4915700/" ]
As you have a timestamp column it's probably better to use `systimestamp` instead of `sysdate`, and add an interval rather than a fraction of a day - which would lose the fractional second precision (and time zone, if your column actually stores that too). You would either just have a date (if you use `sysdate + 30/1440`) or implicitly convert to a date (if you use `systimestamp + 30/1440`); and either way will you'll end up with a date that is then implicitly or explicitly converted to a timestamp as it's stored in your column. As a simple example of using an interval: ``` create table t42 (col1 number, col2 timestamp); create trigger tr42 before insert on t42 for each row begin :new.col2 := systimestamp + interval '30' minute; end; / select systimestamp from dual; SYSTIMESTAMP --------------------------------- 2019-02-13 07:17:11.971542000 GMT insert into t42 (col1) values (42); select col1, col2 from t42; COL1 COL2 ---------- ----------------------------- 42 2019-02-13 07:47:12.253603000 ``` You could also use a default value for the column instead of a trigger: ``` create table t42 ( col1 number, col2 timestamp default systimestamp + interval '30' minute ); select systimestamp from dual; SYSTIMESTAMP --------------------------------- 2019-02-13 07:17:12.962268000 GMT insert into t42 (col1) values (42); select col1, col2 from t42; COL1 COL2 ---------- ----------------------------- 42 2019-02-13 07:47:13.028670000 ``` although that does allow the person doing the insert to provide their own value: ``` insert into t42 (col1, col2) values (43, timestamp '2000-01-01 00:00:00.0'); select col1, col2 from t42; COL1 COL2 ---------- ----------------------------- 42 2019-02-13 07:47:13.028670000 43 2000-01-01 00:00:00.000000000 ``` The trigger would override any user-supplied value (though it could also be modified not to.) You could also use `current_timestamp` instead of `systimestamp` - [they do slightly different things](https://stackoverflow.com/a/17925834/266304).
you can create a trigger as shown below. this will insert current timestamp+30 minutes each time you insert a row to the table. ``` create or replace trigger before_insert before insert on table_name for each row declare v_time date; begin select sysdate+30/1440 into v_time from dual; :new.cur_time :=v_time; end; / ```
54,156,313
For example: in this repo, <https://github.com/evancz/elm-architecture-tutorial/> , how do I load one of the Elm files into elm repl, so I can evaluate functions, look at type signatures, etc ? In Haskell I would use :l
2019/01/12
[ "https://Stackoverflow.com/questions/54156313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9325070/" ]
Unfortunately the examples on the GitHub link don't expose anything, so you cannot import from them as-is. Since you have access to source code you can of course modify the sources to support this, so read on :) In general, it is done in repl by using command `import` > > import SomeModule exposing (fun1, fun2) > > > `SomeModule` is the name of the module where to import, and `fun1` and `fun2` are functions to import. For importing all functions, use `(..)` When the repl is started in the same folder as the modules, the import works. Maybe there's some option for repl to set the sources directory, but I could not find it. But for something to be imported from a module, it needs to export it in the source file, like this for example > > module SomeModule exposing (fun1, fun2) > > >
This would be better placed as a comment on kaskelotti's good answer above, but in order to have the module in a different folder from where you start the repl, you can update the `elm.json` file associated with your project, adding "YOUR\_DESIRED\_DIRECTORY" to the "source-directories" array. Also note that the filename needs to match the module name in the export and import statements: so that ``` module SomeModule exposing (fun1, fun2) ``` would require a file named SomeModule.elm (at least in my experience)
36,533
I have a cast iron skillet and one of the guests coming for dinner is vegan. Since cast iron is seasoned by all kinds of grease over time I wonder if this is suitable for vegans. I don't want to offend anyone or witness some drama.
2013/09/04
[ "https://cooking.stackexchange.com/questions/36533", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/15020/" ]
A vegan is not going to eat your pan, just the food that was made on it. As no animals were harmed in the making of your pan (well, probably but how would you know) the pan itself wouldn't be an issue. Of course if a tiny bit of pan seasoning could go into the food, however anything else used in the preparation of the meal like cutting boards could cause a small amount of meat product to go into the food as well. Your kitchen is not vegan, and if a vegan has a problem with that they should not come over for a meal. I'd be extremely surprised if the subject of your pots and pans came up to be honest, vegans I know appreciate people going to the effort of making a vegan meal for them.
You'd have to ask your vegan to be absolutely sure. If they're practical, they'll acknowledge that there might be a bit of meat fat polymerized onto the pan but they won't be actually eating it, as long as you've seasoned and cleaned well. If however they're sufficiently strict, they could conceivably say, no, it's touching an animal product, I won't eat it. I wouldn't call that person a common vegan (most are more practical), a reasonable vegan (they're not actually consuming animal products), or a polite guest (if you have extremely rare dietary restrictions you should communicate them clearly), but it's at least possible, so I feel it's worth pointing out since you sounded like you might be prioritizing avoiding offense over reason. You could in general safely assume she's the practical kind - I don't know any vegetarians (or vegans) who would be that picky. But if you can't ask her, there's of course no way to be totally sure, so if you want to make sure she'll eat everything and think she could be a very strict vegan, I suppose you could find another pan.
36,533
I have a cast iron skillet and one of the guests coming for dinner is vegan. Since cast iron is seasoned by all kinds of grease over time I wonder if this is suitable for vegans. I don't want to offend anyone or witness some drama.
2013/09/04
[ "https://cooking.stackexchange.com/questions/36533", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/15020/" ]
You'd have to ask your vegan to be absolutely sure. If they're practical, they'll acknowledge that there might be a bit of meat fat polymerized onto the pan but they won't be actually eating it, as long as you've seasoned and cleaned well. If however they're sufficiently strict, they could conceivably say, no, it's touching an animal product, I won't eat it. I wouldn't call that person a common vegan (most are more practical), a reasonable vegan (they're not actually consuming animal products), or a polite guest (if you have extremely rare dietary restrictions you should communicate them clearly), but it's at least possible, so I feel it's worth pointing out since you sounded like you might be prioritizing avoiding offense over reason. You could in general safely assume she's the practical kind - I don't know any vegetarians (or vegans) who would be that picky. But if you can't ask her, there's of course no way to be totally sure, so if you want to make sure she'll eat everything and think she could be a very strict vegan, I suppose you could find another pan.
I am a vegetarian and I am totally put off by the idea of seasoned pans that don't get cleaned with soap and water. One of the reasons I am a vegetarian is because I consider meat to be unclean (not a religious objection, just my own many-years' judgment), and I won't eat out of a pan I would consider uncleaned, which seasoned pans would be to me. It isn't that I don't understand the chemistry---I do---I know the germs are destroyed by the heat. But the concept of having my food cooked in a pan that is never actually stripped of its old oil (for the sake of the iron pan's surface health and nonstickability) makes me know that seasoned pans would not be for me, even with someone else cooking for me, and I love to be cooked for. Just a weigh-in here...also, all the vegans I've ever known are wayyyy fussier than I am, and I would be surprised that they wouldn't object to that type of pan.
36,533
I have a cast iron skillet and one of the guests coming for dinner is vegan. Since cast iron is seasoned by all kinds of grease over time I wonder if this is suitable for vegans. I don't want to offend anyone or witness some drama.
2013/09/04
[ "https://cooking.stackexchange.com/questions/36533", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/15020/" ]
You'd have to ask your vegan to be absolutely sure. If they're practical, they'll acknowledge that there might be a bit of meat fat polymerized onto the pan but they won't be actually eating it, as long as you've seasoned and cleaned well. If however they're sufficiently strict, they could conceivably say, no, it's touching an animal product, I won't eat it. I wouldn't call that person a common vegan (most are more practical), a reasonable vegan (they're not actually consuming animal products), or a polite guest (if you have extremely rare dietary restrictions you should communicate them clearly), but it's at least possible, so I feel it's worth pointing out since you sounded like you might be prioritizing avoiding offense over reason. You could in general safely assume she's the practical kind - I don't know any vegetarians (or vegans) who would be that picky. But if you can't ask her, there's of course no way to be totally sure, so if you want to make sure she'll eat everything and think she could be a very strict vegan, I suppose you could find another pan.
What people seem to be missing in some of these answers is that some people will become very ill upon eating trace amounts of animal material. Ask you guest if it is suitable or inform your guest of your intent so they can decide for themselves if they would like to eat your food. There's no dishonor in asking the question.
36,533
I have a cast iron skillet and one of the guests coming for dinner is vegan. Since cast iron is seasoned by all kinds of grease over time I wonder if this is suitable for vegans. I don't want to offend anyone or witness some drama.
2013/09/04
[ "https://cooking.stackexchange.com/questions/36533", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/15020/" ]
You'd have to ask your vegan to be absolutely sure. If they're practical, they'll acknowledge that there might be a bit of meat fat polymerized onto the pan but they won't be actually eating it, as long as you've seasoned and cleaned well. If however they're sufficiently strict, they could conceivably say, no, it's touching an animal product, I won't eat it. I wouldn't call that person a common vegan (most are more practical), a reasonable vegan (they're not actually consuming animal products), or a polite guest (if you have extremely rare dietary restrictions you should communicate them clearly), but it's at least possible, so I feel it's worth pointing out since you sounded like you might be prioritizing avoiding offense over reason. You could in general safely assume she's the practical kind - I don't know any vegetarians (or vegans) who would be that picky. But if you can't ask her, there's of course no way to be totally sure, so if you want to make sure she'll eat everything and think she could be a very strict vegan, I suppose you could find another pan.
I've only been a vegetarian for a little over 3 years. My roommate used a cast-iron skillet with vegetarian-appropriate seasoning to fry burgers. I thought I could handle it, but when the meat was cooking, and for several hours afterward, the smell of the cooked meat was literally disgusting. I am most surprised at myself, as I always loved burgers, even miss them some times. I didn't quit eating meat because I didn't like the taste, it was specifically for compassionate reasons. I guess after 3 years, it has become repulsive. I tried to cook with the pan after scrubbing it well, but the smell of the cooked meat rose up as soon as the pan was hot, and I knew I could not use the skillet again and went and bought a new one. I don't care if he uses one of my non-stick pans, or forks or knives, they don't absorb the animal juices like the seasoned cast iron skillets do.
36,533
I have a cast iron skillet and one of the guests coming for dinner is vegan. Since cast iron is seasoned by all kinds of grease over time I wonder if this is suitable for vegans. I don't want to offend anyone or witness some drama.
2013/09/04
[ "https://cooking.stackexchange.com/questions/36533", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/15020/" ]
A vegan is not going to eat your pan, just the food that was made on it. As no animals were harmed in the making of your pan (well, probably but how would you know) the pan itself wouldn't be an issue. Of course if a tiny bit of pan seasoning could go into the food, however anything else used in the preparation of the meal like cutting boards could cause a small amount of meat product to go into the food as well. Your kitchen is not vegan, and if a vegan has a problem with that they should not come over for a meal. I'd be extremely surprised if the subject of your pots and pans came up to be honest, vegans I know appreciate people going to the effort of making a vegan meal for them.
I am a vegetarian and I am totally put off by the idea of seasoned pans that don't get cleaned with soap and water. One of the reasons I am a vegetarian is because I consider meat to be unclean (not a religious objection, just my own many-years' judgment), and I won't eat out of a pan I would consider uncleaned, which seasoned pans would be to me. It isn't that I don't understand the chemistry---I do---I know the germs are destroyed by the heat. But the concept of having my food cooked in a pan that is never actually stripped of its old oil (for the sake of the iron pan's surface health and nonstickability) makes me know that seasoned pans would not be for me, even with someone else cooking for me, and I love to be cooked for. Just a weigh-in here...also, all the vegans I've ever known are wayyyy fussier than I am, and I would be surprised that they wouldn't object to that type of pan.
36,533
I have a cast iron skillet and one of the guests coming for dinner is vegan. Since cast iron is seasoned by all kinds of grease over time I wonder if this is suitable for vegans. I don't want to offend anyone or witness some drama.
2013/09/04
[ "https://cooking.stackexchange.com/questions/36533", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/15020/" ]
A vegan is not going to eat your pan, just the food that was made on it. As no animals were harmed in the making of your pan (well, probably but how would you know) the pan itself wouldn't be an issue. Of course if a tiny bit of pan seasoning could go into the food, however anything else used in the preparation of the meal like cutting boards could cause a small amount of meat product to go into the food as well. Your kitchen is not vegan, and if a vegan has a problem with that they should not come over for a meal. I'd be extremely surprised if the subject of your pots and pans came up to be honest, vegans I know appreciate people going to the effort of making a vegan meal for them.
What people seem to be missing in some of these answers is that some people will become very ill upon eating trace amounts of animal material. Ask you guest if it is suitable or inform your guest of your intent so they can decide for themselves if they would like to eat your food. There's no dishonor in asking the question.
36,533
I have a cast iron skillet and one of the guests coming for dinner is vegan. Since cast iron is seasoned by all kinds of grease over time I wonder if this is suitable for vegans. I don't want to offend anyone or witness some drama.
2013/09/04
[ "https://cooking.stackexchange.com/questions/36533", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/15020/" ]
A vegan is not going to eat your pan, just the food that was made on it. As no animals were harmed in the making of your pan (well, probably but how would you know) the pan itself wouldn't be an issue. Of course if a tiny bit of pan seasoning could go into the food, however anything else used in the preparation of the meal like cutting boards could cause a small amount of meat product to go into the food as well. Your kitchen is not vegan, and if a vegan has a problem with that they should not come over for a meal. I'd be extremely surprised if the subject of your pots and pans came up to be honest, vegans I know appreciate people going to the effort of making a vegan meal for them.
I've only been a vegetarian for a little over 3 years. My roommate used a cast-iron skillet with vegetarian-appropriate seasoning to fry burgers. I thought I could handle it, but when the meat was cooking, and for several hours afterward, the smell of the cooked meat was literally disgusting. I am most surprised at myself, as I always loved burgers, even miss them some times. I didn't quit eating meat because I didn't like the taste, it was specifically for compassionate reasons. I guess after 3 years, it has become repulsive. I tried to cook with the pan after scrubbing it well, but the smell of the cooked meat rose up as soon as the pan was hot, and I knew I could not use the skillet again and went and bought a new one. I don't care if he uses one of my non-stick pans, or forks or knives, they don't absorb the animal juices like the seasoned cast iron skillets do.
36,533
I have a cast iron skillet and one of the guests coming for dinner is vegan. Since cast iron is seasoned by all kinds of grease over time I wonder if this is suitable for vegans. I don't want to offend anyone or witness some drama.
2013/09/04
[ "https://cooking.stackexchange.com/questions/36533", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/15020/" ]
I am a vegetarian and I am totally put off by the idea of seasoned pans that don't get cleaned with soap and water. One of the reasons I am a vegetarian is because I consider meat to be unclean (not a religious objection, just my own many-years' judgment), and I won't eat out of a pan I would consider uncleaned, which seasoned pans would be to me. It isn't that I don't understand the chemistry---I do---I know the germs are destroyed by the heat. But the concept of having my food cooked in a pan that is never actually stripped of its old oil (for the sake of the iron pan's surface health and nonstickability) makes me know that seasoned pans would not be for me, even with someone else cooking for me, and I love to be cooked for. Just a weigh-in here...also, all the vegans I've ever known are wayyyy fussier than I am, and I would be surprised that they wouldn't object to that type of pan.
What people seem to be missing in some of these answers is that some people will become very ill upon eating trace amounts of animal material. Ask you guest if it is suitable or inform your guest of your intent so they can decide for themselves if they would like to eat your food. There's no dishonor in asking the question.
36,533
I have a cast iron skillet and one of the guests coming for dinner is vegan. Since cast iron is seasoned by all kinds of grease over time I wonder if this is suitable for vegans. I don't want to offend anyone or witness some drama.
2013/09/04
[ "https://cooking.stackexchange.com/questions/36533", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/15020/" ]
I've only been a vegetarian for a little over 3 years. My roommate used a cast-iron skillet with vegetarian-appropriate seasoning to fry burgers. I thought I could handle it, but when the meat was cooking, and for several hours afterward, the smell of the cooked meat was literally disgusting. I am most surprised at myself, as I always loved burgers, even miss them some times. I didn't quit eating meat because I didn't like the taste, it was specifically for compassionate reasons. I guess after 3 years, it has become repulsive. I tried to cook with the pan after scrubbing it well, but the smell of the cooked meat rose up as soon as the pan was hot, and I knew I could not use the skillet again and went and bought a new one. I don't care if he uses one of my non-stick pans, or forks or knives, they don't absorb the animal juices like the seasoned cast iron skillets do.
What people seem to be missing in some of these answers is that some people will become very ill upon eating trace amounts of animal material. Ask you guest if it is suitable or inform your guest of your intent so they can decide for themselves if they would like to eat your food. There's no dishonor in asking the question.
249,353
Suppose that $f\in L^1(0,+\infty)$ is a monotone decreasing, positive function. Prove that $$\lim\_{x \to +\infty}x(\log x)\cdot f(x)=0.$$
2012/12/02
[ "https://math.stackexchange.com/questions/249353", "https://math.stackexchange.com", "https://math.stackexchange.com/users/84067/" ]
The assertion is not true. Consider $$ f\_0=\sum\limits\_{n\geqslant1}(n^2\mathrm e^{n^2})^{-1}\mathbf 1\_{[0,\mathrm e^{n^2}]}, $$ then $f\_0$ is nonincreasing, $g\_0(x)=f\_0(x)x\log(x)$ does not converge to zero when $x\to\infty$ since $g\_0(\mathrm e^{n^2})\geqslant1$ for every $n\geqslant1$, and the integral of $f\_0$ is $\sum\limits\_{n\geqslant1}n^{-2}$, which is finite, hence $f\_0$ is integrable. One can modify this example slightly to get a decreasing function $f$, for example $$ f(x)=\sum\limits\_{n\geqslant1}(n^2\mathrm e^{n^2})^{-1}\exp(-x\mathrm e^{-n^2})\mathbf 1\_{[0,\mathrm e^{n^2}]}(x). $$ Then $f$ is decreasing, $g(x)=f(x)x\log(x)$ does not converge to zero when $x\to\infty$ since $g(\mathrm e^{n^2})\geqslant\mathrm e^{-1}$ for every $n\geqslant1$, and $f\leqslant f\_0$ hence $f$ is integrable.
I think it's not true, for example $f(x)=1/x$ and we have $\lim\_{x\rightarrow 0}xln(x)(1/x)=+\infty$
249,353
Suppose that $f\in L^1(0,+\infty)$ is a monotone decreasing, positive function. Prove that $$\lim\_{x \to +\infty}x(\log x)\cdot f(x)=0.$$
2012/12/02
[ "https://math.stackexchange.com/questions/249353", "https://math.stackexchange.com", "https://math.stackexchange.com/users/84067/" ]
The assertion is not true. Consider $$ f\_0=\sum\limits\_{n\geqslant1}(n^2\mathrm e^{n^2})^{-1}\mathbf 1\_{[0,\mathrm e^{n^2}]}, $$ then $f\_0$ is nonincreasing, $g\_0(x)=f\_0(x)x\log(x)$ does not converge to zero when $x\to\infty$ since $g\_0(\mathrm e^{n^2})\geqslant1$ for every $n\geqslant1$, and the integral of $f\_0$ is $\sum\limits\_{n\geqslant1}n^{-2}$, which is finite, hence $f\_0$ is integrable. One can modify this example slightly to get a decreasing function $f$, for example $$ f(x)=\sum\limits\_{n\geqslant1}(n^2\mathrm e^{n^2})^{-1}\exp(-x\mathrm e^{-n^2})\mathbf 1\_{[0,\mathrm e^{n^2}]}(x). $$ Then $f$ is decreasing, $g(x)=f(x)x\log(x)$ does not converge to zero when $x\to\infty$ since $g(\mathrm e^{n^2})\geqslant\mathrm e^{-1}$ for every $n\geqslant1$, and $f\leqslant f\_0$ hence $f$ is integrable.
Edit: This argument assumes that the limit exists, which need not happen. A change of variables gives, for $a>1$, $$ \int\_{a}^{\infty} \frac{dx}{xln(x)} = \int\_{\ln(a)}^{\infty} \frac{du}{u} =\infty $$ If the limit was not zero, call it $L$ (admitting $L=\infty$), we would get, for $x>a$ (with $a$ large enough) $f(x)\geq \frac{L}{2} \frac{1}{x\ln(x)}$ if $L$ is finite and $f(x)\geq \frac{1}{x\ln(x)}$ if it's infinite. Either way it contradicts the integrability of $f$ by the initial remark.
2,300,081
I am writing a plugin and need to live bind a click. The plugin works fine when I do a normal click bind, but not a live bind. I've boiled the plugin down to the basics: ``` (function($) { $.fn.liveBindTest = function() { return this.each(function() { $(this).live('click', function(){ console.log('live click'); return false; }); $(this).click(function(){ console.log('click'); return false; }); }); }; })(jQuery); ``` When I call the plugin function on a link, only `click` is printed to my console. What must I do in order for `live()` to work? Thanks.
2010/02/19
[ "https://Stackoverflow.com/questions/2300081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74552/" ]
After thinking this through, I realized it makes no sense to call `live` on an existing DOM element because it's already in the DOM. Trick is to use `live` when invoking the plugin: ``` (function($) { $.fn.liveBindTest = function() { return this.each(function() { $(this).click(function(){ console.log('click'); return false; }); }); }; })(jQuery); $('a').live('click', function(){ $(this).liveBindTest(); }); ```
Any particular reason you have 2 `click` event binded into a single object? The second bind will overwrite the `live` bind, so the `live` will never fired.
2,300,081
I am writing a plugin and need to live bind a click. The plugin works fine when I do a normal click bind, but not a live bind. I've boiled the plugin down to the basics: ``` (function($) { $.fn.liveBindTest = function() { return this.each(function() { $(this).live('click', function(){ console.log('live click'); return false; }); $(this).click(function(){ console.log('click'); return false; }); }); }; })(jQuery); ``` When I call the plugin function on a link, only `click` is printed to my console. What must I do in order for `live()` to work? Thanks.
2010/02/19
[ "https://Stackoverflow.com/questions/2300081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74552/" ]
Any particular reason you have 2 `click` event binded into a single object? The second bind will overwrite the `live` bind, so the `live` will never fired.
I think it's not a good point of view. Now suppose that your plugin is a sort of lightbox,and it is looking to anchor elements inside the DOM. Usually at the dom ready you will do something like ``` $(dom_elements).myplugin(); ``` What if your appending some links via jsor ajax to your page? I don't think that rebinding using your ``` $('a').live('click', function(){ $(this).liveBindTest(); }); ``` is going to be the right way!It will work but telling the truth i don't think that it will be a "best practice". The real problem is that with jQuery 1.4.2 the live event delegation is waiting for a string('a.test') and not for an object(this).Could it be a jQuery 1.4.2 bug?
2,300,081
I am writing a plugin and need to live bind a click. The plugin works fine when I do a normal click bind, but not a live bind. I've boiled the plugin down to the basics: ``` (function($) { $.fn.liveBindTest = function() { return this.each(function() { $(this).live('click', function(){ console.log('live click'); return false; }); $(this).click(function(){ console.log('click'); return false; }); }); }; })(jQuery); ``` When I call the plugin function on a link, only `click` is printed to my console. What must I do in order for `live()` to work? Thanks.
2010/02/19
[ "https://Stackoverflow.com/questions/2300081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74552/" ]
this works without workarounds outside of the plugin: ``` (function ($) { $.fn.liveBindTest = function () { return this['live']('click', function () { console.log('click'); return false; }); }; })(jQuery); $('a').liveBindTest(); ```
Any particular reason you have 2 `click` event binded into a single object? The second bind will overwrite the `live` bind, so the `live` will never fired.
2,300,081
I am writing a plugin and need to live bind a click. The plugin works fine when I do a normal click bind, but not a live bind. I've boiled the plugin down to the basics: ``` (function($) { $.fn.liveBindTest = function() { return this.each(function() { $(this).live('click', function(){ console.log('live click'); return false; }); $(this).click(function(){ console.log('click'); return false; }); }); }; })(jQuery); ``` When I call the plugin function on a link, only `click` is printed to my console. What must I do in order for `live()` to work? Thanks.
2010/02/19
[ "https://Stackoverflow.com/questions/2300081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74552/" ]
After thinking this through, I realized it makes no sense to call `live` on an existing DOM element because it's already in the DOM. Trick is to use `live` when invoking the plugin: ``` (function($) { $.fn.liveBindTest = function() { return this.each(function() { $(this).click(function(){ console.log('click'); return false; }); }); }; })(jQuery); $('a').live('click', function(){ $(this).liveBindTest(); }); ```
I think it's not a good point of view. Now suppose that your plugin is a sort of lightbox,and it is looking to anchor elements inside the DOM. Usually at the dom ready you will do something like ``` $(dom_elements).myplugin(); ``` What if your appending some links via jsor ajax to your page? I don't think that rebinding using your ``` $('a').live('click', function(){ $(this).liveBindTest(); }); ``` is going to be the right way!It will work but telling the truth i don't think that it will be a "best practice". The real problem is that with jQuery 1.4.2 the live event delegation is waiting for a string('a.test') and not for an object(this).Could it be a jQuery 1.4.2 bug?
2,300,081
I am writing a plugin and need to live bind a click. The plugin works fine when I do a normal click bind, but not a live bind. I've boiled the plugin down to the basics: ``` (function($) { $.fn.liveBindTest = function() { return this.each(function() { $(this).live('click', function(){ console.log('live click'); return false; }); $(this).click(function(){ console.log('click'); return false; }); }); }; })(jQuery); ``` When I call the plugin function on a link, only `click` is printed to my console. What must I do in order for `live()` to work? Thanks.
2010/02/19
[ "https://Stackoverflow.com/questions/2300081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74552/" ]
After thinking this through, I realized it makes no sense to call `live` on an existing DOM element because it's already in the DOM. Trick is to use `live` when invoking the plugin: ``` (function($) { $.fn.liveBindTest = function() { return this.each(function() { $(this).click(function(){ console.log('click'); return false; }); }); }; })(jQuery); $('a').live('click', function(){ $(this).liveBindTest(); }); ```
I find this works (jQuery 1.5.2): ``` (function($) { $.fn.clickTest = function () { return this.each(function() { $('.clicker').die('click').live('click', function() { console.log('clicked'); }); $(this).click(function() { $('body').append('<a href="#" class="clicker">click here '+$(this).attr('id')+'</a><br> '); }); }); }; }) (jQuery); ```
2,300,081
I am writing a plugin and need to live bind a click. The plugin works fine when I do a normal click bind, but not a live bind. I've boiled the plugin down to the basics: ``` (function($) { $.fn.liveBindTest = function() { return this.each(function() { $(this).live('click', function(){ console.log('live click'); return false; }); $(this).click(function(){ console.log('click'); return false; }); }); }; })(jQuery); ``` When I call the plugin function on a link, only `click` is printed to my console. What must I do in order for `live()` to work? Thanks.
2010/02/19
[ "https://Stackoverflow.com/questions/2300081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74552/" ]
this works without workarounds outside of the plugin: ``` (function ($) { $.fn.liveBindTest = function () { return this['live']('click', function () { console.log('click'); return false; }); }; })(jQuery); $('a').liveBindTest(); ```
I think it's not a good point of view. Now suppose that your plugin is a sort of lightbox,and it is looking to anchor elements inside the DOM. Usually at the dom ready you will do something like ``` $(dom_elements).myplugin(); ``` What if your appending some links via jsor ajax to your page? I don't think that rebinding using your ``` $('a').live('click', function(){ $(this).liveBindTest(); }); ``` is going to be the right way!It will work but telling the truth i don't think that it will be a "best practice". The real problem is that with jQuery 1.4.2 the live event delegation is waiting for a string('a.test') and not for an object(this).Could it be a jQuery 1.4.2 bug?
2,300,081
I am writing a plugin and need to live bind a click. The plugin works fine when I do a normal click bind, but not a live bind. I've boiled the plugin down to the basics: ``` (function($) { $.fn.liveBindTest = function() { return this.each(function() { $(this).live('click', function(){ console.log('live click'); return false; }); $(this).click(function(){ console.log('click'); return false; }); }); }; })(jQuery); ``` When I call the plugin function on a link, only `click` is printed to my console. What must I do in order for `live()` to work? Thanks.
2010/02/19
[ "https://Stackoverflow.com/questions/2300081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74552/" ]
I find this works (jQuery 1.5.2): ``` (function($) { $.fn.clickTest = function () { return this.each(function() { $('.clicker').die('click').live('click', function() { console.log('clicked'); }); $(this).click(function() { $('body').append('<a href="#" class="clicker">click here '+$(this).attr('id')+'</a><br> '); }); }); }; }) (jQuery); ```
I think it's not a good point of view. Now suppose that your plugin is a sort of lightbox,and it is looking to anchor elements inside the DOM. Usually at the dom ready you will do something like ``` $(dom_elements).myplugin(); ``` What if your appending some links via jsor ajax to your page? I don't think that rebinding using your ``` $('a').live('click', function(){ $(this).liveBindTest(); }); ``` is going to be the right way!It will work but telling the truth i don't think that it will be a "best practice". The real problem is that with jQuery 1.4.2 the live event delegation is waiting for a string('a.test') and not for an object(this).Could it be a jQuery 1.4.2 bug?
2,300,081
I am writing a plugin and need to live bind a click. The plugin works fine when I do a normal click bind, but not a live bind. I've boiled the plugin down to the basics: ``` (function($) { $.fn.liveBindTest = function() { return this.each(function() { $(this).live('click', function(){ console.log('live click'); return false; }); $(this).click(function(){ console.log('click'); return false; }); }); }; })(jQuery); ``` When I call the plugin function on a link, only `click` is printed to my console. What must I do in order for `live()` to work? Thanks.
2010/02/19
[ "https://Stackoverflow.com/questions/2300081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74552/" ]
this works without workarounds outside of the plugin: ``` (function ($) { $.fn.liveBindTest = function () { return this['live']('click', function () { console.log('click'); return false; }); }; })(jQuery); $('a').liveBindTest(); ```
I find this works (jQuery 1.5.2): ``` (function($) { $.fn.clickTest = function () { return this.each(function() { $('.clicker').die('click').live('click', function() { console.log('clicked'); }); $(this).click(function() { $('body').append('<a href="#" class="clicker">click here '+$(this).attr('id')+'</a><br> '); }); }); }; }) (jQuery); ```
29,074,684
I'm not a programmer, I've created a web site using a major hosting service's application. I want to insert code into a box provided by the hosting service that allows you to paste any HTML code. I want to create a link on the site that opens a popup window to display text that I hard-code into the code. I don't want to jump to another HTML page. I found the following code below that allows me to jump to another HTML page (it was set to CNN.com as an example). Is there a way to replace the action of jumping to another HTML page, with opening the popup and displaying the following example text "hello world". (please note in the code below, I deleted the opening and closing "a" tags at the beginning and end of the code since their inclusion causes problems when I type this question out on this web site). ``` <a href="http://www.cnn.com" onclick="javascript:void window.open('http://www.cnn.com','1426494439650','width=440,height=300,toolbar=0,menubar=0,location=1,status=1,scrollbars=1,resizable=1,left=0,top=0');return false;">Pop-up Window</a> ``` Thanks
2015/03/16
[ "https://Stackoverflow.com/questions/29074684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4675385/" ]
You should call ``` a.send "#{attr}=", 1 a.save! ```
You can try this ``` def set_attributes(*attributes) attributes.each {|attribute| self.send("#{attribute}=", 1)} end ```
1,255,371
Proving that $|z-1|-|z+1|=1$ its an hyperbola, and $\Re(1-z)=|z|$ its an ellipse. If $z\in \mathbb C$ I cant see why there are a hyperobla and an ellipse respct.
2015/04/28
[ "https://math.stackexchange.com/questions/1255371", "https://math.stackexchange.com", "https://math.stackexchange.com/users/116309/" ]
I'll give you an idea : $Re(1-z) = Re (1 - x - iy) = 1 - x $ On the other hand, $ |z| = \sqrt{x^2 + y^2} $ So, we can write : $ (1-x)^2 = x^2 + y^2 $ Then you can rearrange the last part..
The set of points whose difference of distances to fixed points, the foci ($(-1,0),(1,0)$ respectively here )is constant, is a hyperbola. Here $|z-1|$ is the distance to -1 and $|z+1|$ is the distance to $-1$.
1,255,371
Proving that $|z-1|-|z+1|=1$ its an hyperbola, and $\Re(1-z)=|z|$ its an ellipse. If $z\in \mathbb C$ I cant see why there are a hyperobla and an ellipse respct.
2015/04/28
[ "https://math.stackexchange.com/questions/1255371", "https://math.stackexchange.com", "https://math.stackexchange.com/users/116309/" ]
**To show that $|z-1|-|z+1|=1$ is a hyperbola** Let $a=|z-1|, b=|z+1|$ where $z=x+iy$. Hence $a^2=(x-1)^2+y^2$ and $ b^2=(x+1)^2+y^2$. Given equation: $\qquad \qquad\qquad \qquad \qquad a-b=1\qquad\qquad $ Multiply by $a+b$ and swapping sides: $\qquad a+b=a^2-b^2\qquad $ Adding: $\qquad\qquad\qquad \qquad\qquad \qquad \qquad 2a=1+a^2-b^2=1-4x$ Squaring: $$4a^2=(1-4x)^2\\ 4((x-1)^2+y^2)=1-8x+16x^2\\ 12x^2-y^2=4\\ \frac{x^2}{\left(\frac 1{\sqrt{3}}\right)^2}-\frac {y^2}{2^2}=1$$ which is a hyperbola. *NB - the method above avoids messy square roots* **To show that $\Re (1-z)=|z|$ is a parabola** Squaring both sides: $(1-x)^2=x^2+y^2\Rightarrow y^2=-2ax+1$ which is a parabola.
The set of points whose difference of distances to fixed points, the foci ($(-1,0),(1,0)$ respectively here )is constant, is a hyperbola. Here $|z-1|$ is the distance to -1 and $|z+1|$ is the distance to $-1$.
1,255,371
Proving that $|z-1|-|z+1|=1$ its an hyperbola, and $\Re(1-z)=|z|$ its an ellipse. If $z\in \mathbb C$ I cant see why there are a hyperobla and an ellipse respct.
2015/04/28
[ "https://math.stackexchange.com/questions/1255371", "https://math.stackexchange.com", "https://math.stackexchange.com/users/116309/" ]
**To show that $|z-1|-|z+1|=1$ is a hyperbola** Let $a=|z-1|, b=|z+1|$ where $z=x+iy$. Hence $a^2=(x-1)^2+y^2$ and $ b^2=(x+1)^2+y^2$. Given equation: $\qquad \qquad\qquad \qquad \qquad a-b=1\qquad\qquad $ Multiply by $a+b$ and swapping sides: $\qquad a+b=a^2-b^2\qquad $ Adding: $\qquad\qquad\qquad \qquad\qquad \qquad \qquad 2a=1+a^2-b^2=1-4x$ Squaring: $$4a^2=(1-4x)^2\\ 4((x-1)^2+y^2)=1-8x+16x^2\\ 12x^2-y^2=4\\ \frac{x^2}{\left(\frac 1{\sqrt{3}}\right)^2}-\frac {y^2}{2^2}=1$$ which is a hyperbola. *NB - the method above avoids messy square roots* **To show that $\Re (1-z)=|z|$ is a parabola** Squaring both sides: $(1-x)^2=x^2+y^2\Rightarrow y^2=-2ax+1$ which is a parabola.
I'll give you an idea : $Re(1-z) = Re (1 - x - iy) = 1 - x $ On the other hand, $ |z| = \sqrt{x^2 + y^2} $ So, we can write : $ (1-x)^2 = x^2 + y^2 $ Then you can rearrange the last part..
61,319,852
I am using a custom UI component in my project which has it's own few attributes. I want to change a specific one using a function when it is clicked. I don't know how to access it though, I am fairly new in this department. ``` <com.chinodev.androidneomorphframelayout.NeomorphFrameLayout android:id="@+id/btnsystem" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" app:neomorph_background_color="@color/appBackground" app:neomorph_corner_radius="10dp" app:neomorph_elevation="4dp" app:neomorph_highlight_color="#ffffff" app:neomorph_shadow_color="#CDCDCD" app:neomorph_view_type="rectangular"> ``` here say I want to change the `app:neomorph_elevation` using onclick function how can I do that?
2020/04/20
[ "https://Stackoverflow.com/questions/61319852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11516530/" ]
In `NeomorphFrameLayout` you can add a public function changeElevation ex ``` fun changeElevation(elevation :Float){ neomorph_elevation = elevation } ``` and can use in onClickListener like ``` btnsystem.changeElevation(5f) ```
As they specified in library that, Attributes: neomorph\_clickable option set it to true and onClick trigger a function from xml or from setOnClickListener whichever you prefer... <https://github.com/4inodev/Neomorphic-FrameLayout-Android>
61,319,852
I am using a custom UI component in my project which has it's own few attributes. I want to change a specific one using a function when it is clicked. I don't know how to access it though, I am fairly new in this department. ``` <com.chinodev.androidneomorphframelayout.NeomorphFrameLayout android:id="@+id/btnsystem" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" app:neomorph_background_color="@color/appBackground" app:neomorph_corner_radius="10dp" app:neomorph_elevation="4dp" app:neomorph_highlight_color="#ffffff" app:neomorph_shadow_color="#CDCDCD" app:neomorph_view_type="rectangular"> ``` here say I want to change the `app:neomorph_elevation` using onclick function how can I do that?
2020/04/20
[ "https://Stackoverflow.com/questions/61319852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11516530/" ]
In `NeomorphFrameLayout` you can add a public function changeElevation ex ``` fun changeElevation(elevation :Float){ neomorph_elevation = elevation } ``` and can use in onClickListener like ``` btnsystem.changeElevation(5f) ```
android-repository-history ========================== History of Android repository XML repository2-$N.xml and addons\_list-3.xml ----------------------------------------- Used by `sdkmanager` command. repository-$N.xml and addons\_list-2.xml ---------------------------------------- Used by `android` command, which is deprecated and unavailable in the latest Android SDK Tools (since r25.3.0)
102,545
I would like to create a custom WP admin area, that uses custom URLs to navigate thought it and have a custom generated HTML. A member will be able to login via a custom URL, for example: mysite.com/dashaboard or my.mysite.com When logged in a member will be able to see custom admin area where she/he can create pages, view/edit profile and so forth. I know this is doable in WP. However, I can't find anything that would explain the whole process well and take me through the steps in more detail. Currently, I don't know at all how to start tackling this. What's the best URL structure as a subdomain or not? What other considerations should be thought about? How to seamlessly integrate login/logout/password reminder WP functionality? How to integrate WP page and post creation (I'm guessing via URL masking)? I know this is a massive task. I would hugely appreciate if someone could explain a general picture of how to achieve this and what should be considered and help me to go through it step by step. Maybe someon can give me some pointers/links to research first, then I will get back to for help for the next step and so on. This might be a massive task for the stackexchange, perhaps someone will consider becoming my programming mentor and we can communicate via email/skype. I really much want to learn this. Please help me :) I'm ready to invest time into research and learning, but I need guidelines and mentoring. What do you guys think? Any ideas and pointers are much appreciated. Thank you, Dasha
2013/06/10
[ "https://wordpress.stackexchange.com/questions/102545", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1343/" ]
I'm not entirely sure you can do this with a single query in MySQL as you can't delete from tables which you reference in a sub-query. I would actually recommend doing this using [wp-cli](http://wp-cli.org/) and using the WordPress API to delete the duplicate posts (which will also delete any post meta and associated term references): ``` global $wpdb; $duplicate_titles = $wpdb->get_col("SELECT post_title FROM {$wpdb->posts} GROUP BY post_title HAVING COUNT(*) > 1"); foreach( $duplicate_titles as $title ) { $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_title=%s", $title ) ); // Iterate over the second ID with this post title till the last foreach( array_slice( $post_ids, 1 ) as $post_id ) { wp_delete_post( $post_id, true ); // Force delete this post } } ``` Hope this helps.
I know, it's an old thread but since i had a similar problem i would like to add some advises to the Answer from Bendoh (unfortunately i dont have the reputation to make a comment) Since wordpress and some Plugins are also storing data in the post table, i would recommend to add an post\_type to your querry: ``` global $wpdb; $duplicate_titles = $wpdb->get_col("SELECT post_title FROM {$wpdb->posts} WHERE `post_type` = 'post' GROUP BY post_title HAVING COUNT(*) > 1"); foreach( $duplicate_titles as $title ) { $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_title=%s", $title ) ); // Iterate over the second ID with this post title till the last foreach( array_slice( $post_ids, 1 ) as $post_id ) { wp_delete_post( $post_id, true ); // Force delete this post } } ``` Depending of the source of your duplicates i would also add another field to check for duplicates, like the publication date. ``` global $wpdb; $duplicate_titles = $wpdb->get_results("SELECT post_title, post_date, CONCAT(post_date, post_title) AS WHOLENAME FROM {$wpdb->posts} WHERE post_type = 'post' GROUP BY WHOLENAME HAVING COUNT(WHOLENAME) > 1"); foreach( $duplicate_titles as $title ) { $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_title=%s AND post_date='".$title->post_date."'", $title->post_title ) ); foreach( array_slice( $post_ids, 1 ) as $post_id ) { wp_delete_post( $post_id, true ); // Force delete this post } } ```
110,157
Which is correct way to create new custom theme in magento 2.0.4 under pub/static/frontend folder or app/design/frontend folder ?
2016/04/08
[ "https://magento.stackexchange.com/questions/110157", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/38266/" ]
Unfortunately, those options are gone now in Magento. Regarding the visitor log, everything is logged via the `\Magento\Customer\Model\Logger` model and via events observers declared under `\Magento\Customer\etc\frontend\events.xml`. However, the automatic cleaning seems to be totally gone. Regarding the system and exceptions logs, same issue, it's not configurable via the backend anymore and it's hardcoded directly in the following classes: * `\Magento\Framework\Logger\Handler\Debug.php` when you use the debug level, logs will go to `/var/log/debug.log` * `\Magento\Framework\Logger\Handler\Exception.php` when you use the exception level, logs will go to `/var/log/exception.log` * `\Magento\Framework\Logger\Handler\System.php` when you use the system level, logs will got to `/var/log/system.log`
If you want to log your variables you can do this way. ``` <?php namespace Test\Testpayment\Observer; class Sendtogateway implements \Magento\Framework\Event\ObserverInterface { protected $_responseFactory; protected $_url; protected $order; protected $logger; protected $_checkoutSession; public function __construct( \Magento\Framework\App\ResponseFactory $responseFactory, \Magento\Framework\UrlInterface $url, \Magento\Sales\Api\Data\OrderInterface $order, \Psr\Log\LoggerInterface $loggerInterface, \Magento\Checkout\Model\Session $checkoutSession ){ $this->_responseFactory = $responseFactory; $this->_url = $url; $this->order = $order; $this->logger = $loggerInterface; $this->_checkoutSession = $checkoutSession; } public function execute(\Magento\Framework\Event\Observer $observer) { $id = $observer->getEvent()->getOrder()->getIncrementId(); $this->_checkoutSession->setOrderNo($id); $orderdetail = $this->order->loadByIncrementId($id); $customerBeforeAuthUrl = $this->_url->getUrl('testpay/index/index/'); $this->_responseFactory->create()->setRedirect($customerBeforeAuthUrl)->sendResponse(); $this->logger->debug('$id'); } } ```
9,477
One of the tools that diamond moderators have at their disposal is the post notice. We have several different types of post notice for example, this one, for posts that require additional citations: > > Some of the information contained in this post requires additional references. Please edit to add citations to reliable sources that support the assertions made here. Unsourced material may be disputed or deleted. > > > These appear below a post and call to action that it needs improvement. [You can see this post for an example.](https://rpg.meta.stackexchange.com/a/9481/1204) Unfortunately, we currently don't have a post notice that handles the topic of subjective support well according to our principles of [Good Subjective, Bad Subjective](https://stackoverflow.blog/2010/09/29/good-subjective-bad-subjective/). Those principles are also covered in these related metas: * [How do we ask and answer subjective questions?](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions) * [What are the citation expectations of answers on RPG Stack Exchange?](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange) Currently, we are forced to use other notices, such as the one above, to handle flags on problematic answers with regards to subjective support. Our main goal for this notice is that it helps to inform people about our requirement that all posts are to be backed up and gives them information on how best to achieve that specifically for subjective content. With that in mind, the moderators have gotten together and put together a proposal which I have put below in the answers. Please vote on it as you deem fit and comment with any suggestions. Additionally, if you have a better proposal (or some sort of other major point to make), feel free to offer it up as your own answer as usual.
2019/10/01
[ "https://rpg.meta.stackexchange.com/questions/9477", "https://rpg.meta.stackexchange.com", "https://rpg.meta.stackexchange.com/users/28591/" ]
↑ Just to demonstrate: I have marked this post with our current “citation needed” post notice. It currently covers *objective* citations perfectly well. The post notice we're asking about will be a sibling to this one, and will be applied by a moderator when a post strongly needs *subjective* citation added (for example: “here, try this to fix your social issues, I've never seen it used but I'm sure it will work” when there's no credibility). --- **Historical note:** The text of this post notice has changed since this post was originally made. You can find the original text of the post notice at the time this post was made quoted in the question above.
To me this is a poor criterion, though well intended. We could do better by nuancing, creating explicit exceptions, or replacing it. ==================================================================================================================================== I've had a comparable answer deleted on another SE because, although I stated it stemmed from my own \* general \* experience over many years, it didn't stem from some, \* single, identified, specific\* experience that I could identify out of my past experiences, as a single reference. I've then seen other answers - numerous - where no such reference was given, and nobody minded. That has put me off answering such questions a great deal, because the requirement often seems unreasonably demanded, and capricious. I feel that the users who up and downvote answers are perfectly capable of deciding whether the answer has merit or fits their experience. For me, the statement that a reference \* must \* be cited in \* all \* cases is redundant. It inhibits good answers rather than helping filter them or ensure their quality. If exceptions are allowed, then I feel it should be restated as something other than a "rule" or "necessity" leading to removal if not complied with. That's the SE reality. ============================================================================================================================================================================ * I've seen it stated in other discussions on this point, that high ranking answers that don't meet this criterion are still accepted because "the community speaks". * I've seen it stated that answers discussing traumatic issues don't need referencing because its probably private and maybe retraumatising to expect them. In all, this suggests that the need for subjective answers to contain cites or personal experience, is not an absolute or necessity. So we should not express it as an absolute or necessity. At a minimum reword to state that **"a subjective answer is best expressed by reference to personal experience. Not including some reference to your own personal experience, may lead to an answer being seen as lower quality."** That would be more honest, and representative, it guides the community how to view and assess such answers, but removes the automatic "it should lead to removal" with its unspoken arbitrary-seeming exceptions.
9,477
One of the tools that diamond moderators have at their disposal is the post notice. We have several different types of post notice for example, this one, for posts that require additional citations: > > Some of the information contained in this post requires additional references. Please edit to add citations to reliable sources that support the assertions made here. Unsourced material may be disputed or deleted. > > > These appear below a post and call to action that it needs improvement. [You can see this post for an example.](https://rpg.meta.stackexchange.com/a/9481/1204) Unfortunately, we currently don't have a post notice that handles the topic of subjective support well according to our principles of [Good Subjective, Bad Subjective](https://stackoverflow.blog/2010/09/29/good-subjective-bad-subjective/). Those principles are also covered in these related metas: * [How do we ask and answer subjective questions?](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions) * [What are the citation expectations of answers on RPG Stack Exchange?](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange) Currently, we are forced to use other notices, such as the one above, to handle flags on problematic answers with regards to subjective support. Our main goal for this notice is that it helps to inform people about our requirement that all posts are to be backed up and gives them information on how best to achieve that specifically for subjective content. With that in mind, the moderators have gotten together and put together a proposal which I have put below in the answers. Please vote on it as you deem fit and comment with any suggestions. Additionally, if you have a better proposal (or some sort of other major point to make), feel free to offer it up as your own answer as usual.
2019/10/01
[ "https://rpg.meta.stackexchange.com/questions/9477", "https://rpg.meta.stackexchange.com", "https://rpg.meta.stackexchange.com/users/28591/" ]
Too Many Words for a post notice: be concise -------------------------------------------- Let's do some liposuction on the proposed post notice: > > Answers should be supported using evidence and/or experience. See [citation expectations for subjective answers](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange) and [guidance for subjective answers](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions). Please cite experience (your own or someone else's) to [show how your solution worked](https://rpg.meta.stackexchange.com/questions/9228/how-do-we-appropriately-back-up-a-subjective-answer/9229#9229) out in practice. This lets users judge whether it fits their situation or not. Answers that recommend "try this" without support may be removed. > > > This may still be too many words, but you are trying to pack a lot into a post notice. ### Here's a tighter version. (thank you, @thedarkwanderer and @doppelgreener) > > Answers should be [supported](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange). Please cite experience (your own or someone else's) to [show how your solution worked out](https://rpg.meta.stackexchange.com/a/9229/22566) in practice. This lets users judge whether it fits their situation or not. [Answers without support](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions) may be removed. > > > I hope that links can be embedded in these notes. Here's a slightly tighter version; thank you @daze413. > > Answers should be [supported](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange) - you can use your experience or > someone else's to [show how your solution worked](https://rpg.meta.stackexchange.com/a/9229/22566) in practice. > This helps users judge whether it fits their situation or not. > [Answers without support](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions) may be removed. > > >
Any post notice for this is inappropriate. ------------------------------------------ You're offering advice to someone on how to improve their post. If you said it (nicely) in a comment it would be friendly and helpful. Putting it in a moderator tool instead makes it hostile and vaguely threatening. Why on Earth would anyone want that?
9,477
One of the tools that diamond moderators have at their disposal is the post notice. We have several different types of post notice for example, this one, for posts that require additional citations: > > Some of the information contained in this post requires additional references. Please edit to add citations to reliable sources that support the assertions made here. Unsourced material may be disputed or deleted. > > > These appear below a post and call to action that it needs improvement. [You can see this post for an example.](https://rpg.meta.stackexchange.com/a/9481/1204) Unfortunately, we currently don't have a post notice that handles the topic of subjective support well according to our principles of [Good Subjective, Bad Subjective](https://stackoverflow.blog/2010/09/29/good-subjective-bad-subjective/). Those principles are also covered in these related metas: * [How do we ask and answer subjective questions?](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions) * [What are the citation expectations of answers on RPG Stack Exchange?](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange) Currently, we are forced to use other notices, such as the one above, to handle flags on problematic answers with regards to subjective support. Our main goal for this notice is that it helps to inform people about our requirement that all posts are to be backed up and gives them information on how best to achieve that specifically for subjective content. With that in mind, the moderators have gotten together and put together a proposal which I have put below in the answers. Please vote on it as you deem fit and comment with any suggestions. Additionally, if you have a better proposal (or some sort of other major point to make), feel free to offer it up as your own answer as usual.
2019/10/01
[ "https://rpg.meta.stackexchange.com/questions/9477", "https://rpg.meta.stackexchange.com", "https://rpg.meta.stackexchange.com/users/28591/" ]
I do not like the assumption that answers are not drawing on experience. ======================================================================== My experience with being pestered about explicitly certifying that my answer is drawn from my own experience is that I don't like it. That practice has mostly put me off answering questions. Additionally, it has not led to positive interactions with mods or other users. ### Evidence of discord from being prodded exists in comments. It's difficult to find previous cases (even from my own answers) of apparent discontent with answerers being prodded about this subject since it is usually in comments that get deleted. One example I could find of [a case](https://rpg.stackexchange.com/posts/149328/revisions) where someone else was put off got recorded in the revisions. Some examples of good answers that don't explicitly certify personal experience ------------------------------------------------------------------------------- ### Good answer without attesting personal experience: [GM Considerations for a Human Barbarian Toddler PC](https://rpg.stackexchange.com/questions/141031/gm-considerations-for-a-human-barbarian-toddler-pc/141032#141032) The answer is essentially, "here's something to try and stuff to watch out for", but does not include that the answerer has done something similar or experienced something similar. It's a great answer without personal experience support explicitly stated. ### Good answer without attesting personal experience citing questions that have good answers that do not attest personal experience [Can the dungeon master have a player character?](https://rpg.stackexchange.com/questions/137643/can-the-dungeon-master-have-a-player-character/137646#137646) The best part of this answer is that the answerer **has not** personally tried it, and wouldn't attempt it. > > For perspective, I've been running games for over 25 years, and I do not feel confident that I could pull off a DMPC successfully, even with all that experience. > > > The answer is neither something that happened to them personally, and the references are to questions with answers that also do not refer to direct personal experience. They're great answers even though they don't satisfy the [good subjective answer criteria](https://stackoverflow.blog/2010/09/29/good-subjective-bad-subjective/): > > * Something that happened to you personally > * Something you can back up with a reference > > > I find the post notice particularly unappealing ----------------------------------------------- [Answer with example post notice](https://rpg.meta.stackexchange.com/a/9481/38434) The comments requesting certifying personal experience with the threat of, "okay but your answer might get deleted..." to be sufficient to put me off answering questions as it is. The post label, to me, appears to be a sticker implying "this answer is bull\*\*\*\*". I do not expect it will contribute significantly to better answers, but I do expect it will not be well received.
I propose a different style for **explicit citation needed questions** Do you remember the Bête question? The one that moderators looked at 3 times in the first hours? Yes, I had put a note to it that demanded citations to books in the very beginning. 2 answers were deleted by mods after I had pointed out the lack of the required citations in them. In one case, the whole thing was a mix of interpretation (which I had explicitly asked *not to do*) and lacked citations. The answer [idled around for a month and a half before it was tagged as citation-needed and at once deleted.](https://rpg.stackexchange.com/posts/133056/timeline) With a +3/-3. What to do? ----------- I suggest having two variants of the back-it-up tag: the ***personal experience*** and the ***hard backup*** ones. Also, the hard backup one should possibly be worded harder - the requirement for hard backup is at times absolute and should be worded just as hard. There are good suggestions for the personal experience one up there. > > **This question requires citations.** Please edit to add citations to reliable sources that support the assertions made here. Unsourced material may be disputed or deleted. > > >
9,477
One of the tools that diamond moderators have at their disposal is the post notice. We have several different types of post notice for example, this one, for posts that require additional citations: > > Some of the information contained in this post requires additional references. Please edit to add citations to reliable sources that support the assertions made here. Unsourced material may be disputed or deleted. > > > These appear below a post and call to action that it needs improvement. [You can see this post for an example.](https://rpg.meta.stackexchange.com/a/9481/1204) Unfortunately, we currently don't have a post notice that handles the topic of subjective support well according to our principles of [Good Subjective, Bad Subjective](https://stackoverflow.blog/2010/09/29/good-subjective-bad-subjective/). Those principles are also covered in these related metas: * [How do we ask and answer subjective questions?](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions) * [What are the citation expectations of answers on RPG Stack Exchange?](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange) Currently, we are forced to use other notices, such as the one above, to handle flags on problematic answers with regards to subjective support. Our main goal for this notice is that it helps to inform people about our requirement that all posts are to be backed up and gives them information on how best to achieve that specifically for subjective content. With that in mind, the moderators have gotten together and put together a proposal which I have put below in the answers. Please vote on it as you deem fit and comment with any suggestions. Additionally, if you have a better proposal (or some sort of other major point to make), feel free to offer it up as your own answer as usual.
2019/10/01
[ "https://rpg.meta.stackexchange.com/questions/9477", "https://rpg.meta.stackexchange.com", "https://rpg.meta.stackexchange.com/users/28591/" ]
↑ Just to demonstrate: I have marked this post with our current “citation needed” post notice. It currently covers *objective* citations perfectly well. The post notice we're asking about will be a sibling to this one, and will be applied by a moderator when a post strongly needs *subjective* citation added (for example: “here, try this to fix your social issues, I've never seen it used but I'm sure it will work” when there's no credibility). --- **Historical note:** The text of this post notice has changed since this post was originally made. You can find the original text of the post notice at the time this post was made quoted in the question above.
Any post notice for this is inappropriate. ------------------------------------------ You're offering advice to someone on how to improve their post. If you said it (nicely) in a comment it would be friendly and helpful. Putting it in a moderator tool instead makes it hostile and vaguely threatening. Why on Earth would anyone want that?
9,477
One of the tools that diamond moderators have at their disposal is the post notice. We have several different types of post notice for example, this one, for posts that require additional citations: > > Some of the information contained in this post requires additional references. Please edit to add citations to reliable sources that support the assertions made here. Unsourced material may be disputed or deleted. > > > These appear below a post and call to action that it needs improvement. [You can see this post for an example.](https://rpg.meta.stackexchange.com/a/9481/1204) Unfortunately, we currently don't have a post notice that handles the topic of subjective support well according to our principles of [Good Subjective, Bad Subjective](https://stackoverflow.blog/2010/09/29/good-subjective-bad-subjective/). Those principles are also covered in these related metas: * [How do we ask and answer subjective questions?](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions) * [What are the citation expectations of answers on RPG Stack Exchange?](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange) Currently, we are forced to use other notices, such as the one above, to handle flags on problematic answers with regards to subjective support. Our main goal for this notice is that it helps to inform people about our requirement that all posts are to be backed up and gives them information on how best to achieve that specifically for subjective content. With that in mind, the moderators have gotten together and put together a proposal which I have put below in the answers. Please vote on it as you deem fit and comment with any suggestions. Additionally, if you have a better proposal (or some sort of other major point to make), feel free to offer it up as your own answer as usual.
2019/10/01
[ "https://rpg.meta.stackexchange.com/questions/9477", "https://rpg.meta.stackexchange.com", "https://rpg.meta.stackexchange.com/users/28591/" ]
Moderator proposal: =================== > > All answers must be supported by citing evidence or experience. Please review [our citation expectations for subjective answers](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange), as well as [our guidance for asking and answering subjective questions](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions). When recommending a course of action, you should cite experience (either your own, or someone else's) of how your recommended solution has worked out in actual practice so that users can judge whether it's an appropriate solution for their situation. Answers that recommend "try this" without any citation may be removed. > > >
To me this is a poor criterion, though well intended. We could do better by nuancing, creating explicit exceptions, or replacing it. ==================================================================================================================================== I've had a comparable answer deleted on another SE because, although I stated it stemmed from my own \* general \* experience over many years, it didn't stem from some, \* single, identified, specific\* experience that I could identify out of my past experiences, as a single reference. I've then seen other answers - numerous - where no such reference was given, and nobody minded. That has put me off answering such questions a great deal, because the requirement often seems unreasonably demanded, and capricious. I feel that the users who up and downvote answers are perfectly capable of deciding whether the answer has merit or fits their experience. For me, the statement that a reference \* must \* be cited in \* all \* cases is redundant. It inhibits good answers rather than helping filter them or ensure their quality. If exceptions are allowed, then I feel it should be restated as something other than a "rule" or "necessity" leading to removal if not complied with. That's the SE reality. ============================================================================================================================================================================ * I've seen it stated in other discussions on this point, that high ranking answers that don't meet this criterion are still accepted because "the community speaks". * I've seen it stated that answers discussing traumatic issues don't need referencing because its probably private and maybe retraumatising to expect them. In all, this suggests that the need for subjective answers to contain cites or personal experience, is not an absolute or necessity. So we should not express it as an absolute or necessity. At a minimum reword to state that **"a subjective answer is best expressed by reference to personal experience. Not including some reference to your own personal experience, may lead to an answer being seen as lower quality."** That would be more honest, and representative, it guides the community how to view and assess such answers, but removes the automatic "it should lead to removal" with its unspoken arbitrary-seeming exceptions.
9,477
One of the tools that diamond moderators have at their disposal is the post notice. We have several different types of post notice for example, this one, for posts that require additional citations: > > Some of the information contained in this post requires additional references. Please edit to add citations to reliable sources that support the assertions made here. Unsourced material may be disputed or deleted. > > > These appear below a post and call to action that it needs improvement. [You can see this post for an example.](https://rpg.meta.stackexchange.com/a/9481/1204) Unfortunately, we currently don't have a post notice that handles the topic of subjective support well according to our principles of [Good Subjective, Bad Subjective](https://stackoverflow.blog/2010/09/29/good-subjective-bad-subjective/). Those principles are also covered in these related metas: * [How do we ask and answer subjective questions?](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions) * [What are the citation expectations of answers on RPG Stack Exchange?](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange) Currently, we are forced to use other notices, such as the one above, to handle flags on problematic answers with regards to subjective support. Our main goal for this notice is that it helps to inform people about our requirement that all posts are to be backed up and gives them information on how best to achieve that specifically for subjective content. With that in mind, the moderators have gotten together and put together a proposal which I have put below in the answers. Please vote on it as you deem fit and comment with any suggestions. Additionally, if you have a better proposal (or some sort of other major point to make), feel free to offer it up as your own answer as usual.
2019/10/01
[ "https://rpg.meta.stackexchange.com/questions/9477", "https://rpg.meta.stackexchange.com", "https://rpg.meta.stackexchange.com/users/28591/" ]
↑ Just to demonstrate: I have marked this post with our current “citation needed” post notice. It currently covers *objective* citations perfectly well. The post notice we're asking about will be a sibling to this one, and will be applied by a moderator when a post strongly needs *subjective* citation added (for example: “here, try this to fix your social issues, I've never seen it used but I'm sure it will work” when there's no credibility). --- **Historical note:** The text of this post notice has changed since this post was originally made. You can find the original text of the post notice at the time this post was made quoted in the question above.
Moderator proposal: =================== > > All answers must be supported by citing evidence or experience. Please review [our citation expectations for subjective answers](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange), as well as [our guidance for asking and answering subjective questions](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions). When recommending a course of action, you should cite experience (either your own, or someone else's) of how your recommended solution has worked out in actual practice so that users can judge whether it's an appropriate solution for their situation. Answers that recommend "try this" without any citation may be removed. > > >
9,477
One of the tools that diamond moderators have at their disposal is the post notice. We have several different types of post notice for example, this one, for posts that require additional citations: > > Some of the information contained in this post requires additional references. Please edit to add citations to reliable sources that support the assertions made here. Unsourced material may be disputed or deleted. > > > These appear below a post and call to action that it needs improvement. [You can see this post for an example.](https://rpg.meta.stackexchange.com/a/9481/1204) Unfortunately, we currently don't have a post notice that handles the topic of subjective support well according to our principles of [Good Subjective, Bad Subjective](https://stackoverflow.blog/2010/09/29/good-subjective-bad-subjective/). Those principles are also covered in these related metas: * [How do we ask and answer subjective questions?](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions) * [What are the citation expectations of answers on RPG Stack Exchange?](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange) Currently, we are forced to use other notices, such as the one above, to handle flags on problematic answers with regards to subjective support. Our main goal for this notice is that it helps to inform people about our requirement that all posts are to be backed up and gives them information on how best to achieve that specifically for subjective content. With that in mind, the moderators have gotten together and put together a proposal which I have put below in the answers. Please vote on it as you deem fit and comment with any suggestions. Additionally, if you have a better proposal (or some sort of other major point to make), feel free to offer it up as your own answer as usual.
2019/10/01
[ "https://rpg.meta.stackexchange.com/questions/9477", "https://rpg.meta.stackexchange.com", "https://rpg.meta.stackexchange.com/users/28591/" ]
An advisory rather than a warning --------------------------------- > > This answer could be improved if you were able to cite experience (your own or someone else's) to help users judge whether it fits their situation or not. [This post](https://rpg.meta.stackexchange.com/questions/9228/how-do-we-appropriately-back-up-a-subjective-answer/9229#9229) provides excellent advice on how to do so. > > >
Moderator proposal: =================== > > All answers must be supported by citing evidence or experience. Please review [our citation expectations for subjective answers](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange), as well as [our guidance for asking and answering subjective questions](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions). When recommending a course of action, you should cite experience (either your own, or someone else's) of how your recommended solution has worked out in actual practice so that users can judge whether it's an appropriate solution for their situation. Answers that recommend "try this" without any citation may be removed. > > >
9,477
One of the tools that diamond moderators have at their disposal is the post notice. We have several different types of post notice for example, this one, for posts that require additional citations: > > Some of the information contained in this post requires additional references. Please edit to add citations to reliable sources that support the assertions made here. Unsourced material may be disputed or deleted. > > > These appear below a post and call to action that it needs improvement. [You can see this post for an example.](https://rpg.meta.stackexchange.com/a/9481/1204) Unfortunately, we currently don't have a post notice that handles the topic of subjective support well according to our principles of [Good Subjective, Bad Subjective](https://stackoverflow.blog/2010/09/29/good-subjective-bad-subjective/). Those principles are also covered in these related metas: * [How do we ask and answer subjective questions?](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions) * [What are the citation expectations of answers on RPG Stack Exchange?](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange) Currently, we are forced to use other notices, such as the one above, to handle flags on problematic answers with regards to subjective support. Our main goal for this notice is that it helps to inform people about our requirement that all posts are to be backed up and gives them information on how best to achieve that specifically for subjective content. With that in mind, the moderators have gotten together and put together a proposal which I have put below in the answers. Please vote on it as you deem fit and comment with any suggestions. Additionally, if you have a better proposal (or some sort of other major point to make), feel free to offer it up as your own answer as usual.
2019/10/01
[ "https://rpg.meta.stackexchange.com/questions/9477", "https://rpg.meta.stackexchange.com", "https://rpg.meta.stackexchange.com/users/28591/" ]
I propose a different style for **explicit citation needed questions** Do you remember the Bête question? The one that moderators looked at 3 times in the first hours? Yes, I had put a note to it that demanded citations to books in the very beginning. 2 answers were deleted by mods after I had pointed out the lack of the required citations in them. In one case, the whole thing was a mix of interpretation (which I had explicitly asked *not to do*) and lacked citations. The answer [idled around for a month and a half before it was tagged as citation-needed and at once deleted.](https://rpg.stackexchange.com/posts/133056/timeline) With a +3/-3. What to do? ----------- I suggest having two variants of the back-it-up tag: the ***personal experience*** and the ***hard backup*** ones. Also, the hard backup one should possibly be worded harder - the requirement for hard backup is at times absolute and should be worded just as hard. There are good suggestions for the personal experience one up there. > > **This question requires citations.** Please edit to add citations to reliable sources that support the assertions made here. Unsourced material may be disputed or deleted. > > >
To me this is a poor criterion, though well intended. We could do better by nuancing, creating explicit exceptions, or replacing it. ==================================================================================================================================== I've had a comparable answer deleted on another SE because, although I stated it stemmed from my own \* general \* experience over many years, it didn't stem from some, \* single, identified, specific\* experience that I could identify out of my past experiences, as a single reference. I've then seen other answers - numerous - where no such reference was given, and nobody minded. That has put me off answering such questions a great deal, because the requirement often seems unreasonably demanded, and capricious. I feel that the users who up and downvote answers are perfectly capable of deciding whether the answer has merit or fits their experience. For me, the statement that a reference \* must \* be cited in \* all \* cases is redundant. It inhibits good answers rather than helping filter them or ensure their quality. If exceptions are allowed, then I feel it should be restated as something other than a "rule" or "necessity" leading to removal if not complied with. That's the SE reality. ============================================================================================================================================================================ * I've seen it stated in other discussions on this point, that high ranking answers that don't meet this criterion are still accepted because "the community speaks". * I've seen it stated that answers discussing traumatic issues don't need referencing because its probably private and maybe retraumatising to expect them. In all, this suggests that the need for subjective answers to contain cites or personal experience, is not an absolute or necessity. So we should not express it as an absolute or necessity. At a minimum reword to state that **"a subjective answer is best expressed by reference to personal experience. Not including some reference to your own personal experience, may lead to an answer being seen as lower quality."** That would be more honest, and representative, it guides the community how to view and assess such answers, but removes the automatic "it should lead to removal" with its unspoken arbitrary-seeming exceptions.
9,477
One of the tools that diamond moderators have at their disposal is the post notice. We have several different types of post notice for example, this one, for posts that require additional citations: > > Some of the information contained in this post requires additional references. Please edit to add citations to reliable sources that support the assertions made here. Unsourced material may be disputed or deleted. > > > These appear below a post and call to action that it needs improvement. [You can see this post for an example.](https://rpg.meta.stackexchange.com/a/9481/1204) Unfortunately, we currently don't have a post notice that handles the topic of subjective support well according to our principles of [Good Subjective, Bad Subjective](https://stackoverflow.blog/2010/09/29/good-subjective-bad-subjective/). Those principles are also covered in these related metas: * [How do we ask and answer subjective questions?](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions) * [What are the citation expectations of answers on RPG Stack Exchange?](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange) Currently, we are forced to use other notices, such as the one above, to handle flags on problematic answers with regards to subjective support. Our main goal for this notice is that it helps to inform people about our requirement that all posts are to be backed up and gives them information on how best to achieve that specifically for subjective content. With that in mind, the moderators have gotten together and put together a proposal which I have put below in the answers. Please vote on it as you deem fit and comment with any suggestions. Additionally, if you have a better proposal (or some sort of other major point to make), feel free to offer it up as your own answer as usual.
2019/10/01
[ "https://rpg.meta.stackexchange.com/questions/9477", "https://rpg.meta.stackexchange.com", "https://rpg.meta.stackexchange.com/users/28591/" ]
Too Many Words for a post notice: be concise -------------------------------------------- Let's do some liposuction on the proposed post notice: > > Answers should be supported using evidence and/or experience. See [citation expectations for subjective answers](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange) and [guidance for subjective answers](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions). Please cite experience (your own or someone else's) to [show how your solution worked](https://rpg.meta.stackexchange.com/questions/9228/how-do-we-appropriately-back-up-a-subjective-answer/9229#9229) out in practice. This lets users judge whether it fits their situation or not. Answers that recommend "try this" without support may be removed. > > > This may still be too many words, but you are trying to pack a lot into a post notice. ### Here's a tighter version. (thank you, @thedarkwanderer and @doppelgreener) > > Answers should be [supported](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange). Please cite experience (your own or someone else's) to [show how your solution worked out](https://rpg.meta.stackexchange.com/a/9229/22566) in practice. This lets users judge whether it fits their situation or not. [Answers without support](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions) may be removed. > > > I hope that links can be embedded in these notes. Here's a slightly tighter version; thank you @daze413. > > Answers should be [supported](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange) - you can use your experience or > someone else's to [show how your solution worked](https://rpg.meta.stackexchange.com/a/9229/22566) in practice. > This helps users judge whether it fits their situation or not. > [Answers without support](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions) may be removed. > > >
To me this is a poor criterion, though well intended. We could do better by nuancing, creating explicit exceptions, or replacing it. ==================================================================================================================================== I've had a comparable answer deleted on another SE because, although I stated it stemmed from my own \* general \* experience over many years, it didn't stem from some, \* single, identified, specific\* experience that I could identify out of my past experiences, as a single reference. I've then seen other answers - numerous - where no such reference was given, and nobody minded. That has put me off answering such questions a great deal, because the requirement often seems unreasonably demanded, and capricious. I feel that the users who up and downvote answers are perfectly capable of deciding whether the answer has merit or fits their experience. For me, the statement that a reference \* must \* be cited in \* all \* cases is redundant. It inhibits good answers rather than helping filter them or ensure their quality. If exceptions are allowed, then I feel it should be restated as something other than a "rule" or "necessity" leading to removal if not complied with. That's the SE reality. ============================================================================================================================================================================ * I've seen it stated in other discussions on this point, that high ranking answers that don't meet this criterion are still accepted because "the community speaks". * I've seen it stated that answers discussing traumatic issues don't need referencing because its probably private and maybe retraumatising to expect them. In all, this suggests that the need for subjective answers to contain cites or personal experience, is not an absolute or necessity. So we should not express it as an absolute or necessity. At a minimum reword to state that **"a subjective answer is best expressed by reference to personal experience. Not including some reference to your own personal experience, may lead to an answer being seen as lower quality."** That would be more honest, and representative, it guides the community how to view and assess such answers, but removes the automatic "it should lead to removal" with its unspoken arbitrary-seeming exceptions.
9,477
One of the tools that diamond moderators have at their disposal is the post notice. We have several different types of post notice for example, this one, for posts that require additional citations: > > Some of the information contained in this post requires additional references. Please edit to add citations to reliable sources that support the assertions made here. Unsourced material may be disputed or deleted. > > > These appear below a post and call to action that it needs improvement. [You can see this post for an example.](https://rpg.meta.stackexchange.com/a/9481/1204) Unfortunately, we currently don't have a post notice that handles the topic of subjective support well according to our principles of [Good Subjective, Bad Subjective](https://stackoverflow.blog/2010/09/29/good-subjective-bad-subjective/). Those principles are also covered in these related metas: * [How do we ask and answer subjective questions?](https://rpg.meta.stackexchange.com/questions/3204/how-do-we-ask-and-answer-subjective-questions) * [What are the citation expectations of answers on RPG Stack Exchange?](https://rpg.meta.stackexchange.com/questions/8696/what-are-the-citation-expectations-of-answers-on-rpg-stack-exchange) Currently, we are forced to use other notices, such as the one above, to handle flags on problematic answers with regards to subjective support. Our main goal for this notice is that it helps to inform people about our requirement that all posts are to be backed up and gives them information on how best to achieve that specifically for subjective content. With that in mind, the moderators have gotten together and put together a proposal which I have put below in the answers. Please vote on it as you deem fit and comment with any suggestions. Additionally, if you have a better proposal (or some sort of other major point to make), feel free to offer it up as your own answer as usual.
2019/10/01
[ "https://rpg.meta.stackexchange.com/questions/9477", "https://rpg.meta.stackexchange.com", "https://rpg.meta.stackexchange.com/users/28591/" ]
I do not like the assumption that answers are not drawing on experience. ======================================================================== My experience with being pestered about explicitly certifying that my answer is drawn from my own experience is that I don't like it. That practice has mostly put me off answering questions. Additionally, it has not led to positive interactions with mods or other users. ### Evidence of discord from being prodded exists in comments. It's difficult to find previous cases (even from my own answers) of apparent discontent with answerers being prodded about this subject since it is usually in comments that get deleted. One example I could find of [a case](https://rpg.stackexchange.com/posts/149328/revisions) where someone else was put off got recorded in the revisions. Some examples of good answers that don't explicitly certify personal experience ------------------------------------------------------------------------------- ### Good answer without attesting personal experience: [GM Considerations for a Human Barbarian Toddler PC](https://rpg.stackexchange.com/questions/141031/gm-considerations-for-a-human-barbarian-toddler-pc/141032#141032) The answer is essentially, "here's something to try and stuff to watch out for", but does not include that the answerer has done something similar or experienced something similar. It's a great answer without personal experience support explicitly stated. ### Good answer without attesting personal experience citing questions that have good answers that do not attest personal experience [Can the dungeon master have a player character?](https://rpg.stackexchange.com/questions/137643/can-the-dungeon-master-have-a-player-character/137646#137646) The best part of this answer is that the answerer **has not** personally tried it, and wouldn't attempt it. > > For perspective, I've been running games for over 25 years, and I do not feel confident that I could pull off a DMPC successfully, even with all that experience. > > > The answer is neither something that happened to them personally, and the references are to questions with answers that also do not refer to direct personal experience. They're great answers even though they don't satisfy the [good subjective answer criteria](https://stackoverflow.blog/2010/09/29/good-subjective-bad-subjective/): > > * Something that happened to you personally > * Something you can back up with a reference > > > I find the post notice particularly unappealing ----------------------------------------------- [Answer with example post notice](https://rpg.meta.stackexchange.com/a/9481/38434) The comments requesting certifying personal experience with the threat of, "okay but your answer might get deleted..." to be sufficient to put me off answering questions as it is. The post label, to me, appears to be a sticker implying "this answer is bull\*\*\*\*". I do not expect it will contribute significantly to better answers, but I do expect it will not be well received.
An advisory rather than a warning --------------------------------- > > This answer could be improved if you were able to cite experience (your own or someone else's) to help users judge whether it fits their situation or not. [This post](https://rpg.meta.stackexchange.com/questions/9228/how-do-we-appropriately-back-up-a-subjective-answer/9229#9229) provides excellent advice on how to do so. > > >
3,267
My [edit for a few capitalization fixes](https://apple.stackexchange.com/review/suggested-edits/239477) was rejected. What was wrong with it?
2018/06/20
[ "https://apple.meta.stackexchange.com/questions/3267", "https://apple.meta.stackexchange.com", "https://apple.meta.stackexchange.com/users/287761/" ]
Hopefully I can provide some further context as the person who rejected the edit. * The edit did not substantially improve the post. I understand editing to fix spelling mistakes since Stack Exchange search does not understand mistakes unlike Google and find similar words, and I have more than once been frustrated because a post only contains a misspelt version. However in this case, the edits were to capitalisation, which would not affect search. * The edit did not fix everything with the post. This is a key factor when an edit is not substantial — if everything possible is fixed with a post with an edit, then it's more likely to be approved; alternatively, not fixing everything means a subsequent edit is required, adding yet another revision and potentially bumping the post again. (The title didn't need a question mark and was poor, ‘The issue is I try’, ‘and [it] works great’, ‘won[']t load’, et al.) * The edit was made to a very old post which wasn't bumped as far as I could tell. I'm more inclined to approve edits to old posts when they're already on the front page and primarily make edits myself like this. * The edit was one of a string of edits ranging from [borderline](https://apple.stackexchange.com/review/suggested-edits/239475) to [unsubstantive](https://apple.stackexchange.com/review/suggested-edits/239472) to [inappropriate](https://apple.stackexchange.com/review/suggested-edits/239474). Hopefully this has given you a chance to reflect on some other past edits. The borderline edit I rejected with an edit, have a look at the edit I performed, namely to the title and to the images. The inappropriate edit was inappropriate because it's never right to add useless content to an answer, taking another editor to remove it again adding another revision. The character limit prevents suggested edits like these which just remove a ‘hi’ taking the time of up to 3 different people on the site to look at a 2 character minor edit. Having said all that, suggested edits are a great way to get started with contributions on the site and they definitely help the site's readability for the future. I definitely don't want to discourage you from suggesting edits in the future and I look forward to your next edits having made excellent contributions previously. Hopefully this guidance can help everyone become better editors!
I see this as an edge case. We typically expect edits to be substantial, but this post is very short so it’s hard to tell how much better the question reads with some punctuation and grammar. I could see rejecting that sort of edit myself, but looking at it I’ve reversed the rejection. Also, that post is already answered, not even you upvoted it once and no one else did until I just cast a +1 and it’s 3 years old. Not sure bumping it will do much of anything so I respect the decision to not bump it and react the edit if that was the thinking. Thanks for posting a question on why.
45,685,463
Normally, I would assume that C++ 11 thread automatically destroy after detach. But the thing is, I can't find anything to prove this assumption. According to [this article](http://www.bogotobogo.com/cplusplus/C11/1_C11_creating_thread.php) > > Once detached, the thread should live that way forever. > > > forever? If the function of the thread finish, Does its resource remain forever? According to [this article](http://www.cplusplus.com/reference/thread/thread/detach/) > > After a call to this function, the thread object becomes non-joinable and can be destroyed safely. > > > It can be destroyed safely, but is it automatically? If it's not destroyed automatically, how to destroy it (not forcefully, but after the function of the thread end) Thanks for reading.
2017/08/15
[ "https://Stackoverflow.com/questions/45685463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4608491/" ]
You should consult a better reference. From [`std::thread::detach`](http://en.cppreference.com/w/cpp/thread/thread/detach): > > Separates the thread of execution from the thread object, allowing execution to continue independently. Any allocated resources will be freed once the thread exits. > > > After calling detach `*this` no longer owns any thread. > > > So to answer your questions (if they aren't already): > > forever? > > > No. If the thread finishes (for example: if it counts to 10), it is done and it is not running anymore. > > Does its resource remain forever? > > > No, when the thread finishes, every resource from the thread is freed (like variables and such). > > It can be destroyed safely, but is it automatically? > > > What do you mean? When the thread is done, it is destroyed (automatically), regardless of whether you call `detach` or not. The only difference is that here, they are referring to the thread *object*, so the actual `std::thread` instance. So when the thread object is destructed, you must have called `join` or `detach` regardless whether you own that the actual thread finished or not. If you don't, `std::terminate` is called.
A std::thread is just a thin wrapper around your platform's native threading library... It doesn't really contain much internally besides a few flags and the native handle to the platform's thread representation (which for both Unix & Windows is a fancy integral identifier). Speaking specifically of Unix-like systems, the call to std::thread::detach() does two things: * calls some variation of pthread\_detach(), which frees a data structure used to store the returning void pointer from platform-native thread-main. * sets a flag in the class denoting that the thread has been detached, and that, in turn, prevents the destructor from throwing an exception. As for any other resources that the thread creation may set up, those should be cleaned up by your platform's run-time when your thread-main exits. So, putting it another way, std::thread::detach just allows the wrapper to be destroyed without throwing an exception; the actual thread's stack and OS resource reclamation happens in the thread's execution context after your thread's main function exits, and that should be 100% automatic.
892,262
I am facing problem in loading data. I have to copy 800,000 rows from one table to another in Oracle database. I tried for 10,000 rows first but the time it took is not satisfactory. I tried using the "BULK COLLECT" and "INSERT INTO SELECT" clause but for both the cases response time is around 35 minutes. This is not the desired response I'm looking for. Does anyone have any suggestions?
2009/05/21
[ "https://Stackoverflow.com/questions/892262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Anirban, Using an "INSERT INTO SELECT" is the fastest way to populate your table. You may want to extend it with one or two of these hints: * APPEND: to use direct path loading, circumventing the buffer cache * PARALLEL: to use parallel processing if your system has multiple cpu's and this is a one-time operation or an operation that takes place at a time when it doesn't matter that one "selfish" process consumes more resources. Just using the append hint on my laptop copies 800,000 very small rows below 5 seconds: ``` SQL> create table one_table (id,name) 2 as 3 select level, 'name' || to_char(level) 4 from dual 5 connect by level <= 800000 6 / Tabel is aangemaakt. SQL> create table another_table as select * from one_table where 1=0 2 / Tabel is aangemaakt. SQL> select count(*) from another_table 2 / COUNT(*) ---------- 0 1 rij is geselecteerd. SQL> set timing on SQL> insert /*+ append */ into another_table select * from one_table 2 / 800000 rijen zijn aangemaakt. Verstreken: 00:00:04.76 ``` You mention that this operation takes 35 minutes in your case. Can you post some more details, so we can see what exactly is taking 35 minutes? Regards, Rob.
Is the table you are copying to the same structure as the other table? Does it have data or are you creating a new one? Can you use exp/imp? Exp can be give a query to limit what it exports and then imported into the db. What is the total size of the table you are copying from? If you are copying most of the data from one table to a second, can you instead copy the full table using exp/imp and then remove the unwanted rows which would be less than copying.
892,262
I am facing problem in loading data. I have to copy 800,000 rows from one table to another in Oracle database. I tried for 10,000 rows first but the time it took is not satisfactory. I tried using the "BULK COLLECT" and "INSERT INTO SELECT" clause but for both the cases response time is around 35 minutes. This is not the desired response I'm looking for. Does anyone have any suggestions?
2009/05/21
[ "https://Stackoverflow.com/questions/892262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I would agree with Rob. Insert into () select is the fastest way to do this. What exactly do you need to do? If you're trying to do a table rename by copying to a new table and then deleting the old, you might be better off doing a table rename: ``` alter table table rename to someothertable; ```
try to drop all indexes/constraints on your destination table and then re-create them after data load. use `/*+NOLOGGING*/` hint in case you use NOARCHIVELOG mode, or consider to do the backup right after the operation.